instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private static String readLongMessage() throws IOException { String data = ""; //update complete location of large message here data = new String(Files.readAllBytes(Paths.get("RandomTextFile.txt"))); return data; } @Bean public LongMessageProducer longMessageProducer() { return new LongMessageProducer(); } @Bean public LongMessageListener longMessageListener() { return new LongMessageListener(); } public static class LongMessageProducer { @Autowired private KafkaTemplate<String, String> kafkaTemplate; @Value(value = "${long.message.topic.name}")
private String topicName; public void sendMessage(String message) { kafkaTemplate.send(topicName, message); System.out.println("Long message Sent"); } } public static class LongMessageListener { @KafkaListener(topics = "${long.message.topic.name}", groupId = "longMessage", containerFactory = "longMessageKafkaListenerContainerFactory") public void listenGroupLongMessage(String message) { System.out.println("Received Message in group 'longMessage'"); } } }
repos\tutorials-master\spring-kafka-4\src\main\java\com\baeldung\spring\kafka\KafkaApplicationLongMessage.java
1
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getRemovalTime() { return removalTime; }
public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public static AttachmentDto fromAttachment(Attachment attachment) { AttachmentDto dto = new AttachmentDto(); dto.id = attachment.getId(); dto.name = attachment.getName(); dto.type = attachment.getType(); dto.description = attachment.getDescription(); dto.taskId = attachment.getTaskId(); dto.url = attachment.getUrl(); dto.createTime = attachment.getCreateTime(); dto.removalTime = attachment.getRemovalTime(); dto.rootProcessInstanceId = attachment.getRootProcessInstanceId(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\task\AttachmentDto.java
1
请完成以下Java代码
public class Jackson2XmlMessageConverter extends AbstractJackson2MessageConverter { /** * Construct with an internal {@link XmlMapper} instance * and trusted packed to all ({@code *}). */ public Jackson2XmlMessageConverter() { this("*"); } /** * Construct with an internal {@link XmlMapper} instance. * The {@link DeserializationFeature#FAIL_ON_UNKNOWN_PROPERTIES} is set to false on * the {@link XmlMapper}. * @param trustedPackages the trusted Java packages for deserialization * @see DefaultJackson2JavaTypeMapper#setTrustedPackages(String...) */ public Jackson2XmlMessageConverter(String... trustedPackages) { this(new XmlMapper(), trustedPackages); this.objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } /**
* Construct with the provided {@link XmlMapper} instance * and trusted packed to all ({@code *}). * @param xmlMapper the {@link XmlMapper} to use. */ public Jackson2XmlMessageConverter(XmlMapper xmlMapper) { this(xmlMapper, "*"); } /** * Construct with the provided {@link XmlMapper} instance. * @param xmlMapper the {@link XmlMapper} to use. * @param trustedPackages the trusted Java packages for deserialization * @see DefaultJackson2JavaTypeMapper#setTrustedPackages(String...) */ public Jackson2XmlMessageConverter(XmlMapper xmlMapper, String... trustedPackages) { super(xmlMapper, MimeTypeUtils.parseMimeType(MessageProperties.CONTENT_TYPE_XML), trustedPackages); } }
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\support\converter\Jackson2XmlMessageConverter.java
1
请完成以下Java代码
public String getId() { return id; } public String getName() { return name; } public FormType getType() { return type; } public String getValue() { return value; }
public boolean isRequired() { return isRequired; } public boolean isReadable() { return isReadable; } public void setValue(String value) { this.value = value; } public boolean isWritable() { return isWritable; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\FormPropertyImpl.java
1
请在Spring Boot框架中完成以下Java代码
public abstract class AbstractConnectionFactoryConfigurer<T extends AbstractConnectionFactory> { private final RabbitProperties rabbitProperties; private @Nullable ConnectionNameStrategy connectionNameStrategy; private final RabbitConnectionDetails connectionDetails; /** * Creates a new configurer that will configure the connection factory using the given * {@code properties}. * @param properties the properties to use to configure the connection factory */ protected AbstractConnectionFactoryConfigurer(RabbitProperties properties) { this(properties, new PropertiesRabbitConnectionDetails(properties, null)); } /** * Creates a new configurer that will configure the connection factory using the given * {@code properties} and {@code connectionDetails}, with the latter taking priority. * @param properties the properties to use to configure the connection factory * @param connectionDetails the connection details to use to configure the connection * factory */ protected AbstractConnectionFactoryConfigurer(RabbitProperties properties, RabbitConnectionDetails connectionDetails) { Assert.notNull(properties, "'properties' must not be null"); Assert.notNull(connectionDetails, "'connectionDetails' must not be null"); this.rabbitProperties = properties; this.connectionDetails = connectionDetails; } protected final @Nullable ConnectionNameStrategy getConnectionNameStrategy() { return this.connectionNameStrategy; } public final void setConnectionNameStrategy(@Nullable ConnectionNameStrategy connectionNameStrategy) { this.connectionNameStrategy = connectionNameStrategy; } /**
* Configures the given {@code connectionFactory} with sensible defaults. * @param connectionFactory connection factory to configure */ public final void configure(T connectionFactory) { Assert.notNull(connectionFactory, "'connectionFactory' must not be null"); PropertyMapper map = PropertyMapper.get(); String addresses = this.connectionDetails.getAddresses() .stream() .map((address) -> address.host() + ":" + address.port()) .collect(Collectors.joining(",")); map.from(addresses).to(connectionFactory::setAddresses); map.from(this.rabbitProperties::getAddressShuffleMode).to(connectionFactory::setAddressShuffleMode); map.from(this.connectionNameStrategy).to(connectionFactory::setConnectionNameStrategy); configure(connectionFactory, this.rabbitProperties); } /** * Configures the given {@code connectionFactory} using the given * {@code rabbitProperties}. * @param connectionFactory connection factory to configure * @param rabbitProperties properties to use for the configuration */ protected abstract void configure(T connectionFactory, RabbitProperties rabbitProperties); }
repos\spring-boot-4.0.1\module\spring-boot-amqp\src\main\java\org\springframework\boot\amqp\autoconfigure\AbstractConnectionFactoryConfigurer.java
2
请完成以下Java代码
private JsonHU toNewJsonHU(final @NonNull HUQRCode huQRCode) { return JsonHU.builder() .id(null) .huStatusCaption("-") .displayName(huQRCode.getPackingInfo().getCaption()) .qrCode(HandlingUnitsService.toJsonHUQRCode(huQRCode)) .warehouseValue(null) .locatorValue(null) .product(huQRCode.getProductId().map(this::toJsonProduct).orElse(null)) .attributes2(JsonHUAttributes.builder() .list(huQRCode.getAttributes().stream() .map(this::toJsonHUAttribute) .collect(ImmutableList.toImmutableList())) .build()) .unitType(toJsonHUType(huQRCode.getPackingInfo().getHuUnitType())) .build(); } private JsonHUProduct toJsonProduct(@NonNull final ProductId productId) { final I_M_Product product = productBL.getById(productId); final I_C_UOM uom = productBL.getStockUOM(product); return JsonHUProduct.builder() .productValue(product.getValue()) .productName(product.getName()) .qty("0") .uom(uom.getX12DE355()) .build(); } @PostMapping("/list/byQRCode") public List<JsonHU> listByQRCode(@RequestBody @NonNull final JsonGetByQRCodeRequest request) { final String adLanguage = Env.getADLanguageOrBaseLanguage(); return handlingUnitsService.getHUsByQrCode(request, adLanguage); } private static @NonNull ResponseEntity<JsonGetSingleHUResponse> toBadRequestResponseEntity(final Exception e) { final String adLanguage = Env.getADLanguageOrBaseLanguage(); return ResponseEntity.badRequest().body(JsonGetSingleHUResponse.ofError(JsonErrors.ofThrowable(e, adLanguage))); } private JsonHUAttribute toJsonHUAttribute(final HUQRCodeAttribute huQRCodeAttribute) { final String adLanguage = Env.getADLanguageOrBaseLanguage(); final AttributeCode attributeCode = huQRCodeAttribute.getCode();
return JsonHUAttribute.builder() .code(attributeCode.getCode()) .caption(attributeDAO.getAttributeByCode(attributeCode).getDisplayName().translate(adLanguage)) .value(huQRCodeAttribute.getValueRendered()) .build(); } private static JsonHUType toJsonHUType(@NonNull final HUQRCodeUnitType huUnitType) { switch (huUnitType) { case LU: return JsonHUType.LU; case TU: return JsonHUType.TU; case VHU: return JsonHUType.CU; default: throw new AdempiereException("Unknown HU Unit Type: " + huUnitType); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.mobileui\src\main\java\de\metas\handlingunits\rest_api\HandlingUnitsRestController.java
1
请完成以下Java代码
public abstract class FindPanelContainer { protected final FindPanel findPanel; FindPanelContainer(final FindPanelBuilder builder) { super(); findPanel = builder.buildFindPanel(); final int findPanelHeight = AdempierePLAF.getInt(FindPanelUI.KEY_StandardWindow_Height, FindPanelUI.DEFAULT_StandardWindow_Height); findPanel.setPreferredSize(new Dimension(500, findPanelHeight)); init(builder); runOnExpandedStateChange(new Runnable() { @Override public void run() { onCollapsedStateChanged(); } }); setExpanded(!builder.isSearchPanelCollapsed()); } protected abstract void init(final FindPanelBuilder builder);
/** @return swing component */ public abstract JComponent getComponent(); public abstract boolean isExpanded(); public abstract void setExpanded(final boolean expanded); public abstract void runOnExpandedStateChange(final Runnable runnable); public abstract boolean isFocusable(); public abstract void requestFocus(); public abstract boolean requestFocusInWindow(); private void onCollapsedStateChanged() { requestFocus(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanelContainer.java
1
请完成以下Java代码
public Optional<AdArchive> getLastArchive( @NonNull final TableRecordReference reference) { return getLastArchiveRecord(reference).map(this::toAdArchive); } @Override public Optional<I_AD_Archive> getLastArchiveRecord( @NonNull final TableRecordReference reference) { final IArchiveDAO archiveDAO = Services.get(IArchiveDAO.class); final List<I_AD_Archive> lastArchives = archiveDAO.retrieveLastArchives(Env.getCtx(), reference, QueryLimit.ONE); if (lastArchives.isEmpty()) { return Optional.empty(); } else { return Optional.of(lastArchives.get(0)); } } @Override public Optional<Resource> getLastArchiveBinaryData(
@NonNull final TableRecordReference reference) { return getLastArchive(reference).map(AdArchive::getArchiveDataAsResource); } @Override public void updatePrintedRecords(final ImmutableSet<ArchiveId> ids, final UserId userId) { archiveDAO.updatePrintedRecords(ids, userId); } private AdArchive toAdArchive(final I_AD_Archive record) { return AdArchive.builder() .id(ArchiveId.ofRepoId(record.getAD_Archive_ID())) .archiveData(getBinaryData(record)) .contentType(getContentType(record)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\archive\api\impl\ArchiveBL.java
1
请完成以下Java代码
public class User { /** * 主键 */ @Id private Long id; /** * 用户名 */ private String username; /** * 密码 */ private String password; /** * 昵称 */ private String nickname; /** * 手机 */ private String phone; /** * 邮箱 */ private String email; /** * 生日 */ private Long birthday;
/** * 性别,男-1,女-2 */ private Integer sex; /** * 状态,启用-1,禁用-0 */ private Integer status; /** * 创建时间 */ @Column(name = "create_time") private Long createTime; /** * 更新时间 */ @Column(name = "update_time") private Long updateTime; }
repos\spring-boot-demo-master\demo-rbac-security\src\main\java\com\xkcoding\rbac\security\model\User.java
1
请在Spring Boot框架中完成以下Java代码
public Result<?> smsCheckCaptcha(@RequestBody SysLoginModel sysLoginModel, HttpServletRequest request){ String captcha = sysLoginModel.getCaptcha(); String checkKey = sysLoginModel.getCheckKey(); if(captcha==null){ return Result.error("验证码无效"); } String lowerCaseCaptcha = captcha.toLowerCase(); String realKey = Md5Util.md5Encode(lowerCaseCaptcha+checkKey+jeecgBaseConfig.getSignatureSecret(), "utf-8"); Object checkCode = redisUtil.get(realKey); if(checkCode==null || !checkCode.equals(lowerCaseCaptcha)) { return Result.error("验证码错误"); } String clientIp = IpUtils.getIpAddr(request); //清空短信记录数量 DySmsLimit.clearSendSmsCount(clientIp); redisUtil.removeAll(realKey); return Result.ok(); } /** * 登录获取用户部门信息 * * @param jsonObject * @return */ @IgnoreAuth @RequestMapping(value = "/loginGetUserDeparts", method = RequestMethod.POST) public Result<JSONObject> loginGetUserDeparts(@RequestBody JSONObject jsonObject, HttpServletRequest request){ return sysUserService.loginGetUserDeparts(jsonObject); } /** * 校验验证码工具方法,校验失败直接返回Result,校验通过返回realKey */ private String validateCaptcha(SysLoginModel sysLoginModel, Result<JSONObject> result) {
// 判断是否启用登录验证码校验 if (jeecgBaseConfig.getFirewall() != null && Boolean.FALSE.equals(jeecgBaseConfig.getFirewall().getEnableLoginCaptcha())) { log.warn("关闭了登录验证码校验,跳过验证码校验!"); return "LoginWithoutVerifyCode"; } String captcha = sysLoginModel.getCaptcha(); if (captcha == null) { result.error500("验证码无效"); return null; } String lowerCaseCaptcha = captcha.toLowerCase(); String keyPrefix = Md5Util.md5Encode(sysLoginModel.getCheckKey() + jeecgBaseConfig.getSignatureSecret(), "utf-8"); String realKey = keyPrefix + lowerCaseCaptcha; Object checkCode = redisUtil.get(realKey); if (checkCode == null || !checkCode.toString().equals(lowerCaseCaptcha)) { log.warn("验证码错误,key= {} , Ui checkCode= {}, Redis checkCode = {}", sysLoginModel.getCheckKey(), lowerCaseCaptcha, checkCode); result.error500("验证码错误"); result.setCode(HttpStatus.PRECONDITION_FAILED.value()); return null; } return realKey; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\LoginController.java
2
请完成以下Java代码
public void setHeaderValue(HeaderValue headerValue) { Assert.notNull(headerValue, "headerValue cannot be null"); this.headerValue = headerValue; } /** * The value of the x-xss-protection header. One of: "0", "1", "1; mode=block" * * @author Daniel Garnier-Moiroux * @since 5.8 */ public enum HeaderValue { DISABLED("0"), ENABLED("1"), ENABLED_MODE_BLOCK("1; mode=block"); private final String value; HeaderValue(String value) { this.value = value; } public static @Nullable HeaderValue from(String headerValue) { for (HeaderValue value : values()) { if (value.toString().equals(headerValue)) { return value; } }
return null; } @Override public String toString() { return this.value; } } @Override public String toString() { return getClass().getName() + " [headerValue=" + this.headerValue + "]"; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\writers\XXssProtectionHeaderWriter.java
1
请完成以下Java代码
public void addToCurrentQtyAndCumulate(@NonNull final CostAmountAndQty amtAndQty) { addToCurrentQtyAndCumulate(amtAndQty.getQty(), amtAndQty.getAmt()); } public void setCostPrice(@NonNull final CostPrice costPrice) { this.costPrice = costPrice; } public void setOwnCostPrice(@NonNull final CostAmount ownCostPrice) { setCostPrice(getCostPrice().withOwnCostPrice(ownCostPrice)); }
public void clearOwnCostPrice() { setCostPrice(getCostPrice().withZeroOwnCostPrice()); } public void addToOwnCostPrice(@NonNull final CostAmount ownCostPriceToAdd) { setCostPrice(getCostPrice().addToOwnCostPrice(ownCostPriceToAdd)); } public void clearComponentsCostPrice() { setCostPrice(getCostPrice().withZeroComponentsCostPrice()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CurrentCost.java
1
请完成以下Spring Boot application配置
server: port: 8081 #logging: # level: ## com.base.voice.mapper: debug # com.base.voice.autodialer.mapper: debug weixin: app-id: wxd8547a419105c817 app-secret: c16f43f4e602ee1ddfcc64d01f766fbe token: aliang media: voice: template: D:\weixinpath\template\ path: D:\weixinpath\voice\ reply-path: D:\weixinpath\voice_reply\ #MYBATIS mybatis: type-aliases-package: com.base.voice.entity,com.base.voice.autodialer.entity mapper-locations: classpath*:/mapper/*/*Mapper.xml,classpath*:/mapper/*Mapper.xml configuration: map-underscore-to-camel-case: true use-generated-keys: true default-fetch-size: 100 default-statement-timeout: 30 spring: datasource: # url: jdbc:mysql://localhost:3306/wx_data?useUnicode=true&characterEncoding=UTF-8 # username: root # password: root123 url: jdbc:mysql://192.168.1.82:3306/autodialer?useUnicode=true&characterEncoding=UTF-8 username: vector password: vector driver-class-name: com.mysql.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource initialSize: 5 minIdle: 5 maxActive: 20 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 validationQuery: SELECT 1 testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 20 filters: stat connectionProperties: druid.stat.mergeSql: true druid.stat.slowSqlMillis: 5000 redis: database: 1 host: localhost port: 6379 password: # pool: # max-active: 8 # max-wait: -1 # max-idle: 8 # min-idle: 0 # timeout: 500 robot: notify-url: http://192.168.22.2:808
1/robot/callNotify # 最好为插卡数-1 maximumcall: 2 is-need-upload-file: false conversion: # v1: # voice-url: http://192.168.1.31:9840/v1/speech/chart # text-url: http://192.168.1.31:9840/v1/text/chart v2: voice-url: http://192.168.216.216:9841/v2/speech/chat text-url: http://192.168.216.216:9841/v2/text/chart v3: text-url: http://192.168.216.216:9844/v3/text/chat voice-url: http://192.168.216.216:9843/v3/speech/chat robot-file-path: # 0 随机 , 1 男声 , 2 女声 , 3 盖茨比 mode: 1 male: /var/smartivr/voice/male female: /var/smartivr/voice/female other: /var/smartivr/voice/gcb # 单位毫秒 block-asr-duration: 4000 oss: bucket: bazatest path: robotrecordfiletest
repos\spring-boot-quick-master\quick-wx-public\src\main\resources\application.yml
2
请完成以下Java代码
protected String doIt() { final PlainContextAware localCtx = PlainContextAware.newWithThreadInheritedTrx(getCtx()); final Set<I_M_DiscountSchemaBreak_V> breaks = getProcessInfo().getSelectedIncludedRecords() .stream() .map(recordRef -> recordRef.getModel(localCtx, I_M_DiscountSchemaBreak_V.class)) .collect(ImmutableSet.toImmutableSet()); final Set<ProductId> products = new HashSet<ProductId>(); final Set<PricingConditionsId> pricingConditions = new HashSet<PricingConditionsId>(); breaks.forEach(record -> { products.add(ProductId.ofRepoId(record.getM_Product_ID())); // pricingConditions.add(PricingConditionsId.ofRepoId(record.getM_DiscountSchema_ID())); }); // run copy for each product separate for (final ProductId product : products) { copyDiscountSchemaBreaks(pricingConditions, product); }; return MSG_OK; } private void copyDiscountSchemaBreaks(final Set<PricingConditionsId> pricingConditions, ProductId product) {
final ICompositeQueryFilter<I_M_DiscountSchemaBreak> queryFilter = Services.get(IQueryBL.class) .createCompositeQueryFilter(I_M_DiscountSchemaBreak.class) .setJoinAnd() .addInArrayFilter(I_M_DiscountSchemaBreak.COLUMNNAME_M_DiscountSchema_ID, pricingConditions) .addInArrayFilter(I_M_DiscountSchemaBreak.COLUMNNAME_M_Product_ID, product); final boolean allowCopyToSameSchema = true; final CopyDiscountSchemaBreaksRequest request = CopyDiscountSchemaBreaksRequest.builder() .filter(queryFilter) .pricingConditionsId(PricingConditionsId.ofRepoId(p_PricingConditionsId)) .productId(ProductId.ofRepoId(p_ProductId)) .allowCopyToSameSchema(allowCopyToSameSchema) .direction(Direction.TargetSource) .makeTargetAsSource(p_MakeTargetAsSource) .build(); pricingConditionsRepo.copyDiscountSchemaBreaksWithProductId(request); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pricing\process\M_DiscountSchemaBreak_CopyToSelectedSchema_Product.java
1
请完成以下Java代码
public int getVersion() { return version; } @Override public void setVersion(int version) { this.version = version; } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public void setDescription(String description) { this.description = description; } @Override public String getDescription() { return description; } @Override public String getType() { return type; } @Override public void setType(String type) { this.type = type; } @Override public String getImplementation() { return implementation; } @Override public void setImplementation(String implementation) { this.implementation = implementation; } @Override public String getDeploymentId() { return deploymentId; } @Override public String getCategory() { return category; }
@Override public void setCategory(String category) { this.category = category; } @Override public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @Override public Date getCreateTime() { return createTime; } @Override public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String getResourceName() { return resourceName; } @Override public void setResourceName(String resourceName) { this.resourceName = resourceName; } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String toString() { return "ChannelDefinitionEntity[" + id + "]"; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\ChannelDefinitionEntityImpl.java
1
请完成以下Java代码
public Map<String, Object> getVariables() { return variables; } public Map<String, Object> getTransientVariables() { return transientVariables; } public Map<String, Object> getStartFormVariables() { return startFormVariables; } public String getOutcome() { return outcome; } public Map<String, Object> getExtraFormVariables() { return extraFormVariables;
} public FormInfo getExtraFormInfo() { return extraFormInfo; } public String getExtraFormOutcome() { return extraFormOutcome; } public boolean isFallbackToDefaultTenant() { return fallbackToDefaultTenant; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\runtime\ProcessInstanceBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
protected ProcessDefinitionEntity findLatestProcessDefinition(ProcessDefinition processDefinition) { ProcessDefinitionEntity latestProcessDefinition = null; if (processDefinition.getTenantId() != null && !ProcessEngineConfiguration.NO_TENANT_ID.equals(processDefinition.getTenantId())) { latestProcessDefinition = getProcessDefinitionEntityManager() .findLatestProcessDefinitionByKeyAndTenantId(processDefinition.getKey(), processDefinition.getTenantId()); } else { latestProcessDefinition = getProcessDefinitionEntityManager() .findLatestProcessDefinitionByKey(processDefinition.getKey()); } return latestProcessDefinition; } protected ProcessDefinition findNewLatestProcessDefinitionAfterRemovalOf(ProcessDefinition processDefinitionToBeRemoved) { // The latest process definition is not necessarily the one with 'version -1' (some versions could have been deleted) // Hence, the following logic ProcessDefinitionQueryImpl query = new ProcessDefinitionQueryImpl(); query.processDefinitionKey(processDefinitionToBeRemoved.getKey()); if (processDefinitionToBeRemoved.getTenantId() != null && !ProcessEngineConfiguration.NO_TENANT_ID.equals(processDefinitionToBeRemoved.getTenantId())) { query.processDefinitionTenantId(processDefinitionToBeRemoved.getTenantId()); } else { query.processDefinitionWithoutTenantId(); } if (processDefinitionToBeRemoved.getVersion() > 0) {
query.processDefinitionVersionLowerThan(processDefinitionToBeRemoved.getVersion()); } query.orderByProcessDefinitionVersion().desc(); query.setFirstResult(0); query.setMaxResults(1); List<ProcessDefinition> processDefinitions = getProcessDefinitionEntityManager().findProcessDefinitionsByQueryCriteria(query); if (processDefinitions != null && processDefinitions.size() > 0) { return processDefinitions.get(0); } return null; } protected ProcessDefinitionEntityManager getProcessDefinitionEntityManager() { return engineConfiguration.getProcessDefinitionEntityManager(); } protected FlowableEventDispatcher getEventDispatcher() { return engineConfiguration.getEventDispatcher(); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\repository\DeploymentProcessDefinitionDeletionManagerImpl.java
2
请完成以下Java代码
protected Class<? extends BaseElement> getHandledType() { return SubProcess.class; } @Override protected void executeParse(BpmnParse bpmnParse, SubProcess subProcess) { ActivityImpl activity = createActivityOnScope(bpmnParse, subProcess, BpmnXMLConstants.ELEMENT_SUBPROCESS, bpmnParse.getCurrentScope()); activity.setAsync(subProcess.isAsynchronous()); activity.setExclusive(!subProcess.isNotExclusive()); boolean triggeredByEvent = false; if (subProcess instanceof EventSubProcess) { triggeredByEvent = true; } activity.setProperty("triggeredByEvent", triggeredByEvent); // event subprocesses are not scopes activity.setScope(!triggeredByEvent); activity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createSubprocActivityBehavior(subProcess)); bpmnParse.setCurrentScope(activity); bpmnParse.setCurrentSubProcess(subProcess);
bpmnParse.processFlowElements(subProcess.getFlowElements()); processArtifacts(bpmnParse, subProcess.getArtifacts(), activity); // no data objects for event subprocesses if (!(subProcess instanceof EventSubProcess)) { // parse out any data objects from the template in order to set up the necessary process variables Map<String, Object> variables = processDataObjects(bpmnParse, subProcess.getDataObjects(), activity); activity.setVariables(variables); } bpmnParse.removeCurrentScope(); bpmnParse.removeCurrentSubProcess(); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\SubProcessParseHandler.java
1
请完成以下Java代码
public static String getEmailAddressStringOrNull(@Nullable final ContactAddress contactAddress) { return cast(contactAddress).map(EmailAddress::getValue).orElse(null); } public static DeactivatedOnRemotePlatform getDeactivatedOnRemotePlatform(@Nullable final ContactAddress contactAddress) { final EmailAddress emailAddress = cast(contactAddress).orElse(null); return emailAddress != null ? emailAddress.getDeactivatedOnRemotePlatform() : DeactivatedOnRemotePlatform.UNKNOWN; } public static EmailAddress ofString(@NonNull final String emailAddress) { return new EmailAddress(emailAddress, DeactivatedOnRemotePlatform.UNKNOWN); } public static EmailAddress ofStringOrNull(@Nullable final String emailAddress) { return emailAddress != null && !Check.isBlank(emailAddress) ? ofString(emailAddress) : null; } public static EmailAddress of( @NonNull final String emailAddress, @NonNull final DeactivatedOnRemotePlatform deactivatedOnRemotePlatform) { return new EmailAddress(emailAddress, deactivatedOnRemotePlatform); } private EmailAddress( @NonNull final String value,
@NonNull final DeactivatedOnRemotePlatform deactivatedOnRemotePlatform) { final String valueNorm = StringUtils.trimBlankToNull(value); if (valueNorm == null) { throw new AdempiereException("blank email address is not allowed"); } this.value = valueNorm; this.deactivatedOnRemotePlatform = deactivatedOnRemotePlatform; } @Override public TYPE getType() { return TYPE.EMAIL; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\model\EmailAddress.java
1
请在Spring Boot框架中完成以下Java代码
private I_AD_WF_Node createWorkflowNode(@NonNull final I_AD_Workflow workflow, @NonNull final String name, final String action, final String docAction) { final I_AD_WF_Node workflowNode = InterfaceWrapperHelper.newInstance(I_AD_WF_Node.class); // Specific details workflowNode.setAD_Workflow_ID(workflow.getAD_Workflow_ID()); workflowNode.setName(name); workflowNode.setValue(name); workflowNode.setAction(action); workflowNode.setDocAction(docAction); // General details workflowNode.setDescription("(Standard Node)"); workflowNode.setEntityType(workflow.getEntityType()); workflowNode.setSplitElement(X_AD_WF_Node.JOINELEMENT_XOR); workflowNode.setJoinElement(X_AD_WF_Node.JOINELEMENT_XOR); InterfaceWrapperHelper.save(workflowNode); return workflowNode;
} private I_AD_WF_NodeNext linkNextNode(@NonNull final I_AD_WF_Node workflowSourceNode, @NonNull final I_AD_WF_Node workflowTargetNode, int seqNo) { final I_AD_WF_NodeNext workflowNodeNext = InterfaceWrapperHelper.newInstance(I_AD_WF_NodeNext.class); // Specific Details workflowNodeNext.setAD_WF_Node_ID(workflowSourceNode.getAD_WF_Node_ID()); workflowNodeNext.setAD_WF_Next_ID(workflowTargetNode.getAD_WF_Node_ID()); workflowNodeNext.setSeqNo(seqNo); workflowNodeNext.setEntityType(workflowSourceNode.getEntityType()); workflowNodeNext.setDescription("Standard Transition"); InterfaceWrapperHelper.save(workflowNodeNext); return workflowNodeNext; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\service\impl\ADWorkflowBL.java
2
请完成以下Java代码
private Iterator<I_C_Payment> retrievePayments() { final Stopwatch stopwatch = Stopwatch.createStarted(); // // Create the selection which we might need to update final IQueryBuilder<I_C_Payment> queryBuilder = queryBL .createQueryBuilder(I_C_Payment.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Payment.COLUMNNAME_AD_Client_ID, getClientId()) .addEqualsFilter(I_C_Payment.COLUMNNAME_IsAllocated, false); if (!getProcessInfo().isInvokedByScheduler()) { // user selection..if any final IQueryFilter<I_C_Payment> userSelectionFilter = getProcessInfo().getQueryFilterOrElseFalse(); queryBuilder.filter(userSelectionFilter); } if (p_SOTrx != null) { queryBuilder.addEqualsFilter(I_C_Payment.COLUMNNAME_IsReceipt, p_SOTrx.toBoolean()); } if (p_PaymentDateFrom != null) { queryBuilder.addCompareFilter(I_C_Payment.COLUMNNAME_DateTrx, Operator.GREATER_OR_EQUAL, p_PaymentDateFrom); } if (p_PaymentDateTo != null) {
queryBuilder.addCompareFilter(I_C_Payment.COLUMNNAME_DateTrx, Operator.LESS_OR_EQUAL, p_PaymentDateTo); } final IQuery<I_C_Payment> query = queryBuilder .orderBy(I_C_Payment.COLUMNNAME_C_Payment_ID) .create(); addLog("Using query: " + query); final int count = query.count(); if (count > 0) { final Iterator<I_C_Payment> iterator = query.iterate(I_C_Payment.class); addLog("Found " + count + " payments to evaluate. Took " + stopwatch); return iterator; } else { addLog("No payments found. Took " + stopwatch); return Collections.emptyIterator(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\payment\process\C_Payment_MassWriteOff.java
1
请完成以下Java代码
private static BPartnerId normalizeValueKey(@Nullable final Object valueKey) { if (valueKey == null) { return null; } else if (valueKey instanceof Number) { final int valueInt = ((Number)valueKey).intValue(); return BPartnerId.ofRepoIdOrNull(valueInt); } else { final int valueInt = NumberUtils.asInt(valueKey.toString(), -1); return BPartnerId.ofRepoIdOrNull(valueInt); } } @Override @Nullable public KeyNamePair getAttributeValueOrNull(final Evaluatee evalCtx_NOTUSED, final Object valueKey) { final BPartnerId bpartnerId = normalizeValueKey(valueKey); if (bpartnerId == null) { return null; } return getCachedVendors() .stream() .filter(vnp -> vnp.getKey() == bpartnerId.getRepoId()) .findFirst() .orElseGet(() -> retrieveBPartnerKNPById(bpartnerId)); } @Nullable private KeyNamePair retrieveBPartnerKNPById(@NonNull final BPartnerId bpartnerId) { final I_C_BPartner bpartner = bpartnerDAO.getByIdOutOfTrx(bpartnerId); return bpartner != null ? toKeyNamePair(bpartner) : null; } @Nullable @Override public AttributeValueId getAttributeValueIdOrNull(final Object valueKey) { return null; } private List<KeyNamePair> getCachedVendors() { final ImmutableList<KeyNamePair> vendors = vendorsCache.getOrLoad(0, this::retrieveVendorKeyNamePairs);
return ImmutableList.<KeyNamePair>builder() .add(staticNullValue()) .addAll(vendors) .build(); } private QueryLimit getMaxVendors() { final int maxVendorsInt = sysconfigBL.getIntValue(SYSCONFIG_MAX_VENDORS, DEFAULT_MAX_VENDORS); return QueryLimit.ofInt(maxVendorsInt); } private ImmutableList<KeyNamePair> retrieveVendorKeyNamePairs() { return bpartnerDAO.retrieveVendors(getMaxVendors()) .stream() .map(HUVendorBPartnerAttributeValuesProvider::toKeyNamePair) .sorted(Comparator.comparing(KeyNamePair::getName)) .collect(ImmutableList.toImmutableList()); } private static KeyNamePair toKeyNamePair(@NonNull final I_C_BPartner bpartner) { return KeyNamePair.of(bpartner.getC_BPartner_ID(), bpartner.getName(), bpartner.getDescription()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\HUVendorBPartnerAttributeValuesProvider.java
1
请完成以下Java代码
private Optional<IExternalSystemChildConfig> getScriptedImportConversionConfigByParentId(@NonNull final ExternalSystemParentConfigId id) { return queryBL.createQueryBuilder(I_ExternalSystem_Config_ScriptedImportConversion.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_ExternalSystem_Config_ScriptedImportConversion.COLUMNNAME_ExternalSystem_Config_ID, id.getRepoId()) .create() .firstOnlyOptional(I_ExternalSystem_Config_ScriptedImportConversion.class) .map(this::buildExternalSystemScriptedImportConversionConfig); } @NonNull private Optional<I_ExternalSystem_Config_ProCareManagement> getPCMConfigByValue(@NonNull final String value) { return queryBL.createQueryBuilder(I_ExternalSystem_Config_ProCareManagement.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_ExternalSystem_Config_ProCareManagement.COLUMNNAME_ExternalSystemValue, value) .create() .firstOnlyOptional(I_ExternalSystem_Config_ProCareManagement.class); } @NonNull private Optional<I_ExternalSystem_Config_ScriptedImportConversion> getScriptedImportConversionConfigByValue(@NonNull final String value) { return queryBL.createQueryBuilder(I_ExternalSystem_Config_ScriptedImportConversion.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_ExternalSystem_Config_ScriptedImportConversion.COLUMNNAME_ExternalSystemValue, value) .create() .firstOnlyOptional(I_ExternalSystem_Config_ScriptedImportConversion.class); } @NonNull private ImmutableList<ExternalSystemParentConfig> getAllByTypePCM() { return queryBL.createQueryBuilder(I_ExternalSystem_Config_ProCareManagement.class)
.addOnlyActiveRecordsFilter() .create() .stream() .map(this::getExternalSystemParentConfig) .collect(ImmutableList.toImmutableList()); } @NonNull private ImmutableList<ExternalSystemParentConfig> getAllByScriptedImportConversion() { return queryBL.createQueryBuilder(I_ExternalSystem_Config_ScriptedImportConversion.class) .addOnlyActiveRecordsFilter() .create() .stream() .map(this::getExternalSystemParentConfig) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\ExternalSystemConfigRepo.java
1
请完成以下Java代码
private ImmutableMap<AcctSchemaId, BPartnerVendorAccounts> retrieveVendorAccounts(final BPartnerId bpartnerId) { return queryBL.createQueryBuilder(I_C_BP_Vendor_Acct.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_BP_Vendor_Acct.COLUMNNAME_C_BPartner_ID, bpartnerId) .create() .stream() .map(BPartnerAccountsRepository::fromRecord) .collect(ImmutableMap.toImmutableMap(BPartnerVendorAccounts::getAcctSchemaId, accts -> accts)); } private static BPartnerVendorAccounts fromRecord(@NonNull final I_C_BP_Vendor_Acct record) { return BPartnerVendorAccounts.builder() .acctSchemaId(AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID())) .V_Liability_Acct(Account.of(AccountId.ofRepoId(record.getV_Liability_Acct()), BPartnerVendorAccountType.V_Liability)) .V_Liability_Services_Acct(Account.of(AccountId.ofRepoId(record.getV_Liability_Services_Acct()), BPartnerVendorAccountType.V_Liability_Services)) .V_Prepayment_Acct(Account.of(AccountId.ofRepoId(record.getV_Prepayment_Acct()), BPartnerVendorAccountType.V_Prepayment)) .build(); } public BPartnerCustomerAccounts getCustomerAccounts( @NonNull final BPartnerId bpartnerId, @NonNull final AcctSchemaId acctSchemaId) { final ImmutableMap<AcctSchemaId, BPartnerCustomerAccounts> map = customerAccountsCache.getOrLoad(bpartnerId, this::retrieveCustomerAccounts); final BPartnerCustomerAccounts accounts = map.get(acctSchemaId); if (accounts == null) { throw new AdempiereException("No customer accounts defined for " + bpartnerId + " and " + acctSchemaId); } return accounts; } private ImmutableMap<AcctSchemaId, BPartnerCustomerAccounts> retrieveCustomerAccounts(final BPartnerId bpartnerId) { return queryBL.createQueryBuilder(I_C_BP_Customer_Acct.class) .addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_BP_Customer_Acct.COLUMNNAME_C_BPartner_ID, bpartnerId) .create() .stream() .map(BPartnerAccountsRepository::fromRecord) .collect(ImmutableMap.toImmutableMap(BPartnerCustomerAccounts::getAcctSchemaId, accts -> accts)); } @NonNull private static BPartnerCustomerAccounts fromRecord(@NonNull final I_C_BP_Customer_Acct record) { return BPartnerCustomerAccounts.builder() .acctSchemaId(AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID())) .C_Receivable_Acct(Account.of(AccountId.ofRepoId(record.getC_Receivable_Acct()), BPartnerCustomerAccountType.C_Receivable)) .C_Receivable_Services_Acct(Account.of(AccountId.ofRepoId(record.getC_Receivable_Services_Acct()), BPartnerCustomerAccountType.C_Receivable_Services)) .C_Prepayment_Acct(Account.of(AccountId.ofRepoId(record.getC_Prepayment_Acct()), BPartnerCustomerAccountType.C_Prepayment)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\accounts\BPartnerAccountsRepository.java
1
请完成以下Java代码
public JsonResponseBPartner getJsonBPartnerById(@Nullable final String orgCode, @NonNull final BPartnerId bpartnerId) { final ResponseEntity<JsonResponseComposite> bpartner = bpartnerRestController.retrieveBPartner( orgCode, Integer.toString(bpartnerId.getRepoId())); return Optional.ofNullable(bpartner.getBody()) .map(JsonResponseComposite::getBpartner) .orElseThrow(() -> new AdempiereException("No BPartner found for the given bPartnerIdentifier!") .appendParametersToMessage() .setParameter("BPartnerIdentifier", bpartnerId)); } @NonNull public JsonResponseLocation getJsonBPartnerLocationById(@Nullable final String orgCode, @NonNull final BPartnerLocationId bpartnerLocationId) { final ResponseEntity<JsonResponseLocation> location = bpartnerRestController.retrieveBPartnerLocation( orgCode, Integer.toString(bpartnerLocationId.getBpartnerId().getRepoId()), Integer.toString(bpartnerLocationId.getRepoId())); return Optional.ofNullable(location.getBody()) .orElseThrow(() -> new AdempiereException("No BPartnerLocation found for the given bPartnerIdentifier,BPartnerLocationIdentifier!") .appendParametersToMessage() .setParameter("BPartnerIdentifier", bpartnerLocationId.getBpartnerId().getRepoId()) .setParameter("BPartnerLocationIdentifier", bpartnerLocationId.getRepoId())); } @NonNull public JsonResponseContact getJsonBPartnerContactById(@Nullable final String orgCode, @NonNull final BPartnerContactId bpartnerContactId)
{ final ResponseEntity<JsonResponseContact> contact = bpartnerRestController.retrieveBPartnerContact( orgCode, Integer.toString(bpartnerContactId.getBpartnerId().getRepoId()), Integer.toString(bpartnerContactId.getRepoId())); return Optional.ofNullable(contact.getBody()) .orElseThrow(() -> new AdempiereException("No BPartnerContact found for the given bPartnerIdentifier,BPartnerContactId!") .appendParametersToMessage() .setParameter("BPartnerIdentifier", bpartnerContactId.getBpartnerId().getRepoId()) .setParameter("bpartnerContactIdentifier", bpartnerContactId.getRepoId())); } @NonNull public JsonResponseBPartner getJsonBPartnerByExternalIdentifier(@Nullable final String orgCode, @NonNull final String externalIdentifier) { final ResponseEntity<JsonResponseComposite> bpartner = bpartnerRestController.retrieveBPartner(orgCode, externalIdentifier); return Optional.ofNullable(bpartner.getBody()) .map(JsonResponseComposite::getBpartner) .orElseThrow(() -> new AdempiereException("No BPartner found for the given external identifier!") .appendParametersToMessage() .setParameter("BPartnerIdentifier", externalIdentifier)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\ordercandidates\impl\BPartnerEndpointAdapter.java
1
请完成以下Java代码
private void destroyEventBus(@NonNull final EventBus eventBus) { eventBus.destroy(); } @Override public void registerGlobalEventListener( @NonNull final Topic topic, @NonNull final IEventListener listener) { // Register the listener to EventBus getEventBus(topic).subscribe(listener); // Add the listener to our global listeners-multimap. // Note that getEventBus(topic) creates the bus on the fly if needed **and subscribes all global listeners to it** // Therefore we need to add this listener to the global map *after* having gotten and possibly on-the-fly-created the event bus. if (!globalEventListeners.put(topic, listener)) { // listener already exists => do nothing return; } logger.info("Registered global listener to {}: {}", topic, listener); } @Override public void addAvailableUserNotificationsTopic(@NonNull final Topic topic) { final boolean added = availableUserNotificationsTopic.add(topic); logger.info("Registered user notifications topic: {} (already registered: {})", topic, !added); }
/** * @return set of available topics on which user can subscribe for UI notifications */ private Set<Topic> getAvailableUserNotificationsTopics() { return ImmutableSet.copyOf(availableUserNotificationsTopic); } @Override public void registerUserNotificationsListener(@NonNull final IEventListener listener) { getAvailableUserNotificationsTopics() .stream() .map(this::getEventBus) .forEach(eventBus -> eventBus.subscribe(listener)); } @Override public void unregisterUserNotificationsListener(@NonNull final IEventListener listener) { getAvailableUserNotificationsTopics() .stream() .map(this::getEventBus) .forEach(eventBus -> eventBus.unsubscribe(listener)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\impl\EventBusFactory.java
1
请在Spring Boot框架中完成以下Java代码
DecodingConfigurer inflate(boolean inflate) { this.inflate = inflate; return this; } DecodingConfigurer requireBase64(boolean requireBase64) { this.requireBase64 = requireBase64; return this; } String decode() { if (this.requireBase64) { BASE_64_CHECKER.checkAcceptable(this.encoded); } byte[] bytes = Saml2Utils.samlDecode(this.encoded); return (this.inflate) ? Saml2Utils.samlInflate(bytes) : new String(bytes, StandardCharsets.UTF_8); } static class Base64Checker { private static final int[] values = genValueMapping(); Base64Checker() { } private static int[] genValueMapping() { byte[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" .getBytes(StandardCharsets.ISO_8859_1); int[] values = new int[256]; Arrays.fill(values, -1); for (int i = 0; i < alphabet.length; i++) { values[alphabet[i] & 0xff] = i; } return values; } boolean isAcceptable(String s) { int goodChars = 0;
int lastGoodCharVal = -1; // count number of characters from Base64 alphabet for (int i = 0; i < s.length(); i++) { int val = values[0xff & s.charAt(i)]; if (val != -1) { lastGoodCharVal = val; goodChars++; } } // in cases of an incomplete final chunk, ensure the unused bits are zero switch (goodChars % 4) { case 0: return true; case 2: return (lastGoodCharVal & 0b1111) == 0; case 3: return (lastGoodCharVal & 0b11) == 0; default: return false; } } void checkAcceptable(String ins) { if (!isAcceptable(ins)) { throw new IllegalArgumentException("Failed to decode SAMLResponse"); } } } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\internal\Saml2Utils.java
2
请完成以下Java代码
@Override protected String doIt() throws Exception { final OrderId orderId = OrderId.ofRepoId(getRecord_ID()); final I_C_Order order = orderDAO.getById(orderId, de.metas.vertical.creditscore.creditpass.model.extended.I_C_Order.class); final BPartnerId bPartnerId = BPartnerId.ofRepoId(order.getC_BPartner_ID()); final String paymentRule = order.getPaymentRule(); final List<TransactionResult> transactionResults = creditPassTransactionService.getAndSaveCreditScore(paymentRule, orderId, bPartnerId); final TransactionResult transactionResult = transactionResults.stream().findFirst().get(); if (transactionResult.getResultCodeEffective() == ResultCode.P) { order.setCreditpassFlag(false); final ITranslatableString message = Services.get(IMsgBL.class).getTranslatableMsgText(CreditPassConstants.CREDITPASS_STATUS_SUCCESS_MESSAGE_KEY); order.setCreditpassStatus(message.translate(Env.getAD_Language())); } else { order.setCreditpassFlag(true); final String paymentRuleName = ADReferenceService.get().retrieveListNameTrl(X_C_Order.PAYMENTRULE_AD_Reference_ID, paymentRule); final ITranslatableString message = Services.get(IMsgBL.class).getTranslatableMsgText(CreditPassConstants.CREDITPASS_STATUS_FAILURE_MESSAGE_KEY, paymentRuleName); order.setCreditpassStatus(message.translate(Env.getAD_Language())); } save(order); final List<Integer> tableRecordReferences = transactionResults.stream() .map(tr -> tr.getTransactionResultId().getRepoId()) .collect(Collectors.toList()); getResult().setRecordsToOpen(I_CS_Transaction_Result.Table_Name, tableRecordReferences, null); return MSG_OK; } @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) {
if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } final OrderId orderId = OrderId.ofRepoId(context.getSingleSelectedRecordId()); final I_C_Order order = orderDAO.getById(orderId, de.metas.vertical.creditscore.creditpass.model.extended.I_C_Order.class); if (order.getC_BPartner_ID() < 0) { return ProcessPreconditionsResolution.rejectWithInternalReason("The order has no business partner"); } if (!order.getCreditpassFlag()) { return ProcessPreconditionsResolution.rejectWithInternalReason("Creditpass request not needed"); } return ProcessPreconditionsResolution.accept(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java\de\metas\vertical\creditscore\creditpass\process\CS_Creditpass_TransactionFrom_C_Order.java
1
请完成以下Java代码
class TaskEvenOdd implements Runnable { private final int max; private final Printer print; private final boolean isEvenNumber; TaskEvenOdd(Printer print, int max, boolean isEvenNumber) { this.print = print; this.max = max; this.isEvenNumber = isEvenNumber; } @Override public void run() { int number = isEvenNumber ? 2 : 1; while (number <= max) { if (isEvenNumber) { print.printEven(number); } else { print.printOdd(number); } number += 2; } } } class Printer { private volatile boolean isOdd; synchronized void printEven(int number) { while (!isOdd) { try { wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } System.out.println(Thread.currentThread().getName() + ":" + number);
isOdd = false; notify(); } synchronized void printOdd(int number) { while (isOdd) { try { wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } System.out.println(Thread.currentThread().getName() + ":" + number); isOdd = true; notify(); } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-2\src\main\java\com\baeldung\concurrent\evenandodd\PrintEvenOddWaitNotify.java
1
请完成以下Java代码
public CustomExceptionObject handleException3Json(CustomException3 ex) { return new CustomExceptionObject() .setMessage("custom exception 3: " + ex.getMessage()); } @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler( produces = MediaType.TEXT_PLAIN_VALUE ) public String handleException3Text(CustomException3 ex) { return "custom exception 3: " + ex.getMessage(); } @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler({ CustomException4.class, CustomException5.class })
public ResponseEntity<CustomExceptionObject> handleException45(Exception ex) { return ResponseEntity .badRequest() .body( new CustomExceptionObject() .setMessage( "custom exception 4/5: " + ex.getMessage()) ); } @ResponseStatus(value = HttpStatus.FORBIDDEN) @ExceptionHandler( AccessDeniedException.class ) public void handleAccessDeniedException() { // ... } }
repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\web\error\MyGlobalExceptionHandler.java
1
请在Spring Boot框架中完成以下Java代码
private VcapPropertySource toVcapPropertySource(Environment environment) { return VcapPropertySource.from(environment); } } static class EnableSecurityCondition extends AllNestedConditions { EnableSecurityCondition() { super(ConfigurationPhase.PARSE_CONFIGURATION); } @ConditionalOnProperty(name = CLOUD_SECURITY_ENVIRONMENT_POST_PROCESSOR_ENABLED_PROPERTY, havingValue = "true", matchIfMissing = true) static class SpringBootDataGemFireSecurityAuthEnvironmentPostProcessorEnabled { } @Conditional(SecurityTriggersCondition.class) static class AnySecurityTriggerCondition { } } static class SecurityTriggersCondition extends AnyNestedCondition { SecurityTriggersCondition() { super(ConfigurationPhase.PARSE_CONFIGURATION); } @ConditionalOnCloudPlatform(CloudPlatform.CLOUD_FOUNDRY) static class CloudPlatformSecurityContextCondition { } @ConditionalOnProperty({ "spring.data.gemfire.security.username", "spring.data.gemfire.security.password", }) static class SpringDataGeodeSecurityContextCondition { } @ConditionalOnProperty({ "gemfire.security-username", "gemfire.security-password", }) static class UsingApacheGeodeSecurityContextCondition { } } // This custom PropertySource is required to prevent Pivotal Spring Cloud Services // (spring-cloud-services-starter-service-registry) from losing the Apache Geode or Cloud Cache Security Context
// credentials stored in the Environment. static class SpringDataGemFirePropertiesPropertySource extends PropertySource<Properties> { private static final String SPRING_DATA_GEMFIRE_PROPERTIES_PROPERTY_SOURCE_NAME = "spring.data.gemfire.properties"; SpringDataGemFirePropertiesPropertySource(Properties springDataGemFireProperties) { this(SPRING_DATA_GEMFIRE_PROPERTIES_PROPERTY_SOURCE_NAME, springDataGemFireProperties); } SpringDataGemFirePropertiesPropertySource(String name, Properties springDataGemFireProperties) { super(name, springDataGemFireProperties); } @Nullable @Override public Object getProperty(String name) { return getSource().getProperty(name); } @Override public boolean containsProperty(String name) { return getSource().containsKey(name); } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\ClientSecurityAutoConfiguration.java
2
请完成以下Java代码
public final String getJMXName() { return jmxName; } @Override public void setDebugTrxCloseStacktrace(boolean debugTrxCloseStacktrace) { getTrxManager().setDebugTrxCloseStacktrace(debugTrxCloseStacktrace); } @Override public boolean isDebugTrxCloseStacktrace() { return getTrxManager().isDebugTrxCloseStacktrace(); } @Override public void setDebugTrxCreateStacktrace(boolean debugTrxCreateStacktrace) { getTrxManager().setDebugTrxCreateStacktrace(debugTrxCreateStacktrace); } @Override public boolean isDebugTrxCreateStacktrace() { return getTrxManager().isDebugTrxCreateStacktrace(); } @Override public void setDebugClosedTransactions(boolean enabled) { getTrxManager().setDebugClosedTransactions(enabled); } @Override public boolean isDebugClosedTransactions() { return getTrxManager().isDebugClosedTransactions(); } @Override public String[] getActiveTransactionInfos() { final List<ITrx> trxs = getTrxManager().getActiveTransactionsList(); return toStringArray(trxs); } @Override public String[] getDebugClosedTransactionInfos() { final List<ITrx> trxs = getTrxManager().getDebugClosedTransactions(); return toStringArray(trxs); } private final String[] toStringArray(final List<ITrx> trxs) { if (trxs == null || trxs.isEmpty()) { return new String[] {}; } final String[] arr = new String[trxs.size()]; for (int i = 0; i < trxs.size(); i++) { final ITrx trx = trxs.get(0); if (trx == null) { arr[i] = "null"; } else { arr[i] = trx.toString(); } } return arr; }
@Override public void rollbackAndCloseActiveTrx(final String trxName) { final ITrxManager trxManager = getTrxManager(); if (trxManager.isNull(trxName)) { throw new IllegalArgumentException("Only not null transactions are allowed: " + trxName); } final ITrx trx = trxManager.getTrx(trxName); if (trxManager.isNull(trx)) { // shall not happen because getTrx is already throwning an exception throw new IllegalArgumentException("No transaction was found for: " + trxName); } boolean rollbackOk = false; try { rollbackOk = trx.rollback(true); } catch (SQLException e) { throw new RuntimeException("Could not rollback '" + trx + "' because: " + e.getLocalizedMessage(), e); } if (!rollbackOk) { throw new RuntimeException("Could not rollback '" + trx + "' for unknown reason"); } } @Override public void setDebugConnectionBackendId(boolean debugConnectionBackendId) { getTrxManager().setDebugConnectionBackendId(debugConnectionBackendId); } @Override public boolean isDebugConnectionBackendId() { return getTrxManager().isDebugConnectionBackendId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\jmx\JMXTrxManager.java
1
请完成以下Java代码
public final C_AllocationLine_Builder writeOffAmt(final BigDecimal writeOffAmt) { allocLine.setWriteOffAmt(writeOffAmt); return this; } public final C_AllocationLine_Builder overUnderAmt(final BigDecimal overUnderAmt) { allocLine.setOverUnderAmt(overUnderAmt); return this; } public C_AllocationLine_Builder paymentWriteOffAmt(final BigDecimal paymentWriteOffAmt) { allocLine.setPaymentWriteOffAmt(paymentWriteOffAmt); return this; } public final C_AllocationLine_Builder skipIfAllAmountsAreZero() { this.skipIfAllAmountsAreZero = true; return this; } private boolean isSkipBecauseAllAmountsAreZero() { if (!skipIfAllAmountsAreZero) { return false; } // NOTE: don't check the OverUnderAmt because that amount is not affecting allocation, // so an allocation is Zero with our without the over/under amount. return allocLine.getAmount().signum() == 0 && allocLine.getDiscountAmt().signum() == 0 && allocLine.getWriteOffAmt().signum() == 0 // && allocLine.getPaymentWriteOffAmt().signum() == 0; }
public final C_AllocationHdr_Builder lineDone() { return parent; } /** * @param allocHdrSupplier allocation header supplier which will provide the allocation header created & saved, just in time, so call it ONLY if you are really gonna create an allocation line. * @return created {@link I_C_AllocationLine} or <code>null</code> if it was not needed. */ @Nullable final I_C_AllocationLine create(@NonNull final Supplier<I_C_AllocationHdr> allocHdrSupplier) { if (isSkipBecauseAllAmountsAreZero()) { return null; } // // Get the allocation header, created & saved. final I_C_AllocationHdr allocHdr = allocHdrSupplier.get(); Check.assumeNotNull(allocHdr, "Param 'allocHdr' not null"); Check.assume(allocHdr.getC_AllocationHdr_ID() > 0, "Param 'allocHdr' has C_AllocationHdr_ID>0"); allocLine.setC_AllocationHdr(allocHdr); allocLine.setAD_Org_ID(allocHdr.getAD_Org_ID()); allocationDAO.save(allocLine); return allocLine; } public final C_AllocationHdr_Builder getParent() { return parent; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\allocation\api\C_AllocationLine_Builder.java
1
请完成以下Java代码
public void setDirection (final java.lang.String Direction) { set_ValueNoCheck (COLUMNNAME_Direction, Direction); } @Override public java.lang.String getDirection() { return get_ValueAsString(COLUMNNAME_Direction); } @Override public void setEvent_UUID (final @Nullable java.lang.String Event_UUID) { set_ValueNoCheck (COLUMNNAME_Event_UUID, Event_UUID); } @Override public java.lang.String getEvent_UUID() { return get_ValueAsString(COLUMNNAME_Event_UUID); } @Override public void setHost (final @Nullable java.lang.String Host) { set_ValueNoCheck (COLUMNNAME_Host, Host); } @Override public java.lang.String getHost() { return get_ValueAsString(COLUMNNAME_Host); } @Override public void setRabbitMQ_Message_Audit_ID (final int RabbitMQ_Message_Audit_ID) { if (RabbitMQ_Message_Audit_ID < 1) set_ValueNoCheck (COLUMNNAME_RabbitMQ_Message_Audit_ID, null); else set_ValueNoCheck (COLUMNNAME_RabbitMQ_Message_Audit_ID, RabbitMQ_Message_Audit_ID); } @Override public int getRabbitMQ_Message_Audit_ID() { return get_ValueAsInt(COLUMNNAME_RabbitMQ_Message_Audit_ID); } @Override
public void setRabbitMQ_QueueName (final @Nullable java.lang.String RabbitMQ_QueueName) { set_ValueNoCheck (COLUMNNAME_RabbitMQ_QueueName, RabbitMQ_QueueName); } @Override public java.lang.String getRabbitMQ_QueueName() { return get_ValueAsString(COLUMNNAME_RabbitMQ_QueueName); } @Override public void setRelated_Event_UUID (final @Nullable java.lang.String Related_Event_UUID) { set_ValueNoCheck (COLUMNNAME_Related_Event_UUID, Related_Event_UUID); } @Override public java.lang.String getRelated_Event_UUID() { return get_ValueAsString(COLUMNNAME_Related_Event_UUID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_RabbitMQ_Message_Audit.java
1
请完成以下Java代码
public class UserDashboardWebsocketSender { private static final Logger logger = LogManager.getLogger(UserDashboardWebsocketSender.class); private final WebsocketSender websocketSender; private final WebSocketProducersRegistry websocketProducersRegistry; public UserDashboardWebsocketSender( @NonNull final WebsocketSender websocketSender, @NonNull final WebSocketProducersRegistry websocketProducersRegistry) { this.websocketSender = websocketSender; this.websocketProducersRegistry = websocketProducersRegistry; } public void sendDashboardItemsOrderChangedEvent( @NonNull final UserDashboard dashboard, @NonNull final DashboardWidgetType widgetType) { sendEvents( getWebsocketTopicNamesByDashboardId(dashboard.getId()), JSONDashboardChangedEventsList.of( JSONDashboardOrderChangedEvent.of( dashboard.getId(), widgetType, dashboard.getItemIds(widgetType)))); } public void sendDashboardItemChangedEvent( @NonNull final UserDashboard dashboard, @NonNull final UserDashboardItemChangeResult changeResult) { sendEvents( getWebsocketTopicNamesByDashboardId(dashboard.getId()), toJSONDashboardChangedEventsList(changeResult)); } private static JSONDashboardChangedEventsList toJSONDashboardChangedEventsList(final @NonNull UserDashboardItemChangeResult changeResult) { final JSONDashboardChangedEventsList.JSONDashboardChangedEventsListBuilder eventBuilder = JSONDashboardChangedEventsList.builder() .event(JSONDashboardItemChangedEvent.of( changeResult.getDashboardId(), changeResult.getDashboardWidgetType(), changeResult.getItemId())); if (changeResult.isPositionChanged()) { eventBuilder.event(JSONDashboardOrderChangedEvent.of(
changeResult.getDashboardId(), changeResult.getDashboardWidgetType(), changeResult.getDashboardOrderedItemIds())); } return eventBuilder.build(); } private void sendEvents( @NonNull final Set<WebsocketTopicName> websocketEndpoints, @NonNull final JSONDashboardChangedEventsList events) { if (websocketEndpoints.isEmpty() || events.isEmpty()) { return; } for (final WebsocketTopicName websocketEndpoint : websocketEndpoints) { websocketSender.convertAndSend(websocketEndpoint, events); logger.trace("Notified WS {}: {}", websocketEndpoint, events); } } private ImmutableSet<WebsocketTopicName> getWebsocketTopicNamesByDashboardId(@NonNull final UserDashboardId dashboardId) { return websocketProducersRegistry.streamActiveProducersOfType(UserDashboardWebsocketProducer.class) .filter(producer -> producer.isMatchingDashboardId(dashboardId)) .map(UserDashboardWebsocketProducer::getWebsocketTopicName) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\websocket\UserDashboardWebsocketSender.java
1
请在Spring Boot框架中完成以下Java代码
public class CarController { @Autowired private CarService carService; @GetMapping(path = "/modelcount") public long getTotalCarsByModel(@RequestParam("model") String model) { return carService.getTotalCarsByModel(model); } @GetMapping(path = "/modelcountP") public long getTotalCarsByModelProcedureName(@RequestParam("model") String model) { return carService.getTotalCarsByModelProcedureName(model); } @GetMapping(path = "/modelcountV") public long getTotalCarsByModelVaue(@RequestParam("model") String model) { return carService.getTotalCarsByModelValue(model); }
@GetMapping(path = "/modelcountEx") public long getTotalCarsByModelExplicit(@RequestParam("model") String model) { return carService.getTotalCarsByModelExplicit(model); } @GetMapping(path = "/modelcountEn") public long getTotalCarsByModelEntity(@RequestParam("model") String model) { return carService.getTotalCarsByModelEntity(model); } @GetMapping(path = "/carsafteryear") public List<Car> findCarsAfterYear(@RequestParam("year") Integer year) { return carService.findCarsAfterYear(year); } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo\src\main\java\com\baeldung\spring\data\persistence\storedprocedure\controller\CarController.java
2
请在Spring Boot框架中完成以下Java代码
public String updateUserProfile(@RequestParam("userid") int userid,@RequestParam("username") String username, @RequestParam("email") String email, @RequestParam("password") String password, @RequestParam("address") String address) { try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ecommjava","root",""); PreparedStatement pst = con.prepareStatement("update users set username= ?,email = ?,password= ?, address= ? where uid = ?;"); pst.setString(1, username); pst.setString(2, email); pst.setString(3, password); pst.setString(4, address); pst.setInt(5, userid); int i = pst.executeUpdate();
Authentication newAuthentication = new UsernamePasswordAuthenticationToken( username, password, SecurityContextHolder.getContext().getAuthentication().getAuthorities()); SecurityContextHolder.getContext().setAuthentication(newAuthentication); } catch(Exception e) { System.out.println("Exception:"+e); } return "redirect:index"; } }
repos\E-commerce-project-springBoot-master2\JtProject\src\main\java\com\jtspringproject\JtSpringProject\controller\AdminController.java
2
请完成以下Java代码
public class ReactiveSessionsEndpoint { private final ReactiveSessionRepository<? extends Session> sessionRepository; private final @Nullable ReactiveFindByIndexNameSessionRepository<? extends Session> indexedSessionRepository; /** * Create a new {@link ReactiveSessionsEndpoint} instance. * @param sessionRepository the session repository * @param indexedSessionRepository the indexed session repository */ public ReactiveSessionsEndpoint(ReactiveSessionRepository<? extends Session> sessionRepository, @Nullable ReactiveFindByIndexNameSessionRepository<? extends Session> indexedSessionRepository) { Assert.notNull(sessionRepository, "'sessionRepository' must not be null"); this.sessionRepository = sessionRepository; this.indexedSessionRepository = indexedSessionRepository; } @ReadOperation
public Mono<SessionsDescriptor> sessionsForUsername(String username) { if (this.indexedSessionRepository == null) { return Mono.empty(); } return this.indexedSessionRepository.findByPrincipalName(username).map(SessionsDescriptor::new); } @ReadOperation public Mono<SessionDescriptor> getSession(@Selector String sessionId) { return this.sessionRepository.findById(sessionId).map(SessionDescriptor::new); } @DeleteOperation public Mono<Void> deleteSession(@Selector String sessionId) { return this.sessionRepository.deleteById(sessionId); } }
repos\spring-boot-4.0.1\module\spring-boot-session\src\main\java\org\springframework\boot\session\actuate\endpoint\ReactiveSessionsEndpoint.java
1
请在Spring Boot框架中完成以下Java代码
public CommonResult delete(@PathVariable Long id) { int count = adminService.delete(id); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("修改帐号状态") @RequestMapping(value = "/updateStatus/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult updateStatus(@PathVariable Long id,@RequestParam(value = "status") Integer status) { UmsAdmin umsAdmin = new UmsAdmin(); umsAdmin.setStatus(status); int count = adminService.update(id,umsAdmin); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("给用户分配角色") @RequestMapping(value = "/role/update", method = RequestMethod.POST) @ResponseBody
public CommonResult updateRole(@RequestParam("adminId") Long adminId, @RequestParam("roleIds") List<Long> roleIds) { int count = adminService.updateRole(adminId, roleIds); if (count >= 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("获取指定用户的角色") @RequestMapping(value = "/role/{adminId}", method = RequestMethod.GET) @ResponseBody public CommonResult<List<UmsRole>> getRoleList(@PathVariable Long adminId) { List<UmsRole> roleList = adminService.getRoleList(adminId); return CommonResult.success(roleList); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\UmsAdminController.java
2
请完成以下Java代码
public void keyTyped(KeyEvent e) {} public void keyPressed(KeyEvent e) {} /** * Key Listener. * @param e event */ public void keyReleased(KeyEvent e) { String newText = String.valueOf(getPassword()); m_setting = true; try { fireVetoableChange(m_columnName, m_oldText, newText); } catch (PropertyVetoException pve) {} m_setting = false; } // keyReleased /** * Data Binding to MTable (via GridController) - Enter pressed * @param e event */ public void actionPerformed(ActionEvent e) { String newText = String.valueOf(getPassword()); // Data Binding try { fireVetoableChange(m_columnName, m_oldText, newText); } catch (PropertyVetoException pve) {} } // actionPerformed
/** * Set Field/WindowNo for ValuePreference * @param mField field */ public void setField (GridField mField) { m_mField = mField; } // setField @Override public GridField getField() { return m_mField; } // metas: Ticket#2011062310000013 public boolean isAutoCommit() { return false; } } // VPassword
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VPassword.java
1
请在Spring Boot框架中完成以下Java代码
protected RequestMatcher createLoginProcessingUrlMatcher(String loginProcessingUrl) { return getRequestMatcherBuilder().matcher(HttpMethod.POST, loginProcessingUrl); } /** * Gets the HTTP parameter that is used to submit the username. * @return the HTTP parameter that is used to submit the username */ private String getUsernameParameter() { return getAuthenticationFilter().getUsernameParameter(); } /** * Gets the HTTP parameter that is used to submit the password. * @return the HTTP parameter that is used to submit the password */ private String getPasswordParameter() { return getAuthenticationFilter().getPasswordParameter(); } /** * If available, initializes the {@link DefaultLoginPageGeneratingFilter} shared * object.
* @param http the {@link HttpSecurityBuilder} to use */ private void initDefaultLoginFilter(H http) { DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http .getSharedObject(DefaultLoginPageGeneratingFilter.class); if (loginPageGeneratingFilter != null && !isCustomLoginPage()) { loginPageGeneratingFilter.setFormLoginEnabled(true); loginPageGeneratingFilter.setUsernameParameter(getUsernameParameter()); loginPageGeneratingFilter.setPasswordParameter(getPasswordParameter()); loginPageGeneratingFilter.setLoginPageUrl(getLoginPage()); loginPageGeneratingFilter.setFailureUrl(getFailureUrl()); loginPageGeneratingFilter.setAuthenticationUrl(getLoginProcessingUrl()); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\FormLoginConfigurer.java
2
请完成以下Java代码
public void setAD_User_AuthToken_ID (int AD_User_AuthToken_ID) { if (AD_User_AuthToken_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_User_AuthToken_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_AuthToken_ID, Integer.valueOf(AD_User_AuthToken_ID)); } /** Get User Authentication Token . @return User Authentication Token */ @Override public int getAD_User_AuthToken_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_AuthToken_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_User getAD_User() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class); } @Override public void setAD_User(org.compiere.model.I_AD_User AD_User) { set_ValueFromPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class, AD_User); } /** Set Ansprechpartner. @param AD_User_ID User within the system - Internal or Business Partner Contact */ @Override public void setAD_User_ID (int AD_User_ID) { if (AD_User_ID < 0) set_Value (COLUMNNAME_AD_User_ID, null); else set_Value (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID)); } /** Get Ansprechpartner. @return User within the system - Internal or Business Partner Contact */ @Override public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Authentication Token.
@param AuthToken Authentication Token */ @Override public void setAuthToken (java.lang.String AuthToken) { set_Value (COLUMNNAME_AuthToken, AuthToken); } /** Get Authentication Token. @return Authentication Token */ @Override public java.lang.String getAuthToken () { return (java.lang.String)get_Value(COLUMNNAME_AuthToken); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_AuthToken.java
1
请完成以下Java代码
protected void prepare() { // TODO Auto-generated method stub } public boolean executeScript(String sql, String fileName) { BufferedReader reader = new BufferedReader(new StringReader(sql)); StringBuffer sqlBuf = new StringBuffer(); String line; boolean statementReady = false; boolean execOk = true; boolean longComment = false; try { while ((line = reader.readLine()) != null) { // different continuation for oracle and postgres line = line.trim(); //Check if it's a comment if (line.startsWith("--") || line.length() == 0){ continue; } else if (line.endsWith(";") && !longComment) { sqlBuf.append(' '); sqlBuf.append(line.substring(0, line.length() - 1)); statementReady = true; } else if(line.startsWith("/*")){ longComment = true; } else if(line.endsWith("*/")){ longComment = false; } else { if(longComment) continue; sqlBuf.append(' '); sqlBuf.append(line); statementReady = false; } if (statementReady) { if (sqlBuf.length() == 0) continue; Connection conn = DB.getConnectionRW(); conn.setAutoCommit(false); Statement stmt = null; try { stmt = conn.createStatement(); stmt.execute(sqlBuf.toString());
System.out.print("."); } catch (SQLException e) { e.printStackTrace(); execOk = false; log.error("Script: " + fileName + " - " + e.getMessage() + ". The line that caused the error is the following ==> " + sqlBuf, e); } finally { stmt.close(); if(execOk) conn.commit(); else conn.rollback(); conn.setAutoCommit(true); conn.close(); if(!execOk) return false; } sqlBuf.setLength(0); } } } catch(SQLException e){ e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\process\ApplyMigrationScripts.java
1
请完成以下Java代码
public static ProcessDefinitionSuspensionStateConfiguration byProcessDefinitionId(String processDefinitionId, boolean includeProcessInstances) { ProcessDefinitionSuspensionStateConfiguration configuration = new ProcessDefinitionSuspensionStateConfiguration(); configuration.by = JOB_HANDLER_CFG_PROCESS_DEFINITION_ID; configuration.processDefinitionId = processDefinitionId; configuration.includeProcessInstances = includeProcessInstances; return configuration; } public static ProcessDefinitionSuspensionStateConfiguration byProcessDefinitionKey(String processDefinitionKey, boolean includeProcessInstances) { ProcessDefinitionSuspensionStateConfiguration configuration = new ProcessDefinitionSuspensionStateConfiguration(); configuration.by = JOB_HANDLER_CFG_PROCESS_DEFINITION_KEY; configuration.processDefinitionKey = processDefinitionKey; configuration.includeProcessInstances = includeProcessInstances; return configuration; } public static ProcessDefinitionSuspensionStateConfiguration byProcessDefinitionKeyAndTenantId(String processDefinitionKey, String tenantId, boolean includeProcessInstances) { ProcessDefinitionSuspensionStateConfiguration configuration = byProcessDefinitionKey(processDefinitionKey, includeProcessInstances);
configuration.isTenantIdSet = true; configuration.tenantId = tenantId; return configuration; } } public void onDelete(ProcessDefinitionSuspensionStateConfiguration configuration, JobEntity jobEntity) { // do nothing } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\TimerChangeProcessDefinitionSuspensionStateJobHandler.java
1
请在Spring Boot框架中完成以下Java代码
public class ReactiveStreamingController { private static final Path UPLOAD_DIR = Path.of("reactive-uploads"); @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @ResponseBody public Mono<String> uploadFileStreaming(@RequestPart("filePart") FilePart filePart) { return Mono.fromCallable(() -> { Path targetPath = UPLOAD_DIR.resolve(filePart.filename()); Files.createDirectories(targetPath.getParent()); return targetPath; }).flatMap(targetPath -> filePart.transferTo(targetPath) .thenReturn("Upload successful: " + filePart.filename()) ); } @GetMapping(value = "/download", produces = "multipart/mixed") public ResponseEntity<Flux<DataBuffer>> downloadFiles() { String boundary = "filesBoundary"; List<Path> files = List.of( UPLOAD_DIR.resolve("file1.txt"), UPLOAD_DIR.resolve("file2.txt") ); // Use concatMap to ensure files are streamed one after another, sequentially. Flux<DataBuffer> fileFlux = Flux.fromIterable(files) .concatMap(file -> { String partHeader = "--" + boundary + "\r\n" + "Content-Type: application/octet-stream\r\n" +
"Content-Disposition: attachment; filename=\"" + file.getFileName() + "\"\r\n\r\n"; Flux<DataBuffer> fileContentFlux = DataBufferUtils.read(file, new DefaultDataBufferFactory(), 4096); DataBuffer footerBuffer = new DefaultDataBufferFactory().wrap("\r\n".getBytes()); // Build the flux for this specific part: header + content + footer return Flux.concat( Flux.just(new DefaultDataBufferFactory().wrap(partHeader.getBytes())), fileContentFlux, Flux.just(footerBuffer) ); }) // After all parts, concat the final boundary .concatWith(Flux.just( new DefaultDataBufferFactory().wrap(("--" + boundary + "--\r\n").getBytes()) )); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_TYPE, "multipart/mixed; boundary=" + boundary) .body(fileFlux); } }
repos\tutorials-master\spring-web-modules\spring-rest-http-3\src\main\java\com\baeldung\streaming\ReactiveStreamingController.java
2
请完成以下Java代码
public void setSubstitutionsgrund(Substitutionsgrund value) { this.substitutionsgrund = value; } /** * Gets the value of the grund property. * * @return * possible object is * {@link VerfuegbarkeitDefektgrund } * */ public VerfuegbarkeitDefektgrund getGrund() { return grund; } /** * Sets the value of the grund property. * * @param value * allowed object is * {@link VerfuegbarkeitDefektgrund } * */ public void setGrund(VerfuegbarkeitDefektgrund value) { this.grund = value; }
/** * Gets the value of the lieferPzn property. * */ public long getLieferPzn() { return lieferPzn; } /** * Sets the value of the lieferPzn property. * */ public void setLieferPzn(long value) { this.lieferPzn = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\VerfuegbarkeitSubstitution.java
1
请完成以下Java代码
private boolean isAvailable() { if (isWeak) { return weakValue.get() != null; } else { return true; } } public T get() { if (isWeak) { return weakValue.get(); } else { return value; } } /** * Always compare by identity. * * @return true if it's the same instance. */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } return false; } @Override
public int hashCode() { // NOTE: we implemented this method only to get rid of "implemented equals() but not hashCode() warning" return super.hashCode(); } @Override public String toString() { if (!isAvailable()) { return DEBUG ? "<GARBAGED: " + valueStr + ">" : "<GARBAGED>"; } else { return String.valueOf(this.get()); } } } /** * Gets internal lock used by this weak list. * * NOTE: use it only if you know what are you doing. * * @return internal lock used by this weak list. */ public final ReentrantLock getReentrantLock() { return lock; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\WeakList.java
1
请完成以下Java代码
public OnLineCapability1Code getOnLineCpblties() { return onLineCpblties; } /** * Sets the value of the onLineCpblties property. * * @param value * allowed object is * {@link OnLineCapability1Code } * */ public void setOnLineCpblties(OnLineCapability1Code value) { this.onLineCpblties = value; } /** * Gets the value of the dispCpblties property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the dispCpblties property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDispCpblties().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DisplayCapabilities1 } * * */ public List<DisplayCapabilities1> getDispCpblties() { if (dispCpblties == null) { dispCpblties = new ArrayList<DisplayCapabilities1>();
} return this.dispCpblties; } /** * Gets the value of the prtLineWidth property. * * @return * possible object is * {@link String } * */ public String getPrtLineWidth() { return prtLineWidth; } /** * Sets the value of the prtLineWidth property. * * @param value * allowed object is * {@link String } * */ public void setPrtLineWidth(String value) { this.prtLineWidth = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\PointOfInteractionCapabilities1.java
1
请完成以下Java代码
public String getContactman() { return contactman; } public void setContactman(String contactman) { this.contactman = contactman; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getCantonlev() { return cantonlev; } public void setCantonlev(String cantonlev) { this.cantonlev = cantonlev; } public String getTaxorgcode() { return taxorgcode; } public void setTaxorgcode(String taxorgcode) { this.taxorgcode = taxorgcode; } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo; } public String getUsing() { return using; } public void setUsing(String using) { this.using = using; } public String getUsingdate() { return usingdate; } public void setUsingdate(String usingdate) { this.usingdate = usingdate; }
public Integer getLevel() { return level; } public void setLevel(Integer level) { this.level = level; } public String getEnd() { return end; } public void setEnd(String end) { this.end = end; } public String getQrcantonid() { return qrcantonid; } public void setQrcantonid(String qrcantonid) { this.qrcantonid = qrcantonid; } public String getDeclare() { return declare; } public void setDeclare(String declare) { this.declare = declare; } public String getDeclareisend() { return declareisend; } public void setDeclareisend(String declareisend) { this.declareisend = declareisend; } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\canton\Canton.java
1
请完成以下Java代码
public final GenericSpecificationsBuilder<U> with(final String precedenceIndicator, final String key, final String operation, final Object value, final String prefix, final String suffix) { SearchOperation op = SearchOperation.getSimpleOperation(operation.charAt(0)); if (op != null) { if (op == SearchOperation.EQUALITY) // the operation may be complex operation { final boolean startWithAsterisk = prefix != null && prefix.contains(SearchOperation.ZERO_OR_MORE_REGEX); final boolean endWithAsterisk = suffix != null && suffix.contains(SearchOperation.ZERO_OR_MORE_REGEX); if (startWithAsterisk && endWithAsterisk) { op = SearchOperation.CONTAINS; } else if (startWithAsterisk) { op = SearchOperation.ENDS_WITH; } else if (endWithAsterisk) { op = SearchOperation.STARTS_WITH; } } params.add(new SpecSearchCriteria(precedenceIndicator, key, op, value)); } return this; } public Specification<U> build(Function<SpecSearchCriteria, Specification<U>> converter) { if (params.size() == 0) { return null; } final List<Specification<U>> specs = params.stream() .map(converter) .collect(Collectors.toCollection(ArrayList::new)); Specification<U> result = specs.get(0); for (int idx = 1; idx < specs.size(); idx++) { result = params.get(idx) .isOrPredicate() ? Specification.where(result) .or(specs.get(idx)) : Specification.where(result)
.and(specs.get(idx)); } return result; } public Specification<U> build(Deque<?> postFixedExprStack, Function<SpecSearchCriteria, Specification<U>> converter) { Deque<Specification<U>> specStack = new LinkedList<>(); Collections.reverse((List<?>) postFixedExprStack); while (!postFixedExprStack.isEmpty()) { Object mayBeOperand = postFixedExprStack.pop(); if (!(mayBeOperand instanceof String)) { specStack.push(converter.apply((SpecSearchCriteria) mayBeOperand)); } else { Specification<U> operand1 = specStack.pop(); Specification<U> operand2 = specStack.pop(); if (mayBeOperand.equals(SearchOperation.AND_OPERATOR)) specStack.push(Specification.where(operand1) .and(operand2)); else if (mayBeOperand.equals(SearchOperation.OR_OPERATOR)) specStack.push(Specification.where(operand1) .or(operand2)); } } return specStack.pop(); } }
repos\tutorials-master\spring-web-modules\spring-rest-query-language\src\main\java\com\baeldung\persistence\dao\GenericSpecificationsBuilder.java
1
请完成以下Java代码
public String getCompatibilityRange() { return this.compatibilityRange; } public void setCompatibilityRange(String compatibilityRange) { this.compatibilityRange = compatibilityRange; } /** * Return the default bom to associate to all dependencies of this group unless * specified otherwise. * @return the BOM */ public String getBom() { return this.bom; } public void setBom(String bom) { this.bom = bom; } /** * Return the default repository to associate to all dependencies of this group unless * specified otherwise. * @return the repository */ public String getRepository() { return this.repository; }
public void setRepository(String repository) { this.repository = repository; } /** * Return the {@link Dependency dependencies} of this group. * @return the content */ public List<Dependency> getContent() { return this.content; } /** * Create a new {@link DependencyGroup} instance with the given name. * @param name the name of the group * @return a new {@link DependencyGroup} instance */ public static DependencyGroup create(String name) { DependencyGroup group = new DependencyGroup(); group.setName(name); return group; } }
repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\DependencyGroup.java
1
请完成以下Java代码
public String getRootProcessInstanceId() { return rootProcessInstanceId; } @Override public String getEventName() { return eventName; } @Override public String getProcessInstanceBusinessKey() { return processInstanceBusinessKey; } @Override public String getProcessInstanceBusinessStatus() { return processInstanceBusinessStatus; } @Override public String getProcessDefinitionId() { return processDefinitionId; } @Override public String getPropagatedStageInstanceId() { return propagatedStageInstanceId; } @Override public String getParentId() { return parentId; } @Override public String getSuperExecutionId() { return superExecutionId; } @Override public String getCurrentActivityId() { return currentActivityId; } @Override public String getTenantId() { return tenantId; } @Override public FlowElement getCurrentFlowElement() { return currentFlowElement; } @Override public boolean isActive() {
return active; } @Override public boolean isEnded() { return ended; } @Override public boolean isConcurrent() { return concurrent; } @Override public boolean isProcessInstanceType() { return processInstanceType; } @Override public boolean isScope() { return scope; } @Override public boolean isMultiInstanceRoot() { return multiInstanceRoot; } @Override public Object getVariable(String variableName) { return variables.get(variableName); } @Override public boolean hasVariable(String variableName) { return variables.containsKey(variableName); } @Override public Set<String> getVariableNames() { return variables.keySet(); } @Override public String toString() { return new StringJoiner(", ", getClass().getSimpleName() + "[", "]") .add("id='" + id + "'") .add("currentActivityId='" + currentActivityId + "'") .add("processInstanceId='" + processInstanceId + "'") .add("processDefinitionId='" + processDefinitionId + "'") .add("tenantId='" + tenantId + "'") .toString(); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\delegate\ReadOnlyDelegateExecutionImpl.java
1
请完成以下Java代码
public Long getOrderId() { return orderId; } public void setOrderId(Long orderId) { this.orderId = orderId; } public Long getCustomerId() { return customerId; } public void setCustomerId(Long customerId) { this.customerId = customerId; } public BigDecimal getTotalPrice() { return totalPrice; } public void setTotalPrice(BigDecimal totalPrice) { this.totalPrice = totalPrice; } public Status getOrderStatus() { return orderStatus; } public void setOrderStatus(Status orderStatus) { this.orderStatus = orderStatus; } public LocalDate getOrderDate() { return orderDate; } public void setOrderDate(LocalDate orderDate) { this.orderDate = orderDate; } public String getDeliveryAddress() { return deliveryAddress; } public void setDeliveryAddress(String deliveryAddress) { this.deliveryAddress = deliveryAddress; }
protected Order() {} public Order(Long orderId, Long customerId, BigDecimal totalPrice, Status orderStatus, LocalDate orderDate, String deliveryAddress) { this.orderId = orderId; this.customerId = customerId; this.totalPrice = totalPrice; this.orderStatus = orderStatus; this.orderDate = orderDate; this.deliveryAddress = deliveryAddress; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Order order = (Order) o; return Objects.equals(orderId, order.orderId); } @Override public int hashCode() { return Objects.hash(orderId); } }
repos\springboot-demo-master\sharding-jdbc\src\main\java\com\et\sharding\jdbc\Order.java
1
请完成以下Java代码
public class HistoryLevelActivity extends AbstractHistoryLevel { public int getId() { return 1; } public String getName() { return ProcessEngineConfiguration.HISTORY_ACTIVITY; } public boolean isHistoryEventProduced(HistoryEventType eventType, Object entity) { return PROCESS_INSTANCE_START == eventType || PROCESS_INSTANCE_UPDATE == eventType || PROCESS_INSTANCE_MIGRATE == eventType || PROCESS_INSTANCE_END == eventType || TASK_INSTANCE_CREATE == eventType || TASK_INSTANCE_UPDATE == eventType || TASK_INSTANCE_MIGRATE == eventType || TASK_INSTANCE_COMPLETE == eventType || TASK_INSTANCE_DELETE == eventType
|| ACTIVITY_INSTANCE_START == eventType || ACTIVITY_INSTANCE_UPDATE == eventType || ACTIVITY_INSTANCE_MIGRATE == eventType || ACTIVITY_INSTANCE_END == eventType || CASE_INSTANCE_CREATE == eventType || CASE_INSTANCE_UPDATE == eventType || CASE_INSTANCE_CLOSE == eventType || CASE_ACTIVITY_INSTANCE_CREATE == eventType || CASE_ACTIVITY_INSTANCE_UPDATE == eventType || CASE_ACTIVITY_INSTANCE_END == eventType ; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\HistoryLevelActivity.java
1
请在Spring Boot框架中完成以下Java代码
private static void updateRecord( @NonNull final I_C_Project_Repair_Consumption_Summary record, @NonNull final ServiceRepairProjectConsumptionSummary from) { record.setC_Project_ID(from.getGroupingKey().getProjectId().getRepoId()); record.setM_Product_ID(from.getGroupingKey().getProductId().getRepoId()); record.setC_UOM_ID(from.getGroupingKey().getUomId().getRepoId()); record.setQtyReserved(from.getQtyReserved().toBigDecimal()); record.setQtyConsumed(from.getQtyConsumed().toBigDecimal()); } @Nullable private I_C_Project_Repair_Consumption_Summary retrieveRecordByGroupingKey(@NonNull final ServiceRepairProjectConsumptionSummary.GroupingKey groupingKey) { return queryBL.createQueryBuilder(I_C_Project_Repair_Consumption_Summary.class) .addEqualsFilter(I_C_Project_Repair_Consumption_Summary.COLUMNNAME_C_Project_ID, groupingKey.getProjectId()) .addEqualsFilter(I_C_Project_Repair_Consumption_Summary.COLUMNNAME_M_Product_ID, groupingKey.getProductId()) .addEqualsFilter(I_C_Project_Repair_Consumption_Summary.COLUMNNAME_C_UOM_ID, groupingKey.getUomId()) .create() .firstOnly(I_C_Project_Repair_Consumption_Summary.class); } private List<I_C_Project_Repair_Consumption_Summary> retrieveRecordByProjectId(@NonNull final ProjectId projectId) { return queryBL.createQueryBuilder(I_C_Project_Repair_Consumption_Summary.class) .addEqualsFilter(I_C_Project_Repair_Consumption_Summary.COLUMNNAME_C_Project_ID, projectId) .create() .listImmutable(I_C_Project_Repair_Consumption_Summary.class); } public void saveProject( @NonNull final ProjectId projectId, @NonNull final Collection<ServiceRepairProjectConsumptionSummary> newValues) { if (newValues.stream().anyMatch(newValue -> !ProjectId.equals(newValue.getGroupingKey().getProjectId(), projectId)))
{ throw new AdempiereException("all values shall match " + projectId + ": " + newValues); } final HashMap<ServiceRepairProjectConsumptionSummary.GroupingKey, I_C_Project_Repair_Consumption_Summary> existingRecordsByGroupingKey = new HashMap<>(Maps.uniqueIndex( retrieveRecordByProjectId(projectId), ServiceRepairProjectConsumptionSummaryRepository::extractGroupingKey)); for (final ServiceRepairProjectConsumptionSummary newValue : newValues) { final I_C_Project_Repair_Consumption_Summary existingRecord = existingRecordsByGroupingKey.remove(newValue.getGroupingKey()); final I_C_Project_Repair_Consumption_Summary record = existingRecord != null ? existingRecord : InterfaceWrapperHelper.newInstance(I_C_Project_Repair_Consumption_Summary.class); updateRecord(record, newValue); InterfaceWrapperHelper.saveRecord(record); } InterfaceWrapperHelper.deleteAll(existingRecordsByGroupingKey.values()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\repository\ServiceRepairProjectConsumptionSummaryRepository.java
2
请完成以下Java代码
public UserDashboardItemChangeResult changeUserDashboardItem(final UserDashboard dashboard, final UserDashboardItemChangeRequest request) { final UserDashboardId dashboardId = dashboard.getId(); final DashboardWidgetType dashboardWidgetType = request.getWidgetType(); final UserDashboardItemId itemId = request.getItemId(); dashboard.assertItemIdExists(dashboardWidgetType, itemId); // // Execute the change request //noinspection ConstantConditions return executeChangeActionAndInvalidateAndReturn(dashboardId, () -> { final UserDashboardItemChangeResultBuilder resultBuilder = UserDashboardItemChangeResult.builder() .dashboardId(dashboardId) .dashboardWidgetType(dashboardWidgetType) .itemId(itemId); // // Actually change the item content changeUserDashboardItemAndSave(request); // // Change item's position final int position = request.getPosition(); if (position >= 0) { final List<UserDashboardItemId> allItemIdsOrdered = new ArrayList<>(retrieveDashboardItemIdsOrdered(dashboardId, dashboardWidgetType)); if (position == Integer.MAX_VALUE || position > allItemIdsOrdered.size() - 1) { allItemIdsOrdered.remove((Object)itemId); allItemIdsOrdered.add(itemId); } else { allItemIdsOrdered.remove((Object)itemId); allItemIdsOrdered.add(position, itemId); } updateUserDashboardItemsOrder(dashboardId, allItemIdsOrdered); resultBuilder.dashboardOrderedItemIds(ImmutableList.copyOf(allItemIdsOrdered)); } return resultBuilder.build(); }); } private ImmutableSet<UserDashboardItemId> retrieveDashboardItemIdsOrdered(final UserDashboardId dashboardId, final DashboardWidgetType dashboardWidgetType) { return retrieveWEBUI_DashboardItemsQuery(dashboardId) .addEqualsFilter(I_WEBUI_DashboardItem.COLUMN_WEBUI_DashboardWidgetType, dashboardWidgetType.getCode()) // .orderBy() .addColumn(I_WEBUI_DashboardItem.COLUMN_SeqNo, Direction.Ascending, Nulls.First) .addColumn(I_WEBUI_DashboardItem.COLUMN_WEBUI_DashboardItem_ID) .endOrderBy() // .create() .idsAsSet(UserDashboardItemId::ofRepoId); }
private int retrieveLastSeqNo(final UserDashboardId dashboardId, final DashboardWidgetType dashboardWidgetType) { final Integer maxSeqNo = queryBL.createQueryBuilder(I_WEBUI_DashboardItem.class) .addEqualsFilter(I_WEBUI_DashboardItem.COLUMN_WEBUI_Dashboard_ID, dashboardId) .addEqualsFilter(I_WEBUI_DashboardItem.COLUMN_WEBUI_DashboardWidgetType, dashboardWidgetType.getCode()) .create() .aggregate(I_WEBUI_DashboardItem.COLUMN_SeqNo, Aggregate.MAX, Integer.class); return maxSeqNo != null ? maxSeqNo : 0; } public Collection<KPI> getKPIsAvailableToAdd() { return kpisRepo.getKPIs(); } // // // @Value(staticConstructor = "of") public static class UserDashboardKey { @Nullable ClientId adClientId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\UserDashboardRepository.java
1
请完成以下Java代码
public void setPostActual (final boolean PostActual) { set_Value (COLUMNNAME_PostActual, PostActual); } @Override public boolean isPostActual() { return get_ValueAsBoolean(COLUMNNAME_PostActual); } @Override public void setPostBudget (final boolean PostBudget) { set_Value (COLUMNNAME_PostBudget, PostBudget); } @Override public boolean isPostBudget() { return get_ValueAsBoolean(COLUMNNAME_PostBudget); } @Override public void setPostEncumbrance (final boolean PostEncumbrance) { set_Value (COLUMNNAME_PostEncumbrance, PostEncumbrance); } @Override public boolean isPostEncumbrance() { return get_ValueAsBoolean(COLUMNNAME_PostEncumbrance); } @Override public void setPostStatistical (final boolean PostStatistical) { set_Value (COLUMNNAME_PostStatistical, PostStatistical); } @Override public boolean isPostStatistical() { return get_ValueAsBoolean(COLUMNNAME_PostStatistical); } @Override public void setSeqNo (final int SeqNo) { set_ValueNoCheck (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override
public void setValidFrom (final @Nullable 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); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ElementValue.java
1
请在Spring Boot框架中完成以下Java代码
public CountryType getCountry() { return country; } /** * Sets the value of the country property. * * @param value * allowed object is * {@link CountryType } * */ public void setCountry(CountryType value) { this.country = value; } /** * Any further elements or attributes which are necessary for an address may be provided here. * Note that extensions should be used with care and only those extensions shall be used, which are officially provided by ERPEL. * Gets the value of the addressExtension property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the addressExtension property. *
* <p> * For example, to add a new item, do as follows: * <pre> * getAddressExtension().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getAddressExtension() { if (addressExtension == null) { addressExtension = new ArrayList<String>(); } return this.addressExtension; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\AddressType.java
2
请在Spring Boot框架中完成以下Java代码
public int delete(long id,JdbcTemplate jdbcTemplate) { if(jdbcTemplate==null){ jdbcTemplate= primaryJdbcTemplate; } return jdbcTemplate.update("DELETE FROM users where id = ? ",id); } @Override public User findById(long id,JdbcTemplate jdbcTemplate) { if(jdbcTemplate==null){ jdbcTemplate= primaryJdbcTemplate; } return jdbcTemplate.queryForObject("SELECT * FROM users WHERE id=?", new Object[] { id }, new BeanPropertyRowMapper<User>(User.class)); } @Override public List<User> findALL(JdbcTemplate jdbcTemplate) { if(jdbcTemplate==null){ jdbcTemplate= primaryJdbcTemplate;
} return jdbcTemplate.query("SELECT * FROM users", new UserRowMapper()); // return jdbcTemplate.query("SELECT * FROM users", new BeanPropertyRowMapper(User.class)); } class UserRowMapper implements RowMapper<User> { @Override public User mapRow(ResultSet rs, int rowNum) throws SQLException { User user = new User(); user.setId(rs.getLong("id")); user.setName(rs.getString("name")); user.setPassword(rs.getString("password")); user.setAge(rs.getInt("age")); return user; } } }
repos\spring-boot-leaning-master\2.x_42_courses\第 3-1 课: Spring Boot 使用 JDBC 操作数据库\spring-boot-multi-jdbc\src\main\java\com\neo\repository\impl\UserRepositoryImpl.java
2
请完成以下Java代码
public Collection<String> getInvolvedGroups() { return involvedGroups; } public String getTenantId() { return tenantId; } public boolean isWithoutTenantId() { return withoutTenantId; } public boolean isIncludeLocalVariables() { return includeLocalVariables; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } @Override
protected void ensureVariablesInitialized() { super.ensureVariablesInitialized(); for (PlanItemInstanceQueryImpl orQueryObject : orQueryObjects) { orQueryObject.ensureVariablesInitialized(); } } public List<PlanItemInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } public List<List<String>> getSafeCaseInstanceIds() { return safeCaseInstanceIds; } public void setSafeCaseInstanceIds(List<List<String>> safeProcessInstanceIds) { this.safeCaseInstanceIds = safeProcessInstanceIds; } public Collection<String> getCaseInstanceIds() { return caseInstanceIds; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\PlanItemInstanceQueryImpl.java
1
请完成以下Java代码
public static void updateFromDateWorkStart(final IRfQWorkDatesAware workDatesAware) { final Timestamp dateWorkStart = workDatesAware.getDateWorkStart(); if(dateWorkStart == null) { return; } setDateWorkComplete(workDatesAware); } public static void updateFromDateWorkComplete(final IRfQWorkDatesAware workDatesAware) { final Timestamp dateWorkComplete = workDatesAware.getDateWorkComplete(); if(dateWorkComplete == null) { return; } setDeliveryDays(workDatesAware); } public static void updateFromDeliveryDays(final IRfQWorkDatesAware workDatesAware) { final Timestamp dateWorkStart = workDatesAware.getDateWorkStart(); if(dateWorkStart == null) { return; }
setDateWorkComplete(workDatesAware); } public static void setDateWorkStart(final IRfQWorkDatesAware workDatesAware) { final Timestamp dateWorkStart = TimeUtil.addDays(workDatesAware.getDateWorkComplete(), workDatesAware.getDeliveryDays() * -1); workDatesAware.setDateWorkStart(dateWorkStart); } public static void setDeliveryDays(final IRfQWorkDatesAware workDatesAware) { final int deliveryDays = TimeUtil.getDaysBetween(workDatesAware.getDateWorkStart(), workDatesAware.getDateWorkComplete()); workDatesAware.setDeliveryDays(deliveryDays); } public static void setDateWorkComplete(final IRfQWorkDatesAware workDatesAware) { final Timestamp dateWorkComplete = TimeUtil.addDays(workDatesAware.getDateWorkStart(), workDatesAware.getDeliveryDays()); workDatesAware.setDateWorkComplete(dateWorkComplete); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\util\RfQWorkDatesUtil.java
1
请完成以下Java代码
public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Statement date. @param StatementDate Date of the statement */ public void setStatementDate (Timestamp StatementDate) { set_Value (COLUMNNAME_StatementDate, StatementDate); } /** Get Statement date. @return Date of the statement */ public Timestamp getStatementDate () { return (Timestamp)get_Value(COLUMNNAME_StatementDate); } /** Set Statement difference. @param StatementDifference Difference between statement ending balance and actual ending balance */ public void setStatementDifference (BigDecimal StatementDifference) { set_Value (COLUMNNAME_StatementDifference, StatementDifference); } /** Get Statement difference. @return Difference between statement ending balance and actual ending balance */ public BigDecimal getStatementDifference () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_StatementDifference); if (bd == null) return Env.ZERO;
return bd; } public I_C_ElementValue getUser1() throws RuntimeException { return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name) .getPO(getUser1_ID(), get_TrxName()); } /** Set User List 1. @param User1_ID User defined list element #1 */ public void setUser1_ID (int User1_ID) { if (User1_ID < 1) set_Value (COLUMNNAME_User1_ID, null); else set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID)); } /** Get User List 1. @return User defined list element #1 */ public int getUser1_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID); if (ii == null) return 0; return ii.intValue(); } public I_C_ElementValue getUser2() throws RuntimeException { return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name) .getPO(getUser2_ID(), get_TrxName()); } /** Set User List 2. @param User2_ID User defined list element #2 */ public void setUser2_ID (int User2_ID) { if (User2_ID < 1) set_Value (COLUMNNAME_User2_ID, null); else set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID)); } /** Get User List 2. @return User defined list element #2 */ public int getUser2_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_User2_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Cash.java
1
请完成以下Java代码
public void setEndWaitTime (final java.sql.Timestamp EndWaitTime) { set_Value (COLUMNNAME_EndWaitTime, EndWaitTime); } @Override public java.sql.Timestamp getEndWaitTime() { return get_ValueAsTimestamp(COLUMNNAME_EndWaitTime); } @Override public void setPriority (final int Priority) { set_Value (COLUMNNAME_Priority, Priority); } @Override public int getPriority() { return get_ValueAsInt(COLUMNNAME_Priority); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); }
@Override public void setTextMsg (final java.lang.String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } @Override public java.lang.String getTextMsg() { return get_ValueAsString(COLUMNNAME_TextMsg); } /** * WFState AD_Reference_ID=305 * Reference name: WF_Instance State */ public static final int WFSTATE_AD_Reference_ID=305; /** NotStarted = ON */ public static final String WFSTATE_NotStarted = "ON"; /** Running = OR */ public static final String WFSTATE_Running = "OR"; /** Suspended = OS */ public static final String WFSTATE_Suspended = "OS"; /** Completed = CC */ public static final String WFSTATE_Completed = "CC"; /** Aborted = CA */ public static final String WFSTATE_Aborted = "CA"; /** Terminated = CT */ public static final String WFSTATE_Terminated = "CT"; @Override public void setWFState (final java.lang.String WFState) { set_Value (COLUMNNAME_WFState, WFState); } @Override public java.lang.String getWFState() { return get_ValueAsString(COLUMNNAME_WFState); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Activity.java
1
请完成以下Java代码
public final void put(final IView view) { views.put(view.getViewId(), ProductsProposalView.cast(view)); } @Nullable @Override public final ProductsProposalView getByIdOrNull(final ViewId viewId) { return views.getIfPresent(viewId); } protected final ProductsProposalView getById(final ViewId viewId) { final ProductsProposalView view = getByIdOrNull(viewId); if (view == null) { throw new EntityNotFoundException("View not found: " + viewId.toJson()); } return view; } @Override public final void closeById(@NonNull final ViewId viewId, @NonNull final ViewCloseAction closeAction) { beforeViewClose(viewId, closeAction); views.invalidate(viewId); views.cleanUp(); } protected void beforeViewClose(@NonNull final ViewId viewId, @NonNull final ViewCloseAction closeAction) { // nothing on this level }
@Override public final Stream<IView> streamAllViews() { return Stream.empty(); } @Override public final void invalidateView(final ViewId viewId) { final ProductsProposalView view = getById(viewId); view.invalidateAll(); } @lombok.Value(staticConstructor = "of") protected static class ViewLayoutKey { WindowId windowId; JSONViewDataType viewDataType; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\view\ProductsProposalViewFactoryTemplate.java
1
请在Spring Boot框架中完成以下Java代码
public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Map<ProductEntity, Integer> getProdEntityCountMap() { return prodEntityCountMap; } public void setProdEntityCountMap(Map<ProductEntity, Integer> prodEntityCountMap) { this.prodEntityCountMap = prodEntityCountMap; } public String getProdIdCountJson() { return prodIdCountJson; } public void setProdIdCountJson(String prodIdCountJson) {
this.prodIdCountJson = prodIdCountJson; } @Override public String toString() { return "OrderInsertReq{" + "userId='" + userId + '\'' + ", prodIdCountJson='" + prodIdCountJson + '\'' + ", prodIdCountMap=" + prodIdCountMap + ", prodEntityCountMap=" + prodEntityCountMap + ", payModeCode=" + payModeCode + ", receiptId='" + receiptId + '\'' + ", locationId='" + locationId + '\'' + ", remark='" + remark + '\'' + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\order\OrderInsertReq.java
2
请完成以下Java代码
protected boolean isExecutionRelatedEntityCountEnabledGlobally() { return processEngineConfiguration.getPerformanceSettings().isEnableExecutionRelationshipCounts(); } protected boolean isExecutionRelatedEntityCountEnabled(ExecutionEntity executionEntity) { if (executionEntity instanceof CountingExecutionEntity) { return isExecutionRelatedEntityCountEnabled((CountingExecutionEntity) executionEntity); } return false; } protected boolean isExecutionRelatedEntityCountEnabled(CountingExecutionEntity executionEntity) { /* * There are two flags here: a global flag and a flag on the execution entity. * The global flag can be switched on and off between different reboots,
* however the flag on the executionEntity refers to the state at that particular moment. * * Global flag / ExecutionEntity flag : result * * T / T : T (all true, regular mode with flags enabled) * T / F : F (global is true, but execution was of a time when it was disabled, thus treating it as disabled) * F / T : F (execution was of time when counting was done. But this is overruled by the global flag and thus the queries will be done) * F / F : F (all disabled) * * From this table it is clear that only when both are true, the result should be true, * which is the regular AND rule for booleans. */ return isExecutionRelatedEntityCountEnabledGlobally() && executionEntity.isCountEnabled(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AbstractEntityManager.java
1
请完成以下Java代码
public List<String> getActivityIds() { return Optional.ofNullable(activityIds).orElse(Collections.emptyList()); } public List<String> getMoveToActivityIds() { return Optional.ofNullable(moveToActivityIds).orElse(Collections.emptyList()); } public boolean isMoveToParentProcess() { return moveToParentProcess; } public void setMoveToParentProcess(boolean moveToParentProcess) { this.moveToParentProcess = moveToParentProcess; } public boolean isMoveToSubProcessInstance() { return moveToSubProcessInstance; } public void setMoveToSubProcessInstance(boolean moveToSubProcessInstance) { this.moveToSubProcessInstance = moveToSubProcessInstance; } public String getCallActivityId() { return callActivityId; } public void setCallActivityId(String callActivityId) { this.callActivityId = callActivityId;
} public Integer getCallActivitySubProcessVersion() { return callActivitySubProcessVersion; } public void setCallActivitySubProcessVersion(Integer callActivitySubProcessVersion) { this.callActivitySubProcessVersion = callActivitySubProcessVersion; } public Optional<String> getNewAssigneeId() { return Optional.ofNullable(newAssigneeId); } public Optional<String> getNewOwnerId() { return Optional.ofNullable(newOwnerId); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\runtime\MoveActivityIdContainer.java
1
请完成以下Java代码
public static Authentication authenticateService(Authentication authentication, final String username, final int lifetimeInSeconds, final String targetService) { KerberosAuthentication kerberosAuthentication = (KerberosAuthentication) authentication; final JaasSubjectHolder jaasSubjectHolder = kerberosAuthentication.getJaasSubjectHolder(); Subject subject = jaasSubjectHolder.getJaasSubject(); Subject.doAs(subject, new PrivilegedAction<Object>() { @Override public Object run() { runAuthentication(jaasSubjectHolder, username, lifetimeInSeconds, targetService); return null; } }); return authentication; } public static byte[] getTokenForService(Authentication authentication, String principalName) { KerberosAuthentication kerberosAuthentication = (KerberosAuthentication) authentication; final JaasSubjectHolder jaasSubjectHolder = kerberosAuthentication.getJaasSubjectHolder(); return jaasSubjectHolder.getToken(principalName); } private static void runAuthentication(JaasSubjectHolder jaasContext, String username, int lifetimeInSeconds, String targetService) { try { GSSManager manager = GSSManager.getInstance(); GSSName clientName = manager.createName(username, GSSName.NT_USER_NAME); GSSCredential clientCredential = manager.createCredential(clientName, lifetimeInSeconds, KERBEROS_OID, GSSCredential.INITIATE_ONLY); GSSName serverName = manager.createName(targetService, GSSName.NT_USER_NAME); GSSContext securityContext = manager.createContext(serverName, KERBEROS_OID, clientCredential, GSSContext.DEFAULT_LIFETIME); securityContext.requestCredDeleg(true); securityContext.requestInteg(false); securityContext.requestAnonymity(false); securityContext.requestMutualAuth(false); securityContext.requestReplayDet(false); securityContext.requestSequenceDet(false); boolean established = false; byte[] outToken = new byte[0];
while (!established) { byte[] inToken = new byte[0]; outToken = securityContext.initSecContext(inToken, 0, inToken.length); established = securityContext.isEstablished(); } jaasContext.addToken(targetService, outToken); } catch (Exception ex) { throw new BadCredentialsException("Kerberos authentication failed", ex); } } private static Oid createOid(String oid) { try { return new Oid(oid); } catch (GSSException ex) { throw new IllegalStateException("Unable to instantiate Oid: ", ex); } } private KerberosMultiTier() { } }
repos\spring-security-main\kerberos\kerberos-core\src\main\java\org\springframework\security\kerberos\authentication\KerberosMultiTier.java
1
请完成以下Java代码
public void setQtyReimbursed (BigDecimal QtyReimbursed) { set_Value (COLUMNNAME_QtyReimbursed, QtyReimbursed); } /** Get Quantity Reimbursed. @return The reimbursed quantity */ public BigDecimal getQtyReimbursed () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyReimbursed); if (bd == null) return Env.ZERO; return bd; } /** Set Resource Assignment. @param S_ResourceAssignment_ID Resource Assignment */ public void setS_ResourceAssignment_ID (int S_ResourceAssignment_ID) { if (S_ResourceAssignment_ID < 1) set_Value (COLUMNNAME_S_ResourceAssignment_ID, null); else set_Value (COLUMNNAME_S_ResourceAssignment_ID, Integer.valueOf(S_ResourceAssignment_ID)); } /** Get Resource Assignment. @return Resource Assignment */ public int getS_ResourceAssignment_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_ResourceAssignment_ID); if (ii == null) return 0; return ii.intValue(); } public I_S_TimeExpense getS_TimeExpense() throws RuntimeException { return (I_S_TimeExpense)MTable.get(getCtx(), I_S_TimeExpense.Table_Name) .getPO(getS_TimeExpense_ID(), get_TrxName()); } /** Set Expense Report. @param S_TimeExpense_ID Time and Expense Report */ public void setS_TimeExpense_ID (int S_TimeExpense_ID) { if (S_TimeExpense_ID < 1) set_ValueNoCheck (COLUMNNAME_S_TimeExpense_ID, null); else set_ValueNoCheck (COLUMNNAME_S_TimeExpense_ID, Integer.valueOf(S_TimeExpense_ID)); } /** Get Expense Report. @return Time and Expense Report */ public int getS_TimeExpense_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_TimeExpense_ID); if (ii == null) return 0;
return ii.intValue(); } /** Set Expense Line. @param S_TimeExpenseLine_ID Time and Expense Report Line */ public void setS_TimeExpenseLine_ID (int S_TimeExpenseLine_ID) { if (S_TimeExpenseLine_ID < 1) set_ValueNoCheck (COLUMNNAME_S_TimeExpenseLine_ID, null); else set_ValueNoCheck (COLUMNNAME_S_TimeExpenseLine_ID, Integer.valueOf(S_TimeExpenseLine_ID)); } /** Get Expense Line. @return Time and Expense Report Line */ public int getS_TimeExpenseLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_TimeExpenseLine_ID); if (ii == null) return 0; return ii.intValue(); } public I_S_TimeType getS_TimeType() throws RuntimeException { return (I_S_TimeType)MTable.get(getCtx(), I_S_TimeType.Table_Name) .getPO(getS_TimeType_ID(), get_TrxName()); } /** Set Time Type. @param S_TimeType_ID Type of time recorded */ public void setS_TimeType_ID (int S_TimeType_ID) { if (S_TimeType_ID < 1) set_Value (COLUMNNAME_S_TimeType_ID, null); else set_Value (COLUMNNAME_S_TimeType_ID, Integer.valueOf(S_TimeType_ID)); } /** Get Time Type. @return Type of time recorded */ public int getS_TimeType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_TimeType_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_TimeExpenseLine.java
1
请完成以下Java代码
public List<String> shortcutFieldOrder() { return Arrays.asList("sources"); } @Override public Predicate<ServerWebExchange> apply(Config config) { if (log.isDebugEnabled()) { log.debug("Applying XForwardedRemoteAddr route predicate with maxTrustedIndex of " + config.getMaxTrustedIndex() + " for " + config.getSources().size() + " source(s)"); } // Reuse the standard RemoteAddrRoutePredicateFactory but instead of using the // default RemoteAddressResolver to determine the client IP address, use an // XForwardedRemoteAddressResolver. RemoteAddrRoutePredicateFactory.Config wrappedConfig = new RemoteAddrRoutePredicateFactory.Config(); wrappedConfig.setSources(config.getSources()); wrappedConfig .setRemoteAddressResolver(XForwardedRemoteAddressResolver.maxTrustedIndex(config.getMaxTrustedIndex())); RemoteAddrRoutePredicateFactory remoteAddrRoutePredicateFactory = new RemoteAddrRoutePredicateFactory(); Predicate<ServerWebExchange> wrappedPredicate = remoteAddrRoutePredicateFactory.apply(wrappedConfig); return exchange -> { Boolean isAllowed = wrappedPredicate.test(exchange); if (log.isDebugEnabled()) { ServerHttpRequest request = exchange.getRequest(); String clientAddress = request.getRemoteAddress() != null ? request.getRemoteAddress().getAddress().getHostAddress() : "unknown"; log.debug("Request for \"" + request.getURI() + "\" from client \"" + clientAddress + "\" with \"" + XForwardedRemoteAddressResolver.X_FORWARDED_FOR + "\" header value of \"" + request.getHeaders().get(XForwardedRemoteAddressResolver.X_FORWARDED_FOR) + "\" is " + (isAllowed ? "ALLOWED" : "NOT ALLOWED")); } return isAllowed; }; } public static class Config { // Trust the last (right-most) value in the "X-Forwarded-For" header by default, // which represents the last reverse proxy that was used when calling the gateway. private int maxTrustedIndex = 1; private List<String> sources = new ArrayList<>(); public int getMaxTrustedIndex() { return this.maxTrustedIndex; }
public Config setMaxTrustedIndex(int maxTrustedIndex) { this.maxTrustedIndex = maxTrustedIndex; return this; } public List<String> getSources() { return this.sources; } public Config setSources(List<String> sources) { this.sources = sources; return this; } public Config setSources(String... sources) { this.sources = Arrays.asList(sources); return this; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\XForwardedRemoteAddrRoutePredicateFactory.java
1
请完成以下Java代码
public class ManualCandidateHandler extends AbstractInvoiceCandidateHandler { /** * Not actually a real table name but a marker that is used to pick this manual handler. Please note that {@link #getSourceTable()} returns this. */ final public static String MANUAL = "ManualCandidateHandler"; /** @return {@code false}. */ @Override public CandidatesAutoCreateMode getGeneralCandidatesAutoCreateMode() { return CandidatesAutoCreateMode.DONT; } /** @return {@code false}. */ @Override public CandidatesAutoCreateMode getSpecificCandidatesAutoCreateMode(final Object model) { return CandidatesAutoCreateMode.DONT; } /** @return empty iterator */ @Override public Iterator<Object> retrieveAllModelsWithMissingCandidates(final QueryLimit limit_IGNORED) { return Collections.emptyIterator(); } /** @return empty result */ @Override public InvoiceCandidateGenerateResult createCandidatesFor(final InvoiceCandidateGenerateRequest request) { return InvoiceCandidateGenerateResult.of(this); } /** Does nothing */ @Override public void invalidateCandidatesFor(final Object model) { // nothing to do } /** * @return {@link #MANUAL} (i.e. not a real table name). */
@Override public String getSourceTable() { return ManualCandidateHandler.MANUAL; } /** @return {@code true}. */ @Override public boolean isUserInChargeUserEditable() { return true; } /** * Does nothing. */ @Override public void setOrderedData(final I_C_Invoice_Candidate ic) { // nothing to do } /** * Does nothing. */ @Override public void setDeliveredData(final I_C_Invoice_Candidate ic) { // nothing to do } @Override public void setBPartnerData(final I_C_Invoice_Candidate ic) { // nothing to do } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\impl\ManualCandidateHandler.java
1
请完成以下Java代码
public static boolean removeConsoleAppender(ch.qos.logback.classic.Logger logger) { return removeAppender(logger, CONSOLE_APPENDER_NAME); } /** * Removes the {@literal delegate} {@link Appender} from the given {@link Logger}. * * @param logger {@link Logger} from which to remove the {@literal delegate} {@link Appender}. * @return {@literal true} if the {@literal delegate} {@link Appender} was registered with * and successfully remove from the given {@link Logger}. * @see #removeAppender(ch.qos.logback.classic.Logger, String) */ public static boolean removeDelegateAppender(ch.qos.logback.classic.Logger logger) { return removeAppender(logger, DELEGATE_APPENDER_NAME); } /** * Converts an SLF4J {@link Logger} to a Logback {@link ch.qos.logback.classic.Logger}. * * @param logger SLF4J {@link Logger} to convert. * @return an {@link Optional} Logback {@link ch.qos.logback.classic.Logger} for the given SLF4J {@link Logger} * iff the SLF4J {@link Logger} is {@literal not-null} and is a Logback {@link ch.qos.logback.classic.Logger}. * @see java.util.Optional * @see ch.qos.logback.classic.Logger * @see org.slf4j.Logger */ public static Optional<ch.qos.logback.classic.Logger> toLogbackLogger(Logger logger) { return slf4jLoggerToLogbackLoggerConverter.apply(logger); } private static String nullSafeLoggerName(Logger logger) { return logger != null ? logger.getName() : null;
} private static Class<?> nullSafeType(Object obj) { return obj != null ? obj.getClass() : null; } private static String nullSafeTypeName(Class<?> type) { return type != null ? type.getName() : null; } private static String nullSafeTypeName(Object obj) { return nullSafeTypeName(nullSafeType(obj)); } private static String nullSafeTypeSimpleName(Class<?> type) { return type != null ? type.getSimpleName() : null; } private static String nullSafeTypeSimpleName(Object obj) { return nullSafeTypeSimpleName(nullSafeType(obj)); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-starters\spring-geode-starter-logging\src\main\java\org\springframework\geode\logging\slf4j\logback\support\LogbackSupport.java
1
请在Spring Boot框架中完成以下Java代码
public class Address { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String street; private String city; private String zipCode; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() {
return city; } public void setCity(String city) { this.city = city; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } }
repos\tutorials-master\persistence-modules\spring-jpa-2\src\main\java\com\baeldung\inheritancevscomposition\composition\Address.java
2
请完成以下Java代码
protected final ImportGroupResult importRecords( final RecordIdGroupKey groupKey, final List<ImportRecordType> importRecords, final IMutable<Object> stateHolder) throws Exception { final ImportRecordType importRecord = CollectionUtils.singleElement(importRecords); final ImportRecordResult result = importRecord(stateHolder, importRecord, isInsertOnly()); if (result == ImportRecordResult.Inserted) { return ImportGroupResult.ONE_INSERTED; } else if (result == ImportRecordResult.Updated) { return ImportGroupResult.ONE_UPDATED; } else
{ return ImportGroupResult.ZERO; } } public enum ImportRecordResult { Inserted, Updated, Nothing, } protected abstract ImportRecordResult importRecord( @NonNull final IMutable<Object> stateHolder, @NonNull final ImportRecordType importRecord, final boolean isInsertOnly) throws Exception; }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\processing\SimpleImportProcessTemplate.java
1
请完成以下Java代码
public Optional<BPPurchaseSchedule> getBPPurchaseSchedule(final BPartnerId bpartnerId, final LocalDate date) { return bpPurchaseScheduleRepo.getByBPartnerIdAndValidFrom(bpartnerId, date); } public Optional<ZonedDateTime> calculatePurchaseDatePromised( @NonNull final ZonedDateTime salesPreparationDate, @NonNull final BPPurchaseSchedule schedule) { final IBusinessDayMatcher businessDayMatcher; if (schedule.getNonBusinessDaysCalendarId() != null) { final ICalendarDAO calendarRepo = Services.get(ICalendarDAO.class); businessDayMatcher = calendarRepo.getCalendarNonBusinessDays(schedule.getNonBusinessDaysCalendarId()); } else { businessDayMatcher = NullBusinessDayMatcher.instance; }
final IDateShifter dateShifter = BusinessDayShifter.builder() .businessDayMatcher(businessDayMatcher) .onNonBussinessDay(OnNonBussinessDay.MoveToClosestBusinessDay) .build(); final Optional<LocalDate> purchaseDayPromised = DateSequenceGenerator.builder() .dateFrom(LocalDate.MIN) .dateTo(LocalDate.MAX) .shifter(dateShifter) .frequency(schedule.getFrequency()) .build() .calculatePrevious(salesPreparationDate.toLocalDate()); // TODO: make sure that after applying the time, our date is BEFORE sales preparation time! return purchaseDayPromised .map(day -> schedule.applyTimeTo(day).atZone(salesPreparationDate.getZone())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\BPPurchaseScheduleService.java
1
请完成以下Java代码
public final LookupValue retrieveLookupValueById(final @NonNull LookupDataSourceContext evalCtx) { final SqlAndParams sqlAndParams = this.sqlForFetchingLookupById.evaluate(evalCtx).orElse(null); if (sqlAndParams == null) { throw new AdempiereException("No ID provided in " + evalCtx); } final String adLanguage = evalCtx.getAD_Language(); final ImmutableList<LookupValue> rows = DB.retrieveRows( sqlAndParams.getSql(), sqlAndParams.getSqlParams(), rs -> SqlForFetchingLookupById.retrieveLookupValue(rs, isNumericKey(), isTranslatable, adLanguage)); if (rows.isEmpty()) { return LOOKUPVALUE_NULL; } else if (rows.size() == 1) { return rows.get(0); } else { // shall not happen throw new AdempiereException("More than one row found for " + evalCtx + ": " + rows); } } @Override public LookupValuesList retrieveLookupValueByIdsInOrder(@NonNull final LookupDataSourceContext evalCtx) {
final SqlAndParams sqlAndParams = this.sqlForFetchingLookupById.evaluate(evalCtx).orElse(null); if (sqlAndParams == null) { return LookupValuesList.EMPTY; } final String adLanguage = evalCtx.getAD_Language(); final ImmutableList<LookupValue> rows = DB.retrieveRows( sqlAndParams.getSql(), sqlAndParams.getSqlParams(), rs -> SqlForFetchingLookupById.retrieveLookupValue(rs, numericKey, isTranslatable, adLanguage)); if (rows.isEmpty()) { return LookupValuesList.EMPTY; } else if (rows.size() == 1) { return LookupValuesList.fromNullable(rows.get(0)); } else { return rows.stream() .sorted(FixedOrderByKeyComparator.<LookupValue, Object>builder() .fixedOrderKeys(LookupValue.normalizeIds(evalCtx.getIdsToFilter().toImmutableList(), numericKey)) .keyMapper(LookupValue::getId) .build()) .collect(LookupValuesList.collect()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\GenericSqlLookupDataSourceFetcher.java
1
请在Spring Boot框架中完成以下Java代码
private void mapReactiveProperties(Reactive properties, ThymeleafReactiveViewResolver resolver) { PropertyMapper map = PropertyMapper.get(); map.from(properties::getMediaTypes).to(resolver::setSupportedMediaTypes); map.from(properties::getMaxChunkSize) .asInt(DataSize::toBytes) .when((size) -> size > 0) .to(resolver::setResponseMaxChunkSizeBytes); map.from(properties::getFullModeViewNames).to(resolver::setFullModeViewNames); map.from(properties::getChunkedModeViewNames).to(resolver::setChunkedModeViewNames); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(LayoutDialect.class) static class ThymeleafWebLayoutConfiguration { @Bean @ConditionalOnMissingBean LayoutDialect layoutDialect() { return new LayoutDialect(); } } @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(DataAttributeDialect.class) static class DataAttributeDialectConfiguration { @Bean @ConditionalOnMissingBean DataAttributeDialect dialect() { return new DataAttributeDialect(); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ SpringSecurityDialect.class, CsrfToken.class }) static class ThymeleafSecurityDialectConfiguration { @Bean @ConditionalOnMissingBean SpringSecurityDialect securityDialect() { return new SpringSecurityDialect(); } } }
repos\spring-boot-4.0.1\module\spring-boot-thymeleaf\src\main\java\org\springframework\boot\thymeleaf\autoconfigure\ThymeleafAutoConfiguration.java
2
请完成以下Java代码
public void setKey(String key) { this.key = key; } @CamundaQueryParam("keyLike") public void setKeyLike(String keyLike) { this.keyLike = keyLike; } @CamundaQueryParam("name") public void setName(String name) { this.name = name; } @CamundaQueryParam("nameLike")
public void setNameLike(String nameLike) { this.nameLike = nameLike; } @Override protected boolean isValidSortByValue(String value) { return VALID_SORT_VALUES.containsKey(value); } @Override protected String getOrderByValue(String sortBy) { return VALID_SORT_VALUES.get(sortBy); } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\query\ProcessDefinitionStatisticsQueryDto.java
1
请在Spring Boot框架中完成以下Java代码
private static class PartitionedInOutLineRecords { @Singular("lineToQuarantine") List<QuarantineInOutLine> linesToQuarantine; @Singular("lineToDD_Order") List<I_M_InOutLine> linesToDD_Order; @Singular("lineToMove") List<org.compiere.model.I_M_InOutLine> linesToMove; } private void setInvoiceCandsInDispute(final List<QuarantineInOutLine> lines) { final IInvoiceCandBL invoiceCandBL = Services.get(IInvoiceCandBL.class); lines.stream() .map(QuarantineInOutLine::getInOutLine) .forEach(invoiceCandBL::markInvoiceCandInDisputeForReceiptLine); } private LotNumberQuarantine getQuarantineLotNoOrNull(final I_M_InOutLine inOutLine) { final ProductId productId = ProductId.ofRepoId(inOutLine.getM_Product_ID()); final I_M_AttributeSetInstance receiptLineASI = inOutLine.getM_AttributeSetInstance(); if (receiptLineASI == null) { // if it has no attributes set it means it has no lot number set either. return null; } final String lotNumberAttributeValue = lotNoBL.getLotNumberAttributeValueOrNull(receiptLineASI); if (Check.isEmpty(lotNumberAttributeValue)) { // if the attribute is not present or set it automatically means the lotno is not to quarantine, either return null;
} return lotNumberQuarantineRepository.getByProductIdAndLot(productId, lotNumberAttributeValue); } private boolean isCreateDDOrder(@NonNull final I_M_InOutLine inOutLine) { final List<I_M_ReceiptSchedule> rsForInOutLine = receiptScheduleDAO.retrieveRsForInOutLine(inOutLine); for (final I_M_ReceiptSchedule resceiptSchedule : rsForInOutLine) { final boolean createDistributionOrder = X_M_ReceiptSchedule.ONMATERIALRECEIPTWITHDESTWAREHOUSE_CreateDistributionOrder .equals(resceiptSchedule.getOnMaterialReceiptWithDestWarehouse()); if (createDistributionOrder) { return true; } } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\impl\DistributeAndMoveReceiptCreator.java
2
请完成以下Java代码
private static void validateOrderLinesConsistency(@NonNull final JsonInvoiceCandidateReference invoiceCandidate) { if (!Check.isEmpty(invoiceCandidate.getOrderLines()) && invoiceCandidate.getOrderDocumentNo() == null) { throw new InvalidEntityException(TranslatableStrings.constant( "orderLines were provided, but orderDocumentNo is missing. Order lines require an order document number.")); } } private static void validateReferenceTypeExclusivity(@NonNull final JsonInvoiceCandidateReference invoiceCandidate) { if (invoiceCandidate.getExternalHeaderId() != null && invoiceCandidate.getOrderDocumentNo() != null) { throw new InvalidEntityException(TranslatableStrings.constant( "Both externalHeaderId and orderDocumentNo are provided. Only one reference type should be used.")); } } private static void validateOrderDocumentTypeWithOrgCode(@NonNull final JsonInvoiceCandidateReference invoiceCandidate) { if (invoiceCandidate.getOrderDocumentType() != null && Check.isBlank(invoiceCandidate.getOrgCode())) { throw new InvalidEntityException(TranslatableStrings.constant( "When specifying Order Document Type, the org code also has to be specified")); } } @Nullable private OrgId getOrgId(@NonNull final JsonInvoiceCandidateReference invoiceCandidate) { final String orgCode = invoiceCandidate.getOrgCode(); if (Check.isNotBlank(orgCode)) { return orgDAO.retrieveOrgIdBy(OrgQuery.ofValue(orgCode)) .orElseThrow(() -> MissingResourceException.builder() .resourceName("organisation") .resourceIdentifier("(val-)" + orgCode) .build()); } else { return null; } } @Nullable private DocTypeId getOrderDocTypeId( @Nullable final JsonDocTypeInfo orderDocumentType, @Nullable final OrgId orgId) { if (orderDocumentType == null) { return null; }
if (orgId == null) { throw new InvalidEntityException(TranslatableStrings.constant( "When specifying Order Document Type, the org code also has to be specified")); } final DocBaseType docBaseType = Optional.of(orderDocumentType) .map(JsonDocTypeInfo::getDocBaseType) .map(DocBaseType::ofCode) .orElse(null); final DocSubType subType = Optional.of(orderDocumentType) .map(JsonDocTypeInfo::getDocSubType) .map(DocSubType::ofNullableCode) .orElse(DocSubType.ANY); return Optional.ofNullable(docBaseType) .map(baseType -> docTypeService.getDocTypeId(docBaseType, subType, orgId)) .orElseThrow(() -> MissingResourceException.builder() .resourceName("DocType") .parentResource(orderDocumentType) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\invoicecandidates\impl\InvoiceJsonConverters.java
1
请完成以下Java代码
public static String getOrigin(){ HttpServletRequest request = getHttpServletRequest(); return request.getHeader("Origin"); } /** * 通过name获取 Bean. * * @param name * @return */ public static Object getBean(String name) { return getApplicationContext().getBean(name); } /** * 通过class获取Bean. * * @param clazz * @param <T> * @return */ public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz); } /** * 通过name,以及Clazz返回指定的Bean * * @param name * @param clazz * @param <T> * @return */ public static <T> T getBean(String name, Class<T> clazz) { return getApplicationContext().getBean(name, clazz); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\SpringContextUtils.java
1
请完成以下Java代码
public SessionInformation getSessionInformation(String sessionId) { S session = this.sessionRepository.findById(sessionId); if (session != null) { return new SpringSessionBackedSessionInformation<>(session, this.sessionRepository); } return null; } /* * This is a no-op, as we don't administer sessions ourselves. */ @Override public void refreshLastRequest(String sessionId) { } /* * This is a no-op, as we don't administer sessions ourselves. */ @Override public void registerNewSession(String sessionId, Object principal) { } /* * This is a no-op, as we don't administer sessions ourselves.
*/ @Override public void removeSessionInformation(String sessionId) { } /** * Derives a String name for the given principal. * @param principal as provided by Spring Security * @return name of the principal, or its {@code toString()} representation if no name * could be derived */ protected String name(Object principal) { // We are reusing the logic from AbstractAuthenticationToken#getName return new TestingAuthenticationToken(principal, null).getName(); } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\security\SpringSessionBackedSessionRegistry.java
1
请完成以下Java代码
public void setConfiguration(String configuration) { this.configuration = configuration; } public String getAnnotation() { return annotation; } public void setAnnotation(String annotation) { this.annotation = annotation; } public String getCauseIncidentProcessInstanceId() { return causeIncidentProcessInstanceId; } public void setCauseIncidentProcessInstanceId(String causeIncidentProcessInstanceId) { this.causeIncidentProcessInstanceId = causeIncidentProcessInstanceId; } public String getCauseIncidentProcessDefinitionId() { return causeIncidentProcessDefinitionId; } public String getCauseIncidentActivityId() { return causeIncidentActivityId; } public void setCauseIncidentActivityId(String causeIncidentActivityId) { this.causeIncidentActivityId = causeIncidentActivityId; } public String getCauseIncidentFailedActivityId() { return causeIncidentFailedActivityId; } public void setCauseIncidentFailedActivityId(String causeIncidentFailedActivityId) { this.causeIncidentFailedActivityId = causeIncidentFailedActivityId; } public void setCauseIncidentProcessDefinitionId(String causeIncidentProcessDefinitionId) { this.causeIncidentProcessDefinitionId = causeIncidentProcessDefinitionId; } public String getRootCauseIncidentProcessInstanceId() { return rootCauseIncidentProcessInstanceId; }
public void setRootCauseIncidentProcessInstanceId(String rootCauseIncidentProcessInstanceId) { this.rootCauseIncidentProcessInstanceId = rootCauseIncidentProcessInstanceId; } public String getRootCauseIncidentProcessDefinitionId() { return rootCauseIncidentProcessDefinitionId; } public void setRootCauseIncidentProcessDefinitionId(String rootCauseIncidentProcessDefinitionId) { this.rootCauseIncidentProcessDefinitionId = rootCauseIncidentProcessDefinitionId; } public String getRootCauseIncidentActivityId() { return rootCauseIncidentActivityId; } public void setRootCauseIncidentActivityId(String rootCauseIncidentActivityId) { this.rootCauseIncidentActivityId = rootCauseIncidentActivityId; } public String getRootCauseIncidentFailedActivityId() { return rootCauseIncidentFailedActivityId; } public void setRootCauseIncidentFailedActivityId(String rootCauseIncidentFailedActivityId) { this.rootCauseIncidentFailedActivityId = rootCauseIncidentFailedActivityId; } public String getRootCauseIncidentConfiguration() { return rootCauseIncidentConfiguration; } public void setRootCauseIncidentConfiguration(String rootCauseIncidentConfiguration) { this.rootCauseIncidentConfiguration = rootCauseIncidentConfiguration; } public String getRootCauseIncidentMessage() { return rootCauseIncidentMessage; } public void setRootCauseIncidentMessage(String rootCauseIncidentMessage) { this.rootCauseIncidentMessage = rootCauseIncidentMessage; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\IncidentDto.java
1
请完成以下Java代码
private static PPOrderId extractPPOrderId(final JsonRequestSetOrderExportStatus item) { return PPOrderId.ofRepoId(item.getOrderId().getValue()); } @Nullable private AdIssueId createADIssue(@Nullable final JsonError error) { if (error == null || error.getErrors().isEmpty()) { return null; } final JsonErrorItem errorItem = error.getErrors().get(0); return errorManager.createIssue(IssueCreateRequest.builder() .summary(errorItem.getMessage() + "; " + errorItem.getDetail()) .stackTrace(errorItem.getStackTrace()) .loggerName(logger.getName())
.build()); } private String toJsonString(@NonNull final JsonRequestSetOrderExportStatus requestItem) { try { return jsonObjectMapper.writeValueAsString(requestItem); } catch (final JsonProcessingException ex) { logger.warn("Failed converting {} to JSON. Returning toString()", requestItem, ex); return requestItem.toString(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\rest_api\v1\ManufacturingOrdersSetExportStatusCommand.java
1
请完成以下Java代码
private static byte[] bytesFromUUID(String uuidHexString) { final String normalizedUUIDHexString = uuidHexString.replace("-", ""); assert normalizedUUIDHexString.length() == 32; final byte[] bytes = new byte[16]; for (int i = 0; i < 16; i++) { final byte b = hexToByte(normalizedUUIDHexString.substring(i * 2, i * 2 + 2)); bytes[i] = b; } return bytes; } public static byte hexToByte(String hexString) { final int firstDigit = Character.digit(hexString.charAt(0), 16); final int secondDigit = Character.digit(hexString.charAt(1), 16); return (byte) ((firstDigit << 4) + secondDigit); } public static byte[] joinBytes(byte[] byteArray1, byte[] byteArray2) { final int finalLength = byteArray1.length + byteArray2.length; final byte[] result = new byte[finalLength]; System.arraycopy(byteArray1, 0, result, 0, byteArray1.length); System.arraycopy(byteArray2, 0, result, byteArray1.length, byteArray2.length); return result; } public static UUID generateType5UUID(String name) { try { final byte[] bytes = name.getBytes(StandardCharsets.UTF_8); final MessageDigest md = MessageDigest.getInstance("SHA-1"); final byte[] hash = md.digest(bytes); long msb = getLeastAndMostSignificantBitsVersion5(hash, 0); long lsb = getLeastAndMostSignificantBitsVersion5(hash, 8); // Set the version field msb &= ~(0xfL << 12);
msb |= 5L << 12; // Set the variant field to 2 lsb &= ~(0x3L << 62); lsb |= 2L << 62; return new UUID(msb, lsb); } catch (NoSuchAlgorithmException e) { throw new AssertionError(e); } } private static long getLeastAndMostSignificantBitsVersion5(final byte[] src, final int offset) { long ans = 0; for (int i = offset + 7; i >= offset; i -= 1) { ans <<= 8; ans |= src[i] & 0xffL; } return ans; } }
repos\tutorials-master\core-java-modules\core-java-uuid-generation\src\main\java\com\baeldung\uuid\UUIDGenerator.java
1
请完成以下Java代码
public Effect __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } public String name() { int o = __offset(4); return o != 0 ? __string(o + bb_pos) : null; } public ByteBuffer nameAsByteBuffer() { return __vector_as_bytebuffer(4, 1); } public ByteBuffer nameInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 4, 1); } public short damage() { int o = __offset(6); return o != 0 ? bb.getShort(o + bb_pos) : 0; } public boolean mutateDamage(short damage) { int o = __offset(6); if (o != 0) { bb.putShort(o + bb_pos, damage); return true; } else { return false; } } public static int createEffect(FlatBufferBuilder builder, int nameOffset, short damage) { builder.startTable(2); Effect.addName(builder, nameOffset); Effect.addDamage(builder, damage); return Effect.endEffect(builder); }
public static void startEffect(FlatBufferBuilder builder) { builder.startTable(2); } public static void addName(FlatBufferBuilder builder, int nameOffset) { builder.addOffset(0, nameOffset, 0); } public static void addDamage(FlatBufferBuilder builder, short damage) { builder.addShort(1, damage, 0); } public static int endEffect(FlatBufferBuilder builder) { int o = builder.endTable(); return o; } public static final class Vector extends BaseVector { public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } public Effect get(int j) { return get(new Effect(), j); } public Effect get(Effect obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } } }
repos\tutorials-master\libraries-data-io-2\src\main\java\com\baeldung\flatbuffers\MyGame\terrains\Effect.java
1
请完成以下Java代码
public Builder setC_BPartner_ID(final int C_BPartner_ID) { this.C_BPartner_ID = C_BPartner_ID; return this; } public Builder setBPartnerName(final String BPartnerName) { this.BPartnerName = BPartnerName; return this; } public Builder setCurrencyISOCode(final CurrencyCode currencyISOCode) { this.currencyISOCode = currencyISOCode; return this; } public Builder setGrandTotal(final BigDecimal grandTotal) { this.grandTotal = grandTotal; return this; } public Builder setGrandTotalConv(final BigDecimal grandTotalConv) { this.grandTotalConv = grandTotalConv; return this; } public Builder setOpenAmtConv(final BigDecimal openAmtConv) { this.openAmtConv = openAmtConv; return this; } public Builder setDiscount(final BigDecimal discount) { this.discount = discount; return this; } public Builder setPaymentRequestAmt(final BigDecimal paymentRequestAmt) { Check.assumeNotNull(paymentRequestAmt, "paymentRequestAmt not null"); this.paymentRequestAmtSupplier = Suppliers.ofInstance(paymentRequestAmt); return this; } public Builder setPaymentRequestAmt(final Supplier<BigDecimal> paymentRequestAmtSupplier) { this.paymentRequestAmtSupplier = paymentRequestAmtSupplier;
return this; } public Builder setMultiplierAP(final BigDecimal multiplierAP) { this.multiplierAP = multiplierAP; return this; } public Builder setIsPrepayOrder(final boolean isPrepayOrder) { this.isPrepayOrder = isPrepayOrder; return this; } public Builder setPOReference(final String POReference) { this.POReference = POReference; return this; } public Builder setCreditMemo(final boolean creditMemo) { this.creditMemo = creditMemo; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\InvoiceRow.java
1
请完成以下Java代码
public void unprocessTourInstance(final I_M_ShipperTransportation shipperTransportation) { final I_M_Tour_Instance tourInstance = retrieveTourInstanceOrNull(shipperTransportation); // No Tour Instance => nothing to do if (tourInstance == null) { return; } Services.get(ITourInstanceBL.class).unprocess(tourInstance); } @DocValidate(timings = { ModelValidator.TIMING_BEFORE_VOID, ModelValidator.TIMING_BEFORE_REVERSECORRECT, ModelValidator.TIMING_BEFORE_REVERSECORRECT }) public void prohibitVoidingIfTourInstanceExists(final I_M_ShipperTransportation shipperTransportation) { final I_M_Tour_Instance tourInstance = retrieveTourInstanceOrNull(shipperTransportation); // No Tour Instance => nothing to do if (tourInstance == null) {
return; } throw new AdempiereException("@NotAllowed@ (@M_Tour_Instance_ID@: " + tourInstance + ")"); } private I_M_Tour_Instance retrieveTourInstanceOrNull(final I_M_ShipperTransportation shipperTransportation) { final Object contextProvider = shipperTransportation; final ITourInstanceQueryParams params = new PlainTourInstanceQueryParams(); params.setM_ShipperTransportation_ID(shipperTransportation.getM_ShipperTransportation_ID()); final I_M_Tour_Instance tourInstance = Services.get(ITourInstanceDAO.class).retrieveTourInstance(contextProvider, params); return tourInstance; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\model\validator\M_ShipperTransportation.java
1
请在Spring Boot框架中完成以下Java代码
public User save(TenantId tenantId, CustomerId customerId, User tbUser, boolean sendActivationMail, HttpServletRequest request, User user) throws ThingsboardException { ActionType actionType = tbUser.getId() == null ? ActionType.ADDED : ActionType.UPDATED; try { boolean sendEmail = tbUser.getId() == null && sendActivationMail; User savedUser = checkNotNull(userService.saveUser(tenantId, tbUser)); if (sendEmail) { UserActivationLink activationLink = getActivationLink(tenantId, customerId, savedUser.getId(), request); try { mailService.sendActivationEmail(activationLink.value(), activationLink.ttlMs(), savedUser.getEmail()); } catch (ThingsboardException e) { userService.deleteUser(tenantId, savedUser); throw new ThingsboardException("Couldn't send user activation email", ThingsboardErrorCode.GENERAL); } } logEntityActionService.logEntityAction(tenantId, savedUser.getId(), savedUser, customerId, actionType, user); return savedUser; } catch (Exception e) { logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.USER), tbUser, actionType, user, e); throw e; } } @Override public void delete(TenantId tenantId, CustomerId customerId, User user, User responsibleUser) throws ThingsboardException { ActionType actionType = ActionType.DELETED; UserId userId = user.getId(); try {
userService.deleteUser(tenantId, user); logEntityActionService.logEntityAction(tenantId, userId, user, customerId, actionType, responsibleUser, customerId.toString()); } catch (Exception e) { logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.USER), actionType, responsibleUser, e, userId.toString()); throw e; } } @Override public UserActivationLink getActivationLink(TenantId tenantId, CustomerId customerId, UserId userId, HttpServletRequest request) throws ThingsboardException { UserCredentials userCredentials = userService.findUserCredentialsByUserId(tenantId, userId); if (!userCredentials.isEnabled() && userCredentials.getActivateToken() != null) { userCredentials = userService.checkUserActivationToken(tenantId, userCredentials); String baseUrl = systemSecurityService.getBaseUrl(tenantId, customerId, request); String link = baseUrl + "/api/noauth/activate?activateToken=" + userCredentials.getActivateToken(); return new UserActivationLink(link, userCredentials.getActivationTokenTtl()); } else { throw new ThingsboardException("User is already activated!", ThingsboardErrorCode.BAD_REQUEST_PARAMS); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\user\DefaultUserService.java
2
请完成以下Java代码
public class Address { private Integer addressId; private String streetAddress; private Integer personId; public Address() { } public Integer getPersonId() { return personId; } public void setPersonId(Integer personId) { this.personId = personId; } public Address(String streetAddress) { this.streetAddress = streetAddress; } public Person getPerson() { return person; } public void setPerson(Person person) {
this.person = person; } private Person person; public Address(int i, String name) { this.streetAddress = name; } public Integer getAddressId() { return addressId; } public String getStreetAddress() { return streetAddress; } }
repos\tutorials-master\mybatis\src\main\java\com\baeldung\mybatis\model\Address.java
1
请完成以下Java代码
public final IQualityInspectionLineBuilder setName(final String name) { _name = name; return this; } protected final String getName() { return _name; } private IHandlingUnitsInfo getHandlingUnitsInfoToSet() { if (_handlingUnitsInfoSet) { return _handlingUnitsInfo; } return null; } @Override public IQualityInspectionLineBuilder setHandlingUnitsInfo(final IHandlingUnitsInfo handlingUnitsInfo) { _handlingUnitsInfo = handlingUnitsInfo; _handlingUnitsInfoSet = true; return this; } private IHandlingUnitsInfo getHandlingUnitsInfoProjectedToSet() {
if (_handlingUnitsInfoProjectedSet) { return _handlingUnitsInfoProjected; } return null; } @Override public IQualityInspectionLineBuilder setHandlingUnitsInfoProjected(final IHandlingUnitsInfo handlingUnitsInfo) { _handlingUnitsInfoProjected = handlingUnitsInfo; _handlingUnitsInfoProjectedSet = true; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityInspectionLineBuilder.java
1
请完成以下Java代码
protected int compare(Comparable original, Comparable other) { if (original == other) { return 0; } if (original == null) { return -1; } if (other == null) { return 1; } return original.compareTo(other); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } else if (!(obj instanceof Entry)) { return false; } else {
Entry<?, ?> other = (Entry<?, ?>) obj; return Objects.equals(this.getKey(), other.getKey()) && Objects.equals(this.getValue(), other.getValue()); } } @Override public int hashCode() { return (this.getKey() == null ? 0 : this.getKey().hashCode()) ^ (this.getValue() == null ? 0 : this.getValue().hashCode()); } @Override public String toString() { return "(" + this.getLeft() + ',' + this.getRight() + ')'; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\ImmutablePair.java
1
请完成以下Java代码
public class PaymentDAO extends AbstractPaymentDAO { @Override public BigDecimal getAvailableAmount(@NonNull final PaymentId paymentId) { final BigDecimal amt = DB.getSQLValueBDEx(ITrx.TRXNAME_ThreadInherited, "SELECT paymentAvailable(?)", paymentId); return amt != null ? amt : BigDecimal.ZERO; } @Override public BigDecimal getAllocatedAmt(final I_C_Payment payment) { final PaymentId paymentId = PaymentId.ofRepoId(payment.getC_Payment_ID()); return getAllocatedAmt(paymentId); } @Override public BigDecimal getAllocatedAmt(final PaymentId paymentId) { final BigDecimal amt = DB.getSQLValueBDEx(ITrx.TRXNAME_ThreadInherited, "SELECT paymentAllocatedAmt(?)", paymentId); return amt != null ? amt : BigDecimal.ZERO; } @Override public void updateDiscountAndPayment(final I_C_Payment payment, final int c_Invoice_ID, final I_C_DocType c_DocType) { final String sql = "SELECT C_BPartner_ID,C_Currency_ID," // 1..2 + " invoiceOpen(C_Invoice_ID, ?)," // 3 #1 + " invoiceDiscount(C_Invoice_ID,?,?), IsSOTrx " // 4..5 #2/3 + "FROM C_Invoice WHERE C_Invoice_ID=?"; // #4 PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, c_Invoice_ID); pstmt.setTimestamp(2, payment.getDateTrx()); pstmt.setInt(3, c_Invoice_ID); pstmt.setInt(4, c_Invoice_ID); rs = pstmt.executeQuery(); if (rs.next()) { final int bpartnerId = rs.getInt(1); payment.setC_BPartner_ID(bpartnerId); // Set Invoice Currency final int C_Currency_ID = rs.getInt(2);
payment.setC_Currency_ID(C_Currency_ID); // BigDecimal InvoiceOpen = rs.getBigDecimal(3); // Set Invoice // OPen Amount if (InvoiceOpen == null) { InvoiceOpen = BigDecimal.ZERO; } BigDecimal DiscountAmt = rs.getBigDecimal(4); // Set Discount // Amt if (DiscountAmt == null) { DiscountAmt = BigDecimal.ZERO; } BigDecimal payAmt = InvoiceOpen.subtract(DiscountAmt); if (X_C_DocType.DOCBASETYPE_APCreditMemo.equals(c_DocType.getDocBaseType()) || X_C_DocType.DOCBASETYPE_ARCreditMemo.equals(c_DocType.getDocBaseType())) { if (payAmt.signum() < 0) { payAmt = payAmt.abs(); } } payment.setPayAmt(payAmt); payment.setDiscountAmt(DiscountAmt); } } catch (final SQLException e) { throw new DBException(e, sql); } finally { DB.close(rs, pstmt); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\api\impl\PaymentDAO.java
1
请在Spring Boot框架中完成以下Java代码
public String getDISCREPANCYCODE() { return discrepancycode; } /** * Sets the value of the discrepancycode property. * * @param value * allowed object is * {@link String } * */ public void setDISCREPANCYCODE(String value) { this.discrepancycode = value; } /** * Gets the value of the discrepancyreason property. * * @return * possible object is * {@link String } * */ public String getDISCREPANCYREASON() { return discrepancyreason; } /** * Sets the value of the discrepancyreason property. * * @param value * allowed object is * {@link String } * */ public void setDISCREPANCYREASON(String value) { this.discrepancyreason = value; } /** * Gets the value of the discrepancydesc property. * * @return * possible object is * {@link String } * */ public String getDISCREPANCYDESC() { return discrepancydesc; } /** * Sets the value of the discrepancydesc property. * * @param value * allowed object is * {@link String } * */ public void setDISCREPANCYDESC(String value) { this.discrepancydesc = value; } /**
* Gets the value of the discrepancydate1 property. * * @return * possible object is * {@link String } * */ public String getDISCREPANCYDATE1() { return discrepancydate1; } /** * Sets the value of the discrepancydate1 property. * * @param value * allowed object is * {@link String } * */ public void setDISCREPANCYDATE1(String value) { this.discrepancydate1 = value; } /** * Gets the value of the discrepancydate2 property. * * @return * possible object is * {@link String } * */ public String getDISCREPANCYDATE2() { return discrepancydate2; } /** * Sets the value of the discrepancydate2 property. * * @param value * allowed object is * {@link String } * */ public void setDISCREPANCYDATE2(String value) { this.discrepancydate2 = 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\DQVAR1.java
2
请完成以下Java代码
public void setTransientVariable(String key, Object value) { this.transientVariables.put(key, value); } /** * Convenience method which returns <code>this</code> for method concatenation. * Same as {@link #setTransientVariable(String, Object)} */ public MapDelegateVariableContainer addTransientVariable(String key, Object variable) { setTransientVariable(key, variable); return this; } /** * Clears all transient variables of this variable container (not touching the delegate). */ public void clearTransientVariables() { this.transientVariables.clear(); } /** * @return all available transient variables */ public Map<String, Object> getTransientVariables(){ return this.transientVariables; } public MapDelegateVariableContainer removeTransientVariable(String key){ this.transientVariables.remove(key); return this; }
@Override public String getTenantId() { return this.delegate.getTenantId(); } @Override public Set<String> getVariableNames() { if (delegate == null || delegate == VariableContainer.empty()) { return this.transientVariables.keySet(); } if (transientVariables.isEmpty()) { return delegate.getVariableNames(); } Set<String> keys = new LinkedHashSet<>(delegate.getVariableNames()); keys.addAll(transientVariables.keySet()); return keys; } @Override public String toString() { return new StringJoiner(", ", getClass().getSimpleName() + "[", "]") .add("delegate=" + delegate) .add("tenantId=" + getTenantId()) .toString(); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\variable\MapDelegateVariableContainer.java
1
请完成以下Java代码
public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public String getEditorSourceValueId() { return editorSourceValueId; } public void setEditorSourceValueId(String editorSourceValueId) { this.editorSourceValueId = editorSourceValueId; } public String getEditorSourceExtraValueId() { return editorSourceExtraValueId; } public void setEditorSourceExtraValueId(String editorSourceExtraValueId) { this.editorSourceExtraValueId = editorSourceExtraValueId;
} public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public boolean hasEditorSource() { return this.editorSourceValueId != null; } public boolean hasEditorSourceExtra() { return this.editorSourceExtraValueId != null; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ModelEntityImpl.java
1
请完成以下Java代码
private void publishRfqClose(final I_C_RfQResponse rfqResponse) { for (final I_C_RfQResponseLine rfqResponseLine : pmmRfqDAO.retrieveResponseLines(rfqResponse)) { publishRfQClose(rfqResponseLine); } } private void publishRfQClose(final I_C_RfQResponseLine rfqResponseLine) { // Create and collect the RfQ close event final boolean winnerKnown = true; final SyncRfQCloseEvent syncRfQCloseEvent = syncObjectsFactory.createSyncRfQCloseEvent(rfqResponseLine, winnerKnown); if (syncRfQCloseEvent != null) { syncRfQCloseEvents.add(syncRfQCloseEvent); syncProductSupplies.addAll(syncRfQCloseEvent.getPlannedSupplies()); } } private void pushToWebUI() { trxManager.getTrxListenerManagerOrAutoCommit(ITrx.TRXNAME_ThreadInherited) .newEventListener(TrxEventTiming.AFTER_COMMIT) .invokeMethodJustOnce(false) // invoke the handling method on *every* commit, because that's how it was and I can't check now if it's really needed .registerHandlingMethod(innerTrx -> pushToWebUINow()); } private void pushToWebUINow() { // // Push new RfQs final List<SyncRfQ> syncRfQsCopy = copyAndClear(this.syncRfQs); if (!syncRfQsCopy.isEmpty()) { webuiPush.pushRfQs(syncRfQsCopy); } // Push close events { final List<SyncRfQCloseEvent> syncRfQCloseEventsCopy = copyAndClear(this.syncRfQCloseEvents); if (!syncRfQCloseEventsCopy.isEmpty()) { webuiPush.pushRfQCloseEvents(syncRfQCloseEventsCopy); }
// Internally push the planned product supplies, to create the PMM_PurchaseCandidates serverSyncBL.reportProductSupplies(PutProductSuppliesRequest.of(syncProductSupplies)); } } private static <T> List<T> copyAndClear(final List<T> list) { if (list == null || list.isEmpty()) { return ImmutableList.of(); } final List<T> listCopy = ImmutableList.copyOf(list); list.clear(); return listCopy; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\rfq\PMMWebuiRfQResponsePublisherInstance.java
1
请完成以下Java代码
public ScriptTaskBuilder builder() { return new ScriptTaskBuilder((BpmnModelInstance) modelInstance, this); } public String getScriptFormat() { return scriptFormatAttribute.getValue(this); } public void setScriptFormat(String scriptFormat) { scriptFormatAttribute.setValue(this, scriptFormat); } public Script getScript() { return scriptChild.getChild(this); } public void setScript(Script script) { scriptChild.setChild(this, script); } /** camunda extensions */
public String getCamundaResultVariable() { return camundaResultVariableAttribute.getValue(this); } public void setCamundaResultVariable(String camundaResultVariable) { camundaResultVariableAttribute.setValue(this, camundaResultVariable); } public String getCamundaResource() { return camundaResourceAttribute.getValue(this); } public void setCamundaResource(String camundaResource) { camundaResourceAttribute.setValue(this, camundaResource); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ScriptTaskImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class PackagingInformationType { @XmlElement(name = "TypeOfPackaging", required = true) protected String typeOfPackaging; @XmlElement(name = "NVE", required = true) protected String nve; @XmlElement(name = "GrossVolume", required = true) protected UnitType grossVolume; @XmlElement(name = "GrossWeight", required = true) protected UnitType grossWeight; /** * Gets the value of the typeOfPackaging property. * * @return * possible object is * {@link String } * */ public String getTypeOfPackaging() { return typeOfPackaging; } /** * Sets the value of the typeOfPackaging property. * * @param value * allowed object is * {@link String } * */ public void setTypeOfPackaging(String value) { this.typeOfPackaging = value; } /** * Gets the value of the nve property. * * @return * possible object is * {@link String } * */ public String getNVE() { return nve; } /** * Sets the value of the nve property. * * @param value * allowed object is * {@link String } * */ public void setNVE(String value) { this.nve = value; } /** * Gets the value of the grossVolume property. * * @return * possible object is
* {@link UnitType } * */ public UnitType getGrossVolume() { return grossVolume; } /** * Sets the value of the grossVolume property. * * @param value * allowed object is * {@link UnitType } * */ public void setGrossVolume(UnitType value) { this.grossVolume = value; } /** * Gets the value of the grossWeight property. * * @return * possible object is * {@link UnitType } * */ public UnitType getGrossWeight() { return grossWeight; } /** * Sets the value of the grossWeight property. * * @param value * allowed object is * {@link UnitType } * */ public void setGrossWeight(UnitType value) { this.grossWeight = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\PackagingInformationType.java
2
请在Spring Boot框架中完成以下Java代码
public void onStart(Observation.Context context) { log.info("Starting context " + toString(context)); } @Override public void onError(Observation.Context context) { log.info("Error for context " + toString(context)); } @Override public void onEvent(Observation.Event event, Observation.Context context) { log.info("Event for context " + toString(context) + " [" + toString(event) + "]"); } @Override
public void onScopeOpened(Observation.Context context) { log.info("Scope opened for context " + toString(context)); } @Override public void onScopeClosed(Observation.Context context) { log.info("Scope closed for context " + toString(context)); } @Override public void onStop(Observation.Context context) { log.info("Stopping context " + toString(context)); } }
repos\tutorials-master\spring-boot-modules\spring-boot-3-observation\src\main\java\com\baeldung\samples\config\SimpleLoggingHandler.java
2