instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void stringTopicListener(String str) { LOGGER.info("Received String message: {}", str); } @Bean DeadLetterPolicy deadLetterPolicy() { return DeadLetterPolicy.builder() .maxRedeliverCount(10) .deadLetterTopic(USER_DEAD_LETTER_TOPIC) .build(); } @PulsarListener( subscriptionName = "user-topic-subscription", topics = USER_TOPIC, subscriptionType = SubscriptionType.Shared, schemaType = SchemaType.JSON,
ackMode = AckMode.RECORD, deadLetterPolicy = "deadLetterPolicy", properties = {"ackTimeout=60s"} ) public void userTopicListener(User user) { LOGGER.info("Received user object with email: {}", user.getEmail()); } @PulsarListener( subscriptionName = "dead-letter-topic-subscription", topics = USER_DEAD_LETTER_TOPIC, subscriptionType = SubscriptionType.Shared ) public void userDlqTopicListener(User user) { LOGGER.info("Received user object in user-DLQ with email: {}", user.getEmail()); } }
repos\tutorials-master\spring-pulsar\src\main\java\com\baeldung\springpulsar\PulsarConsumer.java
1
请完成以下Java代码
public String getName() { return this.name; } @Override public int compareTo(User user) { return this.getName().compareTo(user.getName()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof User)) { return false; } User that = (User) obj; return this.getName().equals(that.getName()); }
@Override public int hashCode() { int hashValue = 17; hashValue = 37 * hashValue + getName().hashCode(); return hashValue; } @Override public String toString() { return getName(); } } }
repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\security\TestSecurityManager.java
1
请完成以下Java代码
public boolean isEmpty() {return set.isEmpty();} public WorkflowLaunchersFacetGroupList toWorkflowLaunchersFacetGroupList(@Nullable ImmutableSet<WorkflowLaunchersFacetId> activeFacetIds) { if (isEmpty()) { return WorkflowLaunchersFacetGroupList.EMPTY; } final HashMap<WorkflowLaunchersFacetGroupId, WorkflowLaunchersFacetGroupBuilder> groupBuilders = new HashMap<>(); for (final DistributionFacet distributionFacet : set) { final WorkflowLaunchersFacet facet = distributionFacet.toWorkflowLaunchersFacet(activeFacetIds); groupBuilders.computeIfAbsent(facet.getGroupId(), k -> distributionFacet.newWorkflowLaunchersFacetGroupBuilder()) .facet(facet); } final ImmutableList<WorkflowLaunchersFacetGroup> groups = groupBuilders.values()
.stream() .map(WorkflowLaunchersFacetGroupBuilder::build) .sorted(orderByGroupSeqNo()) .collect(ImmutableList.toImmutableList()); return WorkflowLaunchersFacetGroupList.ofList(groups); } private static Comparator<? super WorkflowLaunchersFacetGroup> orderByGroupSeqNo() { return Comparator.comparingInt(DistributionFacetsCollection::getGroupSeqNo); } private static int getGroupSeqNo(final WorkflowLaunchersFacetGroup group) { return DistributionFacetGroupType.ofWorkflowLaunchersFacetGroupId(group.getId()).getSeqNo(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\facets\DistributionFacetsCollection.java
1
请完成以下Java代码
public static ProductId toProductId(@NonNull final LookupValue lookupValue) { return lookupValue.getIdAs(ProductId::ofRepoId); } public static ProductAndAttributes toProductAndAttributes(@NonNull final LookupValue lookupValue) { final ProductId productId = lookupValue.getIdAs(ProductId::ofRepoId); final Map<Object, Object> valuesByAttributeIdMap = lookupValue.getAttribute(ATTRIBUTE_ASI); final ImmutableAttributeSet attributes = ImmutableAttributeSet.ofValuesByAttributeIdMap(valuesByAttributeIdMap); return ProductAndAttributes.builder() .productId(productId) .attributes(attributes) .build(); } private boolean isFullTextSearchEnabled() { final boolean disabled = Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_DisableFullTextSearch, false); return !disabled; } @Value @Builder(toBuilder = true) public static class ProductAndAttributes { @NonNull ProductId productId; @Default @NonNull ImmutableAttributeSet attributes = ImmutableAttributeSet.EMPTY;
} private interface I_M_Product_Lookup_V { String Table_Name = "M_Product_Lookup_V"; String COLUMNNAME_AD_Org_ID = "AD_Org_ID"; String COLUMNNAME_IsActive = "IsActive"; String COLUMNNAME_M_Product_ID = "M_Product_ID"; String COLUMNNAME_Value = "Value"; String COLUMNNAME_Name = "Name"; String COLUMNNAME_UPC = "UPC"; String COLUMNNAME_BPartnerProductNo = "BPartnerProductNo"; String COLUMNNAME_BPartnerProductName = "BPartnerProductName"; String COLUMNNAME_C_BPartner_ID = "C_BPartner_ID"; String COLUMNNAME_Discontinued = "Discontinued"; String COLUMNNAME_DiscontinuedFrom = "DiscontinuedFrom"; String COLUMNNAME_IsBOM = "IsBOM"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\ProductLookupDescriptor.java
1
请在Spring Boot框架中完成以下Java代码
public static CamundaJacksonFormatConfiguratorJdk8 spinDataFormatConfiguratorJdk8() { return new CamundaJacksonFormatConfiguratorJdk8(); } } @ConditionalOnClass(SpinProcessEnginePlugin.class) @Configuration static class SpinConfiguration { @Bean @ConditionalOnMissingBean(name = "spinProcessEnginePlugin") public static ProcessEnginePlugin spinProcessEnginePlugin() { return new SpringBootSpinProcessEnginePlugin(); } } @ConditionalOnClass(ConnectProcessEnginePlugin.class) @Configuration static class ConnectConfiguration { @Bean @ConditionalOnMissingBean(name = "connectProcessEnginePlugin") public static ProcessEnginePlugin connectProcessEnginePlugin() { return new ConnectProcessEnginePlugin(); } }
/* Provide option to apply application context classloader switch when Spring Spring Developer tools are enabled For more details: https://jira.camunda.com/browse/CAM-9043 */ @ConditionalOnInitializedRestarter @Configuration static class InitializedRestarterConfiguration { @Bean @ConditionalOnMissingBean(name = "applicationContextClassloaderSwitchPlugin") public ApplicationContextClassloaderSwitchPlugin applicationContextClassloaderSwitchPlugin() { return new ApplicationContextClassloaderSwitchPlugin(); } } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\CamundaBpmPluginConfiguration.java
2
请完成以下Java代码
public void setSource (final @Nullable String Source) { set_ValueNoCheck (COLUMNNAME_Source, Source); } @Override public String getSource() { return get_ValueAsString(COLUMNNAME_Source); } @Override public void setUserElementString1 (final @Nullable String UserElementString1) { set_Value (COLUMNNAME_UserElementString1, UserElementString1); } @Override public String getUserElementString1() { return get_ValueAsString(COLUMNNAME_UserElementString1); } @Override public void setUserElementString2 (final @Nullable String UserElementString2) { set_Value (COLUMNNAME_UserElementString2, UserElementString2); } @Override public String getUserElementString2() { return get_ValueAsString(COLUMNNAME_UserElementString2); } @Override public void setUserElementString3 (final @Nullable String UserElementString3) { set_Value (COLUMNNAME_UserElementString3, UserElementString3); } @Override public String getUserElementString3() { return get_ValueAsString(COLUMNNAME_UserElementString3); } @Override public void setUserElementString4 (final @Nullable String UserElementString4) { set_Value (COLUMNNAME_UserElementString4, UserElementString4); } @Override public String getUserElementString4() { return get_ValueAsString(COLUMNNAME_UserElementString4); }
@Override public void setUserElementString5 (final @Nullable String UserElementString5) { set_Value (COLUMNNAME_UserElementString5, UserElementString5); } @Override public String getUserElementString5() { return get_ValueAsString(COLUMNNAME_UserElementString5); } @Override public void setUserElementString6 (final @Nullable String UserElementString6) { set_Value (COLUMNNAME_UserElementString6, UserElementString6); } @Override public String getUserElementString6() { return get_ValueAsString(COLUMNNAME_UserElementString6); } @Override public void setUserElementString7 (final @Nullable String UserElementString7) { set_Value (COLUMNNAME_UserElementString7, UserElementString7); } @Override public String getUserElementString7() { return get_ValueAsString(COLUMNNAME_UserElementString7); } @Override public void setVendor_ID (final int Vendor_ID) { if (Vendor_ID < 1) set_Value (COLUMNNAME_Vendor_ID, null); else set_Value (COLUMNNAME_Vendor_ID, Vendor_ID); } @Override public int getVendor_ID() { return get_ValueAsInt(COLUMNNAME_Vendor_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java-gen\de\metas\purchasecandidate\model\X_C_PurchaseCandidate.java
1
请完成以下Java代码
public String getId() { return id; } @Override public void setId(String id) { this.id = id; } @Override public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } @Override public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } @Override public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } @Override public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public String getFullMessage() { return fullMessage; } public void setFullMessage(String fullMessage) { this.fullMessage = fullMessage; } @Override public String getAction() { return action; } public void setAction(String action) { this.action = action; } public String getTenantId() {
return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } @Override public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } public String toEventMessage(String message) { String eventMessage = message.replaceAll("\\s+", " "); if (eventMessage.length() > 163) { eventMessage = eventMessage.substring(0, 160) + "..."; } return eventMessage; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", type=" + type + ", userId=" + userId + ", time=" + time + ", taskId=" + taskId + ", processInstanceId=" + processInstanceId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", revision= "+ revision + ", removalTime=" + removalTime + ", action=" + action + ", message=" + message + ", fullMessage=" + fullMessage + ", tenantId=" + tenantId + "]"; } @Override public void setRevision(int revision) { this.revision = revision; } @Override public int getRevision() { return revision; } @Override public int getRevisionNext() { return revision + 1; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CommentEntity.java
1
请完成以下Java代码
public int getC_BPartner_Contact_QuickInput_Attributes_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_Contact_QuickInput_Attributes_ID); } @Override public org.compiere.model.I_C_BPartner_Contact_QuickInput getC_BPartner_Contact_QuickInput() { return get_ValueAsPO(COLUMNNAME_C_BPartner_Contact_QuickInput_ID, org.compiere.model.I_C_BPartner_Contact_QuickInput.class); } @Override public void setC_BPartner_Contact_QuickInput(final org.compiere.model.I_C_BPartner_Contact_QuickInput C_BPartner_Contact_QuickInput) { set_ValueFromPO(COLUMNNAME_C_BPartner_Contact_QuickInput_ID, org.compiere.model.I_C_BPartner_Contact_QuickInput.class, C_BPartner_Contact_QuickInput); }
@Override public void setC_BPartner_Contact_QuickInput_ID (final int C_BPartner_Contact_QuickInput_ID) { if (C_BPartner_Contact_QuickInput_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_Contact_QuickInput_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_Contact_QuickInput_ID, C_BPartner_Contact_QuickInput_ID); } @Override public int getC_BPartner_Contact_QuickInput_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_Contact_QuickInput_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Contact_QuickInput_Attributes.java
1
请完成以下Java代码
public CostSegmentAndElement extractOutboundCostSegmentAndElement(final MoveCostsRequest request) { return extractCommonCostSegmentAndElement(request) .orgId(request.getOutboundOrgId()) .build(); } @Override public CostSegmentAndElement extractInboundCostSegmentAndElement(final MoveCostsRequest request) { return extractCommonCostSegmentAndElement(request) .orgId(request.getInboundOrgId()) .build(); } private CostSegmentAndElementBuilder extractCommonCostSegmentAndElement(final MoveCostsRequest request) { final AcctSchema acctSchema = getAcctSchemaById(request.getAcctSchemaId()); final CostingLevel costingLevel = productCostingBL.getCostingLevel(request.getProductId(), acctSchema); final CostTypeId costTypeId = acctSchema.getCosting().getCostTypeId(); return CostSegmentAndElement.builder() .costingLevel(costingLevel) .acctSchemaId(request.getAcctSchemaId()) .costTypeId(costTypeId) .clientId(request.getClientId()) // .orgId(null) // to be set by caller .productId(request.getProductId()) .attributeSetInstanceId(request.getAttributeSetInstanceId())
.costElementId(request.getCostElementId()); } @Override public void delete(final CostDetail costDetail) { costDetailsRepo.delete(costDetail); } @Override public Stream<CostDetail> stream(@NonNull final CostDetailQuery query) { return costDetailsRepo.stream(query); } @Override public Optional<CostDetail> firstOnly(@NonNull final CostDetailQuery query) { return costDetailsRepo.firstOnly(query); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\impl\CostDetailService.java
1
请完成以下Java代码
public void setM_PricingSystem_ID(int M_PricingSystem_ID) { throw new NotImplementedException(); } @Override public void setM_PriceList_ID(int M_PriceList_ID) { throw new NotImplementedException(); } /** * Sets a private member variable to the given {@code price}. */ @Override public void setPrice(BigDecimal price) {
this.price = price; } /** * * @return the value that was set via {@link #setPrice(BigDecimal)}. */ public BigDecimal getPrice() { return price; } public I_M_AttributeSetInstance getM_AttributeSetInstance() { return orderLine.getM_AttributeSetInstance(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\PMMPricingAware_C_OrderLine.java
1
请完成以下Java代码
public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public void setResources(Map<String, EngineResource> resources) { this.resources = resources; } @Override public Date getDeploymentTime() { return deploymentTime; } @Override public void setDeploymentTime(Date deploymentTime) { this.deploymentTime = deploymentTime; } @Override public boolean isNew() { return isNew; } @Override public void setNew(boolean isNew) { this.isNew = isNew; } @Override public String getDerivedFrom() { return null;
} @Override public String getDerivedFromRoot() { return null; } @Override public String getEngineVersion() { return null; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "AppDeploymentEntity[id=" + id + ", name=" + name + "]"; } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\persistence\entity\AppDeploymentEntityImpl.java
1
请完成以下Java代码
public void setM_Attribute_ID (final int M_Attribute_ID) { if (M_Attribute_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Attribute_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Attribute_ID, M_Attribute_ID); } @Override public int getM_Attribute_ID() { return get_ValueAsInt(COLUMNNAME_M_Attribute_ID); } @Override public void setM_HU_ID (final int M_HU_ID) { if (M_HU_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_ID, M_HU_ID); } @Override public int getM_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_ID); } @Override public void setPIName (final @Nullable java.lang.String PIName) { set_ValueNoCheck (COLUMNNAME_PIName, PIName); } @Override public java.lang.String getPIName() {
return get_ValueAsString(COLUMNNAME_PIName); } @Override public void setValue (final @Nullable java.lang.String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setValueNumber (final @Nullable BigDecimal ValueNumber) { set_ValueNoCheck (COLUMNNAME_ValueNumber, ValueNumber); } @Override public BigDecimal getValueNumber() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumber); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Instance_Properties_v.java
1
请完成以下Java代码
private void checkIsSameSeller(Map<String, Integer> prodIdCountMap) { // 获取prodcutID集合 Set<String> productIdSet = prodIdCountMap.keySet(); // 构造查询请求 List<ProdQueryReq> prodQueryReqList = buildOrderQueryReq(productIdSet); // 查询 List<ProductEntity> productEntityList = query(prodQueryReqList); // 校验 TODO lamada表达式还要检查 Map<UserEntity, List<ProductEntity>> companyMap = productEntityList.stream().collect(groupingBy(ProductEntity::getCompanyEntity)); if (companyMap.size() > 1) { throw new CommonBizException(ExpCodeEnum.SELLER_DIFFERENT); } } /** * 根据产品ID查询产品列表 * @param prodQueryReqList 产品查询请求 * @return 产品列表 */ private List<ProductEntity> query(List<ProdQueryReq> prodQueryReqList) { List<ProductEntity> productEntityList = Lists.newArrayList(); for (ProdQueryReq prodQueryReq : prodQueryReqList) { ProductEntity productEntity = productService.findProducts(prodQueryReq).getData().get(0); productEntityList.add(productEntity); } return productEntityList; } /**
* 构造查询请求 * @param productIdSet 产品ID集合 * @return 查询请求列表 */ private List<ProdQueryReq> buildOrderQueryReq(Set<String> productIdSet) { List<ProdQueryReq> prodQueryReqList = Lists.newArrayList(); for (String productId : productIdSet) { ProdQueryReq prodQueryReq = new ProdQueryReq(); prodQueryReq.setId(productId); prodQueryReqList.add(prodQueryReq); } return prodQueryReqList; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\component\createorder\CreateOrderComponent.java
1
请完成以下Java代码
public class C_Location_Postal_Validate extends JavaProcess { private int cnt_all = 0; private int cnt_ok = 0; private int cnt_err = 0; @Override protected void prepare() { } @Override protected String doIt() throws Exception { String whereClause = I_C_Location.COLUMNNAME_IsPostalValidated + "=?"; Iterator<I_C_Location> it = new Query(getCtx(), I_C_Location.Table_Name, whereClause, null) .setParameters(false) .setRequiredAccess(Access.WRITE) .iterate(I_C_Location.class); while (it.hasNext()) { cnt_all++; validate(it.next()); if (cnt_all % 100 == 0) { log.info("Progress: OK/Error/Total = " + cnt_ok + "/" + cnt_err + "/" + cnt_all); } }
return "@Updated@ OK/Error/Total = " + cnt_ok + "/" + cnt_err + "/" + cnt_all; } private void validate(I_C_Location location) { try { Services.get(ILocationBL.class).validatePostal(location); InterfaceWrapperHelper.save(location); cnt_ok++; } catch (Exception e) { addLog("Error on " + location + ": " + e.getLocalizedMessage()); cnt_err++; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\process\C_Location_Postal_Validate.java
1
请在Spring Boot框架中完成以下Java代码
public String getName() { return name; } public String getNameLike() { return nameLike; } public String getDeploymentId() { return deploymentId; } public String getKey() { return key; } public String getKeyLike() { return keyLike; } public String getResourceName() { return resourceName;
} public String getResourceNameLike() { return resourceNameLike; } public Integer getVersion() { return version; } public boolean isLatest() { return latest; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\repository\CaseDefinitionQueryImpl.java
2
请在Spring Boot框架中完成以下Java代码
public Quantity getQtyEnteredInStockUOM(@NonNull final I_C_InvoiceLine invoiceLine) { final Quantity qtyEntered = Quantitys.of(invoiceLine.getQtyEntered(), UomId.ofRepoId(invoiceLine.getC_UOM_ID())); final UomId stockUOMId = productBL.getStockUOMId(invoiceLine.getM_Product_ID()); return Quantitys.of( qtyEntered, UOMConversionContext.of(ProductId.ofRepoId(invoiceLine.getM_Product_ID())), stockUOMId); } @NonNull @Override public Quantity getQtyInvoicedStockUOM(@NonNull final org.compiere.model.I_C_InvoiceLine invoiceLine) { final BigDecimal qtyInvoiced = invoiceLine.getQtyInvoiced();
final I_C_UOM stockUOM = productBL.getStockUOM(invoiceLine.getM_Product_ID()); return Quantity.of(qtyInvoiced, stockUOM); } @Nullable private CountryId getCountryIdOrNull(@NonNull final I_C_Order order) { final BPartnerLocationAndCaptureId bpartnerAndLocation = BPartnerLocationAndCaptureId .ofRepoId(order.getC_BPartner_ID(), order.getC_BPartner_Location_ID(), order.getC_BPartner_Location_Value_ID()); Check.assumeNotNull(bpartnerAndLocation, "Order {} has no C_BPartner_ID", order); return partnerBL.getCountryId(bpartnerAndLocation); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\service\impl\InvoiceLineBL.java
2
请完成以下Java代码
protected void updateFunctionResolver() { if (this.functionDelegates != null) { this.functionResolver = this.functionResolverFactory.create(this.functionDelegates); } else { this.functionResolver = null; } } @Override public List<FlowableAstFunctionCreator> getAstFunctionCreators() { return astFunctionCreators; } @Override public void setAstFunctionCreators(List<FlowableAstFunctionCreator> astFunctionCreators) { this.astFunctionCreators = astFunctionCreators; if (expressionFactory instanceof FlowableExpressionFactory) { ((FlowableExpressionFactory) expressionFactory).setAstFunctionCreators(astFunctionCreators); } } @Override public FlowableFunctionResolverFactory getFunctionResolverFactory() { return functionResolverFactory; } @Override public void setFunctionResolverFactory(FlowableFunctionResolverFactory functionResolverFactory) { this.functionResolverFactory = functionResolverFactory; updateFunctionResolver(); } public DeploymentCache<Expression> getExpressionCache() { return expressionCache; } public void setExpressionCache(DeploymentCache<Expression> expressionCache) { this.expressionCache = expressionCache; } public int getExpressionTextLengthCacheLimit() { return expressionTextLengthCacheLimit; } public void setExpressionTextLengthCacheLimit(int expressionTextLengthCacheLimit) { this.expressionTextLengthCacheLimit = expressionTextLengthCacheLimit; } public void addPreDefaultResolver(ELResolver elResolver) { if (this.preDefaultResolvers == null) { this.preDefaultResolvers = new ArrayList<>(); } this.preDefaultResolvers.add(elResolver); } public ELResolver getJsonNodeResolver() { return jsonNodeResolver; } public void setJsonNodeResolver(ELResolver jsonNodeResolver) { // When the bean resolver is modified we need to reset the el resolver
this.staticElResolver = null; this.jsonNodeResolver = jsonNodeResolver; } public void addPostDefaultResolver(ELResolver elResolver) { if (this.postDefaultResolvers == null) { this.postDefaultResolvers = new ArrayList<>(); } this.postDefaultResolvers.add(elResolver); } public void addPreBeanResolver(ELResolver elResolver) { if (this.preBeanResolvers == null) { this.preBeanResolvers = new ArrayList<>(); } this.preBeanResolvers.add(elResolver); } public ELResolver getBeanResolver() { return beanResolver; } public void setBeanResolver(ELResolver beanResolver) { // When the bean resolver is modified we need to reset the el resolver this.staticElResolver = null; this.beanResolver = beanResolver; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\el\DefaultExpressionManager.java
1
请完成以下Java代码
class HeaderKeyValueGenerator implements KeyValueGenerator { private final String header; private final String valueSeparator; HeaderKeyValueGenerator(String header, String valueSeparator) { this.valueSeparator = valueSeparator; if (!StringUtils.hasText(header)) { throw new IllegalArgumentException("The parameter cannot be empty or null"); } this.header = header; } @Override public String getKeyValue(ServerHttpRequest request) {
HttpHeaders headers = request.getHeaders(); if (headers.get(header) != null) { StringBuilder keyVaryHeaders = new StringBuilder(); keyVaryHeaders.append(header) .append("=") .append(getHeaderValues(headers).sorted().collect(Collectors.joining(valueSeparator))); return keyVaryHeaders.toString(); } return null; } private Stream<String> getHeaderValues(HttpHeaders headers) { List<String> value = headers.get(header); return value == null ? Stream.empty() : value.stream(); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\keygenerator\HeaderKeyValueGenerator.java
1
请完成以下Java代码
public class CreditLine2 { @XmlElement(name = "Incl") protected boolean incl; @XmlElement(name = "Amt") protected ActiveOrHistoricCurrencyAndAmount amt; /** * Gets the value of the incl property. * */ public boolean isIncl() { return incl; } /** * Sets the value of the incl property. * */ public void setIncl(boolean value) { this.incl = value; } /** * Gets the value of the amt property. * * @return * possible object is * {@link ActiveOrHistoricCurrencyAndAmount }
* */ public ActiveOrHistoricCurrencyAndAmount getAmt() { return amt; } /** * Sets the value of the amt property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setAmt(ActiveOrHistoricCurrencyAndAmount value) { this.amt = 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_02\CreditLine2.java
1
请完成以下Java代码
private void assertNotAny() { if (isAny()) { throw Check.mkEx("Expected predicate to not be ANY"); } } public @NonNull Set<T> toSet() { assertNotAny(); return onlyValues; // we can return it as is because it's already readonly } @SafeVarargs public final InSetPredicate<T> intersectWith(@NonNull final T... onlyValues) { return intersectWith(only(onlyValues)); } public InSetPredicate<T> intersectWith(@NonNull final Set<T> onlyValues) { return intersectWith(only(onlyValues)); } public InSetPredicate<T> intersectWith(@NonNull final InSetPredicate<T> other) { if (isNone() || other.isNone()) { return none(); } if (isAny()) { return other; } else if (other.isAny()) { return this; } return only(Sets.intersection(this.toSet(), other.toSet()));
} public interface CaseConsumer<T> { void anyValue(); void noValue(); void onlyValues(Set<T> onlyValues); } public void apply(@NonNull final CaseConsumer<T> caseConsumer) { switch (mode) { case ANY: caseConsumer.anyValue(); break; case NONE: caseConsumer.noValue(); break; case ONLY: caseConsumer.onlyValues(onlyValues); break; default: throw new IllegalStateException("Unknown mode: " + mode); // shall not happen } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\InSetPredicate.java
1
请完成以下Java代码
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 DeploymentQuery deploymentAfter(Date after) { ensureNotNull("deploymentAfter", after); this.deploymentAfter = after; return this; } public DeploymentQuery tenantIdIn(String... tenantIds) { ensureNotNull("tenantIds", (Object[]) tenantIds); this.tenantIds = tenantIds; isTenantIdSet = true; return this; } public DeploymentQuery withoutTenantId() { isTenantIdSet = true; this.tenantIds = null; return this; } public DeploymentQuery includeDeploymentsWithoutTenantId() { this.includeDeploymentsWithoutTenantId = true; return this; } @Override protected boolean hasExcludingConditions() { return super.hasExcludingConditions() || CompareUtil.areNotInAscendingOrder(deploymentAfter, deploymentBefore); } //sorting //////////////////////////////////////////////////////// public DeploymentQuery orderByDeploymentId() { return orderBy(DeploymentQueryProperty.DEPLOYMENT_ID); } public DeploymentQuery orderByDeploymenTime() { return orderBy(DeploymentQueryProperty.DEPLOY_TIME); } public DeploymentQuery orderByDeploymentTime() { return orderBy(DeploymentQueryProperty.DEPLOY_TIME); } public DeploymentQuery orderByDeploymentName() { return orderBy(DeploymentQueryProperty.DEPLOYMENT_NAME); } public DeploymentQuery orderByTenantId() { return orderBy(DeploymentQueryProperty.TENANT_ID); } //results //////////////////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getDeploymentManager() .findDeploymentCountByQueryCriteria(this); } @Override public List<Deployment> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getDeploymentManager()
.findDeploymentsByQueryCriteria(this, page); } //getters //////////////////////////////////////////////////////// public String getDeploymentId() { return deploymentId; } public String getName() { return name; } public String getNameLike() { return nameLike; } public boolean isSourceQueryParamEnabled() { return sourceQueryParamEnabled; } public String getSource() { return source; } public Date getDeploymentBefore() { return deploymentBefore; } public Date getDeploymentAfter() { return deploymentAfter; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\DeploymentQueryImpl.java
1
请完成以下Java代码
public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Max. Value. @param ValueMax Maximum Value for a field */ public void setValueMax (String ValueMax) { set_Value (COLUMNNAME_ValueMax, ValueMax); } /** Get Max. Value.
@return Maximum Value for a field */ public String getValueMax () { return (String)get_Value(COLUMNNAME_ValueMax); } /** Set Min. Value. @param ValueMin Minimum Value for a field */ public void setValueMin (String ValueMin) { set_Value (COLUMNNAME_ValueMin, ValueMin); } /** Get Min. Value. @return Minimum Value for a field */ public String getValueMin () { return (String)get_Value(COLUMNNAME_ValueMin); } /** Set Value Format. @param VFormat Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09" */ public void setVFormat (String VFormat) { set_Value (COLUMNNAME_VFormat, VFormat); } /** Get Value Format. @return Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09" */ public String getVFormat () { return (String)get_Value(COLUMNNAME_VFormat); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attribute.java
1
请在Spring Boot框架中完成以下Java代码
public DefaultSpringSecurityContextSource getObject() throws Exception { if (!unboundIdPresent) { throw new IllegalStateException("Embedded LDAP server is not provided"); } this.container = getContainer(); this.port = this.container.getPort(); DefaultSpringSecurityContextSource contextSourceFromProviderUrl = new DefaultSpringSecurityContextSource( "ldap://127.0.0.1:" + this.port + "/" + this.root); if (this.managerDn != null) { contextSourceFromProviderUrl.setUserDn(this.managerDn); if (this.managerPassword == null) { throw new IllegalStateException("managerPassword is required if managerDn is supplied"); } contextSourceFromProviderUrl.setPassword(this.managerPassword); } contextSourceFromProviderUrl.afterPropertiesSet(); return contextSourceFromProviderUrl; } @Override public Class<?> getObjectType() { return DefaultSpringSecurityContextSource.class; } @Override public void destroy() { if (this.container instanceof Lifecycle) { ((Lifecycle) this.container).stop(); } } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = applicationContext; }
private EmbeddedLdapServerContainer getContainer() { if (!unboundIdPresent) { throw new IllegalStateException("Embedded LDAP server is not provided"); } UnboundIdContainer unboundIdContainer = new UnboundIdContainer(this.root, this.ldif); unboundIdContainer.setApplicationContext(this.context); unboundIdContainer.setPort(getEmbeddedServerPort()); unboundIdContainer.afterPropertiesSet(); return unboundIdContainer; } private int getEmbeddedServerPort() { if (this.port == null) { this.port = getDefaultEmbeddedServerPort(); } return this.port; } private int getDefaultEmbeddedServerPort() { try (ServerSocket serverSocket = new ServerSocket(DEFAULT_PORT)) { return serverSocket.getLocalPort(); } catch (IOException ex) { return RANDOM_PORT; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\ldap\EmbeddedLdapServerContextSourceFactoryBean.java
2
请在Spring Boot框架中完成以下Java代码
public void initEntityManagers() { if (batchEntityManager == null) { batchEntityManager = new BatchEntityManagerImpl(this, batchDataManager); } if (batchPartEntityManager == null) { batchPartEntityManager = new BatchPartEntityManagerImpl(this, batchPartDataManager); } } // getters and setters // ////////////////////////////////////////////////////// public BatchServiceConfiguration getIdentityLinkServiceConfiguration() { return this; } public BatchService getBatchService() { return batchService; } public BatchServiceConfiguration setBatchService(BatchService batchService) { this.batchService = batchService; return this; } public BatchDataManager getBatchDataManager() { return batchDataManager; } public BatchServiceConfiguration setBatchDataManager(BatchDataManager batchDataManager) { this.batchDataManager = batchDataManager; return this; } public BatchPartDataManager getBatchPartDataManager() { return batchPartDataManager; } public BatchServiceConfiguration setBatchPartDataManager(BatchPartDataManager batchPartDataManager) { this.batchPartDataManager = batchPartDataManager; return this; }
public BatchEntityManager getBatchEntityManager() { return batchEntityManager; } public BatchServiceConfiguration setBatchEntityManager(BatchEntityManager batchEntityManager) { this.batchEntityManager = batchEntityManager; return this; } public BatchPartEntityManager getBatchPartEntityManager() { return batchPartEntityManager; } public BatchServiceConfiguration setBatchPartEntityManager(BatchPartEntityManager batchPartEntityManager) { this.batchPartEntityManager = batchPartEntityManager; return this; } @Override public ObjectMapper getObjectMapper() { return objectMapper; } @Override public BatchServiceConfiguration setObjectMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; return this; } }
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\BatchServiceConfiguration.java
2
请完成以下Java代码
public int getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Date getCreatedAt() {
return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } @Override public String toString() { return "Name: " + this.name + "\nEmail: " + this.email; } }
repos\tutorials-master\web-modules\vraptor\src\main\java\com\baeldung\models\User.java
1
请在Spring Boot框架中完成以下Java代码
public class M_InOut { private final BPartnerProductStatsEventSender eventSender; public M_InOut() { eventSender = new BPartnerProductStatsEventSender(); } @DocValidate(timings = ModelValidator.TIMING_AFTER_COMPLETE) public void onComplete(final I_M_InOut inout) { if (isMaterialReturn(inout)) { return; } if (isReversal(inout)) { // this is the reversal completion. no need to fire event because a reversal event will be fired return; } final boolean reversal = false; eventSender.send(createInOutChangedEvent(inout, reversal)); } private boolean isReversal(final I_M_InOut inout) { return inout.getReversal_ID() > 0; } @DocValidate(timings = { ModelValidator.TIMING_AFTER_REVERSECORRECT, ModelValidator.TIMING_AFTER_REVERSEACCRUAL, ModelValidator.TIMING_AFTER_VOID, ModelValidator.TIMING_AFTER_REACTIVATE }) public void onReverse(final I_M_InOut inout) { if (isMaterialReturn(inout)) { return; } final boolean reversal = true; eventSender.send(createInOutChangedEvent(inout, reversal)); } private InOutChangedEvent createInOutChangedEvent(final I_M_InOut inout, final boolean reversal) { return InOutChangedEvent.builder() .bpartnerId(BPartnerId.ofRepoId(inout.getC_BPartner_ID()))
.movementDate(TimeUtil.asInstant(inout.getMovementDate())) .soTrx(SOTrx.ofBoolean(inout.isSOTrx())) .productIds(extractProductIds(inout)) .reversal(reversal) .build(); } private boolean isMaterialReturn(final I_M_InOut inout) { final String movementType = inout.getMovementType(); return Services.get(IInOutBL.class).isReturnMovementType(movementType); } private Set<ProductId> extractProductIds(final I_M_InOut inout) { final IInOutDAO inoutsRepo = Services.get(IInOutDAO.class); return inoutsRepo.retrieveLines(inout) .stream() .map(I_M_InOutLine::getM_Product_ID) .map(ProductId::ofRepoIdOrNull) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\product\stats\interceptor\M_InOut.java
2
请完成以下Java代码
public class Book { private UUID id; private String title; private float price; private String ISBN; @JsonDeserialize(using = CustomDateDeserializer.class) private Date published; private BigDecimal pages; public Book() { } public Book(String title) { this.id = UUID.randomUUID(); this.title = title; } public String getISBN() { return ISBN; } public void setISBN(String ISBN) { this.ISBN = ISBN; } public Date getPublished() { return published; } public void setPublished(Date published) { this.published = published; } public BigDecimal getPages() { return pages; } public void setPages(BigDecimal pages) { this.pages = pages;
} public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } }
repos\tutorials-master\jackson-modules\jackson-core\src\main\java\com\baeldung\jackson\deserialization\jsondeserialize\Book.java
1
请完成以下Java代码
private Charset resolveCharset(LogbackConfigurator config, String val) { return Charset.forName(resolve(config, val)); } private String resolve(LogbackConfigurator config, String val) { try { return OptionHelper.substVars(val, config.getContext()); } catch (ScanException ex) { throw new RuntimeException(ex); } } private static String faint(String value) { return color(value, AnsiStyle.FAINT); } private static String cyan(String value) { return color(value, AnsiColor.CYAN);
} private static String magenta(String value) { return color(value, AnsiColor.MAGENTA); } private static String colorByLevel(String value) { return "%clr(" + value + "){}"; } private static String color(String value, AnsiElement ansiElement) { return "%clr(" + value + "){" + ColorConverter.getName(ansiElement) + "}"; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\logback\DefaultLogbackConfiguration.java
1
请完成以下Java代码
public long getDurationInSec() { return durationInSec; } public void setDurationInSec(long durationInSec) { this.durationInSec = durationInSec; } public List<ParamFlowItem> getParamFlowItemList() { return paramFlowItemList; } public void setParamFlowItemList(List<ParamFlowItem> paramFlowItemList) { this.paramFlowItemList = paramFlowItemList; } public Map<Object, Integer> getHotItems() { return hotItems; } public void setHotItems(Map<Object, Integer> hotItems) { this.hotItems = hotItems; } public boolean isClusterMode() { return clusterMode; } public void setClusterMode(boolean clusterMode) { this.clusterMode = clusterMode; } public ParamFlowClusterConfig getClusterConfig() { return clusterConfig; } public void setClusterConfig(ParamFlowClusterConfig clusterConfig) { this.clusterConfig = clusterConfig; } @Override public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getApp() { return app; } public void setApp(String app) { this.app = app; } @Override public String getIp() { return ip; }
public void setIp(String ip) { this.ip = ip; } @Override public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public String getLimitApp() { return limitApp; } public void setLimitApp(String limitApp) { this.limitApp = limitApp; } public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } @Override public Rule toRule() { ParamFlowRule rule = new ParamFlowRule(); return rule; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\rule\nacos\entity\ParamFlowRuleCorrectEntity.java
1
请完成以下Java代码
protected boolean isPaginationSupported() { return getPageSize() != null; } /** * Return the pageSize. Returns null if pagination is disabled. * * @return the pageSize */ protected Integer getPageSize() { return ldapConfiguration.getPageSize(); } @Override public TenantQuery createTenantQuery() {
return new LdapTenantQuery(getProcessEngineConfiguration().getCommandExecutorTxRequired()); } @Override public TenantQuery createTenantQuery(CommandContext commandContext) { return new LdapTenantQuery(); } @Override public Tenant findTenantById(String id) { // since multi-tenancy is not supported for the LDAP plugin, always return null return null; } }
repos\camunda-bpm-platform-master\engine-plugins\identity-ldap\src\main\java\org\camunda\bpm\identity\impl\ldap\LdapIdentityProviderSession.java
1
请完成以下Java代码
public void setAD_Language (final java.lang.String AD_Language) { set_ValueNoCheck (COLUMNNAME_AD_Language, AD_Language); } @Override public java.lang.String getAD_Language() { return get_ValueAsString(COLUMNNAME_AD_Language); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setIsTranslated (final boolean IsTranslated) { set_Value (COLUMNNAME_IsTranslated, IsTranslated); } @Override public boolean isTranslated() { return get_ValueAsBoolean(COLUMNNAME_IsTranslated); } @Override public org.compiere.model.I_M_Allergen_Trace getM_Allergen_Trace() { return get_ValueAsPO(COLUMNNAME_M_Allergen_Trace_ID, org.compiere.model.I_M_Allergen_Trace.class); } @Override public void setM_Allergen_Trace(final org.compiere.model.I_M_Allergen_Trace M_Allergen_Trace) { set_ValueFromPO(COLUMNNAME_M_Allergen_Trace_ID, org.compiere.model.I_M_Allergen_Trace.class, M_Allergen_Trace); } @Override public void setM_Allergen_Trace_ID (final int M_Allergen_Trace_ID) { if (M_Allergen_Trace_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Allergen_Trace_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Allergen_Trace_ID, M_Allergen_Trace_ID); } @Override public int getM_Allergen_Trace_ID() { return get_ValueAsInt(COLUMNNAME_M_Allergen_Trace_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Allergen_Trace_Trl.java
1
请在Spring Boot框架中完成以下Java代码
public class JwtAuthController { @Autowired AuthenticationManager authenticationManager; @Autowired PasswordEncoder encoder; @Autowired JwtUtils jwtUtils; @Autowired UserRepository userRepository; @PostMapping("/signup") public ResponseEntity<?> registerUser(@RequestBody User signUpRequest, HttpServletRequest request) throws UnsupportedEncodingException { if (userRepository.existsByUsername(signUpRequest.getUsername())) { return ResponseEntity.badRequest() .body("Error: Username is already taken!"); } User user = new User(); user.setUsername(signUpRequest.getUsername()); user.setPassword(encoder.encode(signUpRequest.getPassword())); userRepository.save(user); return ResponseEntity.ok(user); } @PostMapping("/signin") public ResponseEntity<?> authenticateUser(@RequestBody LoginRequest loginRequest) { Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
SecurityContextHolder.getContext() .setAuthentication(authentication); UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal(); String jwt = jwtUtils.generateJwtToken(authentication); return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getUsername())); } @RequestMapping("/user-dashboard") @PreAuthorize("isAuthenticated()") public String dashboard() { return "My Dashboard"; } }
repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\jwtsignkey\controller\JwtAuthController.java
2
请完成以下Java代码
public Long getSuccessQps() { return successQps; } public void setSuccessQps(Long successQps) { this.successQps = successQps; } public Long getExceptionQps() { return exceptionQps; } public void setExceptionQps(Long exceptionQps) { this.exceptionQps = exceptionQps; } public Long getOneMinutePass() { return oneMinutePass; } public void setOneMinutePass(Long oneMinutePass) { this.oneMinutePass = oneMinutePass; } public Long getOneMinuteBlock() { return oneMinuteBlock; } public void setOneMinuteBlock(Long oneMinuteBlock) { this.oneMinuteBlock = oneMinuteBlock; } public Long getOneMinuteException() { return oneMinuteException; } public void setOneMinuteException(Long oneMinuteException) { this.oneMinuteException = oneMinuteException;
} public Long getOneMinuteTotal() { return oneMinuteTotal; } public void setOneMinuteTotal(Long oneMinuteTotal) { this.oneMinuteTotal = oneMinuteTotal; } public boolean isVisible() { return visible; } public void setVisible(boolean visible) { this.visible = visible; } public List<ResourceTreeNode> getChildren() { return children; } public void setChildren(List<ResourceTreeNode> children) { this.children = children; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\ResourceTreeNode.java
1
请完成以下Java代码
public class InvalidBearerTokenException extends OAuth2AuthenticationException { @Serial private static final long serialVersionUID = 6904689954809100280L; /** * Construct an instance of {@link InvalidBearerTokenException} given the provided * description. * * The description will be wrapped into an * {@link org.springframework.security.oauth2.core.OAuth2Error} instance as the * {@code error_description}. * @param description the description */ public InvalidBearerTokenException(String description) { super(BearerTokenErrors.invalidToken(description));
} /** * Construct an instance of {@link InvalidBearerTokenException} given the provided * description and cause * * The description will be wrapped into an * {@link org.springframework.security.oauth2.core.OAuth2Error} instance as the * {@code error_description}. * @param description the description * @param cause the causing exception */ public InvalidBearerTokenException(String description, Throwable cause) { super(BearerTokenErrors.invalidToken(description), cause); } }
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\InvalidBearerTokenException.java
1
请完成以下Java代码
public void startAddons() { final ArrayList<String> keys = new ArrayList<>(); for (final Object key : props.keySet()) { keys.add((String)key); } Collections.sort(keys); for (final Object addonName : keys) { final String addonClass = (String)props.get(addonName); logger.info("Starting addon " + addonName + " with class " + addonClass); startAddon(addonClass); } } @Override public Properties getAddonProperties() { return props; } private static void startAddon(final String className) { try { final Class<?> clazz = Class.forName(className); final Class<? extends IAddOn> clazzVC = clazz .asSubclass(IAddOn.class);
final IAddOn instance = clazzVC.newInstance(); instance.beforeConnection(); } catch (ClassNotFoundException e) { MetasfreshLastError.saveError(logger, "Addon not available: " + className, e); } catch (ClassCastException e) { MetasfreshLastError.saveError(logger, "Addon class " + className + " doesn't implement " + IAddOn.class.getName(), e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\addon\impl\AddonStarter.java
1
请在Spring Boot框架中完成以下Java代码
public void addForm() { if(Objects.isNull(userInfo.getUser())) { result.include("error", "Please Login to Proceed"); result.redirectTo(AuthController.class).loginForm(); return; } result.use(FreemarkerView.class).withTemplate("posts/add"); } @br.com.caelum.vraptor.Post("/post/add") public void add(Post post) { post.setAuthor(userInfo.getUser()); validator.validate(post); if(validator.hasErrors()) result.include("errors", validator.getErrors()); validator.onErrorRedirectTo(this).addForm(); Object id = postDao.add(post);
if(Objects.nonNull(id)) { result.include("status", "Post Added Successfully"); result.redirectTo(IndexController.class).index(); } else { result.include( "error", "There was an error creating the post. Try Again"); result.redirectTo(this).addForm(); } } @Get("/posts/{id}") public void view(int id) { result.include("post", postDao.findById(id)); result.use(FreemarkerView.class).withTemplate("view"); } }
repos\tutorials-master\web-modules\vraptor\src\main\java\com\baeldung\controllers\PostController.java
2
请完成以下Java代码
public int getGL_Budget_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_Budget_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Primary. @param IsPrimary Indicates if this is the primary budget */ public void setIsPrimary (boolean IsPrimary) { set_Value (COLUMNNAME_IsPrimary, Boolean.valueOf(IsPrimary)); } /** Get Primary. @return Indicates if this is the primary budget */ public boolean isPrimary () { Object oo = get_Value(COLUMNNAME_IsPrimary); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); }
return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_Budget.java
1
请完成以下Java代码
public void forEach(@NonNull final Consumer<BatchToPrint> action) { batches.forEach(action); } } @Getter private static class BatchToPrint { @NonNull private final AdProcessId printFormatProcessId; @NonNull private final ArrayList<HUToReport> hus = new ArrayList<>(); private BatchToPrint(final @NonNull AdProcessId printFormatProcessId)
{ this.printFormatProcessId = printFormatProcessId; } public boolean isMatching(@NonNull final HULabelConfig labelConfig) { return AdProcessId.equals(printFormatProcessId, labelConfig.getPrintFormatProcessId()); } public void addHU(@NonNull final HUToReport hu) { this.hus.add(hu); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\activity_handlers\printReceivedHUQRCodes\PrintReceivedHUQRCodesActivityHandler.java
1
请完成以下Spring Boot application配置
server: port: 8888 spring: application: name: gateway-application cloud: # Spring Cloud Gateway 配置项,全部配置在 Apollo 中 # gateway: # Nacos 作为注册中心的配置项 nacos: discovery: server-addr: 127.0.0.1:8848 # Nacos 服务器地址 # Apollo 相关配置项 app: id: ${spring.application.name} # 使用的 Apollo 的项目(应用)编号 apollo: meta: http://127.0.0.1:8080 # Apollo Meta Server 地址 bootstrap: enabl
ed: true # 是否开启 Apollo 配置预加载功能。默认为 false。 eagerLoad: enable: true # 是否开启 Apollo 支持日志级别的加载时机。默认为 false。 namespaces: application # 使用的 Apollo 的命名空间,默认为 application。
repos\SpringBoot-Labs-master\labx-08-spring-cloud-gateway\labx-08-sc-gateway-demo03-config-apollo\src\main\resources\application.yaml
2
请完成以下Java代码
public BPartnerLocation extractAndMarkUsed(@NonNull final IdentifierString locationIdentifier) { final BPartnerLocation result = extract0(locationIdentifier); if (result != null) { id2UnusedLocation.remove(result.getId()); } return result; } private BPartnerLocation extract0(@NonNull final IdentifierString locationIdentifier) { switch (locationIdentifier.getType()) { case METASFRESH_ID: if (bpartnerId != null) { final BPartnerLocationId bpartnerLocationId = BPartnerLocationId.ofRepoId(bpartnerId, locationIdentifier.asMetasfreshId().getValue()); return id2Location.get(bpartnerLocationId); } else { return null; } case GLN: final BPartnerLocation resultByGLN = gln2Location.get(locationIdentifier.asGLN()); return resultByGLN; case EXTERNAL_ID: final BPartnerLocation resultByExternalId = externalId2Location.get(locationIdentifier.asExternalId()); return resultByExternalId; default: throw new InvalidIdentifierException(locationIdentifier); } } public BPartnerLocation newLocation(@NonNull final IdentifierString locationIdentifier) { final BPartnerLocationBuilder locationBuilder = BPartnerLocation.builder(); final BPartnerLocation location; switch (locationIdentifier.getType()) { case METASFRESH_ID: if (bpartnerId != null) { final BPartnerLocationId bpartnerLocationId = BPartnerLocationId.ofRepoId(bpartnerId, locationIdentifier.asMetasfreshId().getValue()); location = locationBuilder.id(bpartnerLocationId).build(); id2Location.put(bpartnerLocationId, location); } else { location = locationBuilder.build(); } break; case GLN: final GLN gln = locationIdentifier.asGLN(); location = locationBuilder.gln(gln).build(); gln2Location.put(gln, location); break; case EXTERNAL_ID: location = locationBuilder.externalId(locationIdentifier.asExternalId()).build(); externalId2Location.put(locationIdentifier.asExternalId(), location); break;
default: throw new InvalidIdentifierException(locationIdentifier); } bpartnerComposite .getLocations() .add(location); return location; } public Collection<BPartnerLocation> getUnusedLocations() { return id2UnusedLocation.values(); } public void resetBillToDefaultFlags() { for (final BPartnerLocation bpartnerLocation : getUnusedLocations()) { bpartnerLocation.getLocationType().setBillToDefault(false); } } public void resetShipToDefaultFlags() { for (final BPartnerLocation bpartnerLocation : getUnusedLocations()) { bpartnerLocation.getLocationType().setShipToDefault(false); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\bpartner\bpartnercomposite\jsonpersister\ShortTermLocationIndex.java
1
请完成以下Java代码
public static int getInt(final String key, final int defaultValue) { final Object value = UIManager.getDefaults().get(key); if (value instanceof Integer) { return ((Integer)value).intValue(); } return defaultValue; } public static boolean getBoolean(final String key, final boolean defaultValue) { final Object value = UIManager.getDefaults().get(key); if (value instanceof Boolean) { return ((Boolean)value).booleanValue(); }
return defaultValue; } public static String getString(final String key, final String defaultValue) { final Object value = UIManager.getDefaults().get(key); if(value == null) { return defaultValue; } return value.toString(); } public static void setDefaultBackground(final JComponent comp) { comp.putClientProperty(AdempiereLookAndFeel.BACKGROUND, MFColor.ofFlatColor(AdempierePLAF.getFormBackground())); } } // AdempierePLAF
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\plaf\AdempierePLAF.java
1
请完成以下Java代码
public String toString() { return "ByteArrayEntity[id=" + id + ", name=" + name + ", size=" + (bytes != null ? bytes.length : 0) + "]"; } // Wrapper for a byte array, needed to do byte array comparisons // See https://activiti.atlassian.net/browse/ACT-1524 private static class PersistentState { private final String name; private final byte[] bytes; public PersistentState(String name, byte[] bytes) { this.name = name; this.bytes = bytes; }
public boolean equals(Object obj) { if (obj instanceof PersistentState) { PersistentState other = (PersistentState) obj; return StringUtils.equals(this.name, other.name) && Arrays.equals(this.bytes, other.bytes); } return false; } @Override public int hashCode() { throw new UnsupportedOperationException(); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ByteArrayEntityImpl.java
1
请完成以下Java代码
public void setTabLevel (final int TabLevel) { set_Value (COLUMNNAME_TabLevel, TabLevel); } @Override public int getTabLevel() { return get_ValueAsInt(COLUMNNAME_TabLevel); } @Override public org.compiere.model.I_AD_Tab getTemplate_Tab() { return get_ValueAsPO(COLUMNNAME_Template_Tab_ID, org.compiere.model.I_AD_Tab.class); } @Override public void setTemplate_Tab(final org.compiere.model.I_AD_Tab Template_Tab) { set_ValueFromPO(COLUMNNAME_Template_Tab_ID, org.compiere.model.I_AD_Tab.class, Template_Tab); } @Override public void setTemplate_Tab_ID (final int Template_Tab_ID) { if (Template_Tab_ID < 1) set_Value (COLUMNNAME_Template_Tab_ID, null); else set_Value (COLUMNNAME_Template_Tab_ID, Template_Tab_ID); } @Override
public int getTemplate_Tab_ID() { return get_ValueAsInt(COLUMNNAME_Template_Tab_ID); } @Override public void setWhereClause (final @Nullable java.lang.String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } @Override public java.lang.String getWhereClause() { return get_ValueAsString(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Tab.java
1
请完成以下Java代码
public void save(DataOutputStream out) throws IOException { out.writeUTF(template); out.writeInt(offsetList.size()); for (int[] offset : offsetList) { out.writeInt(offset[0]); out.writeInt(offset[1]); } out.writeInt(delimiterList.size()); for (String s : delimiterList) { out.writeUTF(s); } } @Override public boolean load(ByteArray byteArray) { template = byteArray.nextUTF(); int size = byteArray.nextInt(); offsetList = new ArrayList<int[]>(size); for (int i = 0; i < size; ++i) { offsetList.add(new int[]{byteArray.nextInt(), byteArray.nextInt()}); } size = byteArray.nextInt(); delimiterList = new ArrayList<String>(size); for (int i = 0; i < size; ++i) { delimiterList.add(byteArray.nextUTF()); } return true; }
@Override public String toString() { final StringBuilder sb = new StringBuilder("FeatureTemplate{"); sb.append("template='").append(template).append('\''); sb.append(", delimiterList=").append(delimiterList); sb.append('}'); return sb.toString(); } public String getTemplate() { return template; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\FeatureTemplate.java
1
请完成以下Java代码
public AttributeId getAttributeId(final ICountryAware countryAware) { final int adClientId = countryAware.getAD_Client_ID(); final int adOrgId = countryAware.getAD_Org_ID(); return Services.get(ICountryAttributeDAO.class).retrieveCountryAttributeId(adClientId, adOrgId); } @Override public AttributeListValue getCreateAttributeValue(final IContextAware context, final ICountryAware countryAware) { final Properties ctx = context.getCtx(); final String trxName = context.getTrxName(); final I_C_Country country = countryAware.getC_Country(); final SOTrx soTrx = SOTrx.ofBoolean(countryAware.isSOTrx()); final AttributeListValue attributeValue = Services.get(ICountryAttributeDAO.class).retrieveAttributeValue(ctx, country, false/* includeInactive */); final AttributeAction attributeAction = Services.get(IAttributesBL.class).getAttributeAction(ctx); if (attributeValue == null) { if (attributeAction == AttributeAction.Error) { throw new AdempiereException(MSG_NoCountryAttribute, country.getName()); } else if (attributeAction == AttributeAction.GenerateNew) { final Attribute countryAttribute = Services.get(ICountryAttributeDAO.class).retrieveCountryAttribute(ctx); final IAttributeValueGenerator generator = Services.get(IAttributesBL.class).getAttributeValueGenerator(countryAttribute); return generator.generateAttributeValue(ctx, I_C_Country.Table_ID, country.getC_Country_ID(), false, trxName); // SO trx doesn't matter here } else if (attributeAction == AttributeAction.Ignore) { // Ignore: do not throw error, no not generate new attribute } else { throw new AdempiereException("@NotSupported@ AttributeAction " + attributeAction); } return attributeValue; } else { if (!attributeValue.isMatchingSOTrx(soTrx))
{ if (attributeAction == AttributeAction.Error) { throw new AttributeRestrictedException(ctx, soTrx, attributeValue, country.getCountryCode()); } // We have an attribute value, but it is marked for a different transaction. Change type to "null", to make it available for both. final IAttributeDAO attributesRepo = Services.get(IAttributeDAO.class); return attributesRepo.changeAttributeValue(AttributeListValueChangeRequest.builder() .id(attributeValue.getId()) .availableForTrx(AttributeListValueTrxRestriction.ANY_TRANSACTION) .build()); } else { return attributeValue; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\mm\attributes\countryattribute\impl\Country2CountryAwareAttributeService.java
1
请完成以下Java代码
public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public org.compiere.model.I_M_Inventory getReversal() { return get_ValueAsPO(COLUMNNAME_Reversal_ID, org.compiere.model.I_M_Inventory.class); } @Override public void setReversal(final org.compiere.model.I_M_Inventory Reversal) { set_ValueFromPO(COLUMNNAME_Reversal_ID, org.compiere.model.I_M_Inventory.class, Reversal); } @Override public void setReversal_ID (final int Reversal_ID) { if (Reversal_ID < 1) set_Value (COLUMNNAME_Reversal_ID, null); else set_Value (COLUMNNAME_Reversal_ID, Reversal_ID); } @Override public int getReversal_ID() { return get_ValueAsInt(COLUMNNAME_Reversal_ID); } @Override public void setUpdateQty (final @Nullable java.lang.String UpdateQty) { set_Value (COLUMNNAME_UpdateQty, UpdateQty); } @Override public java.lang.String getUpdateQty() { return get_ValueAsString(COLUMNNAME_UpdateQty); } @Override public org.compiere.model.I_C_ElementValue getUser1() { return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser1(final org.compiere.model.I_C_ElementValue User1) { set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1); } @Override public void setUser1_ID (final int User1_ID) {
if (User1_ID < 1) set_Value (COLUMNNAME_User1_ID, null); else set_Value (COLUMNNAME_User1_ID, User1_ID); } @Override public int getUser1_ID() { return get_ValueAsInt(COLUMNNAME_User1_ID); } @Override public org.compiere.model.I_C_ElementValue getUser2() { return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser2(final org.compiere.model.I_C_ElementValue User2) { set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2); } @Override public void setUser2_ID (final int User2_ID) { if (User2_ID < 1) set_Value (COLUMNNAME_User2_ID, null); else set_Value (COLUMNNAME_User2_ID, User2_ID); } @Override public int getUser2_ID() { return get_ValueAsInt(COLUMNNAME_User2_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Inventory.java
1
请完成以下Java代码
public void debugDisabledPessimisticLocks() { logDebug( "106", "No exclusive lock is acquired on H2, " + "as pessimistic locks are disabled on this database."); } public void logTaskWithoutExecution(String taskId) { logDebug("108", "Execution of external task {} is null. This indicates that the task was concurrently completed or deleted. " + "It is not returned by the current fetch and lock command.", taskId); } public ProcessEngineException multipleTenantsForCamundaFormDefinitionKeyException(String camundaFormDefinitionKey) { return new ProcessEngineException(exceptionMessage( "109", "Cannot resolve a unique Camunda Form definition for key '{}' because it exists for multiple tenants.", camundaFormDefinitionKey )); } public void concurrentModificationFailureIgnored(DbOperation operation) { logDebug( "110", "An OptimisticLockingListener attempted to ignore a failure of: {}. " + "Since the database aborted the transaction, ignoring the failure " + "is not possible and an exception is thrown instead.", operation ); } // exception code 110 is already taken. See requiredCamundaAdminOrPermissionException() for details. public static List<SQLException> findRelatedSqlExceptions(Throwable exception) { List<SQLException> sqlExceptionList = new ArrayList<>(); Throwable cause = exception; do { if (cause instanceof SQLException) { SQLException sqlEx = (SQLException) cause; sqlExceptionList.add(sqlEx); while (sqlEx.getNextException() != null) { sqlExceptionList.add(sqlEx.getNextException()); sqlEx = sqlEx.getNextException(); } }
cause = cause.getCause(); } while (cause != null); return sqlExceptionList; } public static String collectExceptionMessages(Throwable cause) { StringBuilder message = new StringBuilder(cause.getMessage()); //collect real SQL exception messages in case of batch processing Throwable exCause = cause; do { if (exCause instanceof BatchExecutorException) { final List<SQLException> relatedSqlExceptions = findRelatedSqlExceptions(exCause); StringBuilder sb = new StringBuilder(); for (SQLException sqlException : relatedSqlExceptions) { sb.append(sqlException).append("\n"); } message.append("\n").append(sb); } exCause = exCause.getCause(); } while (exCause != null); return message.toString(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\EnginePersistenceLogger.java
1
请完成以下Java代码
public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setProductValue (final @Nullable java.lang.String ProductValue) { set_ValueNoCheck (COLUMNNAME_ProductValue, ProductValue); } @Override public java.lang.String getProductValue()
{ return get_ValueAsString(COLUMNNAME_ProductValue); } @Override public void setQtyOnHand (final @Nullable BigDecimal QtyOnHand) { set_ValueNoCheck (COLUMNNAME_QtyOnHand, QtyOnHand); } @Override public BigDecimal getQtyOnHand() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHand); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_MD_Stock_WarehouseAndProduct_v.java
1
请在Spring Boot框架中完成以下Java代码
private Optional<JsonRequestBPartnerUpsertItem> mapPharmacy() { if (pharmacy == null) { return Optional.empty(); } final JsonRequestBPartnerUpsertItem pharmacyUpsertRequest = DataMapper.mapPharmacyToUpsertRequest(pharmacy, orgCode); bPartnerIdentifier2RelationRole.put(pharmacyUpsertRequest.getBpartnerIdentifier(), JsonBPRelationRole.Pharmacy); return Optional.of(pharmacyUpsertRequest); } private Optional<JsonRequestBPartnerUpsertItem> mapCreatedUpdatedBy() { if (rootBPartnerIdForUsers == null || (createdBy == null && updatedBy == null)) { return Optional.empty(); } final JsonRequestContactUpsert.JsonRequestContactUpsertBuilder requestContactUpsert = JsonRequestContactUpsert.builder(); final Optional<JsonRequestContactUpsertItem> createdByContact = DataMapper.userToBPartnerContact(createdBy); createdByContact.ifPresent(requestContactUpsert::requestItem); DataMapper.userToBPartnerContact(updatedBy) .filter(updatedByContact -> createdByContact.isEmpty() || !updatedByContact.getContactIdentifier().equals(createdByContact.get().getContactIdentifier())) .ifPresent(requestContactUpsert::requestItem); final JsonRequestComposite jsonRequestComposite = JsonRequestComposite.builder()
.contacts(requestContactUpsert.build()) .build(); return Optional.of(JsonRequestBPartnerUpsertItem .builder() .bpartnerIdentifier(String.valueOf(rootBPartnerIdForUsers.getValue())) .bpartnerComposite(jsonRequestComposite) .build()); } @Value @Builder public static class BPartnerRequestProducerResult { @NonNull String patientBPartnerIdentifier; @NonNull String patientMainAddressIdentifier; @NonNull Map<String, JsonBPRelationRole> bPartnerIdentifier2RelationRole; @NonNull JsonRequestBPartnerUpsert jsonRequestBPartnerUpsert; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\patient\BPartnerUpsertRequestProducer.java
2
请完成以下Java代码
public void setStd_MinAmt (java.math.BigDecimal Std_MinAmt) { set_Value (COLUMNNAME_Std_MinAmt, Std_MinAmt); } /** Get Standard price min Margin. @return Minimum margin allowed for a product */ @Override public java.math.BigDecimal getStd_MinAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Std_MinAmt); if (bd == null) return Env.ZERO; return bd; } /** * Std_Rounding AD_Reference_ID=155 * Reference name: M_DiscountPriceList RoundingRule */ public static final int STD_ROUNDING_AD_Reference_ID=155; /** Ganze Zahl .00 = 0 */ public static final String STD_ROUNDING_GanzeZahl00 = "0"; /** No Rounding = N */ public static final String STD_ROUNDING_NoRounding = "N"; /** Quarter .25 .50 .75 = Q */ public static final String STD_ROUNDING_Quarter255075 = "Q"; /** Dime .10, .20, .30, ... = D */ public static final String STD_ROUNDING_Dime102030 = "D"; /** Nickel .05, .10, .15, ... = 5 */ public static final String STD_ROUNDING_Nickel051015 = "5"; /** Ten 10.00, 20.00, .. = T */
public static final String STD_ROUNDING_Ten10002000 = "T"; /** Currency Precision = C */ public static final String STD_ROUNDING_CurrencyPrecision = "C"; /** Ending in 9/5 = 9 */ public static final String STD_ROUNDING_EndingIn95 = "9"; /** Set Rundung Standardpreis. @param Std_Rounding Rounding rule for calculated price */ @Override public void setStd_Rounding (java.lang.String Std_Rounding) { set_Value (COLUMNNAME_Std_Rounding, Std_Rounding); } /** Get Rundung Standardpreis. @return Rounding rule for calculated price */ @Override public java.lang.String getStd_Rounding () { return (java.lang.String)get_Value(COLUMNNAME_Std_Rounding); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DiscountSchemaLine.java
1
请在Spring Boot框架中完成以下Java代码
public class SecurityConfig { OAuth2ClientContext oauth2ClientContext; public SecurityConfig(OAuth2ClientContext oauth2ClientContext) { this.oauth2ClientContext = oauth2ClientContext; } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/", "/login**", "/error**") .permitAll() .anyRequest() .authenticated() .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/") .and() .addFilterBefore(oauth2ClientFilter(), BasicAuthenticationFilter.class); return http.build(); } @Bean public FilterRegistrationBean<OAuth2ClientContextFilter> oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) { FilterRegistrationBean<OAuth2ClientContextFilter> registration = new FilterRegistrationBean<>(); registration.setFilter(filter); registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 1); return registration; }
@Bean public OAuth2RestTemplate restTemplate() { return new OAuth2RestTemplate(githubClient(), oauth2ClientContext); } @Bean @ConfigurationProperties("github.client") public AuthorizationCodeResourceDetails githubClient() { return new AuthorizationCodeResourceDetails(); } private Filter oauth2ClientFilter() { OAuth2ClientAuthenticationProcessingFilter oauth2ClientFilter = new OAuth2ClientAuthenticationProcessingFilter("/login/github"); OAuth2RestTemplate restTemplate = restTemplate(); oauth2ClientFilter.setRestTemplate(restTemplate); UserInfoTokenServices tokenServices = new UserInfoTokenServices(githubResource().getUserInfoUri(), githubClient().getClientId()); tokenServices.setRestTemplate(restTemplate); oauth2ClientFilter.setTokenServices(tokenServices); return oauth2ClientFilter; } @Bean @ConfigurationProperties("github.resource") public ResourceServerProperties githubResource() { return new ResourceServerProperties(); } }
repos\tutorials-master\spring-security-modules\spring-security-oauth2\src\main\java\com\baeldung\oauth2resttemplate\SecurityConfig.java
2
请在Spring Boot框架中完成以下Java代码
public void add(int index, VariableInstanceEntity e) { super.add(index, e); initializeVariable(e); } @Override public boolean add(VariableInstanceEntity e) { initializeVariable(e); return super.add(e); } @Override public boolean addAll(Collection<? extends VariableInstanceEntity> c) { for (VariableInstanceEntity e : c) { initializeVariable(e); } return super.addAll(c); } @Override public boolean addAll(int index, Collection<? extends VariableInstanceEntity> c) { for (VariableInstanceEntity e : c) { initializeVariable(e); }
return super.addAll(index, c); } /** * If the passed {@link VariableInstanceEntity} is a binary variable and the command-context is active, the variable value is fetched to ensure the byte-array is populated. */ protected void initializeVariable(VariableInstanceEntity e) { if (Context.getCommandContext() != null && e != null && e.getType() != null) { e.getValue(); // make sure JPA entities are cached for later retrieval if (JPAEntityVariableType.TYPE_NAME.equals(e.getType().getTypeName()) || JPAEntityListVariableType.TYPE_NAME.equals(e.getType().getTypeName())) { ((CacheableVariable) e.getType()).setForceCacheable(true); } } } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\VariableInitializingList.java
2
请完成以下Java代码
public void completeProcessInstanceForm() throws IOException { // start the process instance if (processDefinitionId!=null) { businessProcess.startProcessById(processDefinitionId); processDefinitionId = null; } else { businessProcess.startProcessByKey(processDefinitionKey); processDefinitionKey = null; } // End the conversation conversationInstance.get().end(); // and redirect FacesContext.getCurrentInstance().getExternalContext().redirect(url); } public ProcessDefinition getProcessDefinition() {
// TODO cache result to avoid multiple queries within one page request if (processDefinitionId!=null) { return repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult(); } else { return repositoryService.createProcessDefinitionQuery().processDefinitionKey(processDefinitionKey).latestVersion().singleResult(); } } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\jsf\TaskForm.java
1
请完成以下Java代码
public class User { @NotNull @Email private String email; @NotEmpty @Password private String password; @Size(min = 1, max = 20) private String name; @Min(18) private int age; @Visa private String cardNumber = ""; @IBAN private String iban = ""; @InetAddress private String website = ""; @Directory private File mainDirectory=new File("."); public User() { } public User(String email, String password, String name, int age) { super(); this.email = email; this.password = password; this.name = name; this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() {
return age; } public void setAge(int age) { this.age = age; } public String getCardNumber() { return cardNumber; } public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; } public String getIban() { return iban; } public void setIban(String iban) { this.iban = iban; } public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } public File getMainDirectory() { return mainDirectory; } public void setMainDirectory(File mainDirectory) { this.mainDirectory = mainDirectory; } }
repos\tutorials-master\apache-libraries-2\src\main\java\com\baeldung\apache\bval\model\User.java
1
请在Spring Boot框架中完成以下Java代码
public int getMessageTimeToLive() { return this.messageTimeToLive; } public void setMessageTimeToLive(int messageTimeToLive) { this.messageTimeToLive = messageTimeToLive; } public int getPort() { return this.port; } public void setPort(int port) { this.port = port; } public int getSocketBufferSize() { return this.socketBufferSize; } public void setSocketBufferSize(int socketBufferSize) { this.socketBufferSize = socketBufferSize; } public int getSubscriptionCapacity() { return this.subscriptionCapacity; } public void setSubscriptionCapacity(int subscriptionCapacity) { this.subscriptionCapacity = subscriptionCapacity; } public String getSubscriptionDiskStoreName() { return this.subscriptionDiskStoreName;
} public void setSubscriptionDiskStoreName(String subscriptionDiskStoreName) { this.subscriptionDiskStoreName = subscriptionDiskStoreName; } public SubscriptionEvictionPolicy getSubscriptionEvictionPolicy() { return this.subscriptionEvictionPolicy; } public void setSubscriptionEvictionPolicy(SubscriptionEvictionPolicy subscriptionEvictionPolicy) { this.subscriptionEvictionPolicy = subscriptionEvictionPolicy; } public boolean isTcpNoDelay() { return this.tcpNoDelay; } public void setTcpNoDelay(boolean tcpNoDelay) { this.tcpNoDelay = tcpNoDelay; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\CacheServerProperties.java
2
请完成以下Java代码
public void setDD_Order_Candidate_ID (final int DD_Order_Candidate_ID) { if (DD_Order_Candidate_ID < 1) set_ValueNoCheck (COLUMNNAME_DD_Order_Candidate_ID, null); else set_ValueNoCheck (COLUMNNAME_DD_Order_Candidate_ID, DD_Order_Candidate_ID); } @Override public int getDD_Order_Candidate_ID() { return get_ValueAsInt(COLUMNNAME_DD_Order_Candidate_ID); } @Override public org.eevolution.model.I_DD_Order getDD_Order() { return get_ValueAsPO(COLUMNNAME_DD_Order_ID, org.eevolution.model.I_DD_Order.class); } @Override public void setDD_Order(final org.eevolution.model.I_DD_Order DD_Order) { set_ValueFromPO(COLUMNNAME_DD_Order_ID, org.eevolution.model.I_DD_Order.class, DD_Order); } @Override public void setDD_Order_ID (final int DD_Order_ID) { if (DD_Order_ID < 1) set_ValueNoCheck (COLUMNNAME_DD_Order_ID, null); else set_ValueNoCheck (COLUMNNAME_DD_Order_ID, DD_Order_ID); } @Override public int getDD_Order_ID() { return get_ValueAsInt(COLUMNNAME_DD_Order_ID); } @Override public org.eevolution.model.I_DD_OrderLine getDD_OrderLine() { return get_ValueAsPO(COLUMNNAME_DD_OrderLine_ID, org.eevolution.model.I_DD_OrderLine.class); } @Override
public void setDD_OrderLine(final org.eevolution.model.I_DD_OrderLine DD_OrderLine) { set_ValueFromPO(COLUMNNAME_DD_OrderLine_ID, org.eevolution.model.I_DD_OrderLine.class, DD_OrderLine); } @Override public void setDD_OrderLine_ID (final int DD_OrderLine_ID) { if (DD_OrderLine_ID < 1) set_ValueNoCheck (COLUMNNAME_DD_OrderLine_ID, null); else set_ValueNoCheck (COLUMNNAME_DD_OrderLine_ID, DD_OrderLine_ID); } @Override public int getDD_OrderLine_ID() { return get_ValueAsInt(COLUMNNAME_DD_OrderLine_ID); } @Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_DD_Order_Candidate_DDOrder.java
1
请在Spring Boot框架中完成以下Java代码
public abstract class RelatedRecordsAdapter<T, PARENT_ID> { protected final IQueryBL queryBL = Services.get(IQueryBL.class); protected abstract IQuery<T> queryRecords(final @NonNull PARENT_ID parentId); protected abstract BPartnerRelatedRecordId extractRecordId(final @NonNull T record); protected abstract T createNewRecord(final @NonNull PARENT_ID parentId, final BPartnerRelatedRecordId record); private void deleteRecords(final Collection<T> records) { InterfaceWrapperHelper.deleteAll(records); } public ImmutableSet<BPartnerRelatedRecordId> getRecords(final @NonNull PARENT_ID parentId) { return queryRecords(parentId) .stream() .map(this::extractRecordId) .distinct() .collect(ImmutableSet.toImmutableSet()); } // see also: de.metas.ui.web.window.model.sql.SqlDocumentsRepository.saveLabels public void saveAttributes( @NonNull final ImmutableSet<BPartnerRelatedRecordId> recordIdsSet, @NonNull final PARENT_ID parentId) { final HashMap<BPartnerRelatedRecordId, T> existingRecords = queryRecords(parentId) .stream()
.collect(GuavaCollectors.toHashMapByKey(this::extractRecordId)); for (final BPartnerRelatedRecordId recordId : recordIdsSet) { final T existingRecord = existingRecords.remove(recordId); if (existingRecord == null) { createNewRecord(parentId, recordId); } } deleteRecords(existingRecords.values()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\attributes\related\service\adapter\RelatedRecordsAdapter.java
2
请完成以下Java代码
public void setEnforceRoleSecurity (boolean EnforceRoleSecurity) { set_Value (COLUMNNAME_EnforceRoleSecurity, Boolean.valueOf(EnforceRoleSecurity)); } /** Get Enforce Role Security. @return Send alerts to recipient only if the data security rules of the role allows */ public boolean isEnforceRoleSecurity () { Object oo = get_Value(COLUMNNAME_EnforceRoleSecurity); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Valid. @param IsValid Element is valid */ public void setIsValid (boolean IsValid) { set_Value (COLUMNNAME_IsValid, Boolean.valueOf(IsValid)); } /** Get Valid.
@return Element is valid */ public boolean isValid () { Object oo = get_Value(COLUMNNAME_IsValid); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Alert.java
1
请完成以下Java代码
public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setNegative_Amt_C_DocType_ID (final int Negative_Amt_C_DocType_ID) { if (Negative_Amt_C_DocType_ID < 1) set_Value (COLUMNNAME_Negative_Amt_C_DocType_ID, null); else set_Value (COLUMNNAME_Negative_Amt_C_DocType_ID, Negative_Amt_C_DocType_ID); } @Override public int getNegative_Amt_C_DocType_ID() {
return get_ValueAsInt(COLUMNNAME_Negative_Amt_C_DocType_ID); } @Override public void setPositive_Amt_C_DocType_ID (final int Positive_Amt_C_DocType_ID) { if (Positive_Amt_C_DocType_ID < 1) set_Value (COLUMNNAME_Positive_Amt_C_DocType_ID, null); else set_Value (COLUMNNAME_Positive_Amt_C_DocType_ID, Positive_Amt_C_DocType_ID); } @Override public int getPositive_Amt_C_DocType_ID() { return get_ValueAsInt(COLUMNNAME_Positive_Amt_C_DocType_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocType_Invoicing_Pool.java
1
请完成以下Java代码
void operations_with_no_real_results_produce_NaN() { System.out.println("Operations with no real results produce NaN"); System.out.println("SQUARE ROOT OF -1 = " + Math.sqrt(-1)); System.out.println("LOG OF -1 = " + Math.log(-1)); System.out.println(); } void operations_with_NaN_produce_NaN() { System.out.println("Operations with NaN produce NaN"); System.out.println("2 + NaN = " + (2 + Double.NaN)); System.out.println("2 - NaN = " + (2 - Double.NaN)); System.out.println("2 * NaN = " + (2 * Double.NaN)); System.out.println("2 / NaN = " + (2 / Double.NaN)); System.out.println(); } void assign_NaN_to_missing_values() { System.out.println("Assign NaN to Missing values"); double salaryRequired = Double.NaN; System.out.println(salaryRequired); System.out.println(); } void comparison_with_NaN() { System.out.println("Comparison with NaN"); final double NAN = Double.NaN;
System.out.println("NaN == 1 = " + (NAN == 1)); System.out.println("NaN > 1 = " + (NAN > 1)); System.out.println("NaN < 1 = " + (NAN < 1)); System.out.println("NaN != 1 = " + (NAN != 1)); System.out.println("NaN == NaN = " + (NAN == NAN)); System.out.println("NaN > NaN = " + (NAN > NAN)); System.out.println("NaN < NaN = " + (NAN < NAN)); System.out.println("NaN != NaN = " + (NAN != NAN)); System.out.println(); } void check_if_a_value_is_NaN() { System.out.println("Check if a value is NaN"); double x = 1; System.out.println(x + " is NaN = " + (x != x)); System.out.println(x + " is NaN = " + (Double.isNaN(x))); x = Double.NaN; System.out.println(x + " is NaN = " + (x != x)); System.out.println(x + " is NaN = " + (Double.isNaN(x))); System.out.println(); } }
repos\tutorials-master\core-java-modules\core-java-numbers-2\src\main\java\com\baeldung\nan\NaNExample.java
1
请完成以下Java代码
public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Ausgelagerte Menge. @param QtyIssued Ausgelagerte Menge */ @Override public void setQtyIssued (java.math.BigDecimal QtyIssued) { set_Value (COLUMNNAME_QtyIssued, QtyIssued); } /** Get Ausgelagerte Menge. @return Ausgelagerte Menge */
@Override public java.math.BigDecimal getQtyIssued () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyIssued); if (bd == null) return Env.ZERO; return bd; } /** Set Empfangene Menge. @param QtyReceived Empfangene Menge */ @Override public void setQtyReceived (java.math.BigDecimal QtyReceived) { set_Value (COLUMNNAME_QtyReceived, QtyReceived); } /** Get Empfangene Menge. @return Empfangene Menge */ @Override public java.math.BigDecimal getQtyReceived () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyReceived); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\ch\lagerkonf\model\X_M_Material_Tracking_Report_Line.java
1
请完成以下Java代码
public I_C_BP_BankAccount importRecord(final I_I_BPartner importRecord) { final BPartnerId bpartnerId = BPartnerId.ofRepoId(importRecord.getC_BPartner_ID()); I_C_BP_BankAccount bankAccount = BankAccountId.optionalOfRepoId(importRecord.getC_BP_BankAccount_ID()) .map(bankAccountId -> InterfaceWrapperHelper.load(bankAccountId, I_C_BP_BankAccount.class)) .orElse(null); if (bankAccount != null) { bankAccount.setIBAN(importRecord.getIBAN()); ModelValidationEngine.get().fireImportValidate(process, importRecord, bankAccount, IImportInterceptor.TIMING_AFTER_IMPORT); InterfaceWrapperHelper.save(bankAccount); } else if (!Check.isEmpty(importRecord.getSwiftCode(), true) && !Check.isEmpty(importRecord.getIBAN(), true)) { bankAccount = InterfaceWrapperHelper.newInstance(I_C_BP_BankAccount.class); bankAccount.setC_BPartner_ID(bpartnerId.getRepoId()); bankAccount.setIBAN(importRecord.getIBAN()); bankAccount.setA_Name(importRecord.getSwiftCode()); bankAccount.setC_Currency_ID(currencyBL.getBaseCurrency(process.getCtx()).getId().getRepoId()); final BankId bankId = bankRepository.getBankIdBySwiftCode(importRecord.getSwiftCode()).orElse(null);
if (bankId != null) { bankAccount.setC_Bank_ID(bankId.getRepoId()); } ModelValidationEngine.get().fireImportValidate(process, importRecord, bankAccount, IImportInterceptor.TIMING_AFTER_IMPORT); InterfaceWrapperHelper.save(bankAccount); importRecord.setC_BP_BankAccount_ID(bankAccount.getC_BP_BankAccount_ID()); } return bankAccount; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\impexp\BPartnerBankAccountImportHelper.java
1
请完成以下Java代码
static class OnPropertyEnabled { } @ConditionalOnPropertyExists static class OnTrustedProxiesNotEmpty { } } class OnPropertyExistsCondition extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { try { String property = context.getEnvironment().getProperty(PROPERTY); if (!StringUtils.hasText(property)) { return ConditionOutcome.noMatch(PROPERTY + " property is not set or is empty.");
} return ConditionOutcome.match(PROPERTY + " property is not empty."); } catch (NoSuchElementException e) { return ConditionOutcome.noMatch("Missing required property 'value' of @ConditionalOnPropertyExists"); } } } @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) @Documented @Conditional(OnPropertyExistsCondition.class) @interface ConditionalOnPropertyExists { } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\headers\TrustedProxies.java
1
请完成以下Java代码
private int retrievePackageLableAdProcessId() { final Properties ctx = Env.getCtx(); final int adClientId = Env.getAD_Client_ID(ctx); final int adOrgId = Env.getAD_Org_ID(ctx); final String sysconfigKey = DerKurierConstants.SYSCONFIG_DERKURIER_LABEL_PROCESS_ID; final int adProcessId = Services.get(ISysConfigBL.class).getIntValue(sysconfigKey, -1, adClientId, adOrgId); Check.errorIf(adProcessId <= 0, "Missing sysconfig value for 'Der Kurier' package label jasper report; name={}; AD_Client_ID={}; AD_Org_ID={}", sysconfigKey, adClientId, adOrgId); return adProcessId; } /** * Returns an empty list, because https://leoz.derkurier.de:13000/rs/api/v1/document/label does not yet work, * so we need to fire up our own jasper report and print them ourselves. This is done in {@link #completeDeliveryOrder(DeliveryOrder)}. */ @NonNull @Override
public List<PackageLabels> getPackageLabelsList(@NonNull final DeliveryOrder deliveryOrder) { return ImmutableList.of(); } @Override public @NonNull JsonDeliveryAdvisorResponse adviseShipment(final @NonNull JsonDeliveryAdvisorRequest request) { return JsonDeliveryAdvisorResponse.builder() .requestId(request.getId()) .shipperProduct(JsonShipperProduct.builder() .code(OVERNIGHT.getCode()) .build()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java\de\metas\shipper\gateway\derkurier\DerKurierClient.java
1
请完成以下Java代码
public class JschDemo { public static void main(String args[]) throws Exception { String username = "demo"; String password = "password"; String host = "test.rebex.net"; int port = 22; String command = "ls"; listFolderStructure(username, password, host, port, command); } public static String listFolderStructure(String username, String password, String host, int port, String command) throws Exception { Session session = null; ChannelExec channel = null; String response = null; try { session = new JSch().getSession(username, host, port); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); channel = (ChannelExec) session.openChannel("exec"); channel.setCommand(command); ByteArrayOutputStream responseStream = new ByteArrayOutputStream(); ByteArrayOutputStream errorResponseStream = new ByteArrayOutputStream(); channel.setOutputStream(responseStream); channel.setErrStream(errorResponseStream); channel.connect(); while (channel.isConnected()) { Thread.sleep(100); }
String errorResponse = new String(errorResponseStream.toByteArray()); response = new String(responseStream.toByteArray()); if(!errorResponse.isEmpty()) { throw new Exception(errorResponse); } } finally { if (session != null) { session.disconnect(); } if (channel != null) { channel.disconnect(); } } return response; } }
repos\tutorials-master\libraries-security\src\main\java\com\baeldung\ssh\jsch\JschDemo.java
1
请完成以下Java代码
public DeviceTransportType getType() { return DeviceTransportType.SNMP; } @Override public void validate() { if (!isValid()) { throw new IllegalArgumentException("Transport configuration is not valid"); } } @JsonIgnore private boolean isValid() { boolean isValid = StringUtils.isNotBlank(host) && port != null && protocolVersion != null; if (isValid) {
switch (protocolVersion) { case V1: case V2C: isValid = StringUtils.isNotEmpty(community); break; case V3: isValid = StringUtils.isNotBlank(username) && StringUtils.isNotBlank(securityName) && contextName != null && authenticationProtocol != null && StringUtils.isNotBlank(authenticationPassphrase) && privacyProtocol != null && StringUtils.isNotBlank(privacyPassphrase) && engineId != null; break; } } return isValid; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\device\data\SnmpDeviceTransportConfiguration.java
1
请完成以下Java代码
public static Map<String, Object> success(String message) { return response(200, message); } /** * 失败 * * @param message 信息 * @return */ public static Map<String, Object> fail(String message) { return response(400, message); } /** * 未授权 * * @param message 信息 * @return */ public static Map<String, Object> unAuth(String message) { return response(401, message); } /**
* 服务器异常 * * @param message 信息 * @return */ public static Map<String, Object> error(String message) { return response(500, message); } /** * 构建返回的JSON数据格式 * * @param status 状态码 * @param message 信息 * @return */ public static Map<String, Object> response(int status, String message) { Map<String, Object> map = new HashMap<>(16); map.put("code", status); map.put("msg", message); map.put("data", null); return map; } }
repos\SpringBlade-master\blade-gateway\src\main\java\org\springblade\gateway\provider\ResponseProvider.java
1
请完成以下Java代码
public static WindowId of(final int windowIdInt) { return new WindowId(windowIdInt); } public static WindowId of(@NonNull final AdWindowId adWindowId) { return new WindowId(adWindowId.getRepoId()); } public static WindowId of(final DocumentId documentTypeId) { if (documentTypeId.isInt()) { return new WindowId(documentTypeId.toInt()); } else { return new WindowId(documentTypeId.toJson()); } } @Nullable public static WindowId ofNullable(@Nullable final AdWindowId adWindowId) { return adWindowId != null ? new WindowId(adWindowId.getRepoId()) : null; } private final String value; private transient OptionalInt valueInt = null; // lazy private WindowId(final String value) { Check.assumeNotEmpty(value, "value is not empty"); this.value = value; } private WindowId(final int valueInt) { Check.assumeGreaterThanZero(valueInt, "valueInt"); this.valueInt = OptionalInt.of(valueInt); value = String.valueOf(valueInt); } @Override @Deprecated public String toString() { return toJson(); } @JsonValue public String toJson() { return value; } public int toInt() { return toOptionalInt() .orElseThrow(() -> new AdempiereException("WindowId cannot be converted to int: " + this)); } public int toIntOr(final int fallbackValue) { return toOptionalInt() .orElse(fallbackValue); } private OptionalInt toOptionalInt() { OptionalInt valueInt = this.valueInt; if (valueInt == null) { valueInt = this.valueInt = parseOptionalInt(); } return valueInt;
} private OptionalInt parseOptionalInt() { try { return OptionalInt.of(Integer.parseInt(value)); } catch (final Exception ex) { return OptionalInt.empty(); } } @Nullable public AdWindowId toAdWindowIdOrNull() { return AdWindowId.ofRepoIdOrNull(toIntOr(-1)); } public AdWindowId toAdWindowId() { return AdWindowId.ofRepoId(toInt()); } public boolean isInt() { return toOptionalInt().isPresent(); } public DocumentId toDocumentId() { return DocumentId.of(value); } public static boolean equals(@Nullable final WindowId id1, @Nullable final WindowId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\WindowId.java
1
请完成以下Java代码
public MFColor getBackgroundColor () { try { return (MFColor)getClientProperty(AdempiereLookAndFeel.BACKGROUND); } catch (Exception e) { System.err.println("CButton - ClientProperty: " + e.getMessage()); } return null; } // getBackgroundColor /** Mandatory (default false) */ private boolean m_mandatory = false; /** * Set Editor Mandatory * @param mandatory true, if you have to enter data */ @Override public void setMandatory (boolean mandatory) { m_mandatory = mandatory; setBackground(false); } // setMandatory /** * Is Field mandatory * @return true, if mandatory */ @Override public boolean isMandatory() { return m_mandatory; } // isMandatory /** * Enable Editor * @param rw true, if you can enter/select data */ @Override public void setReadWrite (boolean rw) { if (super.isEnabled() != rw) super.setEnabled(rw); } // setReadWrite /** * Is it possible to edit * @return true, if editable */ @Override public boolean isReadWrite() { return super.isEnabled(); } // isReadWrite /** * Set Editor to value * @param value value of the editor */ @Override public void setValue (Object value)
{ if (value == null) setText(""); else setText(value.toString()); } // setValue /** * Return Editor value * @return current value */ @Override public Object getValue() { return getText(); } // getValue /** * Return Display Value * @return displayed String value */ @Override public String getDisplay() { return getText(); } // getDisplay } // CToggleButton
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CToggleButton.java
1
请在Spring Boot框架中完成以下Java代码
public String[] selectImports(@NonNull AnnotationMetadata importMetadata) { if (!importMetadata.hasAnnotation(EnableMethodSecurity.class.getName()) && !importMetadata.hasMetaAnnotation(EnableMethodSecurity.class.getName())) { return new String[0]; } EnableMethodSecurity annotation = importMetadata.getAnnotations().get(EnableMethodSecurity.class).synthesize(); List<String> imports = new ArrayList<>(Arrays.asList(this.autoProxy.selectImports(importMetadata))); if (annotation.prePostEnabled()) { imports.add(PrePostMethodSecurityConfiguration.class.getName()); } if (annotation.securedEnabled()) { imports.add(SecuredMethodSecurityConfiguration.class.getName()); } if (annotation.jsr250Enabled()) { imports.add(Jsr250MethodSecurityConfiguration.class.getName()); } imports.add(AuthorizationProxyConfiguration.class.getName()); if (isDataPresent) { imports.add(AuthorizationProxyDataConfiguration.class.getName()); } if (isWebPresent) { imports.add(AuthorizationProxyWebConfiguration.class.getName()); } if (isObservabilityPresent) { imports.add(MethodObservationConfiguration.class.getName()); } return imports.toArray(new String[0]); } private static final class AutoProxyRegistrarSelector extends AdviceModeImportSelector<EnableMethodSecurity> { private static final String[] IMPORTS = new String[] { AutoProxyRegistrar.class.getName(), MethodSecurityAdvisorRegistrar.class.getName() };
private static final String[] ASPECTJ_IMPORTS = new String[] { MethodSecurityAspectJAutoProxyRegistrar.class.getName() }; @Override protected String[] selectImports(@NonNull AdviceMode adviceMode) { if (adviceMode == AdviceMode.PROXY) { return IMPORTS; } if (adviceMode == AdviceMode.ASPECTJ) { return ASPECTJ_IMPORTS; } throw new IllegalStateException("AdviceMode '" + adviceMode + "' is not supported"); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\MethodSecuritySelector.java
2
请在Spring Boot框架中完成以下Java代码
public Map<BPartnerId, String> getBPartnerNames(@NonNull final Set<BPartnerId> bpartnerIds) { return bpartnerBL.getBPartnerNames(bpartnerIds); } public ShipmentAllocationBestBeforePolicy getBestBeforePolicy(@NonNull final BPartnerId bpartnerId) { return bpartnerBL.getBestBeforePolicy(bpartnerId); } public Set<DocumentLocation> getDocumentLocations(@NonNull final Set<BPartnerLocationId> bpartnerLocationIds) { return documentLocationBL.getDocumentLocations(bpartnerLocationIds); }
public I_C_BPartner_Location getBPartnerLocationByIdEvenInactive(final @NonNull BPartnerLocationId id) { return bpartnerBL.getBPartnerLocationByIdEvenInactive(id); } public List<I_C_BPartner_Location> getBPartnerLocationsByIds(final Set<BPartnerLocationId> ids) { return bpartnerBL.getBPartnerLocationsByIds(ids); } public RenderedAddressProvider newRenderedAddressProvider() { return documentLocationBL.newRenderedAddressProvider(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\external\bpartner\PickingJobBPartnerService.java
2
请完成以下Java代码
public class DiskSpaceHealthIndicator extends AbstractHealthIndicator { private static final Log logger = LogFactory.getLog(DiskSpaceHealthIndicator.class); private final File path; private final DataSize threshold; /** * Create a new {@code DiskSpaceHealthIndicator} instance. * @param path the Path used to compute the available disk space * @param threshold the minimum disk space that should be available */ public DiskSpaceHealthIndicator(File path, DataSize threshold) { super("DiskSpace health check failed"); this.path = path; this.threshold = threshold; } @Override
protected void doHealthCheck(Health.Builder builder) throws Exception { long diskFreeInBytes = this.path.getUsableSpace(); if (diskFreeInBytes >= this.threshold.toBytes()) { builder.up(); } else { logger.warn(LogMessage.format( "Free disk space at path '%s' below threshold. Available: %d bytes (threshold: %s)", this.path.getAbsolutePath(), diskFreeInBytes, this.threshold)); builder.down(); } builder.withDetail("total", this.path.getTotalSpace()) .withDetail("free", diskFreeInBytes) .withDetail("threshold", this.threshold.toBytes()) .withDetail("path", this.path.getAbsolutePath()) .withDetail("exists", this.path.exists()); } }
repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\application\DiskSpaceHealthIndicator.java
1
请完成以下Java代码
public class CallableElementImpl extends RootElementImpl implements CallableElement { protected static Attribute<String> nameAttribute; protected static ElementReferenceCollection<Interface, SupportedInterfaceRef> supportedInterfaceRefCollection; protected static ChildElement<IoSpecification> ioSpecificationChild; protected static ChildElementCollection<IoBinding> ioBindingCollection; public static void registerType(ModelBuilder bpmnModelBuilder) { ModelElementTypeBuilder typeBuilder = bpmnModelBuilder.defineType(CallableElement.class, BPMN_ELEMENT_CALLABLE_ELEMENT) .namespaceUri(BPMN20_NS) .extendsType(RootElement.class) .instanceProvider(new ModelTypeInstanceProvider<ModelElementInstance>() { public ModelElementInstance newInstance(ModelTypeInstanceContext instanceContext) { return new CallableElementImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); supportedInterfaceRefCollection = sequenceBuilder.elementCollection(SupportedInterfaceRef.class) .qNameElementReferenceCollection(Interface.class) .build(); ioSpecificationChild = sequenceBuilder.element(IoSpecification.class) .build(); ioBindingCollection = sequenceBuilder.elementCollection(IoBinding.class) .build(); typeBuilder.build(); } public CallableElementImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public String getName() { return nameAttribute.getValue(this);
} public void setName(String name) { nameAttribute.setValue(this, name); } public Collection<Interface> getSupportedInterfaces() { return supportedInterfaceRefCollection.getReferenceTargetElements(this); } public IoSpecification getIoSpecification() { return ioSpecificationChild.getChild(this); } public void setIoSpecification(IoSpecification ioSpecification) { ioSpecificationChild.setChild(this, ioSpecification); } public Collection<IoBinding> getIoBindings() { return ioBindingCollection.get(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\CallableElementImpl.java
1
请完成以下Java代码
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
请在Spring Boot框架中完成以下Java代码
static ObjectPostProcessor<AuthorizationManager<HttpServletRequest>> webAuthorizationManagerPostProcessor( ObjectProvider<ObservationRegistry> registry, ObjectProvider<SecurityObservationSettings> predicate) { return new ObjectPostProcessor<>() { @Override public AuthorizationManager postProcess(AuthorizationManager object) { ObservationRegistry r = registry.getIfUnique(() -> ObservationRegistry.NOOP); boolean active = !r.isNoop() && predicate.getIfUnique(() -> all).shouldObserveAuthorizations(); return active ? new ObservationAuthorizationManager<>(r, object) : object; } }; } @Bean @Role(BeanDefinition.ROLE_INFRASTRUCTURE) static ObjectPostProcessor<AuthenticationManager> authenticationManagerPostProcessor( ObjectProvider<ObservationRegistry> registry, ObjectProvider<SecurityObservationSettings> predicate) { return new ObjectPostProcessor<>() { @Override public AuthenticationManager postProcess(AuthenticationManager object) { ObservationRegistry r = registry.getIfUnique(() -> ObservationRegistry.NOOP);
boolean active = !r.isNoop() && predicate.getIfUnique(() -> all).shouldObserveAuthentications(); return active ? new ObservationAuthenticationManager(r, object) : object; } }; } @Bean @Role(BeanDefinition.ROLE_INFRASTRUCTURE) static ObjectPostProcessor<FilterChainDecorator> filterChainDecoratorPostProcessor( ObjectProvider<ObservationRegistry> registry, ObjectProvider<SecurityObservationSettings> predicate) { return new ObjectPostProcessor<>() { @Override public FilterChainDecorator postProcess(FilterChainDecorator object) { ObservationRegistry r = registry.getIfUnique(() -> ObservationRegistry.NOOP); boolean active = !r.isNoop() && predicate.getIfUnique(() -> all).shouldObserveRequests(); return active ? new ObservationFilterChainDecorator(r) : object; } }; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configuration\ObservationConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class DimensionsType { @XmlElement(name = "Length") protected UnitType length; @XmlElement(name = "Height") protected UnitType height; @XmlElement(name = "Width") protected UnitType width; /** * Length of an object. * * @return * possible object is * {@link UnitType } * */ public UnitType getLength() { return length; } /** * Sets the value of the length property. * * @param value * allowed object is * {@link UnitType } * */ public void setLength(UnitType value) { this.length = value; } /** * Heigth of an object. * * @return * possible object is * {@link UnitType } * */ public UnitType getHeight() { return height; } /** * Sets the value of the height property. * * @param value * allowed object is * {@link UnitType } * */ public void setHeight(UnitType value) { this.height = value;
} /** * Width of an object. * * @return * possible object is * {@link UnitType } * */ public UnitType getWidth() { return width; } /** * Sets the value of the width property. * * @param value * allowed object is * {@link UnitType } * */ public void setWidth(UnitType value) { this.width = 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\DimensionsType.java
2
请完成以下Java代码
public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public String getParentIds() { return parentIds; } public void setParentIds(String parentIds) { this.parentIds = parentIds; } public Boolean getAvailable() {
return available; } public void setAvailable(Boolean available) { this.available = available; } public List<SysRole> getRoles() { return roles; } public void setRoles(List<SysRole> roles) { this.roles = roles; } }
repos\springboot-demo-master\shiro\src\main\java\com\et\shiro\entity\SysPermission.java
1
请在Spring Boot框架中完成以下Java代码
public String login(HttpServletRequest request) { // 判断是否已经登陆 Subject subject = SecurityUtils.getSubject(); if (subject.getPrincipal() != null) { return "你已经登陆账号:" + subject.getPrincipal(); } // 获得登陆失败的原因 String shiroLoginFailure = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME); // 翻译成人类看的懂的提示 String msg = ""; if (UnknownAccountException.class.getName().equals(shiroLoginFailure)) { msg = "账号不存在"; } else if (IncorrectCredentialsException.class.getName().equals(shiroLoginFailure)) { msg = "密码不正确"; } else if (LockedAccountException.class.getName().equals(shiroLoginFailure)) { msg = "账号被锁定"; } else if (ExpiredCredentialsException.class.getName().equals(shiroLoginFailure)) { msg = "账号已过期"; } else { msg = "未知"; logger.error("[login][未知登陆错误:{}]", shiroLoginFailure); } return "登陆失败,原因:" + msg;
} @ResponseBody @GetMapping("/login_success") public String loginSuccess() { return "登陆成功"; } @ResponseBody @GetMapping("/unauthorized") public String unauthorized() { return "你没有权限"; } }
repos\SpringBoot-Labs-master\lab-33\lab-33-shiro-demo\src\main\java\cn\iocoder\springboot\lab01\shirodemo\controller\SecurityController.java
2
请完成以下Java代码
private static void updateTrxAmt(final I_C_BankStatementLine bsl) { bsl.setTrxAmt(BankStatementLineAmounts.of(bsl) .addDifferenceToTrxAmt() .getTrxAmt()); } private interface AmountsCallout { void onStmtAmtChanged(final I_C_BankStatementLine bsl); void onTrxAmtChanged(final I_C_BankStatementLine bsl); void onBankFeeAmtChanged(final I_C_BankStatementLine bsl); void onChargeAmtChanged(final I_C_BankStatementLine bsl); void onInterestAmtChanged(final I_C_BankStatementLine bsl); } public static class BankStatementLineAmountsCallout implements AmountsCallout { @Override public void onStmtAmtChanged(final I_C_BankStatementLine bsl) { updateTrxAmt(bsl); } @Override public void onTrxAmtChanged(final I_C_BankStatementLine bsl) { bsl.setBankFeeAmt(BankStatementLineAmounts.of(bsl) .addDifferenceToBankFeeAmt() .getBankFeeAmt()); } @Override public void onBankFeeAmtChanged(final I_C_BankStatementLine bsl) { updateTrxAmt(bsl); } @Override public void onChargeAmtChanged(final I_C_BankStatementLine bsl) { updateTrxAmt(bsl); } @Override public void onInterestAmtChanged(final I_C_BankStatementLine bsl) { updateTrxAmt(bsl); } } public static class CashJournalLineAmountsCallout implements AmountsCallout { @Override public void onStmtAmtChanged(final I_C_BankStatementLine bsl) { updateTrxAmt(bsl); }
@Override public void onTrxAmtChanged(final I_C_BankStatementLine bsl) { // i.e. set the TrxAmt back. // user shall not be allowed to change it // instead, StmtAmt can be changed updateTrxAmt(bsl); } @Override public void onBankFeeAmtChanged(final I_C_BankStatementLine bsl) { bsl.setBankFeeAmt(BigDecimal.ZERO); updateTrxAmt(bsl); } @Override public void onChargeAmtChanged(final I_C_BankStatementLine bsl) { bsl.setChargeAmt(BigDecimal.ZERO); updateTrxAmt(bsl); } @Override public void onInterestAmtChanged(final I_C_BankStatementLine bsl) { bsl.setInterestAmt(BigDecimal.ZERO); updateTrxAmt(bsl); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\callout\C_BankStatementLine.java
1
请完成以下Java代码
public static String reverseUsingIntStreamRangeMethod(String str) { if (str == null) { return null; } char[] charArray = str.toCharArray(); return IntStream.range(0, str.length()) .mapToObj(i -> charArray[str.length() - i - 1]) .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append) .toString(); } public static String reverseUsingStreamOfMethod(String str) { if (str == null) { return null; }
return Stream.of(str) .map(string -> new StringBuilder(string).reverse()) .collect(Collectors.joining()); } public static String reverseUsingCharsMethod(String str) { if (str == null) { return null; } return str.chars() .mapToObj(c -> (char) c) .reduce("", (a, b) -> b + a, (a2, b2) -> b2 + a2); } }
repos\tutorials-master\core-java-modules\core-java-string-algorithms\src\main\java\com\baeldung\reverse\ReverseStringExamples.java
1
请完成以下Java代码
public Capacity getTotalCapacity() { return itemStorage.getCapacity(productId, uom, date); } @Override public ProductId getProductId() { return productId; } @Override public I_C_UOM getC_UOM() { return uom; } @Override public BigDecimal getQtyFree() { final Capacity capacityAvailable = itemStorage.getAvailableCapacity(getProductId(), getC_UOM(), date); if (capacityAvailable.isInfiniteCapacity()) { return Quantity.QTY_INFINITE; } return capacityAvailable.toBigDecimal(); } @Override public Quantity getQty() { return itemStorage.getQuantity(getProductId(), getC_UOM()); } @Override public final Quantity getQty(final I_C_UOM uom) { final ProductId productId = getProductId(); final Quantity qty = getQty(); final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class); final UOMConversionContext conversionCtx= UOMConversionContext.of(productId); return uomConversionBL.convertQuantityTo(qty, conversionCtx, uom); } @Override public BigDecimal getQtyCapacity() { final Capacity capacityTotal = getTotalCapacity(); return capacityTotal.toBigDecimal(); } @Override public IAllocationRequest addQty(final IAllocationRequest request)
{ return itemStorage.requestQtyToAllocate(request); } @Override public IAllocationRequest removeQty(final IAllocationRequest request) { return itemStorage.requestQtyToDeallocate(request); } @Override public void markStaled() { // nothing, so far, itemStorage is always database coupled, no in memory values } @Override public boolean isEmpty() { return itemStorage.isEmpty(getProductId()); } @Override public boolean isAllowNegativeStorage() { return itemStorage.isAllowNegativeStorage(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\HUItemProductStorage.java
1
请在Spring Boot框架中完成以下Java代码
public ReturnT<Map<String, Object>> chartInfo(Date startDate, Date endDate) { ReturnT<Map<String, Object>> chartInfo = xxlJobService.chartInfo(startDate, endDate); return chartInfo; } @RequestMapping("/toLogin") @PermissionLimit(limit=false) public ModelAndView toLogin(HttpServletRequest request, HttpServletResponse response,ModelAndView modelAndView) { if (loginService.ifLogin(request, response) != null) { modelAndView.setView(new RedirectView("/",true,false)); return modelAndView; } return new ModelAndView("login"); } @RequestMapping(value="login", method=RequestMethod.POST) @ResponseBody @PermissionLimit(limit=false) public ReturnT<String> loginDo(HttpServletRequest request, HttpServletResponse response, String userName, String password, String ifRemember){ boolean ifRem = (ifRemember!=null && ifRemember.trim().length()>0 && "on".equals(ifRemember))?true:false; return loginService.login(request, response, userName, password, ifRem); } @RequestMapping(value="logout", method=RequestMethod.POST) @ResponseBody @PermissionLimit(limit=false) public ReturnT<String> logout(HttpServletRequest request, HttpServletResponse response){ return loginService.logout(request, response);
} @RequestMapping("/help") public String help() { /*if (!PermissionInterceptor.ifLogin(request)) { return "redirect:/toLogin"; }*/ return "help"; } @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\controller\IndexController.java
2
请完成以下Java代码
public void setProductName (java.lang.String ProductName) { set_ValueNoCheck (COLUMNNAME_ProductName, ProductName); } /** Get Produktname. @return Name des Produktes */ @Override public java.lang.String getProductName () { return (java.lang.String)get_Value(COLUMNNAME_ProductName); } /** Set Produktschlüssel. @param ProductValue Schlüssel des Produktes */ @Override public void setProductValue (java.lang.String ProductValue) { set_ValueNoCheck (COLUMNNAME_ProductValue, ProductValue); } /** Get Produktschlüssel. @return Schlüssel des Produktes */ @Override public java.lang.String getProductValue () { return (java.lang.String)get_Value(COLUMNNAME_ProductValue); }
/** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (java.lang.String SeqNo) { set_ValueNoCheck (COLUMNNAME_SeqNo, SeqNo); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public java.lang.String getSeqNo () { return (java.lang.String)get_Value(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_M_PriceList_V.java
1
请完成以下Java代码
public void updateUser(String username, User body) throws RestClientException { updateUserWithHttpInfo(username, body); } /** * Updated user * This can only be done by the logged in user. * <p><b>400</b> - Invalid user supplied * <p><b>404</b> - User not found * @param username name that need to be updated (required) * @param body Updated user object (required) * @return ResponseEntity&lt;Void&gt; * @throws RestClientException if an error occurs while attempting to invoke the API */ public ResponseEntity<Void> updateUserWithHttpInfo(String username, User body) throws RestClientException { Object postBody = body; // verify the required parameter 'username' is set if (username == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling updateUser"); } // verify the required parameter 'body' is set if (body == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling updateUser"); } // create path and map variables final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("username", username);
String path = apiClient.expandPath("/user/{username}", uriVariables); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>(); final MultiValueMap formParams = new LinkedMultiValueMap(); final String[] accepts = { }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { "application/json" }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {}; return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); } }
repos\tutorials-master\spring-swagger-codegen-modules\spring-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\api\UserApi.java
1
请完成以下Java代码
private int calculateScore(Board board, int depth) { return Arrays.stream(Move.values()) .parallel() .map(board::move) .filter(moved -> !moved.equals(board)) .mapToInt(newBoard -> generateScore(newBoard, depth)) .max() .orElse(0); } private int calculateFinalScore(Board board) { List<List<Integer>> rowsToScore = new ArrayList<>(); for (int i = 0; i < board.getSize(); ++i) { List<Integer> row = new ArrayList<>(); List<Integer> col = new ArrayList<>(); for (int j = 0; j < board.getSize(); ++j) { row.add(board.getCell(new Cell(i, j))); col.add(board.getCell(new Cell(j, i))); } rowsToScore.add(row); rowsToScore.add(col); } return rowsToScore.stream() .parallel() .mapToInt(row -> { List<Integer> preMerged = row.stream() .filter(value -> value != 0) .collect(Collectors.toList()); int numMerges = 0; int monotonicityLeft = 0; int monotonicityRight = 0; for (int i = 0; i < preMerged.size() - 1; ++i) { Integer first = preMerged.get(i); Integer second = preMerged.get(i + 1); if (first.equals(second)) {
++numMerges; } else if (first > second) { monotonicityLeft += first - second; } else { monotonicityRight += second - first; } } int score = 1000; score += 250 * row.stream().filter(value -> value == 0).count(); score += 750 * numMerges; score -= 10 * row.stream().mapToInt(value -> value).sum(); score -= 50 * Math.min(monotonicityLeft, monotonicityRight); return score; }) .sum(); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-6\src\main\java\com\baeldung\algorithms\play2048\Human.java
1
请在Spring Boot框架中完成以下Java代码
public void setClosingNote (final @Nullable java.lang.String ClosingNote) { set_Value (COLUMNNAME_ClosingNote, ClosingNote); } @Override public java.lang.String getClosingNote() { return get_ValueAsString(COLUMNNAME_ClosingNote); } @Override public org.compiere.model.I_C_POS getC_POS() { return get_ValueAsPO(COLUMNNAME_C_POS_ID, org.compiere.model.I_C_POS.class); } @Override public void setC_POS(final org.compiere.model.I_C_POS C_POS) { set_ValueFromPO(COLUMNNAME_C_POS_ID, org.compiere.model.I_C_POS.class, C_POS); } @Override public void setC_POS_ID (final int C_POS_ID) { if (C_POS_ID < 1) set_Value (COLUMNNAME_C_POS_ID, null); else set_Value (COLUMNNAME_C_POS_ID, C_POS_ID); } @Override public int getC_POS_ID() { return get_ValueAsInt(COLUMNNAME_C_POS_ID); } @Override public void setC_POS_Journal_ID (final int C_POS_Journal_ID) { if (C_POS_Journal_ID < 1) set_ValueNoCheck (COLUMNNAME_C_POS_Journal_ID, null); else set_ValueNoCheck (COLUMNNAME_C_POS_Journal_ID, C_POS_Journal_ID); } @Override public int getC_POS_Journal_ID() { return get_ValueAsInt(COLUMNNAME_C_POS_Journal_ID); } @Override public void setDateTrx (final java.sql.Timestamp DateTrx)
{ set_Value (COLUMNNAME_DateTrx, DateTrx); } @Override public java.sql.Timestamp getDateTrx() { return get_ValueAsTimestamp(COLUMNNAME_DateTrx); } @Override public void setDocumentNo (final java.lang.String DocumentNo) { set_Value (COLUMNNAME_DocumentNo, DocumentNo); } @Override public java.lang.String getDocumentNo() { return get_ValueAsString(COLUMNNAME_DocumentNo); } @Override public void setIsClosed (final boolean IsClosed) { set_Value (COLUMNNAME_IsClosed, IsClosed); } @Override public boolean isClosed() { return get_ValueAsBoolean(COLUMNNAME_IsClosed); } @Override public void setOpeningNote (final @Nullable java.lang.String OpeningNote) { set_Value (COLUMNNAME_OpeningNote, OpeningNote); } @Override public java.lang.String getOpeningNote() { return get_ValueAsString(COLUMNNAME_OpeningNote); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_Journal.java
2
请在Spring Boot框架中完成以下Java代码
public static class EdiDesadvPackItemQuery { @Nullable InOutLineId inOutLineId; @Nullable EDIDesadvPackId ediDesadvPackId; @Nullable EDIDesadvLineId desadvLineId; @Nullable Boolean withInOutLineId; @NonNull public static EdiDesadvPackItemQuery ofInOutLineId(@NonNull final InOutLineId inOutLineId) { return EdiDesadvPackItemQuery.builder() .inOutLineId(inOutLineId) .build(); } @NonNull public static EdiDesadvPackItemQuery ofDesadvPackId(@NonNull final EDIDesadvPackId desadvPackId) { return EdiDesadvPackItemQuery.builder() .ediDesadvPackId(desadvPackId) .build(); } @NonNull public static EdiDesadvPackItemQuery ofDesadvLineWithNoInOutLine(@NonNull final EDIDesadvLineId desadvLineId) { return EdiDesadvPackItemQuery.builder() .desadvLineId(desadvLineId) .withInOutLineId(false) .build(); }
@Builder private EdiDesadvPackItemQuery( @Nullable final InOutLineId inOutLineId, @Nullable final EDIDesadvPackId ediDesadvPackId, @Nullable final EDIDesadvLineId desadvLineId, @Nullable final Boolean withInOutLineId) { if (CoalesceUtil.coalesce(inOutLineId, ediDesadvPackId, desadvLineId, withInOutLineId) == null) { throw new AdempiereException("inOutLineId, ediDesadvPackId, desadvLineId && withInOutLineId cannot be all null!"); } this.inOutLineId = inOutLineId; this.ediDesadvPackId = ediDesadvPackId; this.desadvLineId = desadvLineId; this.withInOutLineId = withInOutLineId; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\impl\pack\EDIDesadvPackRepository.java
2
请完成以下Java代码
public void setPrintOverride(final boolean printOverride) { _printOverride = printOverride; _printBefore = true; } public void saveLines(final Collection<IQualityInvoiceLine> lines) { if (lines == null || lines.isEmpty()) { return; } // // Iterate lines and save one by one for (final IQualityInvoiceLine line : lines) { saveLine(line); } } private void saveLine(@NonNull final IQualityInvoiceLine line) { final I_C_Invoice_Candidate invoiceCandidate = getC_Invoice_Candidate(); final int seqNo = _seqNoNext; final Quantity lineQty = line.getQty(); // Pricing final IPricingResult pricingResult = line.getPrice(); final UomId priceUOMId; final BigDecimal price; final BigDecimal discount; final BigDecimal qtyEnteredInPriceUOM; if (pricingResult != null) { priceUOMId = pricingResult.getPriceUomId(); price = pricingResult.getPriceStd(); discount = pricingResult.getDiscount().toBigDecimal(); final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class); qtyEnteredInPriceUOM = uomConversionBL .convertQuantityTo( lineQty, UOMConversionContext.of(line.getProductId()), priceUOMId) .toBigDecimal(); } else { priceUOMId = lineQty.getUomId();
price = null; discount = null; qtyEnteredInPriceUOM = lineQty.toBigDecimal(); } final I_C_Invoice_Detail invoiceDetail = InterfaceWrapperHelper.newInstance(I_C_Invoice_Detail.class, getContext()); invoiceDetail.setAD_Org_ID(invoiceCandidate.getAD_Org_ID()); invoiceDetail.setC_Invoice_Candidate(invoiceCandidate); invoiceDetail.setSeqNo(seqNo); invoiceDetail.setIsActive(true); invoiceDetail.setIsDetailOverridesLine(isPrintOverride()); invoiceDetail.setIsPrinted(isPrintOverride() ? true : line.isDisplayed()); // the override-details line is always printed invoiceDetail.setDescription(line.getDescription()); invoiceDetail.setIsPrintBefore(isPrintBefore()); invoiceDetail.setM_Product_ID(ProductId.toRepoId(line.getProductId())); invoiceDetail.setNote(line.getProductName()); // invoiceDetail.setM_AttributeSetInstance(M_AttributeSetInstance); invoiceDetail.setQty(lineQty.toBigDecimal()); invoiceDetail.setC_UOM_ID(lineQty.getUomId().getRepoId()); invoiceDetail.setDiscount(discount); invoiceDetail.setPriceEntered(price); invoiceDetail.setPriceActual(price); invoiceDetail.setQtyEnteredInPriceUOM(qtyEnteredInPriceUOM); invoiceDetail.setPrice_UOM_ID(UomId.toRepoId(priceUOMId)); invoiceDetail.setPercentage(line.getPercentage()); invoiceDetail.setPP_Order(line.getPP_Order()); // Set Handling Units specific infos handlingUnitsInfoFactory.updateInvoiceDetail(invoiceDetail, line.getHandlingUnitsInfo()); // // Save detail line InterfaceWrapperHelper.save(invoiceDetail); I_C_Invoice_Detail.DYNATTR_C_Invoice_Detail_IQualityInvoiceLine.setValue(invoiceDetail, line); _createdLines.add(invoiceDetail); _seqNoNext += 10; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\ic\spi\impl\InvoiceDetailWriter.java
1
请完成以下Java代码
public CommandExecutor getCommandExecutor() { return commandExecutor; } public String getBusinessKey() { return businessKey; } public String getProcessDefinitionId() { return processDefinitionId; } public VariableMap getVariables() { return variables; } public String getTenantId() { return tenantId; } public boolean isTenantIdSet() { return isTenantIdSet; } protected <T> T execute(Command<T> command) { return commandExecutor.execute(command); } @Override public ConditionEvaluationBuilder processInstanceBusinessKey(String businessKey) { ensureNotNull("businessKey", businessKey); this.businessKey = businessKey; return this; } @Override public ConditionEvaluationBuilder processDefinitionId(String processDefinitionId) { ensureNotNull("processDefinitionId", processDefinitionId); this.processDefinitionId = processDefinitionId; return this; } @Override public ConditionEvaluationBuilder setVariable(String variableName, Object variableValue) { ensureNotNull("variableName", variableName); this.variables.put(variableName, variableValue); return this; } @Override public ConditionEvaluationBuilder setVariables(Map<String, Object> variables) { ensureNotNull("variables", variables); if (variables != null) {
this.variables.putAll(variables); } return this; } @Override public ConditionEvaluationBuilder tenantId(String tenantId) { ensureNotNull( "The tenant-id cannot be null. Use 'withoutTenantId()' if you want to evaluate conditional start event with a process definition which has no tenant-id.", "tenantId", tenantId); isTenantIdSet = true; this.tenantId = tenantId; return this; } @Override public ConditionEvaluationBuilder withoutTenantId() { isTenantIdSet = true; tenantId = null; return this; } @Override public List<ProcessInstance> evaluateStartConditions() { return execute(new EvaluateStartConditionCmd(this)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ConditionEvaluationBuilderImpl.java
1
请完成以下Java代码
public void eraseCredentials() { super.eraseCredentials(); this.credentials = null; } @Override public Builder<?> toBuilder() { return new Builder<>(this); } /** * A builder of {@link UsernamePasswordAuthenticationToken} instances * * @since 7.0 */ public static class Builder<B extends Builder<B>> extends AbstractAuthenticationBuilder<B> { private @Nullable Object principal; private @Nullable Object credentials; protected Builder(UsernamePasswordAuthenticationToken token) { super(token); this.principal = token.principal; this.credentials = token.credentials;
} @Override public B principal(@Nullable Object principal) { Assert.notNull(principal, "principal cannot be null"); this.principal = principal; return (B) this; } @Override public B credentials(@Nullable Object credentials) { this.credentials = credentials; return (B) this; } @Override public UsernamePasswordAuthenticationToken build() { return new UsernamePasswordAuthenticationToken(this); } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\UsernamePasswordAuthenticationToken.java
1
请完成以下Java代码
public ProductPrice toProductPrice(@NonNull final I_M_ProductPrice record) { return ProductPrice.builder() .orgId(OrgId.ofRepoId(record.getAD_Org_ID())) .productId(ProductId.ofRepoId(record.getM_Product_ID())) .productPriceId(ProductPriceId.ofRepoId(record.getM_ProductPrice_ID())) .priceListVersionId(PriceListVersionId.ofRepoId(record.getM_PriceList_Version_ID())) .priceLimit(record.getPriceLimit()) .priceList(record.getPriceList()) .priceStd(record.getPriceStd()) .taxCategoryId(productTaxCategoryService.getTaxCategoryId(record)) .isActive(record.isActive()) .uomId(UomId.ofRepoId(record.getC_UOM_ID())) .seqNo(record.getSeqNo()) .build(); } @NonNull private I_M_ProductPrice buildNewProductPriceRecord(@NonNull final CreateProductPriceRequest request) { final I_M_ProductPrice record = InterfaceWrapperHelper.newInstance(I_M_ProductPrice.class); record.setAD_Org_ID(request.getOrgId().getRepoId()); record.setM_Product_ID(request.getProductId().getRepoId()); record.setM_PriceList_Version_ID(request.getPriceListVersionId().getRepoId()); record.setPriceLimit(request.getPriceLimit()); record.setPriceList(request.getPriceList()); record.setPriceStd(request.getPriceStd()); record.setC_UOM_ID(request.getUomId().getRepoId()); record.setC_TaxCategory_ID(request.getTaxCategoryId().getRepoId()); if (request.getIsActive() != null) { record.setIsActive(request.getIsActive()); } if (request.getSeqNo() != null) { record.setSeqNo(request.getSeqNo()); } return record; } @NonNull private I_M_ProductPrice toProductPriceRecord(@NonNull final ProductPrice request) { final I_M_ProductPrice record = getRecordById(request.getProductPriceId()); record.setAD_Org_ID(request.getOrgId().getRepoId()); record.setM_Product_ID(request.getProductId().getRepoId()); record.setM_PriceList_Version_ID(request.getPriceListVersionId().getRepoId()); record.setPriceLimit(request.getPriceLimit()); record.setPriceList(request.getPriceList()); record.setPriceStd(request.getPriceStd());
record.setC_UOM_ID(request.getUomId().getRepoId()); record.setC_TaxCategory_ID(request.getTaxCategoryId().getRepoId()); record.setSeqNo(request.getSeqNo()); record.setIsActive(request.getIsActive()); return record; } @NonNull private I_M_ProductPrice getRecordById(@NonNull final ProductPriceId productPriceId) { return queryBL .createQueryBuilder(I_M_ProductPrice.class) .addEqualsFilter(I_M_ProductPrice.COLUMNNAME_M_ProductPrice_ID, productPriceId.getRepoId()) .create() .firstOnlyNotNull(I_M_ProductPrice.class); } @NonNull public <T extends I_M_ProductPrice> T getRecordById(@NonNull final ProductPriceId productPriceId, @NonNull final Class<T> productPriceClass) { return InterfaceWrapperHelper.load(productPriceId, productPriceClass); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\productprice\ProductPriceRepository.java
1
请完成以下Java代码
public int getAD_Client_ID() { return inoutLine.getAD_Client_ID(); } @Override public int getAD_Org_ID() { return inoutLine.getAD_Org_ID(); } @Override public boolean isSOTrx() { final I_M_InOut inout = getM_InOut(); return inout.isSOTrx(); } @Override public I_C_Country getC_Country() { final I_M_InOut inout = getM_InOut(); final I_C_BPartner_Location bpLocation = InterfaceWrapperHelper.load(inout.getC_BPartner_Location_ID(), I_C_BPartner_Location.class); if (bpLocation == null)
{ return null; } return bpLocation.getC_Location().getC_Country(); } private I_M_InOut getM_InOut() { final I_M_InOut inout = inoutLine.getM_InOut(); if (inout == null) { throw new AdempiereException("M_InOut_ID was not set in " + inoutLine); } return inout; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\mm\attributes\countryattribute\impl\InOutLineCountryAware.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isContinueOnError() { return this.continueOnError; } public void setContinueOnError(boolean continueOnError) { this.continueOnError = continueOnError; } public String getSeparator() { return this.separator; } public void setSeparator(String separator) { this.separator = separator; } public @Nullable Charset getEncoding() {
return this.encoding; } public void setEncoding(@Nullable Charset encoding) { this.encoding = encoding; } public DatabaseInitializationMode getMode() { return this.mode; } public void setMode(DatabaseInitializationMode mode) { this.mode = mode; } }
repos\spring-boot-4.0.1\module\spring-boot-sql\src\main\java\org\springframework\boot\sql\autoconfigure\init\SqlInitializationProperties.java
2
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setCamelHttpResourceAuthKey (final @Nullable java.lang.String CamelHttpResourceAuthKey) { set_Value (COLUMNNAME_CamelHttpResourceAuthKey, CamelHttpResourceAuthKey); } @Override public java.lang.String getCamelHttpResourceAuthKey() { return get_ValueAsString(COLUMNNAME_CamelHttpResourceAuthKey); } @Override public de.metas.externalsystem.model.I_ExternalSystem_Config getExternalSystem_Config() { return get_ValueAsPO(COLUMNNAME_ExternalSystem_Config_ID, de.metas.externalsystem.model.I_ExternalSystem_Config.class); } @Override public void setExternalSystem_Config(final de.metas.externalsystem.model.I_ExternalSystem_Config ExternalSystem_Config) { set_ValueFromPO(COLUMNNAME_ExternalSystem_Config_ID, de.metas.externalsystem.model.I_ExternalSystem_Config.class, ExternalSystem_Config); } @Override public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID) { if (ExternalSystem_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID); }
@Override public int getExternalSystem_Config_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID); } @Override public void setExternalSystem_Config_WooCommerce_ID (final int ExternalSystem_Config_WooCommerce_ID) { if (ExternalSystem_Config_WooCommerce_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_WooCommerce_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_WooCommerce_ID, ExternalSystem_Config_WooCommerce_ID); } @Override public int getExternalSystem_Config_WooCommerce_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_WooCommerce_ID); } @Override public void setExternalSystemValue (final java.lang.String ExternalSystemValue) { set_Value (COLUMNNAME_ExternalSystemValue, ExternalSystemValue); } @Override public java.lang.String getExternalSystemValue() { return get_ValueAsString(COLUMNNAME_ExternalSystemValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_WooCommerce.java
1
请完成以下Java代码
public UpdateTaskVariablePayload handleUpdateTaskVariablePayload( UpdateTaskVariablePayload updateTaskVariablePayload ) { checkNotValidCharactersInVariableName( updateTaskVariablePayload.getName(), "You cannot update a variable with not a valid name: " ); Object value = updateTaskVariablePayload.getValue(); if (value instanceof String) { handleAsDate((String) value).ifPresent(updateTaskVariablePayload::setValue); } return updateTaskVariablePayload; } public Map<String, Object> handlePayloadVariables(Map<String, Object> variables) { if (variables != null) { Set<String> mismatchedVars = variableNameValidator.validateVariables(variables);
if (!mismatchedVars.isEmpty()) { throw new IllegalStateException("Variables have not valid names: " + String.join(", ", mismatchedVars)); } handleStringVariablesAsDates(variables); } return variables; } private void handleStringVariablesAsDates(Map<String, Object> variables) { if (variables != null) { variables .entrySet() .stream() .filter(stringObjectEntry -> stringObjectEntry.getValue() instanceof String) .forEach(stringObjectEntry -> handleAsDate((String) stringObjectEntry.getValue()).ifPresent(stringObjectEntry::setValue) ); } } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-runtime-impl\src\main\java\org\activiti\runtime\api\impl\TaskVariablesPayloadValidator.java
1
请完成以下Java代码
public class EnglishAlphabetLetters { public static boolean checkStringForAllTheLetters(String input) { boolean[] visited = new boolean[26]; int index = 0; for (int id = 0; id < input.length(); id++) { if ('a' <= input.charAt(id) && input.charAt(id) <= 'z') { index = input.charAt(id) - 'a'; } else if ('A' <= input.charAt(id) && input.charAt(id) <= 'Z') { index = input.charAt(id) - 'A'; } visited[index] = true; } for (int id = 0; id < 26; id++) { if (!visited[id]) {
return false; } } return true; } public static boolean checkStringForAllLetterUsingStream(String input) { long c = input.toLowerCase().chars().filter(ch -> ch >= 'a' && ch <= 'z').distinct().count(); return c == 26; } public static void main(String[] args) { checkStringForAllLetterUsingStream("intit"); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-4\src\main\java\com\baeldung\algorithms\string\EnglishAlphabetLetters.java
1
请在Spring Boot框架中完成以下Java代码
public String getProcessInstanceUrl() { return processInstanceUrl; } public void setProcessInstanceUrl(String processInstanceUrl) { this.processInstanceUrl = processInstanceUrl; } @ApiModelProperty(example = "4") public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } @ApiModelProperty(example = "4") public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } @ApiModelProperty(example = "null") public String getCalledProcessInstanceId() { return calledProcessInstanceId; } public void setCalledProcessInstanceId(String calledProcessInstanceId) { this.calledProcessInstanceId = calledProcessInstanceId; } @ApiModelProperty(example = "fozzie") public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } @ApiModelProperty(example = "2013-04-17T10:17:43.902+0000") public Date getStartTime() { return startTime; }
public void setStartTime(Date startTime) { this.startTime = startTime; } @ApiModelProperty(example = "2013-04-18T14:06:32.715+0000") public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } @ApiModelProperty(example = "86400056") public Long getDurationInMillis() { return durationInMillis; } public void setDurationInMillis(Long durationInMillis) { this.durationInMillis = durationInMillis; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricActivityInstanceResponse.java
2
请完成以下Java代码
public class HtmlCrawler extends WebCrawler { private final static Pattern EXCLUSIONS = Pattern.compile(".*(\\.(css|js|xml|gif|jpg|png|mp3|mp4|zip|gz|pdf))$"); private CrawlerStatistics stats; public HtmlCrawler(CrawlerStatistics stats) { this.stats = stats; } @Override public boolean shouldVisit(Page referringPage, WebURL url) { String urlString = url.getURL().toLowerCase(); return !EXCLUSIONS.matcher(urlString).matches() && urlString.startsWith("https://www.baeldung.com/"); } @Override public void visit(Page page) { String url = page.getWebURL().getURL(); stats.incrementProcessedPageCount();
if (page.getParseData() instanceof HtmlParseData) { HtmlParseData htmlParseData = (HtmlParseData) page.getParseData(); String title = htmlParseData.getTitle(); String text = htmlParseData.getText(); String html = htmlParseData.getHtml(); Set<WebURL> links = htmlParseData.getOutgoingUrls(); stats.incrementTotalLinksCount(links.size()); System.out.printf("Page with title '%s' %n", title); System.out.printf(" Text length: %d %n", text.length()); System.out.printf(" HTML length: %d %n", html.length()); System.out.printf(" %d outbound links %n", links.size()); } } }
repos\tutorials-master\libraries-4\src\main\java\com\baeldung\crawler4j\HtmlCrawler.java
1
请在Spring Boot框架中完成以下Java代码
public class BaeldungArticle { @Id @GeneratedValue private Long id; private String title; private String content; private String author; @Transient private boolean alreadySaved = false; @PostPersist @PostUpdate private void markAsSaved() { this.alreadySaved = true; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content;
} public void setContent(String content) { this.content = content; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public boolean isAlreadySaved() { return alreadySaved; } public void setAlreadySaved(boolean alreadySaved) { this.alreadySaved = alreadySaved; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-5\src\main\java\com\baeldung\returnedvalueofsave\entity\BaeldungArticle.java
2