instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private Optional<I_ExternalSystem_Config_ProCareManagement> getPCMConfigByValue(@NonNull final String value) { return queryBL.createQueryBuilder(I_ExternalSystem_Config_ProCareManagement.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_ExternalSystem_Config_ProCareManagement.COLUMNNAME_ExternalSystemValue, value) .create() .firstOnlyOptional(I_ExternalSystem_Config_ProCareManagement.class); } @NonNull private Optional<I_ExternalSystem_Config_ScriptedImportConversion> getScriptedImportConversionConfigByValue(@NonNull final String value) { return queryBL.createQueryBuilder(I_ExternalSystem_Config_ScriptedImportConversion.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_ExternalSystem_Config_ScriptedImportConversion.COLUMNNAME_ExternalSystemValue, value) .create() .firstOnlyOptional(I_ExternalSystem_Config_ScriptedImportConversion.class); } @NonNull private ImmutableList<ExternalSystemParentConfig> getAllByTypePCM() { return queryBL.createQueryBuilder(I_ExternalSystem_Config_ProCareManagement.class) .addOnlyActiveRecordsFilter()
.create() .stream() .map(this::getExternalSystemParentConfig) .collect(ImmutableList.toImmutableList()); } @NonNull private ImmutableList<ExternalSystemParentConfig> getAllByScriptedImportConversion() { return queryBL.createQueryBuilder(I_ExternalSystem_Config_ScriptedImportConversion.class) .addOnlyActiveRecordsFilter() .create() .stream() .map(this::getExternalSystemParentConfig) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\ExternalSystemConfigRepo.java
1
请完成以下Java代码
public String getValue() { return this.value; } /** * Returns {@code true} if this path has the given {@link WebServerNamespace}. * @param webServerNamespace the server namespace * @return the new instance */ public boolean hasNamespace(WebServerNamespace webServerNamespace) { return this.namespace.equals(webServerNamespace); } @Override public boolean equals(@Nullable Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } AdditionalHealthEndpointPath other = (AdditionalHealthEndpointPath) obj; boolean result = true; result = result && this.namespace.equals(other.namespace); result = result && this.canonicalValue.equals(other.canonicalValue); return result; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.namespace.hashCode(); result = prime * result + this.canonicalValue.hashCode(); return result; } @Override public String toString() { return this.namespace.getValue() + ":" + this.value; } /**
* Creates an {@link AdditionalHealthEndpointPath} from the given input. The input * must contain a prefix and value separated by a `:`. The value must be limited to * one path segment. For example, `server:/healthz`. * @param value the value to parse * @return the new instance */ public static AdditionalHealthEndpointPath from(String value) { Assert.hasText(value, "'value' must not be null"); String[] values = value.split(":"); Assert.isTrue(values.length == 2, "'value' must contain a valid namespace and value separated by ':'."); Assert.isTrue(StringUtils.hasText(values[0]), "'value' must contain a valid namespace."); WebServerNamespace namespace = WebServerNamespace.from(values[0]); validateValue(values[1]); return new AdditionalHealthEndpointPath(namespace, values[1]); } /** * Creates an {@link AdditionalHealthEndpointPath} from the given * {@link WebServerNamespace} and value. * @param webServerNamespace the server namespace * @param value the value * @return the new instance */ public static AdditionalHealthEndpointPath of(WebServerNamespace webServerNamespace, String value) { Assert.notNull(webServerNamespace, "'webServerNamespace' must not be null."); Assert.notNull(value, "'value' must not be null."); validateValue(value); return new AdditionalHealthEndpointPath(webServerNamespace, value); } private static void validateValue(String value) { Assert.isTrue(StringUtils.countOccurrencesOf(value, "/") <= 1 && value.indexOf("/") <= 0, "'value' must contain only one segment."); } }
repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\actuate\endpoint\AdditionalHealthEndpointPath.java
1
请完成以下Java代码
protected final Mono<Health> doHealthCheck(Health.Builder builder) { return validate(builder).defaultIfEmpty(builder.build()) .onErrorResume(Exception.class, (ex) -> Mono.just(builder.down(ex).build())); } private Mono<Health> validate(Health.Builder builder) { builder.withDetail("database", this.connectionFactory.getMetadata().getName()); return (StringUtils.hasText(this.validationQuery)) ? validateWithQuery(builder) : validateWithConnectionValidation(builder); } private Mono<Health> validateWithQuery(Health.Builder builder) { Assert.state(this.validationQuery != null, "'validationQuery' must not be null"); builder.withDetail("validationQuery", this.validationQuery); Mono<Object> connectionValidation = Mono.usingWhen(this.connectionFactory.create(), (conn) -> Flux.from(conn.createStatement(this.validationQuery).execute()) .flatMap((it) -> it.map(this::extractResult)) .next(),
Connection::close, (o, throwable) -> o.close(), Connection::close); return connectionValidation.map((result) -> builder.up().withDetail("result", result).build()); } private Mono<Health> validateWithConnectionValidation(Health.Builder builder) { builder.withDetail("validationQuery", "validate(REMOTE)"); Mono<Boolean> connectionValidation = Mono.usingWhen(this.connectionFactory.create(), (connection) -> Mono.from(connection.validate(ValidationDepth.REMOTE)), Connection::close, (connection, ex) -> connection.close(), Connection::close); return connectionValidation.map((valid) -> builder.status((valid) ? Status.UP : Status.DOWN).build()); } private @Nullable Object extractResult(Row row, RowMetadata metadata) { return row.get(metadata.getColumnMetadatas().iterator().next().getName()); } }
repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\health\ConnectionFactoryHealthIndicator.java
1
请完成以下Java代码
public CreditorReferenceInformation2 getCdtrRefInf() { return cdtrRefInf; } /** * Sets the value of the cdtrRefInf property. * * @param value * allowed object is * {@link CreditorReferenceInformation2 } * */ public void setCdtrRefInf(CreditorReferenceInformation2 value) { this.cdtrRefInf = value; } /** * Gets the value of the invcr property. * * @return * possible object is * {@link PartyIdentification32 } * */ public PartyIdentification32 getInvcr() { return invcr; } /** * Sets the value of the invcr property. * * @param value * allowed object is * {@link PartyIdentification32 } * */ public void setInvcr(PartyIdentification32 value) { this.invcr = value; } /** * Gets the value of the invcee property. * * @return * possible object is * {@link PartyIdentification32 } * */ public PartyIdentification32 getInvcee() { return invcee; }
/** * Sets the value of the invcee property. * * @param value * allowed object is * {@link PartyIdentification32 } * */ public void setInvcee(PartyIdentification32 value) { this.invcee = value; } /** * Gets the value of the addtlRmtInf property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the addtlRmtInf property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAddtlRmtInf().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getAddtlRmtInf() { if (addtlRmtInf == null) { addtlRmtInf = new ArrayList<String>(); } return this.addtlRmtInf; } }
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\StructuredRemittanceInformation7.java
1
请完成以下Java代码
public OrderCostType getById(@NonNull OrderCostTypeId id) { return getMap().getById(id); } private OrderCostTypeMap getMap() { return cache.getOrLoad(0, this::retrieveMap); } private OrderCostTypeMap retrieveMap() { final ImmutableList<OrderCostType> list = queryBL.createQueryBuilder(I_C_Cost_Type.class) .addOnlyActiveRecordsFilter() .create() .stream() .map(OrderCostTypeRepository::fromRecord) .collect(ImmutableList.toImmutableList()); return new OrderCostTypeMap(list); } private static OrderCostType fromRecord(@NonNull final I_C_Cost_Type record) { return OrderCostType.builder() .id(OrderCostTypeId.ofRepoId(record.getC_Cost_Type_ID())) .code(record.getValue()) .name(record.getName()) .distributionMethod(CostDistributionMethod.ofCode(record.getCostDistributionMethod())) .calculationMethod(CostCalculationMethod.ofCode(record.getCostCalculationMethod())) .costElementId(CostElementId.ofRepoId(record.getM_CostElement_ID())) .invoiceableProductId(record.isAllowInvoicing() ? ProductId.ofRepoId(record.getM_Product_ID()) : null)
.build(); } // // // private static class OrderCostTypeMap { private final ImmutableMap<OrderCostTypeId, OrderCostType> byId; public OrderCostTypeMap(final ImmutableList<OrderCostType> list) { this.byId = Maps.uniqueIndex(list, OrderCostType::getId); } public OrderCostType getById(@NonNull final OrderCostTypeId id) { return Check.assumeNotNull(byId.get(id), "No cost type found for {}", id); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\OrderCostTypeRepository.java
1
请完成以下Java代码
private static SumUpTransaction.Card extractSumUpTransactionCard(@Nullable JsonGetTransactionResponse.Card from) { if (from == null) { return null; } final String type = StringUtils.trimBlankToNull(from.getType()); if (type == null) { return null; } final String last4Digits = StringUtils.trimBlankToNull(from.getLast_4_digits()); if (last4Digits == null) { return null; } return SumUpTransaction.Card.builder() .type(type) .last4Digits(last4Digits) .build(); } public BulkUpdateByQueryResult bulkUpdatePendingTransactions(boolean isForceSendingChangeEvents) { return bulkUpdateTransactions(SumUpTransactionQuery.ofStatus(SumUpTransactionStatus.PENDING), isForceSendingChangeEvents); } public BulkUpdateByQueryResult bulkUpdateTransactions(@NonNull SumUpTransactionQuery query, boolean isForceSendingChangeEvents) { return trxRepository.bulkUpdateByQuery(query, isForceSendingChangeEvents, this::updateTransactionFromRemote); } public SumUpTransaction refundTransaction(@NonNull final SumUpPOSRef posRef) { final SumUpTransactionExternalId id = findTransactionToRefundByPOSRef(posRef); return refundTransaction(id); } private @NonNull SumUpTransactionExternalId findTransactionToRefundByPOSRef(final @NonNull SumUpPOSRef posRef) { if (posRef.getPosPaymentId() <= 0) { throw new AdempiereException("posPaymentId not provided"); } final List<SumUpTransaction> trxs = trxRepository.stream(SumUpTransactionQuery.builder() .status(SumUpTransactionStatus.SUCCESSFUL) .posRef(posRef)
.build()) .filter(trx -> !trx.isRefunded()) .collect(Collectors.toList()); if (trxs.isEmpty()) { throw new AdempiereException("No successful transactions found"); } else if (trxs.size() != 1) { throw new AdempiereException("More than successful transaction found"); } else { return trxs.get(0).getExternalId(); } } public SumUpTransaction refundTransaction(@NonNull final SumUpTransactionExternalId id) { return trxRepository.updateById(id, trx -> { final SumUpConfig config = configRepository.getById(trx.getConfigId()); final SumUpClient client = clientFactory.newClient(config); client.setPosRef(trx.getPosRef()); client.refundTransaction(trx.getExternalId()); final JsonGetTransactionResponse remoteTrx = client.getTransactionById(trx.getExternalId()); return updateTransactionFromRemote(trx, remoteTrx); }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\SumUpService.java
1
请在Spring Boot框架中完成以下Java代码
public class Effort { public final static Effort ZERO = new Effort(0); long seconds; @NonNull public static Effort ofNullable(@Nullable final String hmm) { final long seconds = hmm != null ? HmmUtils.hmmToSeconds(hmm) : 0; return new Effort(seconds); } @NonNull public static Effort ofSeconds(final long seconds) { return new Effort(seconds); } @NonNull public Effort addNullSafe(@Nullable final Effort effort) { final long secondsToAdd = effort != null ? effort.getSeconds() : 0; final long secondsSum = getSeconds() + secondsToAdd; return new Effort(secondsSum); }
@NonNull public String getHmm() { return HmmUtils.secondsToHmm(seconds); } @NonNull public Effort negate() { return new Effort(-seconds); } private Effort(final long seconds) { this.seconds = seconds; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\timebooking\Effort.java
2
请完成以下Java代码
public void afterPropertiesSet() { Assert.notNull(this.messages, "A message source must be set"); } @Override public @Nullable Authentication authenticate(Authentication authentication) throws AuthenticationException { if (!supports(authentication.getClass())) { return null; } if (this.key.hashCode() != ((RememberMeAuthenticationToken) authentication).getKeyHash()) { throw new BadCredentialsException(this.messages.getMessage("RememberMeAuthenticationProvider.incorrectKey", "The presented RememberMeAuthenticationToken does not contain the expected key")); } return authentication; }
public String getKey() { return this.key; } @Override public void setMessageSource(MessageSource messageSource) { this.messages = new MessageSourceAccessor(messageSource); } @Override public boolean supports(Class<?> authentication) { return (RememberMeAuthenticationToken.class.isAssignableFrom(authentication)); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\RememberMeAuthenticationProvider.java
1
请完成以下Java代码
protected void updateTypedValue(ObjectValue value, String serializedStringValue) { String objectTypeName = getObjectTypeName(value, null); ObjectValueImpl objectValue =(ObjectValueImpl) value; objectValue.setObjectTypeName(objectTypeName); objectValue.setSerializedValue(serializedStringValue); objectValue.setSerializationDataFormat(serializationDataFormat); } protected ObjectValue createDeserializedValue(Object deserializedObject, String serializedStringValue, ValueFields valueFields, boolean asTransientValue) { String objectTypeName = readObjectNameFromFields(valueFields); ObjectValueImpl objectValue = new ObjectValueImpl(deserializedObject, serializedStringValue, serializationDataFormat, objectTypeName, true); objectValue.setTransient(asTransientValue); return objectValue; } protected ObjectValue createSerializedValue(String serializedStringValue, ValueFields valueFields, boolean asTransientValue) { String objectTypeName = readObjectNameFromFields(valueFields); ObjectValueImpl objectValue = new ObjectValueImpl(null, serializedStringValue, serializationDataFormat, objectTypeName, false); objectValue.setTransient(asTransientValue); return objectValue; } protected String readObjectNameFromFields(ValueFields valueFields) { return valueFields.getTextValue2(); } public boolean isMutableValue(ObjectValue typedValue) { return typedValue.isDeserialized(); } // methods to be implemented by subclasses //////////// /** * Returns the type name for the deserialized object. * * @param deserializedObject. Guaranteed not to be null * @return the type name fot the object.
*/ protected abstract String getTypeNameForDeserialized(Object deserializedObject); /** * Implementations must return a byte[] representation of the provided object. * The object is guaranteed not to be null. * * @param deserializedObject the object to serialize * @return the byte array value of the object * @throws exception in case the object cannot be serialized */ protected abstract byte[] serializeToByteArray(Object deserializedObject) throws Exception; protected Object deserializeFromByteArray(byte[] object, ValueFields valueFields) throws Exception { String objectTypeName = readObjectNameFromFields(valueFields); return deserializeFromByteArray(object, objectTypeName); } /** * Deserialize the object from a byte array. * * @param object the object to deserialize * @param objectTypeName the type name of the object to deserialize * @return the deserialized object * @throws exception in case the object cannot be deserialized */ protected abstract Object deserializeFromByteArray(byte[] object, String objectTypeName) throws Exception; /** * Return true if the serialization is text based. Return false otherwise * */ protected abstract boolean isSerializationTextBased(); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\serializer\AbstractObjectValueSerializer.java
1
请完成以下Java代码
public java.math.BigDecimal getStd_Discount () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Std_Discount); if (bd == null) return Env.ZERO; return bd; } /** Set Fixed Standard Price. @param Std_Fixed Fixed Standard Price (not calculated) */ @Override public void setStd_Fixed (java.math.BigDecimal Std_Fixed) { set_Value (COLUMNNAME_Std_Fixed, Std_Fixed); } /** Get Fixed Standard Price. @return Fixed Standard Price (not calculated) */ @Override public java.math.BigDecimal getStd_Fixed () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Std_Fixed); if (bd == null) return Env.ZERO; return bd; } /** Set Standard max Margin. @param Std_MaxAmt Maximum margin allowed for a product */ @Override public void setStd_MaxAmt (java.math.BigDecimal Std_MaxAmt) { set_Value (COLUMNNAME_Std_MaxAmt, Std_MaxAmt); } /** Get Standard max Margin. @return Maximum margin allowed for a product */ @Override public java.math.BigDecimal getStd_MaxAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Std_MaxAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Standard price min Margin. @param Std_MinAmt Minimum margin allowed for a product */ @Override 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 JsonTUPickingTarget { @NonNull String id; @NonNull String caption; // // New TU @Nullable HuPackingInstructionsId tuPIId; boolean isDefault; // // Existing TU @Nullable HuId tuId; @Nullable String tuQRCode; public static JsonTUPickingTarget of(@NonNull final TUPickingTarget target) { return builder() .id(target.getId()) .caption(target.getCaption()) .tuPIId(target.getTuPIId()) .isDefault(target.isDefaultPacking())
.tuId(target.getTuId()) .tuQRCode(target.getTuQRCode() != null ? target.getTuQRCode().toGlobalQRCodeString() : null) .build(); } public TUPickingTarget unbox() { return TUPickingTarget.builder() .caption(caption) .tuPIId(tuPIId) .isDefaultPacking(isDefault) .tuId(tuId) .tuQRCode(HUQRCode.fromNullableGlobalQRCodeJsonString(tuQRCode)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\rest_api\json\JsonTUPickingTarget.java
2
请完成以下Java代码
public Builder setCaption(final String caption) { this.caption = caption; return this; } public Builder setCaptionBreadcrumb(final String captionBreadcrumb) { this.captionBreadcrumb = captionBreadcrumb; return this; } public Builder setType(final MenuNodeType type, @Nullable final DocumentId elementId) { this.type = type; this.elementId = elementId; return this; } public Builder setTypeNewRecord(@NonNull final AdWindowId adWindowId) { return setType(MenuNodeType.NewRecord, DocumentId.of(adWindowId)); } public void setTypeGroup()
{ setType(MenuNodeType.Group, null); } public void addChildToFirstsList(@NonNull final MenuNode child) { childrenFirst.add(child); } public void addChild(@NonNull final MenuNode child) { childrenRest.add(child); } public Builder setMainTableName(final String mainTableName) { this.mainTableName = mainTableName; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\menu\MenuNode.java
1
请在Spring Boot框架中完成以下Java代码
public void setIsTaxIncluded (final boolean IsTaxIncluded) { set_Value (COLUMNNAME_IsTaxIncluded, IsTaxIncluded); } @Override public boolean isTaxIncluded() { return get_ValueAsBoolean(COLUMNNAME_IsTaxIncluded); } @Override public void setM_PriceList_ID (final int M_PriceList_ID) { if (M_PriceList_ID < 1) set_Value (COLUMNNAME_M_PriceList_ID, null); else set_Value (COLUMNNAME_M_PriceList_ID, M_PriceList_ID); } @Override public int getM_PriceList_ID() { return get_ValueAsInt(COLUMNNAME_M_PriceList_ID); } @Override public void setM_PricingSystem_ID (final int M_PricingSystem_ID) { if (M_PricingSystem_ID < 1) set_Value (COLUMNNAME_M_PricingSystem_ID, null); else set_Value (COLUMNNAME_M_PricingSystem_ID, M_PricingSystem_ID); } @Override public int getM_PricingSystem_ID() { return get_ValueAsInt(COLUMNNAME_M_PricingSystem_ID); } @Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setOpenAmt (final BigDecimal OpenAmt) { set_Value (COLUMNNAME_OpenAmt, OpenAmt); } @Override public BigDecimal getOpenAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_OpenAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPaidAmt (final BigDecimal PaidAmt) { set_Value (COLUMNNAME_PaidAmt, PaidAmt); } @Override public BigDecimal getPaidAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PaidAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed);
} @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } /** * Status AD_Reference_ID=541890 * Reference name: C_POS_Order_Status */ public static final int STATUS_AD_Reference_ID=541890; /** Drafted = DR */ public static final String STATUS_Drafted = "DR"; /** WaitingPayment = WP */ public static final String STATUS_WaitingPayment = "WP"; /** Completed = CO */ public static final String STATUS_Completed = "CO"; /** Voided = VO */ public static final String STATUS_Voided = "VO"; /** Closed = CL */ public static final String STATUS_Closed = "CL"; @Override public void setStatus (final java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return get_ValueAsString(COLUMNNAME_Status); } @Override public void setTaxAmt (final BigDecimal TaxAmt) { set_Value (COLUMNNAME_TaxAmt, TaxAmt); } @Override public BigDecimal getTaxAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_Order.java
2
请完成以下Java代码
public static HUAggregationType ofCode(@NonNull final String code) { final HUAggregationType type = typesByCode.get(code); if (type == null) { throw new AdempiereException("No " + HUAggregationType.class + " found for code: " + code); } return type; } public static HUAggregationType ofNullableCode(@Nullable final String code) { return code != null ? ofCode(code) : null; }
public static String toCodeOrNull(@Nullable final HUAggregationType type) { return type != null ? type.getCode() : null; } private static final ImmutableMap<String, HUAggregationType> typesByCode = ReferenceListAwareEnums.indexByCode(values()); public static boolean equals(@Nullable final HUAggregationType o1, @Nullable final HUAggregationType o2) { return Objects.equals(o1, o2); } public boolean isSingleHU() {return this.equals(SINGLE_HU);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inventory\HUAggregationType.java
1
请完成以下Java代码
public final <T> PInstanceId createSelectionFromModels(T... models) { final PInstanceId adPInstanceId = createSelectionPInstanceId(); if (models != null) { createSelectionFromModelsCollection(adPInstanceId, Arrays.asList(models)); } return adPInstanceId; } public <T> PInstanceId createSelectionFromModelsCollection(Collection<T> models) { final PInstanceId adPInstanceId = createSelectionPInstanceId(); createSelectionFromModelsCollection(adPInstanceId, models); return adPInstanceId; } public <T> void createSelectionFromModelsCollection(final PInstanceId selectionId, final Collection<T> models) { if (models == null || models.isEmpty()) { return; } final Set<Integer> selection = new HashSet<>(models.size()); for (final T model : models) { final int modelId = InterfaceWrapperHelper.getId(model); selection.add(modelId); } createSelection(selectionId, selection); } public boolean isInSelection(final PInstanceId selectionId, final int id) { return getSelectionIds(selectionId).contains(id); }
public Set<Integer> getSelectionIds(final PInstanceId selectionId) { final Set<Integer> selection = selectionId2selection.get(selectionId); return selection != null ? selection : ImmutableSet.of(); } public void dumpSelections() { StringBuilder sb = new StringBuilder(); sb.append("=====================[ SELECTIONS ]============================================================"); for (final PInstanceId selectionId : selectionId2selection.keySet()) { sb.append("\n\t").append(selectionId).append(": ").append(selectionId2selection.get(selectionId)); } sb.append("\n"); System.out.println(sb); } /** * @return new database restore point. */ public POJOLookupMapRestorePoint createRestorePoint() { return new POJOLookupMapRestorePoint(this); } @Override public void addImportInterceptor(String importTableName, IImportInterceptor listener) { // nothing } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POJOLookupMap.java
1
请完成以下Java代码
protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { // // Check if class is in the loaded classes cache // Class cachedClass = findLoadedClass(name); if (cachedClass != null) { if (resolve) { resolveClass(cachedClass); } return cachedClass; } // // Check parent class loaders // for (int i = 0; i < parents.length; i++) { ClassLoader parent = parents[i]; try { Class clazz = parent.loadClass(name); if (resolve) { resolveClass(clazz); } return clazz; } catch (ClassNotFoundException ignored) { // this parent didn't have the class; try the next one } } throw new ClassNotFoundException(name); } @Override public URL getResource(String name) { // // Check parent class loaders // for (int i = 0; i < parents.length; i++) { ClassLoader parent = parents[i]; URL url = parent.getResource(name); if (url != null) { return url;
} } return null; } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public Enumeration findResources(String name) throws IOException { List resources = new ArrayList(); // // Add parent resources // for (int i = 0; i < parents.length; i++) { ClassLoader parent = parents[i]; List parentResources = Collections.list(parent.getResources(name)); resources.addAll(parentResources); } return Collections.enumeration(resources); } }
repos\flowable-engine-main\modules\flowable-osgi\src\main\java\org\flowable\osgi\blueprint\ClassLoaderWrapper.java
1
请完成以下Java代码
private MovementId createDirectMovement( final @NonNull DDOrderMoveSchedule schedule, final @NonNull HuId huIdToMove) { final HUMovementGeneratorResult result = new HUMovementGenerator(toMovementGenerateRequest(schedule, huIdToMove)) .sharedHUIdsWithPackingMaterialsTransferred(huIdsWithPackingMaterialsTransferred) .createMovement(); return result.getSingleMovementLineId().getMovementId(); } private HUMovementGenerateRequest toMovementGenerateRequest( final @NonNull DDOrderMoveSchedule schedule, final @NonNull HuId huIdToMove) {
final I_DD_Order ddOrder = ddOrdersCache.getById(schedule.getDdOrderId()); return DDOrderMovementHelper.prepareMovementGenerateRequest(ddOrder, schedule.getDdOrderLineId()) .movementDate(movementDate) .fromLocatorId(schedule.getPickFromLocatorId()) .toLocatorId(locatorToIdOverride != null ? locatorToIdOverride : schedule.getDropToLocatorId()) .huIdToMove(huIdToMove) .build(); } private I_DD_Order getDDOrderById(final DDOrderId ddOrderId) { return ddOrdersCache.getById(ddOrderId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\generate\DirectMovementsFromSchedulesGenerator.java
1
请完成以下Java代码
public class X_AD_TreeBar extends org.compiere.model.PO implements I_AD_TreeBar, org.compiere.model.I_Persistent { /** * */ private static final long serialVersionUID = -180659685L; /** Standard Constructor */ public X_AD_TreeBar (Properties ctx, int AD_TreeBar_ID, String trxName) { super (ctx, AD_TreeBar_ID, trxName); /** if (AD_TreeBar_ID == 0) { setAD_User_ID (0); setNode_ID (0); } */ } /** Load Constructor */ public X_AD_TreeBar (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } @Override public org.compiere.model.I_AD_User getAD_User() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class); } @Override public void setAD_User(org.compiere.model.I_AD_User AD_User) { set_ValueFromPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class, AD_User); } /** Set Ansprechpartner. @param AD_User_ID User within the system - Internal or Business Partner Contact */
@Override public void setAD_User_ID (int AD_User_ID) { if (AD_User_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID)); } /** Get Ansprechpartner. @return User within the system - Internal or Business Partner Contact */ @Override public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Node_ID. @param Node_ID Node_ID */ @Override public void setNode_ID (int Node_ID) { if (Node_ID < 0) set_Value (COLUMNNAME_Node_ID, null); else set_Value (COLUMNNAME_Node_ID, Integer.valueOf(Node_ID)); } /** Get Node_ID. @return Node_ID */ @Override public int getNode_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Node_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_TreeBar.java
1
请完成以下Java代码
public class OAuth2UserRequestEntityConverter implements Converter<OAuth2UserRequest, RequestEntity<?>> { private static final MediaType DEFAULT_CONTENT_TYPE = MediaType .valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8"); /** * Returns the {@link RequestEntity} used for the UserInfo Request. * @param userRequest the user request * @return the {@link RequestEntity} used for the UserInfo Request */ @Override public RequestEntity<?> convert(OAuth2UserRequest userRequest) { ClientRegistration clientRegistration = userRequest.getClientRegistration(); HttpMethod httpMethod = getHttpMethod(clientRegistration); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); URI uri = UriComponentsBuilder .fromUriString(clientRegistration.getProviderDetails().getUserInfoEndpoint().getUri()) .build() .toUri(); RequestEntity<?> request; if (HttpMethod.POST.equals(httpMethod)) { headers.setContentType(DEFAULT_CONTENT_TYPE);
MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>(); formParameters.add(OAuth2ParameterNames.ACCESS_TOKEN, userRequest.getAccessToken().getTokenValue()); request = new RequestEntity<>(formParameters, headers, httpMethod, uri); } else { headers.setBearerAuth(userRequest.getAccessToken().getTokenValue()); request = new RequestEntity<>(headers, httpMethod, uri); } return request; } private HttpMethod getHttpMethod(ClientRegistration clientRegistration) { if (AuthenticationMethod.FORM .equals(clientRegistration.getProviderDetails().getUserInfoEndpoint().getAuthenticationMethod())) { return HttpMethod.POST; } return HttpMethod.GET; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\userinfo\OAuth2UserRequestEntityConverter.java
1
请完成以下Java代码
public org.compiere.model.I_C_Phase getC_Phase() { return get_ValueAsPO(COLUMNNAME_C_Phase_ID, org.compiere.model.I_C_Phase.class); } @Override public void setC_Phase(final org.compiere.model.I_C_Phase C_Phase) { set_ValueFromPO(COLUMNNAME_C_Phase_ID, org.compiere.model.I_C_Phase.class, C_Phase); } @Override public void setC_Phase_ID (final int C_Phase_ID) { if (C_Phase_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Phase_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Phase_ID, C_Phase_ID); } @Override public int getC_Phase_ID() { return get_ValueAsInt(COLUMNNAME_C_Phase_ID); } @Override public void setC_Task_ID (final int C_Task_ID) { if (C_Task_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Task_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Task_ID, C_Task_ID); } @Override public int getC_Task_ID() { return get_ValueAsInt(COLUMNNAME_C_Task_ID); } @Override public void setDescription (final java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setHelp (final java.lang.String Help) { set_Value (COLUMNNAME_Help, Help); } @Override public java.lang.String getHelp() {
return get_ValueAsString(COLUMNNAME_Help); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_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); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setStandardQty (final BigDecimal StandardQty) { set_Value (COLUMNNAME_StandardQty, StandardQty); } @Override public BigDecimal getStandardQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_StandardQty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Task.java
1
请完成以下Java代码
public ColumnInfo setPrecision(final int precision) { this.precision = precision; return this; } /** * * @return precision to be used in case it's a number */ public int getPrecision() { return this.precision; } public ColumnInfo setSortNo(final int sortNo) { this.sortNo = sortNo; return this; } /**
* Gets SortNo. * * @return * @see I_AD_Field#COLUMNNAME_SortNo. */ public int getSortNo() { return sortNo; } @Override public String toString() { return ObjectUtils.toString(this); } } // infoColumn
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\minigrid\ColumnInfo.java
1
请完成以下Java代码
public String getTaxTp() { return taxTp; } /** * Sets the value of the taxTp property. * * @param value * allowed object is * {@link String } * */ public void setTaxTp(String value) { this.taxTp = value; } /** * Gets the value of the authstn property. * * @return * possible object is * {@link TaxAuthorisation1 } *
*/ public TaxAuthorisation1 getAuthstn() { return authstn; } /** * Sets the value of the authstn property. * * @param value * allowed object is * {@link TaxAuthorisation1 } * */ public void setAuthstn(TaxAuthorisation1 value) { this.authstn = 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\TaxParty2.java
1
请完成以下Java代码
public void setCdtDbtInd(CreditDebitCode value) { this.cdtDbtInd = value; } /** * Gets the value of the dt property. * * @return * possible object is * {@link DateAndDateTimeChoice } * */ public DateAndDateTimeChoice getDt() { return dt; } /** * Sets the value of the dt property. * * @param value * allowed object is * {@link DateAndDateTimeChoice } * */ public void setDt(DateAndDateTimeChoice value) { this.dt = value; } /** * Gets the value of the avlbty property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the avlbty property. * * <p>
* For example, to add a new item, do as follows: * <pre> * getAvlbty().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CashBalanceAvailability2 } * * */ public List<CashBalanceAvailability2> getAvlbty() { if (avlbty == null) { avlbty = new ArrayList<CashBalanceAvailability2>(); } return this.avlbty; } }
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\CashBalance3.java
1
请完成以下Java代码
public LookupValue createProductLookupValue(final ProductId productId) { final String productValue = null; final String productName = null; return createProductLookupValue(productId, productValue, productName); } public LookupValue createProductLookupValue( @Nullable final ProductId productId, @Nullable final String productValue, @Nullable final String productName) { if (productId == null) { return null; } final I_M_Product product = productsRepo.getById(productId); if (product == null) { return IntegerLookupValue.unknown(productId.getRepoId()); } final String productValueEffective = !Check.isEmpty(productValue, true) ? productValue.trim() : product.getValue(); final String productNameEffective = !Check.isEmpty(productName, true) ? productName.trim() : product.getName(); final String displayName = productValueEffective + "_" + productNameEffective; return IntegerLookupValue.of(product.getM_Product_ID(), displayName); } public LookupValue createASILookupValue(final AttributeSetInstanceId attributeSetInstanceId) { if (attributeSetInstanceId == null) { return null; } final I_M_AttributeSetInstance asi = loadOutOfTrx(attributeSetInstanceId.getRepoId(), I_M_AttributeSetInstance.class); if (asi == null) { return null; } String description = asi.getDescription(); if (Check.isEmpty(description, true)) { description = "<" + attributeSetInstanceId.getRepoId() + ">"; } return IntegerLookupValue.of(attributeSetInstanceId.getRepoId(), description); } public LookupValue createBPartnerLookupValue(final BPartnerId bpartnerId) { if (bpartnerId == null) { return null; }
final I_C_BPartner bpartner = bpartnersRepo.getById(bpartnerId); if (bpartner == null) { return null; } final String displayName = bpartner.getValue() + "_" + bpartner.getName(); return IntegerLookupValue.of(bpartner.getC_BPartner_ID(), displayName); } public String createUOMLookupValueForProductId(final ProductId productId) { if (productId == null) { return null; } final I_C_UOM uom = productBL.getStockUOM(productId); if (uom == null) { return null; } return createUOMLookupValue(uom); } public String createUOMLookupValue(final I_C_UOM uom) { return translate(uom, I_C_UOM.class).getUOMSymbol(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseRowLookups.java
1
请在Spring Boot框架中完成以下Java代码
public void addListener(TenantId tenantId, EntityId listenerId, Consumer<AssetProfile> profileListener, BiConsumer<AssetId, AssetProfile> assetListener) { if (profileListener != null) { profileListeners.computeIfAbsent(tenantId, id -> new ConcurrentHashMap<>()).put(listenerId, profileListener); } if (assetListener != null) { assetProfileListeners.computeIfAbsent(tenantId, id -> new ConcurrentHashMap<>()).put(listenerId, assetListener); } } @Override public AssetProfile find(AssetProfileId assetProfileId) { return assetProfileService.findAssetProfileById(TenantId.SYS_TENANT_ID, assetProfileId); } @Override public AssetProfile findOrCreateAssetProfile(TenantId tenantId, String profileName) { return assetProfileService.findOrCreateAssetProfile(tenantId, profileName); } @Override public void removeListener(TenantId tenantId, EntityId listenerId) { ConcurrentMap<EntityId, Consumer<AssetProfile>> tenantListeners = profileListeners.get(tenantId); if (tenantListeners != null) { tenantListeners.remove(listenerId); } ConcurrentMap<EntityId, BiConsumer<AssetId, AssetProfile>> assetListeners = assetProfileListeners.get(tenantId);
if (assetListeners != null) { assetListeners.remove(listenerId); } } private void notifyProfileListeners(AssetProfile profile) { ConcurrentMap<EntityId, Consumer<AssetProfile>> tenantListeners = profileListeners.get(profile.getTenantId()); if (tenantListeners != null) { tenantListeners.forEach((id, listener) -> listener.accept(profile)); } } private void notifyAssetListeners(TenantId tenantId, AssetId assetId, AssetProfile profile) { if (profile != null) { ConcurrentMap<EntityId, BiConsumer<AssetId, AssetProfile>> tenantListeners = assetProfileListeners.get(tenantId); if (tenantListeners != null) { tenantListeners.forEach((id, listener) -> listener.accept(assetId, profile)); } } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\profile\DefaultTbAssetProfileCache.java
2
请完成以下Java代码
public java.lang.String getNote () { return (java.lang.String)get_Value(COLUMNNAME_Note); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } @Override public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class); } @Override
public void setSalesRep(org.compiere.model.I_AD_User SalesRep) { set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep); } /** Set Aussendienst. @param SalesRep_ID Aussendienst */ @Override public void setSalesRep_ID (int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID)); } /** Get Aussendienst. @return Aussendienst */ @Override public int getSalesRep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java-gen\de\metas\dunning\model\X_C_DunningDoc_Line.java
1
请完成以下Java代码
public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Before Approval. @param IsBeforeApproval The Check is before the (manual) approval */ public void setIsBeforeApproval (boolean IsBeforeApproval) { set_Value (COLUMNNAME_IsBeforeApproval, Boolean.valueOf(IsBeforeApproval)); } /** Get Before Approval. @return The Check is before the (manual) approval */ public boolean isBeforeApproval () { Object oo = get_Value(COLUMNNAME_IsBeforeApproval); 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_BudgetControl.java
1
请在Spring Boot框架中完成以下Java代码
private void saveRecursivelyAndPush(@NonNull final Rfq rfq) { saveRecursively(rfq); pushToMetasfresh(rfq); } @Override public void saveRecursively(@NonNull final Rfq rfq) { //rfqQuantityRepo.saveAll(rfq.getQuantities()); // not needed rfqRepo.save(rfq); } private void pushToMetasfresh(@NonNull final Rfq rfq) { final ISyncAfterCommitCollector syncAfterCommitCollector = senderToMetasfreshService.syncAfterCommit(); syncAfterCommitCollector.add(rfq); } @Override @Transactional public Rfq changeActiveRfq( @NonNull final JsonChangeRfqRequest request, @NonNull final User loggedUser) { final Rfq rfq = getUserActiveRfq( loggedUser, Long.parseLong(request.getRfqId())); for (final JsonChangeRfqQtyRequest qtyChangeRequest : request.getQuantities()) { rfq.setQtyPromised(qtyChangeRequest.getDate(), qtyChangeRequest.getQtyPromised()); } if (request.getPrice() != null) { rfq.setPricePromisedUserEntered(request.getPrice());
} saveRecursively(rfq); return rfq; } @Override public long getCountUnconfirmed(@NonNull final User user) { return rfqRepo.countUnconfirmed(user.getBpartner()); } @Override @Transactional public void confirmUserEntries(@NonNull final User user) { final BPartner bpartner = user.getBpartner(); final List<Rfq> rfqs = rfqRepo.findUnconfirmed(bpartner); for (final Rfq rfq : rfqs) { rfq.confirmByUser(); saveRecursivelyAndPush(rfq); } } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\service\impl\RfQService.java
2
请完成以下Java代码
public class BaseResponse<T> { /** * 是否成功 */ @ApiModelProperty(value = "是否成功", name = "success", example = "true", required = true) private boolean success; /** * 说明 */ @ApiModelProperty(value = "返回的详细说明", name = "msg", example = "成功") private String msg; /** * 返回数据 */ @ApiModelProperty(value = "返回的数据", name = "data") private T data; public BaseResponse() { } public BaseResponse(boolean success, String msg, T data) { this.success = success; this.msg = msg; this.data = data; } public boolean isSuccess() { return success; } public void setSuccess(boolean success) {
this.success = success; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; } }
repos\SpringBootBucket-master\springboot-swagger2\src\main\java\com\xncoding\jwt\api\model\BaseResponse.java
1
请完成以下Java代码
public boolean isWithException() { return withException; } public String getExceptionMessage() { return exceptionMessage; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public static long getSerialversionuid() { return serialVersionUID; } public String getId() { return id; } public String getProcessDefinitionId() { return processDefinitionId; } public boolean isOnlyTimers() { return onlyTimers; }
public boolean isOnlyMessages() { return onlyMessages; } public Date getDuedateHigherThan() { return duedateHigherThan; } public Date getDuedateLowerThan() { return duedateLowerThan; } public Date getDuedateHigherThanOrEqual() { return duedateHigherThanOrEqual; } public Date getDuedateLowerThanOrEqual() { return duedateLowerThanOrEqual; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\DeadLetterJobQueryImpl.java
1
请完成以下Java代码
public boolean isMatch() { return this.match; } /** * Returns the extracted variable values where the key is the variable name and * the value is the variable value * @return a map containing key-value pairs representing extracted variable names * and variable values */ public Map<String, String> getVariables() { return this.variables; } /** * Creates an instance of {@link MatchResult} that is a match with no variables * @return {@link MatchResult} that is a match with no variables */ public static MatchResult match() { return new MatchResult(true, Collections.emptyMap()); } /** * Creates an instance of {@link MatchResult} that is a match with the specified * variables * @param variables the specified variables * @return {@link MatchResult} that is a match with the specified variables */
public static MatchResult match(Map<String, String> variables) { return new MatchResult(true, variables); } /** * Creates an instance of {@link MatchResult} that is not a match. * @return {@link MatchResult} that is not a match */ public static MatchResult notMatch() { return new MatchResult(false, Collections.emptyMap()); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\util\matcher\RequestMatcher.java
1
请完成以下Java代码
protected boolean afterSave (boolean newRecord, boolean success) { // Set Translation from Element if (newRecord // && MClient.get(getCtx()).isMultiLingualDocument() && getPrintName() != null && getPrintName().length() > 0) { String sql = "UPDATE AD_PrintFormatItem_Trl trl " + "SET PrintName = (SELECT e.PrintName " + "FROM AD_Element_Trl e, AD_Column c " + "WHERE e.AD_Language=trl.AD_Language" + " AND e.AD_Element_ID=c.AD_Element_ID" + " AND c.AD_Column_ID=" + getAD_Column_ID() + ") " + "WHERE AD_PrintFormatItem_ID = " + get_ID() + " AND EXISTS (SELECT * " + "FROM AD_Element_Trl e, AD_Column c "
+ "WHERE e.AD_Language=trl.AD_Language" + " AND e.AD_Element_ID=c.AD_Element_ID" + " AND c.AD_Column_ID=" + getAD_Column_ID() + " AND trl.AD_PrintFormatItem_ID = " + get_ID() + ")" + " AND EXISTS (SELECT * FROM AD_Client " + "WHERE AD_Client_ID=trl.AD_Client_ID AND IsMultiLingualDocument='Y')"; int no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName()); log.debug("translations updated #" + no); } // metas-tsa: we need to reset the cache if an item value is changed CacheMgt.get().resetLocalNowAndBroadcastOnTrxCommit(get_TrxName(), CacheInvalidateMultiRequest.rootRecord(I_AD_PrintFormat.Table_Name, getAD_PrintFormat_ID())); return success; } // afterSave } // MPrintFormatItem
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\MPrintFormatItem.java
1
请完成以下Java代码
public class ImportProductsRouteContext { @NonNull private final ShopwareClient shopwareClient; @NonNull private final JsonExternalSystemRequest externalSystemRequest; @NonNull private final String orgCode; @NonNull private final UOMInfoProvider shopwareUomInfoProvider; @NonNull private final CurrencyInfoProvider currencyInfoProvider; @NonNull private final ImmutableMap<String, JsonUOM> uomMappings; @NonNull private final TaxCategoryProvider taxCategoryProvider; @Nullable private final PriceListBasicInfo priceListBasicInfo; @NonNull @Setter(AccessLevel.NONE) private Instant nextImportStartingTimestamp; @Nullable @Getter(AccessLevel.NONE) private JsonProduct jsonProduct; @Nullable @Getter(AccessLevel.NONE) private JsonProduct parentJsonProduct; public void setNextImportStartingTimestamp(@NonNull final Instant candidate)
{ if (candidate.isAfter(nextImportStartingTimestamp)) { nextImportStartingTimestamp = candidate; } } @Nullable public Integer getPInstanceId() { return JsonMetasfreshId.toValue(externalSystemRequest.getAdPInstanceId()); } @NonNull public JsonProduct getJsonProduct() { if (jsonProduct == null) { throw new RuntimeException("getJsonProduct() called before assigning a product!"); } return jsonProduct; } @Nullable public JsonProduct getParentJsonProduct() { return parentJsonProduct; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\product\ImportProductsRouteContext.java
1
请在Spring Boot框架中完成以下Java代码
private CandidateType computeCounterCandidateType( @NonNull final Candidate candidate, @NonNull final AbstractTransactionEvent event) { switch (candidate.getType()) { case SUPPLY: case UNEXPECTED_INCREASE: return event.getQuantity().signum() < 0 ? CandidateType.UNEXPECTED_DECREASE : CandidateType.UNEXPECTED_INCREASE; case UNEXPECTED_DECREASE: case DEMAND: return CandidateType.UNEXPECTED_DECREASE; default: throw new AdempiereException("Unexpected candidate.type=" + candidate.getType()).appendParametersToMessage() .setParameter("candidate", candidate); } } private Instant extractMinTransactionDate(@NonNull final TreeSet<TransactionDetail> transactionDetailsSet) { return transactionDetailsSet .stream() .min(Comparator.comparing(TransactionDetail::getTransactionDate)) .orElseThrow(() -> new AdempiereException("Expected at least one transaction detail")) .getTransactionDate(); } private TreeSet<TransactionDetail> extractAllTransactionDetails( @NonNull final Candidate candidate, @NonNull final TransactionDetail changedTransactionDetail) { final ImmutableList<TransactionDetail> otherTransactionDetails = candidate.getTransactionDetails() .stream() .filter(transactionDetail -> transactionDetail.getTransactionId() != changedTransactionDetail.getTransactionId()) .collect(ImmutableList.toImmutableList()); // note: using TreeSet to make sure we don't end up with duplicated transactionDetails final TreeSet<TransactionDetail> newTransactionDetailsSet = new TreeSet<>(Comparator.comparing(TransactionDetail::getTransactionId)); newTransactionDetailsSet.addAll(otherTransactionDetails); newTransactionDetailsSet.add(changedTransactionDetail); return newTransactionDetailsSet;
} /** * @param transactionCreatedEvent note that creating a new candidate doesn't make sense for a {@link TransactionDeletedEvent} */ @VisibleForTesting static CandidateBuilder createBuilderForNewUnrelatedCandidate( @NonNull final TransactionCreatedEvent transactionCreatedEvent, @NonNull final BigDecimal quantity) { final CandidateBuilder builder = Candidate.builderForEventDescriptor(transactionCreatedEvent.getEventDescriptor()); // TODO INVENTORY_UP/DOWN are not CandidateTypes, but business-cases! if (quantity.signum() <= 0) { final CandidateType type = transactionCreatedEvent.getInventoryLineId() > 0 ? CandidateType.INVENTORY_DOWN : CandidateType.UNEXPECTED_DECREASE; return builder.type(type) .materialDescriptor(transactionCreatedEvent.getMaterialDescriptor().withQuantity(quantity.negate())) .minMaxDescriptor(transactionCreatedEvent.getMinMaxDescriptor()); } else { final CandidateType type = transactionCreatedEvent.getInventoryLineId() > 0 ? CandidateType.INVENTORY_UP : CandidateType.UNEXPECTED_INCREASE; return builder.type(type) .materialDescriptor(transactionCreatedEvent.getMaterialDescriptor()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\TransactionEventHandler.java
2
请在Spring Boot框架中完成以下Java代码
final List<JsonExternalReferenceTarget> computeTargets(@NonNull final Document document) { final ImmutableList.Builder<JsonExternalReferenceTarget> targets = ImmutableList.builder(); final String patientId = document.getPatientId(); if (!EmptyUtil.isBlank(patientId)) { targets.add(JsonExternalReferenceTarget.ofTypeAndId(GetAttachmentRouteConstants.ESR_TYPE_BPARTNER, formatExternalId(patientId))); } final String createdBy = document.getCreatedBy(); if (!EmptyUtil.isBlank(createdBy)) { targets.add(JsonExternalReferenceTarget.ofTypeAndId(GetAttachmentRouteConstants.ESR_TYPE_USERID, formatExternalId(createdBy))); } final String updatedBy = document.getUpdatedBy(); if (!EmptyUtil.isBlank(updatedBy) && (EmptyUtil.isBlank(createdBy) || !createdBy.equals(updatedBy))) { targets.add(JsonExternalReferenceTarget.ofTypeAndId(GetAttachmentRouteConstants.ESR_TYPE_USERID, formatExternalId(updatedBy))); } final ImmutableList<JsonExternalReferenceTarget> computedTargets = targets.build(); if (EmptyUtil.isEmpty(computedTargets)) { throw new RuntimeException("Document targets cannot be null! DocumentId: " + document.getId()); } return computedTargets; } @NonNull final List<JsonTag> computeTags(@NonNull final Document document) { final ImmutableList.Builder<JsonTag> tags = ImmutableList.builder(); tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_DOCUMENT_ID, document.getId())); if (document.isArchived() != null) { tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_DOCUMENT_ARCHIVED, String.valueOf(document.isArchived()))); } final BigDecimal therapyId = document.getTherapyId(); if (therapyId != null) { tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_DOCUMENT_THERAPYID, String.valueOf(therapyId))); } final BigDecimal therapyTypeId = document.getTherapyTypeId();
if (therapyTypeId != null) { tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_DOCUMENT_THERAPYTYPEID, String.valueOf(therapyTypeId))); } final OffsetDateTime createdAt = document.getCreatedAt(); if (createdAt != null) { final Instant createdAtInstant = AlbertaUtil.asInstant(createdAt); tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_DOCUMENT_CREATEDAT, String.valueOf(createdAtInstant))); } final OffsetDateTime updatedAt = document.getUpdatedAt(); if (updatedAt != null) { final Instant updatedAtInstant = AlbertaUtil.asInstant(updatedAt); tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_DOCUMENT_UPDATEDAT, String.valueOf(updatedAtInstant))); } tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_DOCUMENT_ENDPOINT, GetAttachmentRouteConstants.ALBERTA_DOCUMENT_ENDPOINT_VALUE)); return tags.build(); } }
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\attachment\processor\DocumentProcessor.java
2
请完成以下Java代码
public Flux<Account> findAll() { return Mono.from(connectionFactory.create()) .flatMap((c) -> Mono.from(c.createStatement("select id,iban,balance from Account") .execute()) .doFinally((st) -> close(c))) .flatMapMany(result -> Flux.from(result.map((row, meta) -> { Account acc = new Account(); acc.setId(row.get("id", Long.class)); acc.setIban(row.get("iban", String.class)); acc.setBalance(row.get("balance", BigDecimal.class)); return acc; }))); } public Mono<Account> createAccount(Account account) { return Mono.from(connectionFactory.create()) .flatMap(c -> Mono.from(c.beginTransaction()) .then(Mono.from(c.createStatement("insert into Account(iban,balance) values($1,$2)") .bind("$1", account.getIban()) .bind("$2", account.getBalance())
.returnGeneratedValues("id") .execute())) .map(result -> result.map((row, meta) -> new Account(row.get("id", Long.class), account.getIban(), account.getBalance()))) .flatMap(pub -> Mono.from(pub)) .delayUntil(r -> c.commitTransaction()) .doFinally((st) -> c.close())); } private <T> Mono<T> close(Connection connection) { return Mono.from(connection.close()) .then(Mono.empty()); } }
repos\tutorials-master\persistence-modules\r2dbc\src\main\java\com\baeldung\examples\r2dbc\ReactiveAccountDao.java
1
请完成以下Java代码
public SqlAndParams buildSqlDeleteSelection(@NonNull final Set<String> selectionIds) { final ArrayList<Object> sqlParams = new ArrayList<>(selectionIds.size()); final String sql = "DELETE FROM " + I_T_WEBUI_ViewSelection.Table_Name + " WHERE " + DB.buildSqlList(I_T_WEBUI_ViewSelection.COLUMNNAME_UUID, selectionIds, sqlParams); return SqlAndParams.of(sql, sqlParams); } public SqlAndParams buildSqlDeleteSelectionLines(@NonNull final Set<String> selectionIds) { final ArrayList<Object> sqlParams = new ArrayList<>(selectionIds.size()); final String sql = "DELETE FROM " + I_T_WEBUI_ViewSelectionLine.Table_Name + " WHERE " + DB.buildSqlList(I_T_WEBUI_ViewSelectionLine.COLUMNNAME_UUID, selectionIds, sqlParams); return SqlAndParams.of(sql, sqlParams); } public static SqlAndParams buildSqlSelectRowIdsForLineIds( @NonNull final SqlViewKeyColumnNamesMap keyColumnNamesMap, @NonNull final String selectionId, final Collection<Integer> lineIds) { Check.assumeNotEmpty(lineIds, "lineIds is not empty"); final List<Object> sqlParams = new ArrayList<>(); sqlParams.add(selectionId); final String sql = "SELECT "
+ keyColumnNamesMap.getWebuiSelectionColumnNamesCommaSeparated() + " FROM " + I_T_WEBUI_ViewSelectionLine.Table_Name + " WHERE " + I_T_WEBUI_ViewSelectionLine.COLUMNNAME_UUID + "=?" + " AND " + DB.buildSqlList(I_T_WEBUI_ViewSelectionLine.COLUMNNAME_Line_ID, lineIds, sqlParams); return SqlAndParams.of(sql, sqlParams); } private IStringExpressionWrapper securityRestrictionsWrapper(final String sqlTableAlias) { if (applySecurityRestrictions) { return AccessSqlStringExpression.wrapper(sqlTableAlias, IUserRolePermissions.SQL_FULLYQUALIFIED, Access.READ); } else { return expression -> expression; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlViewSelectionQueryBuilder.java
1
请完成以下Java代码
public Map<String, String> getInitParameters() { return this.initParameters; } public List<? extends CookieSameSiteSupplier> getCookieSameSiteSuppliers() { return this.cookieSameSiteSuppliers; } public void setMimeMappings(MimeMappings mimeMappings) { Assert.notNull(mimeMappings, "'mimeMappings' must not be null"); this.mimeMappings = new MimeMappings(mimeMappings); } public void addMimeMappings(MimeMappings mimeMappings) { mimeMappings.forEach((mapping) -> this.mimeMappings.add(mapping.getExtension(), mapping.getMimeType())); } public void setInitializers(List<? extends ServletContextInitializer> initializers) { Assert.notNull(initializers, "'initializers' must not be null"); this.initializers = new ArrayList<>(initializers); } public void addInitializers(ServletContextInitializer... initializers) { Assert.notNull(initializers, "'initializers' must not be null"); this.initializers.addAll(Arrays.asList(initializers)); } public void setLocaleCharsetMappings(Map<Locale, Charset> localeCharsetMappings) { Assert.notNull(localeCharsetMappings, "'localeCharsetMappings' must not be null"); this.localeCharsetMappings = localeCharsetMappings; } public void setInitParameters(Map<String, String> initParameters) { this.initParameters = initParameters; } public void setCookieSameSiteSuppliers(List<? extends CookieSameSiteSupplier> cookieSameSiteSuppliers) { Assert.notNull(cookieSameSiteSuppliers, "'cookieSameSiteSuppliers' must not be null"); this.cookieSameSiteSuppliers = new ArrayList<>(cookieSameSiteSuppliers); }
public void addCookieSameSiteSuppliers(CookieSameSiteSupplier... cookieSameSiteSuppliers) { Assert.notNull(cookieSameSiteSuppliers, "'cookieSameSiteSuppliers' must not be null"); this.cookieSameSiteSuppliers.addAll(Arrays.asList(cookieSameSiteSuppliers)); } public void addWebListenerClassNames(String... webListenerClassNames) { this.webListenerClassNames.addAll(Arrays.asList(webListenerClassNames)); } public Set<String> getWebListenerClassNames() { return this.webListenerClassNames; } public List<URL> getStaticResourceUrls() { return this.staticResourceJars.getUrls(); } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\ServletWebServerSettings.java
1
请完成以下Java代码
public ImmutableCredentialRecordBuilder backupEligible(boolean backupEligible) { this.backupEligible = backupEligible; return this; } public ImmutableCredentialRecordBuilder backupState(boolean backupState) { this.backupState = backupState; return this; } public ImmutableCredentialRecordBuilder attestationObject(@Nullable Bytes attestationObject) { this.attestationObject = attestationObject; return this; } public ImmutableCredentialRecordBuilder attestationClientDataJSON(@Nullable Bytes attestationClientDataJSON) { this.attestationClientDataJSON = attestationClientDataJSON; return this; } public ImmutableCredentialRecordBuilder created(Instant created) { this.created = created;
return this; } public ImmutableCredentialRecordBuilder lastUsed(Instant lastUsed) { this.lastUsed = lastUsed; return this; } public ImmutableCredentialRecordBuilder label(String label) { this.label = label; return this; } public ImmutableCredentialRecord build() { return new ImmutableCredentialRecord(this.credentialType, this.credentialId, this.userEntityUserId, this.publicKey, this.signatureCount, this.uvInitialized, this.transports, this.backupEligible, this.backupState, this.attestationObject, this.attestationClientDataJSON, this.created, this.lastUsed, this.label); } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\ImmutableCredentialRecord.java
1
请在Spring Boot框架中完成以下Java代码
public class ApiController { @Resource private LoggerService loggerService; @RequestMapping("/show") public Map<String,Object> shotLog(@RequestParam("name")String name,@RequestParam("age") int age){ Map<String,Object> result = new HashMap<>(); result.put("name",name); result.put("age",age); return result; } @RequestMapping("/show2") public Map<String,Object> shotLog(@RequestBody String parms){ Map<String,Object> result = new HashMap<>(); // result.put("name",name); // result.put("age",age); // System.out.println(parms); loggerService.showLog();
return result; } @RequestMapping("s") public String ss() { return "123"; } @GetMapping("/exception") public String exce() { System.out.println("异常"); throw new IllegalArgumentException("异常了"); } }
repos\spring-boot-quick-master\quick-log\src\main\java\com\quick\log\controller\ApiController.java
2
请完成以下Java代码
public String getXmlEncoding() { return xmlEncoding; } public ProcessEngineConfiguration setXmlEncoding(String xmlEncoding) { this.xmlEncoding = xmlEncoding; return this; } public Clock getClock() { return clock; } public ProcessEngineConfiguration setClock(Clock clock) { this.clock = clock; return this; } public AsyncExecutor getAsyncExecutor() { return asyncExecutor; } public ProcessEngineConfiguration setAsyncExecutor(AsyncExecutor asyncExecutor) { this.asyncExecutor = asyncExecutor; return this; } public int getLockTimeAsyncJobWaitTime() { return lockTimeAsyncJobWaitTime; } public ProcessEngineConfiguration setLockTimeAsyncJobWaitTime(int lockTimeAsyncJobWaitTime) { this.lockTimeAsyncJobWaitTime = lockTimeAsyncJobWaitTime; return this; } public int getDefaultFailedJobWaitTime() { return defaultFailedJobWaitTime; } public ProcessEngineConfiguration setDefaultFailedJobWaitTime(int defaultFailedJobWaitTime) { this.defaultFailedJobWaitTime = defaultFailedJobWaitTime; return this; } public int getAsyncFailedJobWaitTime() { return asyncFailedJobWaitTime; } public ProcessEngineConfiguration setAsyncFailedJobWaitTime(int asyncFailedJobWaitTime) { this.asyncFailedJobWaitTime = asyncFailedJobWaitTime; return this; }
public boolean isEnableProcessDefinitionInfoCache() { return enableProcessDefinitionInfoCache; } public ProcessEngineConfiguration setEnableProcessDefinitionInfoCache(boolean enableProcessDefinitionInfoCache) { this.enableProcessDefinitionInfoCache = enableProcessDefinitionInfoCache; return this; } public ProcessEngineConfiguration setCopyVariablesToLocalForTasks(boolean copyVariablesToLocalForTasks) { this.copyVariablesToLocalForTasks = copyVariablesToLocalForTasks; return this; } public boolean isCopyVariablesToLocalForTasks() { return copyVariablesToLocalForTasks; } public void setEngineAgendaFactory(ActivitiEngineAgendaFactory engineAgendaFactory) { this.engineAgendaFactory = engineAgendaFactory; } public ActivitiEngineAgendaFactory getEngineAgendaFactory() { return engineAgendaFactory; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\ProcessEngineConfiguration.java
1
请完成以下Java代码
public class SoundPlayerUsingClip implements LineListener { boolean isPlaybackCompleted; @Override public void update(LineEvent event) { if (LineEvent.Type.START == event.getType()) { System.out.println("Playback started."); } else if (LineEvent.Type.STOP == event.getType()) { isPlaybackCompleted = true; System.out.println("Playback completed."); } } /** * * Play a given audio file. * @param audioFilePath Path of the audio file. * */ void play(String audioFilePath) { try { InputStream inputStream = getClass().getClassLoader() .getResourceAsStream(audioFilePath); AudioInputStream audioStream = AudioSystem.getAudioInputStream(inputStream); AudioFormat format = audioStream.getFormat(); DataLine.Info info = new DataLine.Info(Clip.class, format); Clip audioClip = (Clip) AudioSystem.getLine(info); audioClip.addLineListener(this);
audioClip.open(audioStream); audioClip.start(); while (!isPlaybackCompleted) { try { Thread.sleep(1000); } catch (InterruptedException ex) { ex.printStackTrace(); } } audioClip.close(); audioStream.close(); } catch (UnsupportedAudioFileException | LineUnavailableException | IOException ex) { System.out.println("Error occured during playback process:"+ ex.getMessage()); } } public static void main(String[] args) { String audioFilePath = "AudioFileWithWavFormat.wav"; // Clip can not play mpeg/mp3 format audio. We'll get exception if we run with below commented mp3 and mpeg format audio. // String audioFilePath = "AudioFileWithMpegFormat.mpeg"; // String audioFilePath = "AudioFileWithMp3Format.mp3"; SoundPlayerUsingClip player = new SoundPlayerUsingClip(); player.play(audioFilePath); } }
repos\tutorials-master\javax-sound\src\main\java\com\baeldung\SoundPlayerUsingClip.java
1
请完成以下Java代码
public static String readClasspathResourceAsString(String resourceName) { InputStream resourceAsStream = IoUtil.class.getClassLoader().getResourceAsStream(resourceName); if (resourceAsStream == null) { throw new ProcessEngineException("resource " + resourceName + " not found"); } ByteArrayOutputStream outStream = new ByteArrayOutputStream(); int next; byte[] result; byte[] buffer = new byte[1024]; BufferedInputStream inputStream = null; try { inputStream = new BufferedInputStream(resourceAsStream); while ((next = inputStream.read(buffer)) >= 0) { outStream.write(buffer, 0, next); } result = outStream.toByteArray(); } catch(Exception e) { throw LOG.exceptionWhileReadingFile(resourceName, e); } finally { IoUtil.closeSilently(inputStream); IoUtil.closeSilently(outStream); } return new String(result, Charset.forName("UTF-8")); } public static File getFile(String filePath) { URL url = IoUtil.class.getClassLoader().getResource(filePath); try { return new File(url.toURI()); } catch (Exception e) { throw LOG.exceptionWhileGettingFile(filePath, e); } } public static void writeStringToFile(String content, String filePath) { BufferedOutputStream outputStream = null;
try { outputStream = new BufferedOutputStream(new FileOutputStream(getFile(filePath))); outputStream.write(content.getBytes()); outputStream.flush(); } catch(Exception e) { throw LOG.exceptionWhileWritingToFile(filePath, e); } finally { IoUtil.closeSilently(outputStream); } } /** * Closes the given stream. The same as calling {@link Closeable#close()}, but * errors while closing are silently ignored. */ public static void closeSilently(Closeable closeable) { try { if(closeable != null) { closeable.close(); } } catch(IOException ignore) { LOG.debugCloseException(ignore); } } /** * Flushes the given object. The same as calling {@link Flushable#flush()}, but * errors while flushing are silently ignored. */ public static void flushSilently(Flushable flushable) { try { if(flushable != null) { flushable.flush(); } } catch(IOException ignore) { LOG.debugCloseException(ignore); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\IoUtil.java
1
请完成以下Java代码
public void setM_Shipper_ID (final int M_Shipper_ID) { if (M_Shipper_ID < 1) set_Value (COLUMNNAME_M_Shipper_ID, null); else set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID); } @Override public int getM_Shipper_ID() { return get_ValueAsInt(COLUMNNAME_M_Shipper_ID); } @Override public void setSignature (final @Nullable java.lang.String Signature) { set_Value (COLUMNNAME_Signature, Signature); } @Override public java.lang.String getSignature()
{ return get_ValueAsString(COLUMNNAME_Signature); } @Override public void setUserName (final @Nullable java.lang.String UserName) { set_Value (COLUMNNAME_UserName, UserName); } @Override public java.lang.String getUserName() { return get_ValueAsString(COLUMNNAME_UserName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java-gen\de\metas\shipper\gateway\dhl\model\X_DHL_Shipper_Config.java
1
请完成以下Java代码
public static boolean isPermutationWithTwoCounters(String s1, String s2) { if (s1.length() != s2.length()) { return false; } int[] counter1 = new int[256]; int[] counter2 = new int[256]; for (int i = 0; i < s1.length(); i++) { counter1[s1.charAt(i)]++; } for (int i = 0; i < s2.length(); i++) { counter2[s2.charAt(i)]++; } return Arrays.equals(counter1, counter2); } public static boolean isPermutationWithMap(String s1, String s2) { if (s1.length() != s2.length()) { return false; } Map<Character, Integer> charsMap = new HashMap<>(); for (int i = 0; i < s1.length(); i++) { charsMap.merge(s1.charAt(i), 1, Integer::sum); } for (int i = 0; i < s2.length(); i++) { if (!charsMap.containsKey(s2.charAt(i)) || charsMap.get(s2.charAt(i)) == 0) { return false; } charsMap.merge(s2.charAt(i), -1, Integer::sum); } return true; }
public static boolean isPermutationInclusion(String s1, String s2) { int ns1 = s1.length(), ns2 = s2.length(); if (ns1 < ns2) { return false; } int[] s1Count = new int[26]; int[] s2Count = new int[26]; for (char ch : s2.toCharArray()) { s2Count[ch - 'a']++; } for (int i = 0; i < ns1; ++i) { s1Count[s1.charAt(i) - 'a']++; if (i >= ns2) { s1Count[s1.charAt(i - ns2) - 'a']--; } if (Arrays.equals(s2Count, s1Count)) { return true; } } return false; } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-9\src\main\java\com\baeldung\algorithms\permutation\StringPermutation.java
1
请完成以下Java代码
public class AsyncApiCall { public static void main(String[] args) { AsyncApiCall apiCall = new AsyncApiCall(); CompletableFuture<String> completableFuture = apiCall.nonBlockingApiCall("test parameter"); completableFuture.thenAccept(result -> System.out.println("Future completed successfully: " + result)) .exceptionally(error -> { System.out.println("Future completed exceptionally: " + error.getMessage()); return null; }); } public void myAsyncCall(String param, BiConsumer<String, Throwable> callback) { new Thread(() -> { try { Thread.sleep(1000); callback.accept("Response from API with param: " + param, null);
} catch (InterruptedException e) { Thread.currentThread().interrupt(); } }).start(); } public CompletableFuture<String> nonBlockingApiCall(String param) { CompletableFuture<String> completableFuture = new CompletableFuture<>(); myAsyncCall(param, (result, error) -> { if (error != null) { completableFuture.completeExceptionally(error); } else { completableFuture.complete(result); } }); return completableFuture; } }
repos\tutorials-master\spring-reactive-modules\reactor-core-2\src\main\java\com\baeldung\reactor\completablefuturevsmono\AsyncApiCall.java
1
请在Spring Boot框架中完成以下Java代码
public static DistributionJobStep toDistributionJobStep( @NonNull final DDOrderMoveSchedule schedule, @NonNull final DistributionJobLoaderSupportingServices loadingSupportServices) { return DistributionJobStep.builder() .id(DistributionJobStepId.ofScheduleId(schedule.getId())) .qtyToMoveTarget(schedule.getQtyToPick()) // // Pick From .pickFromHU(loadingSupportServices.getHUInfo(schedule.getPickFromHUId())) .qtyPicked(schedule.getQtyPicked()) .qtyNotPickedReasonCode(schedule.getQtyNotPickedReason()) .isPickedFromLocator(schedule.isPickedFrom()) .inTransitLocatorId(schedule.getInTransitLocatorId().orElse(null)) // // Drop To .isDroppedToLocator(schedule.isDropTo()) // .build(); } private void warmUpById(final DDOrderId ddOrderId) { final I_DD_Order ddOrder = loadingSupportServices.getDDOrderById(ddOrderId); addToCache(ddOrder); } private void addToCache(@NonNull final I_DD_Order ddOrder) { addToCache(ImmutableList.of(ddOrder)); } private void addToCache(@NonNull final List<I_DD_Order> ddOrders) {
ddOrders.forEach(ddOrder -> ddOrdersCache.put(DDOrderId.ofRepoId(ddOrder.getDD_Order_ID()), ddOrder)); CollectionUtils.getAllOrLoad(ddOrderLinesCache, ddOrdersCache.keySet(), loadingSupportServices::getLinesByDDOrderIds); final ImmutableSet<DDOrderLineId> ddOrderLineIds = ddOrderLinesCache.values() .stream() .flatMap(Collection::stream) .map(ddOrderLine -> DDOrderLineId.ofRepoId(ddOrderLine.getDD_OrderLine_ID())) .collect(ImmutableSet.toImmutableSet()); CollectionUtils.getAllOrLoad(schedulesCache, ddOrderLineIds, loadingSupportServices::getSchedulesByDDOrderLineIds); } I_DD_Order getDDOrder(final DDOrderId ddOrderId) { return ddOrdersCache.computeIfAbsent(ddOrderId, loadingSupportServices::getDDOrderById); } private List<I_DD_OrderLine> getDDOrderLines(final DDOrderId ddOrderId) { return CollectionUtils.getOrLoad(ddOrderLinesCache, ddOrderId, loadingSupportServices::getLinesByDDOrderIds); } private List<DDOrderMoveSchedule> getSchedules(final DDOrderLineId ddOrderLineId) { return CollectionUtils.getOrLoad(schedulesCache, ddOrderLineId, loadingSupportServices::getSchedulesByDDOrderLineIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\service\DistributionJobLoader.java
2
请在Spring Boot框架中完成以下Java代码
public class MovieCrudService { private Map<String, Movie> inventory = new HashMap<String, Movie>(); @GET @Path("/") @Produces({ MediaType.TEXT_PLAIN }) public Response index() { return Response.status(200).header("Access-Control-Allow-Origin", "*") .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization") .header("Access-Control-Allow-Credentials", "true") .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD").entity("").build(); } @GET @Path("/getinfo") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Movie movieByImdbId(@QueryParam("imdbId") String imdbId) { System.out.println("*** Calling getinfo for a given ImdbID***"); if (inventory.containsKey(imdbId)) { return inventory.get(imdbId); } else return null; } @POST @Path("/addmovie") @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Response addMovie(Movie movie) { System.out.println("*** Calling addMovie ***"); if (null != inventory.get(movie.getImdbId())) { return Response.status(Response.Status.NOT_MODIFIED).entity("Movie is Already in the database.").build(); } inventory.put(movie.getImdbId(), movie); return Response.status(Response.Status.CREATED).build(); } @PUT @Path("/updatemovie")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Response updateMovie(Movie movie) { System.out.println("*** Calling updateMovie ***"); if (null == inventory.get(movie.getImdbId())) { return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is not in the database.\nUnable to Update").build(); } inventory.put(movie.getImdbId(), movie); return Response.status(Response.Status.OK).build(); } @DELETE @Path("/deletemovie") public Response deleteMovie(@QueryParam("imdbId") String imdbId) { System.out.println("*** Calling deleteMovie ***"); if (null == inventory.get(imdbId)) { return Response.status(Response.Status.NOT_FOUND).entity("Movie is not in the database.\nUnable to Delete") .build(); } inventory.remove(imdbId); return Response.status(Response.Status.OK).build(); } @GET @Path("/listmovies") @Produces({ "application/json" }) public List<Movie> listMovies() { return inventory.values().stream().collect(Collectors.toCollection(ArrayList::new)); } }
repos\tutorials-master\web-modules\resteasy\src\main\java\com\baeldung\server\MovieCrudService.java
2
请完成以下Java代码
public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Times Dunned. @param TimesDunned Number of times dunned previously */ public void setTimesDunned (int TimesDunned) { set_Value (COLUMNNAME_TimesDunned, Integer.valueOf(TimesDunned)); } /** Get Times Dunned. @return Number of times dunned previously */ public int getTimesDunned ()
{ Integer ii = (Integer)get_Value(COLUMNNAME_TimesDunned); if (ii == null) return 0; return ii.intValue(); } /** Set Total Amount. @param TotalAmt Total Amount */ public void setTotalAmt (BigDecimal TotalAmt) { set_Value (COLUMNNAME_TotalAmt, TotalAmt); } /** Get Total Amount. @return Total Amount */ public BigDecimal getTotalAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalAmt); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DunningRunLine.java
1
请完成以下Java代码
public void setQty (BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Quantity. @return Quantity */ public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } public I_AD_User getSalesRep() throws RuntimeException { return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name) .getPO(getSalesRep_ID(), get_TrxName()); } /** Set Sales Representative. @param SalesRep_ID Sales Representative or Company Agent */ public void setSalesRep_ID (int SalesRep_ID) {
if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID)); } /** Get Sales Representative. @return Sales Representative or Company Agent */ public int getSalesRep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DunningRunEntry.java
1
请完成以下Java代码
public void init(PartitionedQueueConsumerManager<TbProtoQueueMsg<ToEdqsMsg>> eventConsumer, List<PartitionedQueueConsumerManager<?>> otherConsumers) { this.eventConsumer = eventConsumer; this.otherConsumers = otherConsumers; } @Override public void process(Set<TopicPartitionInfo> partitions) { if (!ready) { db.forEach((key, value) -> { try { ToEdqsMsg edqsMsg = ToEdqsMsg.parseFrom(value); log.trace("[{}] Restored msg from RocksDB: {}", key, edqsMsg); processor.process(edqsMsg, false); } catch (Exception e) { log.error("[{}] Failed to restore value", key, e); } }); log.info("Restore completed"); } ready = true; discoveryService.setReady(true); eventConsumer.update(withTopic(partitions, eventConsumer.getTopic())); for (PartitionedQueueConsumerManager<?> consumer : otherConsumers) { consumer.update(withTopic(partitions, consumer.getTopic())); }
} @Override public void save(TenantId tenantId, ObjectType type, String key, EdqsEventType eventType, ToEdqsMsg msg) { log.trace("Save to RocksDB: {} {} {} {}", tenantId, type, key, msg); try { if (eventType == EdqsEventType.DELETED) { db.delete(key); } else { db.put(key, msg.toByteArray()); } } catch (Exception e) { log.error("[{}] Failed to save event {}", key, msg, e); } } @Override public boolean isReady() { return ready; } @Override public void stop() { } }
repos\thingsboard-master\common\edqs\src\main\java\org\thingsboard\server\edqs\state\LocalEdqsStateService.java
1
请完成以下Java代码
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 String getProcessInstanceUrl() { return processInstanceUrl; } public void setProcessInstanceUrl(String processInstanceUrl) { this.processInstanceUrl = processInstanceUrl; } @ApiModelProperty(example = "6") public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } @ApiModelProperty(example = "10") public String getActivityInstanceId() { return activityInstanceId; } public void setActivityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; } @ApiModelProperty(example = "6") public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } @ApiModelProperty(example = "http://localhost:8182/history/historic-task-instances/6") public String getTaskUrl() { return taskUrl; } public void setTaskUrl(String taskUrl) { this.taskUrl = taskUrl; } @ApiModelProperty(example = "2013-04-17T10:17:43.902+0000") public Date getTime() { return time; }
public void setTime(Date time) { this.time = time; } @ApiModelProperty(example = "variableUpdate") public String getDetailType() { return detailType; } public void setDetailType(String detailType) { this.detailType = detailType; } @ApiModelProperty(example = "2") public Integer getRevision() { return revision; } public void setRevision(Integer revision) { this.revision = revision; } public RestVariable getVariable() { return variable; } public void setVariable(RestVariable variable) { this.variable = variable; } @ApiModelProperty(example = "null") public String getPropertyId() { return propertyId; } public void setPropertyId(String propertyId) { this.propertyId = propertyId; } @ApiModelProperty(example = "null") public String getPropertyValue() { return propertyValue; } public void setPropertyValue(String propertyValue) { this.propertyValue = propertyValue; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricDetailResponse.java
2
请完成以下Java代码
List<String> search() { List<String> result = tables.entrySet() .stream() .filter(entry -> entry.getKey().equalsIgnoreCase(table)) .flatMap(entry -> Stream.of(entry.getValue())) .flatMap(Collection::stream) .map(Row::toString) .flatMap(columnMapper) .filter(whereFilter) .collect(Collectors.toList()); clear(); return result; } /** * Sets column mapper based on {@link #column} attribute. * Note: If column is unknown, will remain to look for all columns. */ private void setColumnMapper() {
switch (column) { case "*": colIndex = -1; break; case "name": colIndex = 0; break; case "surname": colIndex = 1; break; } if (colIndex != -1) { columnMapper = s -> Stream.of(s.split(" ")[colIndex]); } } }
repos\tutorials-master\patterns-modules\design-patterns-behavioral-2\src\main\java\com\baeldung\interpreter\Context.java
1
请完成以下Java代码
public String getNameLike() { return nameLike; } public String getCategory() { return category; } public String getCategoryNotEquals() { return categoryNotEquals; } public String getTenantId() { return tenantId; }
public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getDecisionKey() { return decisionKey; } public String getDecisionKeyLike() { return decisionKeyLike; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\DmnDeploymentQueryImpl.java
1
请完成以下Java代码
public static boolean isBlacklisted(ExtensionAttribute attribute, List<ExtensionAttribute>... blackLists) { if (blackLists != null) { for (List<ExtensionAttribute> blackList : blackLists) { for (ExtensionAttribute blackAttribute : blackList) { if (blackAttribute.getName().equals(attribute.getName())) { if (attribute.getNamespace() != null && FLOWABLE_EXTENSIONS_NAMESPACE.equals(attribute.getNamespace())) { return true; } if (blackAttribute.getNamespace() == null && attribute.getNamespace() == null) { return true; } } } } } return false; } public static boolean containsNewLine(String str) { return str != null && str.contains("\n"); } public static boolean writeIOParameters(String elementName, List<IOParameter> parameterList, boolean didWriteParameterStartElement, XMLStreamWriter xtw) throws Exception { if (parameterList == null || parameterList.isEmpty()) { return didWriteParameterStartElement; }
for (IOParameter ioParameter : parameterList) { if (!didWriteParameterStartElement) { xtw.writeStartElement(ELEMENT_EXTENSION_ELEMENTS); didWriteParameterStartElement = true; } xtw.writeStartElement(FLOWABLE_EXTENSIONS_PREFIX, elementName, FLOWABLE_EXTENSIONS_NAMESPACE); if (StringUtils.isNotEmpty(ioParameter.getSource())) { xtw.writeAttribute(ATTRIBUTE_IOPARAMETER_SOURCE, ioParameter.getSource()); } if (StringUtils.isNotEmpty(ioParameter.getSourceExpression())) { xtw.writeAttribute(ATTRIBUTE_IOPARAMETER_SOURCE_EXPRESSION, ioParameter.getSourceExpression()); } if (StringUtils.isNotEmpty(ioParameter.getTarget())) { xtw.writeAttribute(ATTRIBUTE_IOPARAMETER_TARGET, ioParameter.getTarget()); } if (StringUtils.isNotEmpty(ioParameter.getTargetExpression())) { xtw.writeAttribute(ATTRIBUTE_IOPARAMETER_TARGET_EXPRESSION, ioParameter.getTargetExpression()); } xtw.writeEndElement(); } return didWriteParameterStartElement; } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\util\CmmnXmlUtil.java
1
请完成以下Java代码
public de.metas.material.dispo.model.I_MD_Candidate getMD_Candidate() { return get_ValueAsPO(COLUMNNAME_MD_Candidate_ID, de.metas.material.dispo.model.I_MD_Candidate.class); } @Override public void setMD_Candidate(final de.metas.material.dispo.model.I_MD_Candidate MD_Candidate) { set_ValueFromPO(COLUMNNAME_MD_Candidate_ID, de.metas.material.dispo.model.I_MD_Candidate.class, MD_Candidate); } @Override public void setMD_Candidate_ID (final int MD_Candidate_ID) { if (MD_Candidate_ID < 1) set_Value (COLUMNNAME_MD_Candidate_ID, null); else set_Value (COLUMNNAME_MD_Candidate_ID, MD_Candidate_ID); } @Override public int getMD_Candidate_ID() { return get_ValueAsInt(COLUMNNAME_MD_Candidate_ID); } @Override public void setMD_Candidate_QtyDetails_ID (final int MD_Candidate_QtyDetails_ID) { if (MD_Candidate_QtyDetails_ID < 1) set_ValueNoCheck (COLUMNNAME_MD_Candidate_QtyDetails_ID, null); else set_ValueNoCheck (COLUMNNAME_MD_Candidate_QtyDetails_ID, MD_Candidate_QtyDetails_ID); }
@Override public int getMD_Candidate_QtyDetails_ID() { return get_ValueAsInt(COLUMNNAME_MD_Candidate_QtyDetails_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; } @Override public void setStock_MD_Candidate_ID (final int Stock_MD_Candidate_ID) { if (Stock_MD_Candidate_ID < 1) set_Value (COLUMNNAME_Stock_MD_Candidate_ID, null); else set_Value (COLUMNNAME_Stock_MD_Candidate_ID, Stock_MD_Candidate_ID); } @Override public int getStock_MD_Candidate_ID() { return get_ValueAsInt(COLUMNNAME_Stock_MD_Candidate_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_QtyDetails.java
1
请完成以下Java代码
private PricingConditionsRowData getAllRowsData() { return allRowsData != null ? allRowsData : this; } private static final Stream<PricingConditionsRow> stream(final PricingConditionsRow editableRow, final List<PricingConditionsRow> rows) { return editableRow != null ? Stream.concat(Stream.of(editableRow), rows.stream()) : rows.stream(); } @Override public int size() { return rowIds.size(); } @Override public Map<DocumentId, PricingConditionsRow> getDocumentId2TopLevelRows() { return ImmutableMap.copyOf(rowsById); } @Override public Map<DocumentId, PricingConditionsRow> getDocumentId2AllRows() { return getDocumentId2TopLevelRows(); } @Override public Collection<PricingConditionsRow> getTopLevelRows() { return rowIds.stream() .map(rowsById::get) .collect(ImmutableList.toImmutableList()); } @Override public Collection<PricingConditionsRow> getAllRows() { return getTopLevelRows(); } @Override public DocumentIdsSelection getDocumentIdsToInvalidate(final TableRecordReferenceSet recordRefs) { return DocumentIdsSelection.EMPTY; } @Override public void invalidateAll() { } private void changeRow(final DocumentId rowId, final UnaryOperator<PricingConditionsRow> mapper) { if (!rowIds.contains(rowId)) { throw new EntityNotFoundException(rowId.toJson()); } rowsById.compute(rowId, (key, oldRow) -> { if (oldRow == null) { throw new EntityNotFoundException(rowId.toJson()); } return mapper.apply(oldRow); });
} @Override public void patchRow(final RowEditingContext ctx, final List<JSONDocumentChangedEvent> fieldChangeRequests) { final PricingConditionsRowChangeRequest request = PricingConditionsRowActions.toChangeRequest(fieldChangeRequests, getDefaultCurrencyId()); changeRow(ctx.getRowId(), row -> PricingConditionsRowReducers.copyAndChange(request, row)); } public void patchEditableRow(final PricingConditionsRowChangeRequest request) { changeRow(getEditableRowId(), editableRow -> PricingConditionsRowReducers.copyAndChange(request, editableRow)); } public boolean hasEditableRow() { return editableRowId != null; } public DocumentId getEditableRowId() { if (editableRowId == null) { throw new AdempiereException("No editable row found"); } return editableRowId; } public PricingConditionsRow getEditableRow() { return getById(getEditableRowId()); } public DocumentFilterList getFilters() { return filters; } public PricingConditionsRowData filter(@NonNull final DocumentFilterList filters) { if (DocumentFilterList.equals(this.filters, filters)) { return this; } if (filters.isEmpty()) { return getAllRowsData(); } return new PricingConditionsRowData(this, filters); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsRowData.java
1
请完成以下Java代码
public List<Job> findJobsByQueryCriteria(JobQueryImpl jobQuery, Page page) { return jobDataManager.findJobsByQueryCriteria(jobQuery, page); } @Override public long findJobCountByQueryCriteria(JobQueryImpl jobQuery) { return jobDataManager.findJobCountByQueryCriteria(jobQuery); } @Override public void updateJobTenantIdForDeployment(String deploymentId, String newTenantId) { jobDataManager.updateJobTenantIdForDeployment(deploymentId, newTenantId); } @Override public void delete(JobEntity jobEntity) { super.delete(jobEntity); deleteExceptionByteArrayRef(jobEntity); removeExecutionLink(jobEntity); // Send event if (getEventDispatcher().isEnabled()) { getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_DELETED, this) ); } } @Override public void delete(JobEntity entity, boolean fireDeleteEvent) { if (entity.getExecutionId() != null && isExecutionRelatedEntityCountEnabledGlobally()) { CountingExecutionEntity executionEntity = (CountingExecutionEntity) getExecutionEntityManager().findById( entity.getExecutionId() ); if (isExecutionRelatedEntityCountEnabled(executionEntity)) { executionEntity.setJobCount(executionEntity.getJobCount() - 1); } } super.delete(entity, fireDeleteEvent);
} /** * Removes the job's execution's reference to this job, if the job has an associated execution. * Subclasses may override to provide custom implementations. */ protected void removeExecutionLink(JobEntity jobEntity) { if (jobEntity.getExecutionId() != null) { ExecutionEntity execution = getExecutionEntityManager().findById(jobEntity.getExecutionId()); if (execution != null) { execution.getJobs().remove(jobEntity); } } } /** * Deletes a the byte array used to store the exception information. Subclasses may override * to provide custom implementations. */ protected void deleteExceptionByteArrayRef(JobEntity jobEntity) { ByteArrayRef exceptionByteArrayRef = jobEntity.getExceptionByteArrayRef(); if (exceptionByteArrayRef != null) { exceptionByteArrayRef.delete(); } } public JobDataManager getJobDataManager() { return jobDataManager; } public void setJobDataManager(JobDataManager jobDataManager) { this.jobDataManager = jobDataManager; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\JobEntityManagerImpl.java
1
请完成以下Java代码
protected List<IAttributeValue> generateAndGetInitialAttributes(final IAttributeValueContext attributesCtx, final Map<AttributeId, Object> defaultAttributesValue) { throw new UnsupportedOperationException("Generating initial attributes not supported for " + this); } @Override public void updateHUTrxAttribute(final MutableHUTransactionAttribute huTrxAttribute, final IAttributeValue fromAttributeValue) { huTrxAttribute.setReferencedObject(asi); } /** * Method not supported. * * @throws UnsupportedOperationException */ @Override protected void addChildAttributeStorage(final IAttributeStorage childAttributeStorage) { throw new UnsupportedOperationException("Child attribute storages are not supported for " + this); } /** * Method not supported. * * @throws UnsupportedOperationException */
@Override protected IAttributeStorage removeChildAttributeStorage(final IAttributeStorage childAttributeStorage) { throw new UnsupportedOperationException("Child attribute storages are not supported for " + this); } @Override public void saveChangesIfNeeded() { throw new UnsupportedOperationException(); } @Override public void setSaveOnChange(boolean saveOnChange) { throw new UnsupportedOperationException(); } @Override public UOMType getQtyUOMTypeOrNull() { // ASI attribute storages does not support Qty Storage return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\ASIAttributeStorage.java
1
请完成以下Java代码
public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRole() { return role; }
public void setRole(String role) { this.role = role; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "User [username=" + username + ", password=" + password + ", role=" + role + "]"; } }
repos\tutorials-master\spring-boot-modules\spring-boot-springdoc\src\main\java\com\baeldung\jwt\User.java
1
请完成以下Java代码
private void destroyEmptySourceHUs() { final Collection<I_M_HU> sourceHUs = sourceHUsRepository.retrieveActualSourceHUs(pickFromHuIds); final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory(); // clean up and unselect used up source HUs for (final I_M_HU sourceHU : sourceHUs) { if (!storageFactory.getStorage(sourceHU).isEmpty()) { return; } takeSnapshotAndDestroyHU(sourceHU); } } private void takeSnapshotAndDestroyHU(@NonNull final I_M_HU sourceHU) { final SourceHUsService sourceHuService = SourceHUsService.get(); sourceHuService.snapshotHuIfMarkedAsSourceHu(sourceHU); handlingUnitsBL.destroyIfEmptyStorage(sourceHU); Check.errorUnless(handlingUnitsBL.isDestroyed(sourceHU), "We invoked IHandlingUnitsBL.destroyIfEmptyStorage on an HU with empty storage, but its not destroyed; hu={}", sourceHU); logger.info("Source M_HU with M_HU_ID={} is now destroyed", sourceHU.getM_HU_ID()); } private ImmutableList<PickingCandidate> changeStatusToProcessedAndSave() { final ImmutableList<PickingCandidate> pickingCandidates = getPickingCandidates(); pickingCandidates.forEach(pc -> pc.changeStatusToProcessed(getPickedHUId(pc))); pickingCandidateRepository.saveAll(pickingCandidates); return pickingCandidates; } @Nullable private PickedHuAndQty getPickedHuAndQty(@NonNull final PickingCandidate pc) { final HuId initialHuId = pc.getPickFrom().getHuId(); return initialHuId != null ? transactionedHus.get(initialHuId) : null; } @Nullable private HuId getPickedHUId(@NonNull final PickingCandidate pc) { final PickedHuAndQty item = getPickedHuAndQty(pc); final HuId initialHuId = pc.getPickFrom().getHuId(); // allow fallback on picking candidate HU as picked HU return item != null ? item.getPickedHUId() : initialHuId; }
private void validateClearedHUs(@NonNull final List<PickingCandidate> pickingCandidates, @NonNull final Set<HuId> additionalPickFromHuIds) { final ImmutableSet.Builder<HuId> huIdCollector = ImmutableSet.builder(); pickingCandidates .stream() .map(PickingCandidate::getPickFrom) .map(PickFrom::getHuId) .filter(Objects::nonNull) .forEach(huIdCollector::add); final ImmutableSet<HuId> husToValidate = huIdCollector.addAll(additionalPickFromHuIds).build(); final boolean anyNotClearedHUs = husToValidate.stream() .anyMatch(huId -> !handlingUnitsBL.isHUHierarchyCleared(huId)); if (anyNotClearedHUs) { throw new AdempiereException(MSG_ONLY_CLEARED_HUs_CAN_BE_PICKED); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\ProcessHUsAndPickingCandidateCommand.java
1
请完成以下Java代码
public TbQueueProducer<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> getTbEdgeEventsMsgProducer() { throw new RuntimeException("Not Implemented! Should not be used by Transport!"); } @Override public TbQueueProducer<TbProtoQueueMsg<ToVersionControlServiceMsg>> getTbVersionControlMsgProducer() { throw new RuntimeException("Not Implemented! Should not be used by Transport!"); } @Override public TbQueueProducer<TbProtoQueueMsg<ToUsageStatsServiceMsg>> getTbUsageStatsMsgProducer() { return toUsageStats; } @Override
public TbQueueProducer<TbProtoQueueMsg<ToHousekeeperServiceMsg>> getHousekeeperMsgProducer() { return toHousekeeper; } @Override public TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCalculatedFieldMsg>> getCalculatedFieldsMsgProducer() { throw new RuntimeException("Not Implemented! Should not be used by Transport!"); } @Override public TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCalculatedFieldNotificationMsg>> getCalculatedFieldsNotificationsMsgProducer() { throw new RuntimeException("Not Implemented! Should not be used by Transport!"); } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\provider\TbTransportQueueProducerProvider.java
1
请在Spring Boot框架中完成以下Java代码
public Deployment deploy() { return repositoryService.deploy(this); } // getters and setters // ////////////////////////////////////////////////////// public DeploymentEntity getDeployment() { return deployment; } public boolean isProcessValidationEnabled() { return isProcessValidationEnabled; }
public boolean isBpmn20XsdValidationEnabled() { return isBpmn20XsdValidationEnabled; } public boolean isDuplicateFilterEnabled() { return isDuplicateFilterEnabled; } public Date getProcessDefinitionsActivationDate() { return processDefinitionsActivationDate; } public Map<String, Object> getDeploymentProperties() { return deploymentProperties; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\repository\DeploymentBuilderImpl.java
2
请完成以下Spring Boot application配置
server: port: 80 spring: mail: host: smtp.163.com username: xxxx@163.com password: xxxx properties: mail: smtp: auth: true
starttls: enable: true required: true
repos\SpringAll-master\22.Spring-Boot-Email\src\main\resources\application.yml
2
请完成以下Java代码
public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (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 Percent. @param Percent Percentage */ @Override public void setPercent (int Percent) { set_Value (COLUMNNAME_Percent, Integer.valueOf(Percent)); }
/** Get Percent. @return Percentage */ @Override public int getPercent () { Integer ii = (Integer)get_Value(COLUMNNAME_Percent); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { throw new IllegalArgumentException ("Processed is virtual column"); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Cost.java
1
请完成以下Java代码
public class UmsGrowthChangeHistory implements Serializable { private Long id; private Long memberId; private Date createTime; @ApiModelProperty(value = "改变类型:0->增加;1->减少") private Integer changeType; @ApiModelProperty(value = "积分改变数量") private Integer changeCount; @ApiModelProperty(value = "操作人员") private String operateMan; @ApiModelProperty(value = "操作备注") private String operateNote; @ApiModelProperty(value = "积分来源:0->购物;1->管理员修改") private Integer sourceType; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Integer getChangeType() { return changeType; } public void setChangeType(Integer changeType) { this.changeType = changeType; } public Integer getChangeCount() { return changeCount; } public void setChangeCount(Integer changeCount) { this.changeCount = changeCount; } public String getOperateMan() { return operateMan; } public void setOperateMan(String operateMan) { this.operateMan = operateMan; } public String getOperateNote() { return operateNote;
} public void setOperateNote(String operateNote) { this.operateNote = operateNote; } public Integer getSourceType() { return sourceType; } public void setSourceType(Integer sourceType) { this.sourceType = sourceType; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", memberId=").append(memberId); sb.append(", createTime=").append(createTime); sb.append(", changeType=").append(changeType); sb.append(", changeCount=").append(changeCount); sb.append(", operateMan=").append(operateMan); sb.append(", operateNote=").append(operateNote); sb.append(", sourceType=").append(sourceType); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsGrowthChangeHistory.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } public static class Apiversion { /** * Whether the API version is required with each request. */ private @Nullable Boolean required; /** * Default version that should be used for each request. */ @Name("default") private @Nullable String defaultVersion; /** * Supported versions. */ private @Nullable List<String> supported; /** * Whether supported versions should be detected from controllers. */ private @Nullable Boolean detectSupported; /** * How version details should be inserted into requests. */ private final Use use = new Use(); public @Nullable Boolean getRequired() { return this.required; } public void setRequired(@Nullable Boolean required) { this.required = required; } public @Nullable String getDefaultVersion() { return this.defaultVersion; } public void setDefaultVersion(@Nullable String defaultVersion) { this.defaultVersion = defaultVersion; } public @Nullable List<String> getSupported() { return this.supported; } public void setSupported(@Nullable List<String> supported) { this.supported = supported; } public @Nullable Boolean getDetectSupported() { return this.detectSupported; } public void setDetectSupported(@Nullable Boolean detectSupported) { this.detectSupported = detectSupported; } public Use getUse() { return this.use; } public static class Use { /** * Use the HTTP header with the given name to obtain the version. */ private @Nullable String header;
/** * Use the query parameter with the given name to obtain the version. */ private @Nullable String queryParameter; /** * Use the path segment at the given index to obtain the version. */ private @Nullable Integer pathSegment; /** * Use the media type parameter with the given name to obtain the version. */ private Map<MediaType, String> mediaTypeParameter = new LinkedHashMap<>(); public @Nullable String getHeader() { return this.header; } public void setHeader(@Nullable String header) { this.header = header; } public @Nullable String getQueryParameter() { return this.queryParameter; } public void setQueryParameter(@Nullable String queryParameter) { this.queryParameter = queryParameter; } public @Nullable Integer getPathSegment() { return this.pathSegment; } public void setPathSegment(@Nullable Integer pathSegment) { this.pathSegment = pathSegment; } public Map<MediaType, String> getMediaTypeParameter() { return this.mediaTypeParameter; } public void setMediaTypeParameter(Map<MediaType, String> mediaTypeParameter) { this.mediaTypeParameter = mediaTypeParameter; } } } }
repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\autoconfigure\WebFluxProperties.java
2
请完成以下Java代码
public String getRootProcessInstanceId() { return rootProcessInstanceId; } public static HistoricDetailDto fromHistoricDetail(HistoricDetail historicDetail) { HistoricDetailDto dto = null; if (historicDetail instanceof HistoricFormField) { HistoricFormField historicFormField = (HistoricFormField) historicDetail; dto = HistoricFormFieldDto.fromHistoricFormField(historicFormField); } else if (historicDetail instanceof HistoricVariableUpdate) { HistoricVariableUpdate historicVariableUpdate = (HistoricVariableUpdate) historicDetail; dto = HistoricVariableUpdateDto.fromHistoricVariableUpdate(historicVariableUpdate); } fromHistoricDetail(historicDetail, dto); return dto; } protected static void fromHistoricDetail(HistoricDetail historicDetail, HistoricDetailDto dto) { dto.id = historicDetail.getId(); dto.processDefinitionKey = historicDetail.getProcessDefinitionKey(); dto.processDefinitionId = historicDetail.getProcessDefinitionId();
dto.processInstanceId = historicDetail.getProcessInstanceId(); dto.activityInstanceId = historicDetail.getActivityInstanceId(); dto.executionId = historicDetail.getExecutionId(); dto.taskId = historicDetail.getTaskId(); dto.caseDefinitionKey = historicDetail.getCaseDefinitionKey(); dto.caseDefinitionId = historicDetail.getCaseDefinitionId(); dto.caseInstanceId = historicDetail.getCaseInstanceId(); dto.caseExecutionId = historicDetail.getCaseExecutionId(); dto.tenantId = historicDetail.getTenantId(); dto.userOperationId = historicDetail.getUserOperationId(); dto.time = historicDetail.getTime(); dto.removalTime = historicDetail.getRemovalTime(); dto.rootProcessInstanceId = historicDetail.getRootProcessInstanceId(); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricDetailDto.java
1
请在Spring Boot框架中完成以下Java代码
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { registerBeanDefinition("preFilterAuthorizationMethodInterceptor", "org.springframework.security.authorization.method.aspectj.PreFilterAspect", "preFilterAspect$0", registry); registerBeanDefinition("postFilterAuthorizationMethodInterceptor", "org.springframework.security.authorization.method.aspectj.PostFilterAspect", "postFilterAspect$0", registry); registerBeanDefinition("preAuthorizeAuthorizationMethodInterceptor", "org.springframework.security.authorization.method.aspectj.PreAuthorizeAspect", "preAuthorizeAspect$0", registry); registerBeanDefinition("postAuthorizeAuthorizationMethodInterceptor", "org.springframework.security.authorization.method.aspectj.PostAuthorizeAspect", "postAuthorizeAspect$0", registry); registerBeanDefinition("securedAuthorizationMethodInterceptor", "org.springframework.security.authorization.method.aspectj.SecuredAspect", "securedAspect$0", registry); }
private void registerBeanDefinition(String beanName, String aspectClassName, String aspectBeanName, BeanDefinitionRegistry registry) { if (!registry.containsBeanDefinition(beanName)) { return; } BeanDefinition interceptor = registry.getBeanDefinition(beanName); BeanDefinitionBuilder aspect = BeanDefinitionBuilder.rootBeanDefinition(aspectClassName); aspect.setFactoryMethod("aspectOf"); aspect.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); aspect.addPropertyValue("securityInterceptor", interceptor); registry.registerBeanDefinition(aspectBeanName, aspect.getBeanDefinition()); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\MethodSecurityAspectJAutoProxyRegistrar.java
2
请完成以下Java代码
public void writeExcel() throws IOException { Workbook workbook = new XSSFWorkbook(); try { Sheet sheet = workbook.createSheet("Persons"); sheet.setColumnWidth(0, 6000); sheet.setColumnWidth(1, 4000); Row header = sheet.createRow(0); CellStyle headerStyle = workbook.createCellStyle(); headerStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex()); headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); XSSFFont font = ((XSSFWorkbook) workbook).createFont(); font.setFontName("Arial"); font.setFontHeightInPoints((short) 16); font.setBold(true); headerStyle.setFont(font); Cell headerCell = header.createCell(0); headerCell.setCellValue("Name"); headerCell.setCellStyle(headerStyle); headerCell = header.createCell(1); headerCell.setCellValue("Age"); headerCell.setCellStyle(headerStyle);
CellStyle style = workbook.createCellStyle(); style.setWrapText(true); Row row = sheet.createRow(2); Cell cell = row.createCell(0); cell.setCellValue("John Smith"); cell.setCellStyle(style); cell = row.createCell(1); cell.setCellValue(20); cell.setCellStyle(style); File currDir = new File("."); String path = currDir.getAbsolutePath(); String fileLocation = path.substring(0, path.length() - 1) + "temp.xlsx"; FileOutputStream outputStream = new FileOutputStream(fileLocation); workbook.write(outputStream); } finally { if (workbook != null) { workbook.close(); } } } }
repos\tutorials-master\apache-poi\src\main\java\com\baeldung\poi\excel\ExcelPOIHelper.java
1
请完成以下Java代码
public class Fare { private Long nightSurcharge; private Long rideFare; public Fare() { nightSurcharge = 0L; rideFare = 0L; } public Long getNightSurcharge() { return nightSurcharge; } public void setNightSurcharge(Long nightSurcharge) {
this.nightSurcharge = nightSurcharge; } public Long getRideFare() { return rideFare; } public void setRideFare(Long rideFare) { this.rideFare = rideFare; } public Long getTotalFare() { return nightSurcharge + rideFare; } }
repos\tutorials-master\spring-drools\src\main\java\com\baeldung\spring\drools\model\Fare.java
1
请在Spring Boot框架中完成以下Java代码
public String getTopCateEntityID() { return topCateEntityID; } public void setTopCateEntityID(String topCateEntityID) { this.topCateEntityID = topCateEntityID; } public String getSubCategEntityID() { return subCategEntityID; } public void setSubCategEntityID(String subCategEntityID) { this.subCategEntityID = subCategEntityID; } public String getBrandEntityID() { return brandEntityID; } public void setBrandEntityID(String brandEntityID) { this.brandEntityID = brandEntityID; } public Integer getProdState() { return prodState; } public void setProdState(Integer prodState) { this.prodState = prodState; } public String getContent() { return content; } public void setContent(String content) { this.content = content;
} public String getCompanyEntityID() { return companyEntityID; } public void setCompanyEntityID(String companyEntityID) { this.companyEntityID = companyEntityID; } @Override public String toString() { return "ProdInsertReq{" + "id='" + id + '\'' + ", prodName='" + prodName + '\'' + ", marketPrice='" + marketPrice + '\'' + ", shopPrice='" + shopPrice + '\'' + ", stock=" + stock + ", sales=" + sales + ", weight='" + weight + '\'' + ", topCateEntityID='" + topCateEntityID + '\'' + ", subCategEntityID='" + subCategEntityID + '\'' + ", brandEntityID='" + brandEntityID + '\'' + ", prodState=" + prodState + ", content='" + content + '\'' + ", companyEntityID='" + companyEntityID + '\'' + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\product\ProdInsertReq.java
2
请完成以下Java代码
public class ResultDTO_wo_Ids { public ResultDTO_wo_Ids(String customerName, String customerEmail, LocalDate orderDate, String productName, Double productPrice) { this.customerName = customerName; this.customerEmail = customerEmail; this.orderDate = orderDate; this.productName = productName; this.productPrice = productPrice; } private String customerName; private String customerEmail; private LocalDate orderDate; private String productName; private Double productPrice; public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public String getCustomerEmail() { return customerEmail; } public void setCustomerEmail(String customerEmail) { this.customerEmail = customerEmail; }
public LocalDate getOrderDate() { return orderDate; } public void setOrderDate(LocalDate orderDate) { this.orderDate = orderDate; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public Double getProductPrice() { return productPrice; } public void setProductPrice(Double productPrice) { this.productPrice = productPrice; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\spring\data\jpa\joinquery\DTO\ResultDTO_wo_Ids.java
1
请完成以下Java代码
private I_C_Invoice retrieveInvoiceRecordByDocumentNoAndCreatedOrNull(@NonNull final String documentNo, @NonNull final Instant created) { return Services.get(IQueryBL.class) .createQueryBuilder(I_C_Invoice.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Invoice.COLUMN_DocumentNo, documentNo) .addEqualsFilter(I_C_Invoice.COLUMN_Created, created) .create() .setRequiredAccess(Access.WRITE) .firstOnly(I_C_Invoice.class); } private I_C_Invoice retrieveInvoiceRecordById(@NonNull final InvoiceId invoiceId) { final I_C_Invoice invoiceRecord; invoiceRecord = load(invoiceId, I_C_Invoice.class); if (invoiceRecord == null) { throw new InvoiceResponseRepoException(MSG_INVOICE_NOT_FOUND_BY_ID_1P, invoiceId.getRepoId()) .markAsUserValidationError(); } return invoiceRecord; } private void updateInvoiceRecord(@NonNull final ImportedInvoiceResponse response, @NonNull final I_C_Invoice invoiceRecord) { invoiceRecord.setIsInDispute(ImportedInvoiceResponse.Status.REJECTED.equals(response.getStatus())); saveRecord(invoiceRecord); } private void attachFileToInvoiceRecord( @NonNull final ImportedInvoiceResponse response, @NonNull final I_C_Invoice invoiceRecord) { final AttachmentTags attachmentTags = AttachmentTags.builder() .tags(response.getAdditionalTags()) .build();
final AttachmentEntryCreateRequest attachmentEntryCreateRequest = AttachmentEntryCreateRequest .builderFromByteArray(response.getRequest().getFileName(), response.getRequest().getData()) .tags(attachmentTags) .build(); attachmentEntryService.createNewAttachment(invoiceRecord, attachmentEntryCreateRequest); } @SuppressWarnings("WeakerAccess") public static final class InvoiceResponseRepoException extends AdempiereException { private static final long serialVersionUID = -4024895067979792864L; public InvoiceResponseRepoException(@NonNull final ITranslatableString message) { super(message); } public InvoiceResponseRepoException(@NonNull final AdMessageKey adMessage, final Object... params) { super(adMessage, params); } } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\base\imp\InvoiceResponseRepo.java
1
请在Spring Boot框架中完成以下Java代码
public boolean compressed() { return obtain(InfluxProperties::isCompressed, InfluxConfig.super::compressed); } @Override public boolean autoCreateDb() { return obtain(InfluxProperties::isAutoCreateDb, InfluxConfig.super::autoCreateDb); } @Override public InfluxApiVersion apiVersion() { return obtain(InfluxProperties::getApiVersion, InfluxConfig.super::apiVersion); } @Override
public @Nullable String org() { return get(InfluxProperties::getOrg, InfluxConfig.super::org); } @Override public String bucket() { return obtain(InfluxProperties::getBucket, InfluxConfig.super::bucket); } @Override public @Nullable String token() { return get(InfluxProperties::getToken, InfluxConfig.super::token); } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\influx\InfluxPropertiesConfigAdapter.java
2
请在Spring Boot框架中完成以下Java代码
public BigDecimal getTotalAmount() { return totalAmount; } /** * 总金额 */ public void setTotalAmount(BigDecimal totalAmount) { this.totalAmount = totalAmount; } /** * 总笔数 */ public Integer getTotalNum() { return totalNum; } /** * 总笔数 */ public void setTotalNum(Integer totalNum) { this.totalNum = totalNum; } /** * 最后ID * * @return */ public Long getLastId() { return lastId; } /**
* 最后ID * * @return */ public void setLastId(Long lastId) { this.lastId = lastId; } /** * 风险预存期 */ public Integer getRiskDay() { return riskDay; } /** * 风险预存期 */ public void setRiskDay(Integer riskDay) { this.riskDay = riskDay; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\vo\DailyCollectAccountHistoryVo.java
2
请完成以下Java代码
public SqlDocumentOrderByBuilder useColumnNameAlias(final boolean useColumnNameAlias) { this.useColumnNameAlias = useColumnNameAlias; return this; } public SqlDocumentOrderByBuilder beforeOrderBy(@Nullable final SqlAndParams beforeOrderBy) { if (beforeOrderBy != null && !beforeOrderBy.isEmpty()) { if (this.beforeOrderBys == null) { this.beforeOrderBys = new ArrayList<>(); } this.beforeOrderBys.add(beforeOrderBy); } return this; } public SqlDocumentOrderByBuilder beforeOrderBy(@Nullable final String beforeOrderBy) { if (beforeOrderBy != null) { beforeOrderBy(SqlAndParams.of(beforeOrderBy)); } return this; } /** * @return SQL order by (e.g. Column1 ASC, Column2 DESC) */ public Optional<SqlAndParamsExpression> buildSqlOrderBy(final DocumentQueryOrderByList orderBys) { if (orderBys.isEmpty()) { return Optional.empty(); } final SqlAndParamsExpression.Builder result = SqlAndParamsExpression.builder(); // // First ORDER BYs if (beforeOrderBys != null && !beforeOrderBys.isEmpty()) { for (final SqlAndParams beforeOrderBy : beforeOrderBys) { if (!result.isEmpty()) { result.append(", "); } result.append(beforeOrderBy); } } // // Actual ORDER BY columns {
final IStringExpression orderBysExpression = orderBys .stream() .map(this::buildSqlOrderBy) .filter(sql -> sql != null && !sql.isNullExpression()) .collect(IStringExpression.collectJoining(", ")); if (orderBysExpression != null && !orderBysExpression.isNullExpression()) { if (!result.isEmpty()) { result.append(", "); } result.append(orderBysExpression); } } return !result.isEmpty() ? Optional.of(result.build()) : Optional.empty(); } private IStringExpression buildSqlOrderBy(final DocumentQueryOrderBy orderBy) { final String fieldName = orderBy.getFieldName(); final SqlOrderByValue sqlExpression = bindings.getFieldOrderBy(fieldName); return buildSqlOrderBy(sqlExpression, orderBy.isAscending(), orderBy.isNullsLast()); } private IStringExpression buildSqlOrderBy( final SqlOrderByValue orderBy, final boolean ascending, final boolean nullsLast) { if (orderBy.isNull()) { return IStringExpression.NULL; } final CompositeStringExpression.Builder sql = IStringExpression.composer(); if (useColumnNameAlias) { sql.append(orderBy.withJoinOnTableNameOrAlias(joinOnTableNameOrAlias).toSqlUsingColumnNameAlias()); } else { sql.append("(").append(orderBy.withJoinOnTableNameOrAlias(joinOnTableNameOrAlias).toSourceSqlExpression()).append(")"); } return sql.append(ascending ? " ASC" : " DESC") .append(nullsLast ? " NULLS LAST" : " NULLS FIRST") .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\SqlDocumentOrderByBuilder.java
1
请完成以下Java代码
public class DecisionImpl extends CmmnElementImpl implements Decision { protected static Attribute<String> nameAttribute; protected static Attribute<String> implementationTypeAttribute; protected static ChildElementCollection<InputDecisionParameter> inputCollection; protected static ChildElementCollection<OutputDecisionParameter> outputCollection; public DecisionImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); } public String getImplementationType() { return implementationTypeAttribute.getValue(this); } public void setImplementationType(String implementationType) { implementationTypeAttribute.setValue(this, implementationType); } public Collection<InputDecisionParameter> getInputs() { return inputCollection.get(this); } public Collection<OutputDecisionParameter> getOutputs() { return outputCollection.get(this); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Decision.class, CMMN_ELEMENT_DECISION) .extendsType(CmmnElement.class) .namespaceUri(CMMN11_NS) .instanceProvider(new ModelTypeInstanceProvider<Decision>() { public Decision newInstance(ModelTypeInstanceContext instanceContext) { return new DecisionImpl(instanceContext); } });
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); implementationTypeAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_IMPLEMENTATION_TYPE) .defaultValue("http://www.omg.org/spec/CMMN/DecisionType/Unspecified") .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); inputCollection = sequenceBuilder.elementCollection(InputDecisionParameter.class) .build(); outputCollection = sequenceBuilder.elementCollection(OutputDecisionParameter.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\DecisionImpl.java
1
请在Spring Boot框架中完成以下Java代码
public long executeCount(CommandContext commandContext) { if (isDmnEnabled(commandContext)) { checkQueryOk(); return commandContext .getDecisionDefinitionManager() .findDecisionDefinitionCountByQueryCriteria(this); } return 0; } @Override public List<DecisionDefinition> executeList(CommandContext commandContext, Page page) { if (isDmnEnabled(commandContext)) { checkQueryOk(); return commandContext .getDecisionDefinitionManager() .findDecisionDefinitionsByQueryCriteria(this, page); } return Collections.emptyList(); } @Override public void checkQueryOk() { super.checkQueryOk(); // latest() makes only sense when used with key() or keyLike() if (latest && ( (id != null) || (name != null) || (nameLike != null) || (version != null) || (deploymentId != null) ) ){ throw new NotValidException("Calling latest() can only be used in combination with key(String) and keyLike(String)"); } } private boolean isDmnEnabled(CommandContext commandContext) { return commandContext .getProcessEngineConfiguration() .isDmnEnabled(); } // getters //////////////////////////////////////////// public String getId() { return id; } public String[] getIds() { return ids; } public String getCategory() { return category; } public String getCategoryLike() { return categoryLike; } public String getName() { return name; } public String getNameLike() { return nameLike; } public String getDeploymentId() { return deploymentId; } public Date getDeployedAfter() { return deployedAfter; } public Date getDeployedAt() { return deployedAt; } 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 String getVersionTag() { return versionTag; } public String getVersionTagLike() { return versionTagLike; } public boolean isLatest() { return latest; } public boolean isShouldJoinDeploymentTable() { return shouldJoinDeploymentTable; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\entity\repository\DecisionDefinitionQueryImpl.java
2
请完成以下Java代码
public class SetJobRetriesByJobsAsyncBuilderImpl implements SetJobRetriesByJobsAsyncBuilder { protected final static CommandLogger LOG = ProcessEngineLogger.CMD_LOGGER; protected final CommandExecutor commandExecutor; protected List<String> jobIds; protected JobQuery jobQuery; protected Integer retries; protected Date dueDate; protected boolean isDueDateSet; public SetJobRetriesByJobsAsyncBuilderImpl(CommandExecutor commandExecutor, int retries) { this.commandExecutor = commandExecutor; this.retries = retries; } @Override public SetJobRetriesByJobsAsyncBuilder jobQuery(JobQuery query) { this.jobQuery = query; return this; } @Override public SetJobRetriesByJobsAsyncBuilder jobIds(List<String> jobIds) { this.jobIds = jobIds; return this; } @Override public SetJobRetriesAsyncBuilder dueDate(Date dueDate) { this.dueDate = dueDate; isDueDateSet = true;
return this; } @Override public Batch executeAsync() { validateParameters(); return commandExecutor.execute(new SetJobsRetriesBatchCmd(jobIds, jobQuery, retries, dueDate, isDueDateSet)); } protected void validateParameters() { ensureNotNull("commandExecutor", commandExecutor); ensureNotNull("retries", retries); if((jobIds == null || jobIds.isEmpty()) && jobQuery == null) { throw LOG.exceptionSettingJobRetriesAsyncNoJobsSpecified(); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\management\SetJobRetriesByJobsAsyncBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
private static class InvalidEmail { String email; String errorMessage; } private LocalToRemoteSyncResult createOrUpdateGroup(@NonNull final Campaign campaign) { if (Check.isEmpty(campaign.getRemoteId())) { final Group createdGroup = createGroup(campaign); final Campaign campaignWithRemoteId = campaign .toBuilder() .remoteId(Integer.toString(createdGroup.getId())) .build(); return LocalToRemoteSyncResult.inserted(campaignWithRemoteId); } updateGroup(campaign); return LocalToRemoteSyncResult.updated(campaign); }
@Override public void sendEmailActivationForm( @NonNull final String formId, @NonNull final String email) { final String url = "/forms/" + formId + "/send/activate"; final SendEmailActivationFormRequest body = SendEmailActivationFormRequest.builder() .email(email) .doidata(SendEmailActivationFormRequest.DoubleOptInData.builder() .user_ip("1.2.3.4") .referer("metasfresh") .user_agent("metasfresh") .build()) .build(); getLowLevelClient().post(body, SINGLE_HETEROGENOUS_TYPE, url); // returns the email as string in case of success } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\cleverreach\src\main\java\de\metas\marketing\gateway\cleverreach\CleverReachClient.java
2
请完成以下Java代码
public SecurityUser withUserName(String userName) { this.userName = userName; return this; } @Override public String getUsername() { return this.userName; } @Override public boolean isAccountNonExpired() { return false; }
@Override public boolean isAccountNonLocked() { return false; } @Override public boolean isCredentialsNonExpired() { return false; } @Override public boolean isEnabled() { return false; } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-4\src\main\java\com\baeldung\enablemethodsecurity\user\SecurityUser.java
1
请在Spring Boot框架中完成以下Java代码
public boolean canRead(Class<?> clazz, MediaType mediaType) { LOG.info("canRead"); if (DataMessage.class.equals(clazz) && (MediaType.APPLICATION_JSON.equals(mediaType) || MediaType.APPLICATION_JSON_UTF8.equals(mediaType))) { return true; } else { return false; } } @Override public boolean canWrite(Class<?> clazz, MediaType mediaType) { LOG.info("canWrite"); if (DataMessage.class.equals(clazz) && ( MediaType.APPLICATION_JSON.equals(mediaType) || MediaType.APPLICATION_JSON_UTF8.equals(mediaType))) { return true; } else { return false; } } @Override public List<MediaType> getSupportedMediaTypes() { LOG.info("getSupportedMediaTypes"); return getMediaTypes(); }
@Override public DataMessage read(Class<? extends DataMessage> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { LOG.info("read"); ObjectMapper objectMapper = getObjectMapper(); JsonNode jsonNode = objectMapper.readTree(inputMessage.getBody()); String data = jsonNode.get("data").textValue(); return new DataMessage(data); } @Override public void write(DataMessage dataMessage, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { LOG.info("write"); ObjectMapper objectMapper = getObjectMapper(); OutputStream stream = outputMessage.getBody(); objectMapper.writeValue(stream, dataMessage); stream.flush(); } }
repos\spring-examples-java-17\spring-demo\src\main\java\itx\examples\springboot\demo\config\converters\DataMessageConverter.java
2
请完成以下Java代码
public class Customer { //Id注解加上后,在Elasticsearch里相应于该列就是主键了,在查询时就可以直接用主键查询 @Id private String id; private String userName; private String address; private int age; public Customer() { } public Customer(String userName, String address, int age) { this.userName = userName; this.address = address; this.age = age; } public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getUserName() { return userName; }
public void setUserName(String userName) { this.userName = userName; } public String getAddress() { return address; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Customer{" + "id='" + id + '\'' + ", userName='" + userName + '\'' + ", address='" + address + '\'' + ", age=" + age + '}'; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 4-8 课:Spring Boot 集成 ElasticSearch\spring-boot-elasticsearch\src\main\java\com\neo\model\Customer.java
1
请完成以下Java代码
public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getA_Depreciation_Table_Header_ID())); } /** A_Table_Rate_Type AD_Reference_ID=53255 */ public static final int A_TABLE_RATE_TYPE_AD_Reference_ID=53255; /** Amount = AM */ public static final String A_TABLE_RATE_TYPE_Amount = "AM"; /** Rate = RT */ public static final String A_TABLE_RATE_TYPE_Rate = "RT"; /** Set Type. @param A_Table_Rate_Type Type */ public void setA_Table_Rate_Type (String A_Table_Rate_Type) { set_Value (COLUMNNAME_A_Table_Rate_Type, A_Table_Rate_Type); } /** Get Type. @return Type */ public String getA_Table_Rate_Type () { return (String)get_Value(COLUMNNAME_A_Table_Rate_Type); } /** A_Term AD_Reference_ID=53256 */ public static final int A_TERM_AD_Reference_ID=53256; /** Period = PR */ public static final String A_TERM_Period = "PR"; /** Yearly = YR */ public static final String A_TERM_Yearly = "YR"; /** Set Period/Yearly. @param A_Term Period/Yearly */ public void setA_Term (String A_Term) { set_Value (COLUMNNAME_A_Term, A_Term); } /** Get Period/Yearly. @return Period/Yearly */ public String getA_Term () { return (String)get_Value(COLUMNNAME_A_Term); } /** Set Description. @param Description Optional short description of the record */
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Table_Header.java
1
请完成以下Java代码
private static ImmutableMap<DocumentId, HUEditorRow> buildRowsByIdMap(final List<HUEditorRow> rows) { if (rows.isEmpty()) { return ImmutableMap.of(); } final ImmutableMap.Builder<DocumentId, HUEditorRow> rowsById = ImmutableMap.builder(); rows.forEach(row -> indexByIdRecursively(rowsById, row)); return rowsById.build(); } private static void indexByIdRecursively(final ImmutableMap.Builder<DocumentId, HUEditorRow> collector, final HUEditorRow row) { collector.put(row.getId(), row); row.getIncludedRows() .forEach(includedRow -> indexByIdRecursively(collector, includedRow)); } private static ImmutableMap<HUEditorRowId, HUEditorRowId> buildRowId2ParentIdMap(final List<HUEditorRow> rows) { if (rows.isEmpty()) {
return ImmutableMap.of(); } final ImmutableMap.Builder<HUEditorRowId, HUEditorRowId> rowId2parentId = ImmutableMap.builder(); rows.forEach(row -> buildRowId2ParentIdMap(rowId2parentId, row)); return rowId2parentId.build(); } private static void buildRowId2ParentIdMap(final ImmutableMap.Builder<HUEditorRowId, HUEditorRowId> rowId2parentId, final HUEditorRow parentRow) { final HUEditorRowId parentId = parentRow.getHURowId(); parentRow.getIncludedRows() .forEach(includedRow -> rowId2parentId.put(includedRow.getHURowId(), parentId)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorViewBuffer_FullyCached.java
1
请完成以下Java代码
public void save(@NonNull final DecommissionResponse response) { if (response.getId() != null) { throw new AdempiereException("Response was already saved: " + response); } final I_M_Securpharm_Action_Result record = newInstance(I_M_Securpharm_Action_Result.class); record.setIsError(response.isError()); record.setAction(SecurPharmAction.DECOMMISSION.getCode()); record.setM_Inventory_ID(InventoryId.toRepoId(response.getInventoryId())); record.setM_Securpharm_Productdata_Result_ID(response.getProductId().getRepoId()); record.setTransactionIDServer(response.getServerTransactionId()); saveRecord(record); response.setId(SecurPharmActionResultId.ofRepoId(record.getM_Securpharm_Action_Result_ID())); }
public void save(@NonNull final UndoDecommissionResponse response) { if (response.getId() != null) { throw new AdempiereException("Response was already saved: " + response); } final I_M_Securpharm_Action_Result record = newInstance(I_M_Securpharm_Action_Result.class); record.setIsError(response.isError()); record.setAction(SecurPharmAction.UNDO_DECOMMISSION.getCode()); record.setM_Inventory_ID(InventoryId.toRepoId(response.getInventoryId())); record.setM_Securpharm_Productdata_Result_ID(response.getProductId().getRepoId()); record.setTransactionIDServer(response.getServerTransactionId()); saveRecord(record); response.setId(SecurPharmActionResultId.ofRepoId(record.getM_Securpharm_Action_Result_ID())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\actions\SecurPharmaActionRepository.java
1
请完成以下Java代码
public void setSenderZipCode (java.lang.String SenderZipCode) { set_Value (COLUMNNAME_SenderZipCode, SenderZipCode); } /** Get PLZ Absender. @return PLZ Absender */ @Override public java.lang.String getSenderZipCode () { return (java.lang.String)get_Value(COLUMNNAME_SenderZipCode); } /** Set Versandlager. @param SendingDepot Versandlager */ @Override public void setSendingDepot (java.lang.String SendingDepot) { set_Value (COLUMNNAME_SendingDepot, SendingDepot); } /** Get Versandlager. @return Versandlager */ @Override public java.lang.String getSendingDepot () { return (java.lang.String)get_Value(COLUMNNAME_SendingDepot); } /** Set Nachverfolgungs-URL.
@param TrackingURL URL des Spediteurs um Sendungen zu verfolgen */ @Override public void setTrackingURL (java.lang.String TrackingURL) { set_Value (COLUMNNAME_TrackingURL, TrackingURL); } /** Get Nachverfolgungs-URL. @return URL des Spediteurs um Sendungen zu verfolgen */ @Override public java.lang.String getTrackingURL () { return (java.lang.String)get_Value(COLUMNNAME_TrackingURL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-gen\de\metas\shipper\gateway\dpd\model\X_DPD_StoreOrder.java
1
请在Spring Boot框架中完成以下Java代码
RabbitStreamTemplateConfigurer rabbitStreamTemplateConfigurer(RabbitProperties properties, ObjectProvider<MessageConverter> messageConverter, ObjectProvider<StreamMessageConverter> streamMessageConverter, ObjectProvider<ProducerCustomizer> producerCustomizer) { RabbitStreamTemplateConfigurer configurer = new RabbitStreamTemplateConfigurer(); configurer.setMessageConverter(messageConverter.getIfUnique()); configurer.setStreamMessageConverter(streamMessageConverter.getIfUnique()); configurer.setProducerCustomizer(producerCustomizer.getIfUnique()); return configurer; } @Bean @ConditionalOnMissingBean(RabbitStreamOperations.class) @ConditionalOnProperty(name = "spring.rabbitmq.stream.name") RabbitStreamTemplate rabbitStreamTemplate(Environment rabbitStreamEnvironment, RabbitProperties properties, RabbitStreamTemplateConfigurer configurer) { String name = properties.getStream().getName(); Assert.state(name != null, "'name' must not be null"); RabbitStreamTemplate template = new RabbitStreamTemplate(rabbitStreamEnvironment, name); configurer.configure(template); return template; }
static EnvironmentBuilder configure(EnvironmentBuilder builder, RabbitProperties properties, RabbitConnectionDetails connectionDetails) { return configure(builder, properties.getStream(), connectionDetails); } private static EnvironmentBuilder configure(EnvironmentBuilder builder, RabbitProperties.Stream stream, RabbitConnectionDetails connectionDetails) { builder.lazyInitialization(true); PropertyMapper map = PropertyMapper.get(); map.from(stream.getHost()).to(builder::host); map.from(stream.getPort()).to(builder::port); map.from(stream.getVirtualHost()).orFrom(connectionDetails::getVirtualHost).to(builder::virtualHost); map.from(stream.getUsername()).orFrom(connectionDetails::getUsername).to(builder::username); map.from(stream.getPassword()).orFrom(connectionDetails::getPassword).to(builder::password); return builder; } }
repos\spring-boot-4.0.1\module\spring-boot-amqp\src\main\java\org\springframework\boot\amqp\autoconfigure\RabbitStreamConfiguration.java
2
请完成以下Java代码
public static ColumnInfo[] createColumnInfo(GridTab gridTab) { final List<ColumnInfo> list = new ArrayList<ColumnInfo>(); for (GridField gridField : gridTab.getFields()) { final boolean isID = gridField.getDisplayType() == DisplayType.ID; if (!gridField.isDisplayed() && !isID) continue; ColumnInfo ci = createColumnInfo(gridField); if (ci != null) { if (isID) list.add(0, ci); else list.add(ci); }
} return list.toArray(new ColumnInfo[list.size()]); } public static ColumnInfo createColumnInfo(GridField gridField) { final String tableName = gridField.getGridTab().getTableName(); final String header = gridField.getHeader(); final int displayType = gridField.getDisplayType(); final ReferenceId referenceId = gridField.getAD_Reference_Value_ID(); final String columnName = gridField.getColumnName(); final String columnSQL = gridField.getColumnSQL(false); return createColumnInfo(header, tableName, columnName, columnSQL, displayType, ReferenceId.toRepoId(referenceId)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\ui\MiniTableUtil.java
1
请完成以下Java代码
public boolean isAllowNegative () { Object oo = get_Value(COLUMNNAME_IsAllowNegative); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Allow Positive. @param IsAllowPositive Allow Positive */ public void setIsAllowPositive (boolean IsAllowPositive) { set_Value (COLUMNNAME_IsAllowPositive, Boolean.valueOf(IsAllowPositive)); }
/** Get Allow Positive. @return Allow Positive */ public boolean isAllowPositive () { Object oo = get_Value(COLUMNNAME_IsAllowPositive); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ChargeType_DocType.java
1
请在Spring Boot框架中完成以下Java代码
public Collection<String> getResourceNames() { if(deployment.getResources() == null) { return Collections.<String>emptySet(); } else { return deployment.getResources().keySet(); } } // getters and setters ////////////////////////////////////////////////////// public DeploymentEntity getDeployment() { return deployment; } public boolean isDuplicateFilterEnabled() { return isDuplicateFilterEnabled; } public boolean isDeployChangedOnly() { return deployChangedOnly; }
public Date getProcessDefinitionsActivationDate() { return processDefinitionsActivationDate; } public String getNameFromDeployment() { return nameFromDeployment; } public Set<String> getDeployments() { return deployments; } public Map<String, Set<String>> getDeploymentResourcesById() { return deploymentResourcesById; } public Map<String, Set<String>> getDeploymentResourcesByName() { return deploymentResourcesByName; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\repository\DeploymentBuilderImpl.java
2
请完成以下Java代码
protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } @Override protected CleanableHistoricDecisionInstanceReport createNewQuery(ProcessEngine engine) { return engine.getHistoryService().createCleanableHistoricDecisionInstanceReport(); } @Override protected void applyFilters(CleanableHistoricDecisionInstanceReport query) { if (decisionDefinitionIdIn != null && decisionDefinitionIdIn.length > 0) { query.decisionDefinitionIdIn(decisionDefinitionIdIn); } if (decisionDefinitionKeyIn != null && decisionDefinitionKeyIn.length > 0) { query.decisionDefinitionKeyIn(decisionDefinitionKeyIn); } if (Boolean.TRUE.equals(withoutTenantId)) { query.withoutTenantId();
} if (tenantIdIn != null && tenantIdIn.length > 0) { query.tenantIdIn(tenantIdIn); } if (Boolean.TRUE.equals(compact)) { query.compact(); } } @Override protected void applySortBy(CleanableHistoricDecisionInstanceReport query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_FINISHED_VALUE)) { query.orderByFinished(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\CleanableHistoricDecisionInstanceReportDto.java
1
请完成以下Java代码
public PickingSlotsClearingView createView(final @NonNull CreateViewRequest request) { request.assertNoParentViewOrRow(); final DocumentFilterDescriptorsProvider filterDescriptors = getFilterDescriptorsProvider(); final DocumentFilterList filters = request.getFiltersUnwrapped(filterDescriptors); final ViewId viewId = ViewId.random(PickingSlotsClearingViewFactory.WINDOW_ID); final PickingSlotQuery query = createPickingSlotQuery(filters); return PickingSlotsClearingView.builder() .viewId(viewId) .rows(() -> pickingSlotRepo.retrievePickingSlotsRowsForClearing(query)) .additionalRelatedProcessDescriptors(createAdditionalRelatedProcessDescriptors()) .filterDescriptors(filterDescriptors) .filters(filters) .build(); } private static PickingSlotQuery createPickingSlotQuery(@NonNull final DocumentFilterList filters) { final PickingSlotQueryBuilder queryBuilder = PickingSlotQuery.builder(); final BPartnerId bpartnerId = PickingSlotsClearingViewFilters.getBPartnerId(filters); if (bpartnerId != null) { queryBuilder.assignedToBPartnerId(bpartnerId); } final PickingSlotQRCode qrCode = PickingSlotsClearingViewFilters.getPickingSlotQRCode(filters); if (qrCode != null) { queryBuilder.qrCode(qrCode); }
return queryBuilder.build(); } private List<RelatedProcessDescriptor> createAdditionalRelatedProcessDescriptors() { // TODO: cache it return ImmutableList.of( createProcessDescriptor(WEBUI_PickingSlotsClearingView_TakeOutHU.class), createProcessDescriptor(WEBUI_PickingSlotsClearingView_TakeOutCUsAndAddToTU.class), createProcessDescriptor(WEBUI_PickingSlotsClearingView_TakeOutTUAndAddToLU.class), createProcessDescriptor(WEBUI_PickingSlotsClearingView_TakeOutHUAndAddToNewHU.class), createProcessDescriptor(WEBUI_PickingSlotsClearingView_TakeOutMultiHUsAndAddToNewHU.class), createProcessDescriptor(de.metas.ui.web.process.adprocess.WEBUI_TestParentChildViewParams.class), createProcessDescriptor(WEBUI_PickingSlotsClearingView_TakeOutTUsAndAddToNewLUs.class)); } private RelatedProcessDescriptor createProcessDescriptor(final Class<?> processClass) { return RelatedProcessDescriptor.builder() .processId(adProcessDAO.retrieveProcessIdByClass(processClass)) .anyTable().anyWindow() .displayPlace(DisplayPlace.ViewQuickActions) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\PickingSlotsClearingViewFactory.java
1
请完成以下Java代码
public void run() { commandContext.setResult(command.execute(commandContext)); } } ); // Run loop for agenda executeOperations(commandContext); // At the end, call the execution tree change listeners. // TODO: optimization: only do this when the tree has actually changed (ie check dbSqlSession). if (commandContext.hasInvolvedExecutions()) { Context.getAgenda().planExecuteInactiveBehaviorsOperation(); executeOperations(commandContext); } return (T) commandContext.getResult(); } protected void executeOperations(final CommandContext commandContext) { while (!commandContext.getAgenda().isEmpty()) { Runnable runnable = commandContext.getAgenda().getNextOperation(); executeOperation(runnable); } } public void executeOperation(Runnable runnable) { if (runnable instanceof AbstractOperation) { AbstractOperation operation = (AbstractOperation) runnable;
// Execute the operation if the operation has no execution (i.e. it's an operation not working on a process instance) // or the operation has an execution and it is not ended if (operation.getExecution() == null || !operation.getExecution().isEnded()) { if (logger.isDebugEnabled()) { logger.debug("Executing operation {} ", operation.getClass()); } runnable.run(); } } else { runnable.run(); } } @Override public CommandInterceptor getNext() { return null; } @Override public void setNext(CommandInterceptor next) { throw new UnsupportedOperationException("CommandInvoker must be the last interceptor in the chain"); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\interceptor\CommandInvoker.java
1
请完成以下Java代码
public void setDueAmt (final BigDecimal DueAmt) { set_Value (COLUMNNAME_DueAmt, DueAmt); } @Override public BigDecimal getDueAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_DueAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setDueDate (final java.sql.Timestamp DueDate) { set_Value (COLUMNNAME_DueDate, DueDate); } @Override public java.sql.Timestamp getDueDate() { return get_ValueAsTimestamp(COLUMNNAME_DueDate); } @Override public void setIsValid (final boolean IsValid) { set_Value (COLUMNNAME_IsValid, IsValid); } @Override public boolean isValid() { return get_ValueAsBoolean(COLUMNNAME_IsValid); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); }
@Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_InvoicePaySchedule.java
1
请完成以下Java代码
public void setLastRecalculated (Timestamp LastRecalculated) { set_Value (COLUMNNAME_LastRecalculated, LastRecalculated); } /** Get Last Recalculated. @return The time last recalculated. */ public Timestamp getLastRecalculated () { return (Timestamp)get_Value(COLUMNNAME_LastRecalculated); } /** 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); } /** Set Report Cube. @param PA_ReportCube_ID Define reporting cube for pre-calculation of summary accounting data. */ public void setPA_ReportCube_ID (int PA_ReportCube_ID) { if (PA_ReportCube_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_ReportCube_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_ReportCube_ID, Integer.valueOf(PA_ReportCube_ID)); } /** Get Report Cube. @return Define reporting cube for pre-calculation of summary accounting data. */ public int getPA_ReportCube_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportCube_ID);
if (ii == null) return 0; return ii.intValue(); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_ReportCube.java
1
请完成以下Java代码
public void setLabel (java.lang.String Label) { set_Value (COLUMNNAME_Label, Label); } /** Get Label. @return Label */ @Override public java.lang.String getLabel () { return (java.lang.String)get_Value(COLUMNNAME_Label); } /** Set Label List. @param M_Label_ID Label List */ @Override public void setM_Label_ID (int M_Label_ID) { if (M_Label_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Label_ID, null);
else set_ValueNoCheck (COLUMNNAME_M_Label_ID, Integer.valueOf(M_Label_ID)); } /** Get Label List. @return Label List */ @Override public int getM_Label_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Label_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Label.java
1
请完成以下Java代码
public JsonElement serialize(Color src, Type typeOfSrc, JsonSerializationContext context) { JsonObject jo = new JsonObject(); jo.addProperty(PROPERTY_Classname, src.getClass().getName()); jo.addProperty("r", src.getRed()); jo.addProperty("g", src.getGreen()); jo.addProperty("b", src.getBlue()); jo.addProperty("a", src.getAlpha()); return jo; } @Override public Color deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { final JsonObject jo = json.getAsJsonObject(); final int r = jo.get("r").getAsInt(); final int g = jo.get("g").getAsInt(); final int b = jo.get("b").getAsInt(); final int a = jo.get("a").getAsInt(); return new ColorUIResource(new Color(r, g, b, a)); } } public static class FontJsonSerializer extends UIResourceJsonSerializer<Font> { @Override public JsonElement serialize(Font src, Type typeOfSrc, JsonSerializationContext context) { JsonObject jo = new JsonObject(); jo.addProperty(PROPERTY_Classname, src.getClass().getName()); jo.addProperty("name", src.getName()); jo.addProperty("style", src.getStyle()); jo.addProperty("size", src.getSize()); return jo; } @Override public Font deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { final JsonObject jo = json.getAsJsonObject(); String name = jo.get("name").getAsString(); int style = jo.get("style").getAsInt(); int size = jo.get("size").getAsInt(); return new FontUIResource(name, style, size); } } public static class VEditorDialogButtonAlignJsonSerializer extends UIResourceJsonSerializer<VEditorDialogButtonAlign> { @Override public JsonElement serialize(VEditorDialogButtonAlign src, Type typeOfSrc, JsonSerializationContext context) {
final JsonObject jo = new JsonObject(); jo.addProperty(PROPERTY_Classname, src.getClass().getName()); jo.addProperty("value", src.toString()); return jo; } @Override public VEditorDialogButtonAlign deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { final JsonObject jo = json.getAsJsonObject(); final String value = jo.get("value").getAsString(); try { return VEditorDialogButtonAlign.valueOf(value); } catch (Exception e) { logger.warn("Failed parsing value {}. Using default", value); } return VEditorDialogButtonAlign.DEFAULT_Value; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\UIDefaultsSerializer.java
1