instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public JsonResponseManufacturingOrdersReport report(@NonNull final JsonRequestManufacturingOrdersReport request)
{
final ManufacturingOrderReportProcessCommand command = ManufacturingOrderReportProcessCommand.builder()
.huReservationService(huReservationService)
.auditRepository(orderReportAuditRepo)
.jsonObjectMapper(jsonObjectMapper)
//
.request(request)
//
.build();
return command.execute();
}
@NonNull
public JsonResponseManufacturingOrder retrievePPOrder(@NonNull final PPOrderId ppOrderId)
{
final I_PP_Order ppOrder = ppOrderDAO.getById(ppOrderId);
final ImmutableList<JsonResponseManufacturingOrderBOMLine> bomLinesResponse = retrieveBomLines(ppOrderId);
final MapToJsonResponseManufacturingOrderRequest request = MapToJsonResponseManufacturingOrderRequest
.builder()
.components(bomLinesResponse)
.order(ppOrder) | .ppOrderBOMBL(ppOrderBOMBL)
.orgDAO(orgDAO)
.productRepository(productRepo)
.build();
return JsonConverter.toJson(request);
}
@NonNull
public ImmutableList<JsonResponseManufacturingOrderBOMLine> retrieveBomLines(@NonNull final PPOrderId ppOrderId)
{
return ppOrderBOMDAO.retrieveOrderBOMLines(ppOrderId)
.stream()
.map(bomLine -> JsonConverter.toJson(bomLine, ppOrderBOMBL, productRepo))
.collect(ImmutableList.toImmutableList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\rest_api\v2\ManufacturingOrderAPIService.java | 1 |
请完成以下Java代码 | public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Record ID.
@param Record_ID
Direct internal record ID
*/
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Record ID.
@return Direct internal record ID
*/
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Remote Addr.
@param Remote_Addr
Remote Address
*/
public void setRemote_Addr (String Remote_Addr)
{
set_ValueNoCheck (COLUMNNAME_Remote_Addr, Remote_Addr);
}
/** Get Remote Addr.
@return Remote Address
*/
public String getRemote_Addr ()
{
return (String)get_Value(COLUMNNAME_Remote_Addr);
}
/** Set Remote Host.
@param Remote_Host
Remote host Info
*/
public void setRemote_Host (String Remote_Host)
{
set_ValueNoCheck (COLUMNNAME_Remote_Host, Remote_Host);
}
/** Get Remote Host.
@return Remote host Info | */
public String getRemote_Host ()
{
return (String)get_Value(COLUMNNAME_Remote_Host);
}
/** Set Sales Volume in 1.000.
@param SalesVolume
Total Volume of Sales in Thousands of Currency
*/
public void setSalesVolume (int SalesVolume)
{
set_Value (COLUMNNAME_SalesVolume, Integer.valueOf(SalesVolume));
}
/** Get Sales Volume in 1.000.
@return Total Volume of Sales in Thousands of Currency
*/
public int getSalesVolume ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesVolume);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Start Implementation/Production.
@param StartProductionDate
The day you started the implementation (if implementing) - or production (went life) with Adempiere
*/
public void setStartProductionDate (Timestamp StartProductionDate)
{
set_Value (COLUMNNAME_StartProductionDate, StartProductionDate);
}
/** Get Start Implementation/Production.
@return The day you started the implementation (if implementing) - or production (went life) with Adempiere
*/
public Timestamp getStartProductionDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartProductionDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Registration.java | 1 |
请完成以下Java代码 | private final boolean isNonPackingMaterialShipment(final I_M_InOutLine inoutLine)
{
// make sure the shipment is not null
final I_M_InOut shipment = inoutLine.getM_InOut();
if (shipment == null)
{
return false;
}
// Make sure we are dealing with a shipment (and not with a receipt)
if (!shipment.isSOTrx())
{
return false;
}
// Do nothing if we are dealing with a packing material line
if (inoutLine.isPackagingMaterial())
{
return false;
}
return true;
}
/**
* Task #1306: only updating on QtyEntered, but not on M_HU_PI_Item_Product_ID, because when the HU_PI_Item_Product changes, we want QtyEnteredTU to stay the same.
* Applied only to customer return inout lines.
*
* @param orderLine
* @param field
*/
@CalloutMethod(columnNames = { I_M_InOutLine.COLUMNNAME_QtyEntered })
public void updateQtyTU(final I_M_InOutLine inOutLine, final ICalloutField field)
{
final IHUInOutBL huInOutBL = Services.get(IHUInOutBL.class);
final I_M_InOut inOut = inOutLine.getM_InOut();
// Applied only to customer return inout lines.
if (!huInOutBL.isCustomerReturn(inOut))
{
return;
} | final IHUPackingAware packingAware = new InOutLineHUPackingAware(inOutLine);
Services.get(IHUPackingAwareBL.class).setQtyTU(packingAware);
packingAware.setQty(packingAware.getQty());
}
/**
* Task #1306: If QtyEnteredTU or M_HU_PI_Item_Product_ID change, then update QtyEntered (i.e. the CU qty).
* Applied only to customer return inout lines.
*
* @param inOutLine
* @param field
*/
@CalloutMethod(columnNames = { I_M_InOutLine.COLUMNNAME_QtyEnteredTU, I_M_InOutLine.COLUMNNAME_M_HU_PI_Item_Product_ID })
public void updateQtyCU(final I_M_InOutLine inOutLine, final ICalloutField field)
{
final IHUInOutBL huInOutBL = Services.get(IHUInOutBL.class);
final I_M_InOut inOut = inOutLine.getM_InOut();
// Applied only to customer return inout lines.
if (!huInOutBL.isCustomerReturn(inOut))
{
return;
}
final IHUPackingAware packingAware = new InOutLineHUPackingAware(inOutLine);
final Integer qtyPacks = packingAware.getQtyTU().intValue();
Services.get(IHUPackingAwareBL.class).setQtyCUFromQtyTU(packingAware, qtyPacks);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\callout\M_InOutLine.java | 1 |
请完成以下Java代码 | public <K, V> ImmutableMap<K, V> merge(@NonNull final ImmutableMap<K, V> map, K key, V value, BinaryOperator<V> remappingFunction)
{
if (map.isEmpty())
{
return ImmutableMap.of(key, value);
}
final ImmutableMap.Builder<K, V> mapBuilder = ImmutableMap.builder();
boolean added = false;
boolean changed = false;
for (Map.Entry<K, V> entry : map.entrySet())
{
if (!added && Objects.equals(key, entry.getKey()))
{
final V valueOld = entry.getValue();
final V valueNew = remappingFunction.apply(valueOld, value);
mapBuilder.put(key, valueNew);
added = true;
if (!Objects.equals(valueOld, valueNew))
{
changed = true;
}
}
else
{
mapBuilder.put(entry.getKey(), entry.getValue());
}
}
if (!added)
{
mapBuilder.put(key, value);
changed = true;
} | if (!changed)
{
return map;
}
return mapBuilder.build();
}
public static <T> ImmutableList<T> removeIf(@NonNull ImmutableList<T> list, @NonNull Predicate<T> predicate)
{
if (list.isEmpty()) {return list;}
final ImmutableList<T> result = list.stream()
.filter(item -> !predicate.test(item))
.collect(ImmutableList.toImmutableList());
return list.size() == result.size() ? list : result;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\CollectionUtils.java | 1 |
请完成以下Java代码 | public static AppsAction createAppsAction(final APanel parent, final boolean small)
{
final AProcess app = new AProcess(parent, small);
return app.action;
}
private AProcess(final APanel parent, final boolean small)
{
super();
this.parent = parent;
action = AppsAction.builder()
.setAction(model.getActionName())
.setSmallSize(small)
.build();
action.setDelegate(event -> showPopup());
}
private Properties getCtx()
{
return Env.getCtx();
}
private JPopupMenu getPopupMenu()
{
final Properties ctx = getCtx();
final List<SwingRelatedProcessDescriptor> processes = model.fetchProcesses(ctx, parent.getCurrentTab());
if (processes.isEmpty())
{
return null;
}
final String adLanguage = Env.getAD_Language(ctx);
final JPopupMenu popup = new JPopupMenu("ProcessMenu");
processes.stream()
.map(process -> createProcessMenuItem(process, adLanguage))
.sorted(Comparator.comparing(CMenuItem::getText))
.forEach(mi -> popup.add(mi));
return popup;
}
public void showPopup()
{
final JPopupMenu popup = getPopupMenu();
if (popup == null)
{
return; | }
final AbstractButton button = action.getButton();
if (button.isShowing())
{
popup.show(button, 0, button.getHeight()); // below button
}
}
private CMenuItem createProcessMenuItem(final SwingRelatedProcessDescriptor process, final String adLanguage)
{
final CMenuItem mi = new CMenuItem(process.getCaption(adLanguage));
mi.setIcon(process.getIcon());
mi.setToolTipText(process.getDescription(adLanguage));
if (process.isEnabled())
{
mi.setEnabled(true);
mi.addActionListener(event -> startProcess(process));
}
else
{
mi.setEnabled(false);
mi.setToolTipText(process.getDisabledReason(adLanguage));
}
return mi;
}
private void startProcess(final SwingRelatedProcessDescriptor process)
{
final String adLanguage = Env.getAD_Language(getCtx());
final VButton button = new VButton(
"StartProcess", // columnName,
false, // mandatory,
false, // isReadOnly,
true, // isUpdateable,
process.getCaption(adLanguage),
process.getDescription(adLanguage),
process.getHelp(adLanguage),
process.getAD_Process_ID());
// Invoke action
parent.actionButton(button);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\process\ui\AProcess.java | 1 |
请完成以下Java代码 | private void createMissingProductCategoryAccts(@NonNull final ProductCategoryId productCategoryId)
{
final I_M_Product_Category pc = productDAO.getProductCategoryById(productCategoryId);
InterfaceWrapperHelper.getPO(pc).insert_Accounting(
I_M_Product_Category_Acct.Table_Name,
I_C_AcctSchema_Default.Table_Name,
null // whereClause
);
}
private Optional<I_M_Product_Category_Acct> retrieveProductCategoryAcctRecord(
@NonNull final ProductCategoryId productCategoryId,
@NonNull final AcctSchemaId acctSchemaId
)
{
return queryBL.createQueryBuilderOutOfTrx(I_M_Product_Category_Acct.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_Product_Category_Acct.COLUMNNAME_M_Product_Category_ID, productCategoryId)
.addEqualsFilter(I_M_Product_Category_Acct.COLUMNNAME_C_AcctSchema_ID, acctSchemaId)
.orderBy(I_M_Product_Category_Acct.COLUMNNAME_M_Product_Category_Acct_ID)
.firstOptional();
}
private static ProductCategoryAcct toProductCategoryAcct(@NonNull final I_M_Product_Category_Acct record)
{
return ProductCategoryAcct.builder()
.productCategoryId(ProductCategoryId.ofRepoId(record.getM_Product_Category_ID()))
.acctSchemaId(AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID()))
.costingMethod(CostingMethod.ofNullableCode(record.getCostingMethod()))
.costingLevel(CostingLevel.ofNullableCode(record.getCostingLevel()))
.build();
}
@Value(staticConstructor = "of") | private static class ProductCategoryAcctKey
{
@NonNull ProductCategoryId productCategoryId;
@NonNull AcctSchemaId acctSchemaId;
}
@Value
@Builder
private static class ProductCategoryAcct
{
@NonNull ProductCategoryId productCategoryId;
@NonNull AcctSchemaId acctSchemaId;
@Nullable CostingMethod costingMethod;
@Nullable CostingLevel costingLevel;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\impl\ProductCostingBL.java | 1 |
请完成以下Java代码 | public Money getTaxAmt()
{
updateTaxAmtsIfNeeded();
return _taxAmt;
}
public Money getReverseChargeAmt()
{
updateTaxAmtsIfNeeded();
return _reverseChargeAmt;
}
private void updateTaxAmtsIfNeeded()
{
if (!isTaxCalculated)
{
final CalculateTaxResult result = tax.calculateTax(taxBaseAmt.toBigDecimal(), false, precision.toInt());
this._taxAmt = Money.of(result.getTaxAmount(), taxBaseAmt.getCurrencyId()); | this._reverseChargeAmt = Money.of(result.getReverseChargeAmt(), taxBaseAmt.getCurrencyId());
this.isTaxCalculated = true;
}
}
public void updateDocTax(@NonNull final DocTax docTax)
{
if (!TaxId.equals(tax.getTaxId(), docTax.getTaxId()))
{
throw new AdempiereException("TaxId not matching: " + this + ", " + docTax);
}
docTax.setTaxBaseAmt(getTaxBaseAmt().toBigDecimal());
docTax.setTaxAmt(getTaxAmt().toBigDecimal());
docTax.setReverseChargeTaxAmt(getReverseChargeAmt().toBigDecimal());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocTaxUpdater.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void insert(SuspendedJobEntity jobEntity) {
insert(jobEntity, true);
}
@Override
public void delete(SuspendedJobEntity jobEntity) {
delete(jobEntity, false);
deleteByteArrayRef(jobEntity.getExceptionByteArrayRef());
deleteByteArrayRef(jobEntity.getCustomValuesByteArrayRef());
// Send event
if (getEventDispatcher() != null && getEventDispatcher().isEnabled()) {
getEventDispatcher().dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, jobEntity),
serviceConfiguration.getEngineName());
}
}
@Override
public void delete(SuspendedJobEntity jobEntity, boolean fireDeleteEvent) {
if (serviceConfiguration.getInternalJobManager() != null) {
serviceConfiguration.getInternalJobManager().handleJobDelete(jobEntity);
}
super.delete(jobEntity, fireDeleteEvent);
} | protected SuspendedJobEntity createSuspendedJob(AbstractRuntimeJobEntity job) {
SuspendedJobEntity newSuspendedJobEntity = create();
newSuspendedJobEntity.setJobHandlerConfiguration(job.getJobHandlerConfiguration());
newSuspendedJobEntity.setCustomValues(job.getCustomValues());
newSuspendedJobEntity.setJobHandlerType(job.getJobHandlerType());
newSuspendedJobEntity.setExclusive(job.isExclusive());
newSuspendedJobEntity.setRepeat(job.getRepeat());
newSuspendedJobEntity.setRetries(job.getRetries());
newSuspendedJobEntity.setEndDate(job.getEndDate());
newSuspendedJobEntity.setExecutionId(job.getExecutionId());
newSuspendedJobEntity.setProcessInstanceId(job.getProcessInstanceId());
newSuspendedJobEntity.setProcessDefinitionId(job.getProcessDefinitionId());
newSuspendedJobEntity.setScopeId(job.getScopeId());
newSuspendedJobEntity.setSubScopeId(job.getSubScopeId());
newSuspendedJobEntity.setScopeType(job.getScopeType());
newSuspendedJobEntity.setScopeDefinitionId(job.getScopeDefinitionId());
// Inherit tenant
newSuspendedJobEntity.setTenantId(job.getTenantId());
newSuspendedJobEntity.setJobType(job.getJobType());
return newSuspendedJobEntity;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\SuspendedJobEntityManagerImpl.java | 2 |
请完成以下Java代码 | public class ImpDataCell
{
public static ImpDataCell value(final Object value)
{
final ErrorMessage errorMessage = null;
return new ImpDataCell(value, errorMessage);
}
public static ImpDataCell error(final ErrorMessage errorMessage)
{
final Object value = null;
return new ImpDataCell(value, errorMessage);
}
private final Object value;
private final ErrorMessage errorMessage;
private ImpDataCell(
@Nullable final Object value,
@Nullable ErrorMessage errorMessage)
{
this.value = value;
this.errorMessage = errorMessage;
}
/** @return true if the cell has some errors (i.e. {@link #getCellErrorMessage()} is not null) */ | public boolean isCellError()
{
return errorMessage != null;
}
/** @return cell error message or null */
public ErrorMessage getCellErrorMessage()
{
return errorMessage;
}
public final Object getJdbcValue()
{
return value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\parser\ImpDataCell.java | 1 |
请完成以下Java代码 | public void setAuthenticated(boolean authenticated) {
Assert.isTrue(!authenticated, "Cannot set this token to trusted");
super.setAuthenticated(authenticated);
}
@Override
public @Nullable Object getCredentials() {
return null;
}
@Override
public PublicKeyCredentialUserEntity getPrincipal() {
return this.principal;
}
@Override
public String getName() {
return this.principal.getName();
}
@Override
public Builder<?> toBuilder() {
return new Builder<>(this);
}
/**
* A builder of {@link WebAuthnAuthentication} instances
*
* @since 7.0
*/
public static final class Builder<B extends Builder<B>> extends AbstractAuthenticationBuilder<B> {
private PublicKeyCredentialUserEntity principal;
private Builder(WebAuthnAuthentication token) {
super(token);
this.principal = token.principal;
} | /**
* Use this principal. It must be of type {@link PublicKeyCredentialUserEntity}
* @param principal the principal to use
* @return the {@link Builder} for further configurations
*/
@Override
public B principal(@Nullable Object principal) {
Assert.isInstanceOf(PublicKeyCredentialUserEntity.class, principal,
"principal must be of type PublicKeyCredentialUserEntity");
this.principal = (PublicKeyCredentialUserEntity) principal;
return (B) this;
}
@Override
public WebAuthnAuthentication build() {
return new WebAuthnAuthentication(this);
}
}
} | repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\authentication\WebAuthnAuthentication.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal getTimePeriod() {
return timePeriod;
}
public void setTimePeriod(BigDecimal timePeriod) {
this.timePeriod = timePeriod;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InsuranceContractMaxPermanentPrescriptionPeriod insuranceContractMaxPermanentPrescriptionPeriod = (InsuranceContractMaxPermanentPrescriptionPeriod) o;
return Objects.equals(this.amount, insuranceContractMaxPermanentPrescriptionPeriod.amount) &&
Objects.equals(this.timePeriod, insuranceContractMaxPermanentPrescriptionPeriod.timePeriod);
}
@Override
public int hashCode() {
return Objects.hash(amount, timePeriod);
}
@Override
public String toString() { | StringBuilder sb = new StringBuilder();
sb.append("class InsuranceContractMaxPermanentPrescriptionPeriod {\n");
sb.append(" amount: ").append(toIndentedString(amount)).append("\n");
sb.append(" timePeriod: ").append(toIndentedString(timePeriod)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\InsuranceContractMaxPermanentPrescriptionPeriod.java | 2 |
请完成以下Java代码 | protected ImportRecordResult importRecord(@NonNull final IMutable<Object> state,
@NonNull final I_I_ElementValue importRecord,
final boolean isInsertOnly)
{
final ChartOfAccountsId chartOfAccountsId = chartOfAccountsImportHelper.importChartOfAccounts(importRecord);
final ElementValueId existingElementValueId = ElementValueId.ofRepoIdOrNull(importRecord.getC_ElementValue_ID());
if (existingElementValueId != null && isInsertOnly)
{
return ImportRecordResult.Nothing;
}
final ElementValue elementValue = elementValueService.createOrUpdate(
ElementValueCreateOrUpdateRequest.builder()
.existingElementValueId(existingElementValueId)
.orgId(chartOfAccountsImportHelper.extractOrgId(importRecord))
.chartOfAccountsId(chartOfAccountsId)
.value(Check.assumeNotNull(importRecord.getValue(), "Value shall be set"))
.name(Check.assumeNotNull(importRecord.getName(), "Name shall be set"))
.accountSign(Check.assumeNotNull(importRecord.getAccountSign(), "AccountSign shall be set"))
.accountType(Check.assumeNotNull(importRecord.getAccountType(), "AccountType shall be set"))
.isSummary(importRecord.isSummary())
.isDocControlled(importRecord.isDocControlled())
.isPostActual(importRecord.isPostActual())
.isPostBudget(importRecord.isPostBudget())
.isPostStatistical(importRecord.isPostStatistical())
.parentId(getParentElementValueId(importRecord))
.defaultAccountName(importRecord.getDefault_Account())
.build()
);
importRecord.setC_ElementValue_ID(elementValue.getId().getRepoId());
importRecord.setParentElementValue_ID(ElementValueId.toRepoId(elementValue.getParentId()));
InterfaceWrapperHelper.save(importRecord);
affectedChartOfAccountsIds.add(chartOfAccountsId);
return existingElementValueId == null ? ImportRecordResult.Inserted : ImportRecordResult.Updated;
}
@Nullable
private ElementValueId getParentElementValueId(final @NonNull I_I_ElementValue importRecord)
{
final ElementValueId parentId = ElementValueId.ofRepoIdOrNull(importRecord.getParentElementValue_ID());
if (parentId != null)
{ | return parentId;
}
final ChartOfAccountsId chartOfAccountsId = ChartOfAccountsId.ofRepoId(importRecord.getC_Element_ID());
final String parentAccountNo = StringUtils.trimBlankToNull(importRecord.getParentValue());
if (parentAccountNo != null)
{
return elementValueService.getByAccountNo(parentAccountNo, chartOfAccountsId)
.map(ElementValue::getId)
.orElseThrow(() -> new AdempiereException("No parent account found for `" + parentAccountNo + "` and " + chartOfAccountsId));
}
else
{
return null;
}
}
@Override
protected void afterImport()
{
affectedChartOfAccountsIds.forEach(elementValueService::reorderByAccountNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\impexp\AccountImportProcess.java | 1 |
请完成以下Java代码 | default List<String> getTokenIntrospectionEndpointAuthenticationMethods() {
return getClaimAsStringList(
OAuth2AuthorizationServerMetadataClaimNames.INTROSPECTION_ENDPOINT_AUTH_METHODS_SUPPORTED);
}
/**
* Returns the {@code URL} of the OAuth 2.0 Dynamic Client Registration Endpoint
* {@code (registration_endpoint)}.
* @return the {@code URL} of the OAuth 2.0 Dynamic Client Registration Endpoint
*/
default URL getClientRegistrationEndpoint() {
return getClaimAsURL(OAuth2AuthorizationServerMetadataClaimNames.REGISTRATION_ENDPOINT);
}
/**
* Returns the Proof Key for Code Exchange (PKCE) {@code code_challenge_method} values
* supported {@code (code_challenge_methods_supported)}.
* @return the {@code code_challenge_method} values supported
*/
default List<String> getCodeChallengeMethods() {
return getClaimAsStringList(OAuth2AuthorizationServerMetadataClaimNames.CODE_CHALLENGE_METHODS_SUPPORTED);
}
/** | * Returns {@code true} to indicate support for mutual-TLS client certificate-bound
* access tokens {@code (tls_client_certificate_bound_access_tokens)}.
* @return {@code true} to indicate support for mutual-TLS client certificate-bound
* access tokens, {@code false} otherwise
*/
default boolean isTlsClientCertificateBoundAccessTokens() {
return Boolean.TRUE.equals(getClaimAsBoolean(
OAuth2AuthorizationServerMetadataClaimNames.TLS_CLIENT_CERTIFICATE_BOUND_ACCESS_TOKENS));
}
/**
* Returns the {@link JwsAlgorithms JSON Web Signature (JWS) algorithms} supported for
* DPoP Proof JWTs {@code (dpop_signing_alg_values_supported)}.
* @return the {@link JwsAlgorithms JSON Web Signature (JWS) algorithms} supported for
* DPoP Proof JWTs
*/
default List<String> getDPoPSigningAlgorithms() {
return getClaimAsStringList(OAuth2AuthorizationServerMetadataClaimNames.DPOP_SIGNING_ALG_VALUES_SUPPORTED);
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\OAuth2AuthorizationServerMetadataClaimAccessor.java | 1 |
请完成以下Spring Boot application配置 | security:
oauth2:
client:
client-id: app-a
client-secret: app-a-1234
user-authorization-uri: http://127.0.0.1:8080/server/oauth/authorize
access-token-uri: http://127.0.0.1:8080/server/oauth/token
resource:
jwt:
| key-uri: http://127.0.0.1:8080/server/oauth/token_key
server:
port: 9090
servlet:
context-path: /app1 | repos\SpringAll-master\66.Spring-Security-OAuth2-SSO\sso-application-one\src\main\resources\application.yml | 2 |
请在Spring Boot框架中完成以下Java代码 | BatchLoaderRegistry batchLoaderRegistry() {
return new DefaultBatchLoaderRegistry();
}
@Bean
@ConditionalOnMissingBean
ExecutionGraphQlService executionGraphQlService(GraphQlSource graphQlSource,
BatchLoaderRegistry batchLoaderRegistry) {
DefaultExecutionGraphQlService service = new DefaultExecutionGraphQlService(graphQlSource);
service.addDataLoaderRegistrar(batchLoaderRegistry);
return service;
}
@Bean
@ConditionalOnMissingBean
AnnotatedControllerConfigurer annotatedControllerConfigurer(
@Qualifier(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME) ObjectProvider<Executor> executorProvider,
ObjectProvider<HandlerMethodArgumentResolver> argumentResolvers) {
AnnotatedControllerConfigurer controllerConfigurer = new AnnotatedControllerConfigurer();
controllerConfigurer
.configureBinder((options) -> options.conversionService(ApplicationConversionService.getSharedInstance()));
executorProvider.ifAvailable(controllerConfigurer::setExecutor);
argumentResolvers.orderedStream().forEach(controllerConfigurer::addCustomArgumentResolver);
return controllerConfigurer;
}
@Bean
DataFetcherExceptionResolver annotatedControllerConfigurerDataFetcherExceptionResolver(
AnnotatedControllerConfigurer annotatedControllerConfigurer) {
return annotatedControllerConfigurer.getExceptionResolver();
}
@ConditionalOnClass(ScrollPosition.class)
@Configuration(proxyBeanMethods = false)
static class GraphQlDataAutoConfiguration {
@Bean
@ConditionalOnMissingBean
EncodingCursorStrategy<ScrollPosition> cursorStrategy() {
return CursorStrategy.withEncoder(new ScrollPositionCursorStrategy(), CursorEncoder.base64());
} | @Bean
@SuppressWarnings("unchecked")
GraphQlSourceBuilderCustomizer cursorStrategyCustomizer(CursorStrategy<?> cursorStrategy) {
if (cursorStrategy.supports(ScrollPosition.class)) {
CursorStrategy<ScrollPosition> scrollCursorStrategy = (CursorStrategy<ScrollPosition>) cursorStrategy;
ConnectionFieldTypeVisitor connectionFieldTypeVisitor = ConnectionFieldTypeVisitor
.create(List.of(new WindowConnectionAdapter(scrollCursorStrategy),
new SliceConnectionAdapter(scrollCursorStrategy)));
return (builder) -> builder.typeVisitors(List.of(connectionFieldTypeVisitor));
}
return (builder) -> {
};
}
}
static class GraphQlResourcesRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.resources().registerPattern("graphql/**/*.graphqls").registerPattern("graphql/**/*.gqls");
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-graphql\src\main\java\org\springframework\boot\graphql\autoconfigure\GraphQlAutoConfiguration.java | 2 |
请完成以下Java代码 | public int getRemindDays ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_RemindDays);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Request Processor.
@param R_RequestProcessor_ID
Processor for Requests
*/
public void setR_RequestProcessor_ID (int R_RequestProcessor_ID)
{
if (R_RequestProcessor_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_RequestProcessor_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_RequestProcessor_ID, Integer.valueOf(R_RequestProcessor_ID));
}
/** Get Request Processor.
@return Processor for Requests
*/
public int getR_RequestProcessor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestProcessor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_R_RequestType getR_RequestType() throws RuntimeException
{
return (I_R_RequestType)MTable.get(getCtx(), I_R_RequestType.Table_Name)
.getPO(getR_RequestType_ID(), get_TrxName()); }
/** Set Request Type.
@param R_RequestType_ID
Type of request (e.g. Inquiry, Complaint, ..)
*/
public void setR_RequestType_ID (int R_RequestType_ID)
{
if (R_RequestType_ID < 1)
set_Value (COLUMNNAME_R_RequestType_ID, null);
else
set_Value (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID));
}
/** Get Request Type.
@return Type of request (e.g. Inquiry, Complaint, ..)
*/
public int getR_RequestType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID);
if (ii == null)
return 0;
return ii.intValue();
} | public I_AD_User getSupervisor() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getSupervisor_ID(), get_TrxName()); }
/** Set Supervisor.
@param Supervisor_ID
Supervisor for this user/organization - used for escalation and approval
*/
public void setSupervisor_ID (int Supervisor_ID)
{
if (Supervisor_ID < 1)
set_Value (COLUMNNAME_Supervisor_ID, null);
else
set_Value (COLUMNNAME_Supervisor_ID, Integer.valueOf(Supervisor_ID));
}
/** Get Supervisor.
@return Supervisor for this user/organization - used for escalation and approval
*/
public int getSupervisor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Supervisor_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_R_RequestProcessor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public HttpTracing httpTracing(Tracing tracing) {
return HttpTracing.create(tracing);
}
/**
* Creates server spans for http requests
*/
@Bean
public Filter tracingFilter(HttpTracing httpTracing) {
return TracingFilter.create(httpTracing);
}
// ==================== SpringMVC 相关 ====================
// @see SpringMvcConfiguration 类上的,@Import(SpanCustomizingAsyncHandlerInterceptor.class) | // ==================== Redis 相关 ====================
@Bean
public RedisConnectionFactory redisConnectionFactory(Tracer tracer, RedisProperties redisProperties) {
// 创建 JedisConnectionFactory 对象
RedisConnectionFactory connectionFactory = new JedisConnectionFactory();
// 创建 TracingConfiguration 对象
TracingConfiguration tracingConfiguration = new TracingConfiguration.Builder(tracer)
// 设置拓展 Tag ,设置 Redis 服务器地址。因为默认情况下,不会在操作 Redis 链路的 Span 上记录 Redis 服务器的地址,所以这里需要设置。
.extensionTag("Server Address", redisProperties.getHost() + ":" + redisProperties.getPort())
.build();
// 创建 TracingRedisConnectionFactory 对象
return new TracingRedisConnectionFactory(connectionFactory, tracingConfiguration);
}
} | repos\SpringBoot-Labs-master\lab-40\lab-40-redis\src\main\java\cn\iocoder\springboot\lab40\zipkindemo\config\ZipkinConfiguration.java | 2 |
请完成以下Java代码 | public void staleTabs(@NonNull final Collection<DetailId> tabIds)
{
tabIds.stream().map(this::getIncludedTabInfo).forEach(JSONIncludedTabInfo::markAllRowsStaled);
}
public void staleIncludedRows(@NonNull final DetailId tabId, @NonNull final DocumentIdsSelection rowIds)
{
getIncludedTabInfo(tabId).staleRows(rowIds);
}
void mergeFrom(@NonNull final JSONDocumentChangedWebSocketEvent from)
{
if (!Objects.equals(windowId, from.windowId)
|| !Objects.equals(id, from.id))
{
throw new AdempiereException("Cannot merge events because they are not matching")
.setParameter("from", from)
.setParameter("to", this)
.appendParametersToMessage(); | }
if (from.stale != null && from.stale)
{
stale = from.stale;
}
from.getIncludedTabsInfo().values().forEach(this::addIncludedTabInfo);
if (from.activeTabStaled != null && from.activeTabStaled)
{
activeTabStaled = from.activeTabStaled;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\events\JSONDocumentChangedWebSocketEvent.java | 1 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
else if (context.isMoreThanOneSelected())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
else
{
final I_C_PaySelection paySelection = paySelectionDAO.getById(PaySelectionId.ofRepoId(context.getSingleSelectedRecordId()))
.orElseThrow(() -> AdempiereException.newWithPlainMessage("No paySelection found for selected record")
.appendParametersToMessage()
.setParameter("recordId", context.getSingleSelectedRecordId()));
if(!DocStatus.ofNullableCodeOrUnknown(paySelection.getDocStatus()).isCompletedOrClosed())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("C_PaySelection_ID=" + paySelection.getC_PaySelection_ID() + " needs to be completed or closed");
}
if (!paySelection.getPaySelectionTrxType().equals(X_C_PaySelection.PAYSELECTIONTRXTYPE_CreditTransfer))
{
return ProcessPreconditionsResolution.rejectWithInternalReason(msgBL.getTranslatableMsgText(REVOLUT_AVAILABLE_ONLY_FOR_CREDIT_TRANSFER_ERROR));
}
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
final RevolutExportService revolutExportService = SpringContextHolder.instance.getBean(RevolutExportService.class);
final PaySelectionService paySelectionService = SpringContextHolder.instance.getBean(PaySelectionService.class);
final I_C_PaySelection paySelection = paySelectionDAO.getById(PaySelectionId.ofRepoId(getRecord_ID()))
.orElseThrow(() -> new AdempiereException("No paySelection found for selected record") | .appendParametersToMessage()
.setParameter("recordId", getRecord_ID()));
final List<RevolutPaymentExport> revolutPaymentExportList = paySelectionService.computeRevolutPaymentExportList(paySelection);
final List<RevolutPaymentExport> savedRevolutPaymentExportList = revolutExportService.saveAll(revolutPaymentExportList);
final PaySelectionId paySelectionId = PaySelectionId.ofRepoId(paySelection.getC_PaySelection_ID());
final ReportResultData reportResultData = revolutExportService.exportToCsv(paySelectionId, savedRevolutPaymentExportList);
paySelection.setLastRevolutExport(Timestamp.from(Instant.now()));
paySelection.setLastRevolutExportBy_ID(getAD_User_ID());
paySelectionDAO.save(paySelection);
getProcessInfo().getResult().setReportData(reportResultData);
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.revolut\src\main\java\de\metas\payment\revolut\process\C_PaySelection_RevolutPayment_CSVExport.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonResponseCreditLimitType
{
public static final String METASFRESH_ID = "metasfreshId";
public static final String NAME = "name";
public static final String SEQNO = "seqNo";
public static final String AUTOAPPROVAL = "autoApproval";
@ApiModelProperty( //
required = true, //
dataType = "java.lang.Integer", //
value = "This translates to `C_CreditLimit_Type.C_CreditLimit_Type_ID`.")
@JsonProperty(METASFRESH_ID)
@JsonInclude(JsonInclude.Include.NON_NULL)
JsonMetasfreshId metasfreshId;
@ApiModelProperty(value = "This translates to `C_CreditLimit_Type.Name`.")
@JsonProperty(NAME)
String name;
@ApiModelProperty(value = "This translates to `C_CreditLimit_Type.IsAutoApproval`.") | @JsonProperty(AUTOAPPROVAL)
boolean autoApproval;
@JsonCreator
@Builder(toBuilder = true)
private JsonResponseCreditLimitType(
@JsonProperty(METASFRESH_ID) @NonNull final JsonMetasfreshId metasfreshId,
@JsonProperty(NAME) @NonNull final String name,
@JsonProperty(AUTOAPPROVAL) final boolean autoApproval)
{
this.metasfreshId = metasfreshId;
this.name = name;
this.autoApproval = autoApproval;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\response\JsonResponseCreditLimitType.java | 2 |
请完成以下Java代码 | public void setSubject (java.lang.String Subject)
{
set_Value (COLUMNNAME_Subject, Subject);
}
/** Get Betreff.
@return Mail Betreff
*/
@Override
public java.lang.String getSubject ()
{
return (java.lang.String)get_Value(COLUMNNAME_Subject);
}
@Override
public org.compiere.model.I_AD_User getTo_User() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_To_User_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setTo_User(org.compiere.model.I_AD_User To_User)
{
set_ValueFromPO(COLUMNNAME_To_User_ID, org.compiere.model.I_AD_User.class, To_User);
}
/** Set To User.
@param To_User_ID To User */
@Override | public void setTo_User_ID (int To_User_ID)
{
if (To_User_ID < 1)
set_Value (COLUMNNAME_To_User_ID, null);
else
set_Value (COLUMNNAME_To_User_ID, Integer.valueOf(To_User_ID));
}
/** Get To User.
@return To User */
@Override
public int getTo_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_To_User_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_Mail.java | 1 |
请完成以下Java代码 | public class LuhnChecker {
private static final Logger LOGGER = LoggerFactory.getLogger(LuhnChecker.class);
/*
* Starting from the rightmost digit, we add all the digits together, performing
* a special step for every second digit.
*
* If the result is not divisible by 10, then the card number must not be valid.
*
* We can form a number that passes the Luhn Check by subtracting the result of
* the Luhn algorithm from 10.
*
* This is how the final digit of a credit card is calculated.
*/
public static boolean checkLuhn(String cardNumber) {
int sum = 0;
try {
for (int i = cardNumber.length() - 1; i >= 0; i--) {
int digit = Integer.parseInt(cardNumber.substring(i, i + 1));
if ((cardNumber.length() - i) % 2 == 0) {
digit = doubleAndSumDigits(digit);
}
sum += digit;
}
LOGGER.info("Luhn Algorithm sum of digits is " + sum);
} catch (NumberFormatException e) {
LOGGER.error("NumberFormatException - Card number probably contained some non-numeric characters, returning false");
return false;
} catch (NullPointerException e) {
LOGGER.error("Null pointer - Card number was probably null, returning false");
return false; | }
boolean result = sum % 10 == 0;
LOGGER.info("Luhn check result (sum divisible by 10): " + result);
return result;
}
/*
* We apply this method to every second number from the right of the card
* number. First, we double the digit, then we sum the digits.
*
* Note: subtracting 9 is equivalent to doubling and summing digits (when
* starting with a single digit) 0-4 -> produce single digit when doubled
* 5*2 = 10 -> 1+0 = 1 = 10-9
* 6*2 = 12 -> 1+3 = 3 = 12-9
* 7*2 = 14 -> 1+5 = 5 = 14-9
* 8*2 = 16 -> 1+7 = 7 = 16-9
* 9*2 = 18 -> 1+9 = 9 = 18-9
*/
public static int doubleAndSumDigits(int digit) {
int ret = digit * 2;
if (ret > 9) {
ret -= 9;
}
return ret;
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-7\src\main\java\com\baeldung\algorithms\luhn\LuhnChecker.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static EdgeEvent createFilteredEdgeEvent(EdgeEvent edgeEvent, JsonNode filteredBody) {
EdgeEvent filtered = new EdgeEvent();
filtered.setSeqId(edgeEvent.getSeqId());
filtered.setTenantId(edgeEvent.getTenantId());
filtered.setEdgeId(edgeEvent.getEdgeId());
filtered.setAction(edgeEvent.getAction());
filtered.setEntityId(edgeEvent.getEntityId());
filtered.setUid(edgeEvent.getUid());
filtered.setType(edgeEvent.getType());
filtered.setBody(filteredBody);
return filtered;
}
private static List<EdgeEvent> removeDownlinkDuplicates(List<EdgeEvent> edgeEvents) {
Set<EventKey> seen = new HashSet<>();
return edgeEvents.stream()
.filter(e -> seen.add(new EventKey(
e.getTenantId(),
e.getAction(), | e.getEntityId(),
e.getType().name(),
(e.getBody() != null ? e.getBody().toString() : "null"))))
.collect(Collectors.toList());
}
private record EventKey(TenantId tenantId,
EdgeEventActionType action,
UUID entityId,
String type,
String body) {
}
private record AttrsTs(long ts, List<AttributeKvEntry> attrs) {
}
private record AttrUpdateMsg(UUID entityId, JsonNode body) {
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edge\EdgeMsgConstructorUtils.java | 2 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setAD_User_ID (final int AD_User_ID)
{
if (AD_User_ID < 0)
set_Value (COLUMNNAME_AD_User_ID, null);
else
set_Value (COLUMNNAME_AD_User_ID, AD_User_ID);
}
@Override
public int getAD_User_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_ID);
}
@Override
public org.compiere.model.I_C_Workplace getC_Workplace()
{
return get_ValueAsPO(COLUMNNAME_C_Workplace_ID, org.compiere.model.I_C_Workplace.class);
}
@Override
public void setC_Workplace(final org.compiere.model.I_C_Workplace C_Workplace)
{
set_ValueFromPO(COLUMNNAME_C_Workplace_ID, org.compiere.model.I_C_Workplace.class, C_Workplace);
}
@Override
public void setC_Workplace_ID (final int C_Workplace_ID)
{
if (C_Workplace_ID < 1)
set_Value (COLUMNNAME_C_Workplace_ID, null);
else
set_Value (COLUMNNAME_C_Workplace_ID, C_Workplace_ID);
} | @Override
public int getC_Workplace_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Workplace_ID);
}
@Override
public void setC_Workplace_User_Assign_ID (final int C_Workplace_User_Assign_ID)
{
if (C_Workplace_User_Assign_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Workplace_User_Assign_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Workplace_User_Assign_ID, C_Workplace_User_Assign_ID);
}
@Override
public int getC_Workplace_User_Assign_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Workplace_User_Assign_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Workplace_User_Assign.java | 1 |
请完成以下Java代码 | public void setTextValue(String textValue) {
this.textValue = textValue;
}
public String getTextValue2() {
return textValue2;
}
public void setTextValue2(String textValue2) {
this.textValue2 = textValue2;
}
public Long getLongValue() {
return longValue;
}
public void setLongValue(Long longValue) {
this.longValue = longValue;
}
public Double getDoubleValue() {
return doubleValue;
}
public void setDoubleValue(Double doubleValue) {
this.doubleValue = doubleValue;
} | public byte[] getByteArrayValue() {
return null;
}
public void setByteArrayValue(byte[] bytes) {
}
public String getType() {
return type;
}
public boolean getFindNulledEmptyStrings() {
return findNulledEmptyStrings;
}
public void setFindNulledEmptyStrings(boolean findNulledEmptyStrings) {
this.findNulledEmptyStrings = findNulledEmptyStrings;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\SingleQueryVariableValueCondition.java | 1 |
请完成以下Java代码 | public static void deleteFile(String groupName, String remoteFileName)
throws Exception {
StorageClient storageClient = getStorageClient();
int i = storageClient.delete_file(groupName, remoteFileName);
logger.info("delete file successfully!!!" + i);
}
public static StorageServer[] getStoreStorages(String groupName)
throws IOException {
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
return trackerClient.getStoreStorages(trackerServer, groupName);
}
public static ServerInfo[] getFetchStorages(String groupName,
String remoteFileName) throws IOException {
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
} | public static String getTrackerUrl() throws IOException {
return "http://"+getTrackerServer().getInetSocketAddress().getHostString()+":"+ClientGlobal.getG_tracker_http_port()+"/";
}
private static StorageClient getStorageClient() throws IOException {
TrackerServer trackerServer = getTrackerServer();
StorageClient storageClient = new StorageClient(trackerServer, null);
return storageClient;
}
private static TrackerServer getTrackerServer() throws IOException {
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
return trackerServer;
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 2-7 课:使用 Spring Boot 上传文件到 FastDFS\spring-boot-fastDFS\src\main\java\com\neo\fastdfs\FastDFSClient.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getTypeName() {
return TYPE_NAME;
}
@Override
public boolean isCachable() {
return true;
}
@Override
public boolean isAbleToStore(Object value) {
if (value instanceof Collection) {
return EMPTY_LIST_CLASS.isInstance(value) || EMPTY_SET_CLASS.isInstance(value);
}
return false;
}
@Override
public void setValue(Object value, ValueFields valueFields) { | if (EMPTY_LIST_CLASS.isInstance(value)) {
valueFields.setTextValue("list");
} else {
valueFields.setTextValue("set");
}
}
@Override
public Object getValue(ValueFields valueFields) {
String value = valueFields.getTextValue();
if (LIST.equals(value)) {
return Collections.emptyList();
} else if (SET.equals(value)) {
return Collections.emptySet();
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\EmptyCollectionType.java | 2 |
请完成以下Java代码 | public int getFrequency(String from, String to)
{
return getFrequency(convert(from), convert(to));
}
/**
* 获取转移频次
*
* @param from
* @param to
* @return
*/
public int getFrequency(E from, E to)
{
return matrix[from.ordinal()][to.ordinal()];
}
/**
* 获取e的总频次
*
* @param e
* @return
*/
public int getTotalFrequency(E e)
{
return total[e.ordinal()];
}
/**
* 获取所有标签的总频次
* | * @return
*/
public int getTotalFrequency()
{
return totalFrequency;
}
protected E convert(String label)
{
return Enum.valueOf(enumType, label);
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder("TransformMatrixDictionary{");
sb.append("enumType=").append(enumType);
sb.append(", ordinaryMax=").append(ordinaryMax);
sb.append(", matrix=").append(Arrays.toString(matrix));
sb.append(", total=").append(Arrays.toString(total));
sb.append(", totalFrequency=").append(totalFrequency);
sb.append('}');
return sb.toString();
}
@Override
public int ordinal(String tag)
{
return Enum.valueOf(enumType, tag).ordinal();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\TransformMatrixDictionary.java | 1 |
请完成以下Java代码 | public File createPDF(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
@Override
public String completeIt(final DocumentTableFields docFields)
{
final I_M_Forecast forecast = extractForecast(docFields);
forecast.setDocAction(IDocument.ACTION_None);
return IDocument.STATUS_Completed;
}
@Override
public void approveIt(final DocumentTableFields docFields)
{
}
@Override
public void rejectIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
@Override
public void voidIt(final DocumentTableFields docFields)
{
final I_M_Forecast forecast = extractForecast(docFields);
final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(forecast.getDocStatus());
if (docStatus.isClosedReversedOrVoided())
{
throw new AdempiereException("Document Closed: " + docStatus);
}
getLines(forecast).forEach(this::voidLine);
forecast.setProcessed(true);
forecast.setDocAction(IDocument.ACTION_None);
}
@Override
public void unCloseIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
@Override
public void reverseCorrectIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
} | @Override
public void reverseAccrualIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
@Override
public void reactivateIt(final DocumentTableFields docFields)
{
final I_M_Forecast forecast = extractForecast(docFields);
forecast.setProcessed(false);
forecast.setDocAction(IDocument.ACTION_Complete);
}
@Override
public LocalDate getDocumentDate(@NonNull final DocumentTableFields docFields)
{
final I_M_Forecast forecast = extractForecast(docFields);
return TimeUtil.asLocalDate(forecast.getDatePromised());
}
private void voidLine(@NonNull final I_M_ForecastLine line)
{
line.setQty(BigDecimal.ZERO);
line.setQtyCalculated(BigDecimal.ZERO);
InterfaceWrapperHelper.save(line);
}
private List<I_M_ForecastLine> getLines(@NonNull final I_M_Forecast forecast)
{
return forecastDAO.retrieveLinesByForecastId(ForecastId.ofRepoId(forecast.getM_Forecast_ID()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\mforecast\ForecastDocumentHandler.java | 1 |
请完成以下Java代码 | public static boolean setAttribute(String word, String natureWithFrequency)
{
CoreDictionary.Attribute attribute = CoreDictionary.Attribute.create(natureWithFrequency);
return setAttribute(word, attribute);
}
/**
* 将字符串词性转为Enum词性
* @param name 词性名称
* @param customNatureCollector 一个收集集合
* @return 转换结果
*/
public static Nature convertStringToNature(String name, LinkedHashSet<Nature> customNatureCollector)
{
Nature nature = Nature.fromString(name);
if (nature == null)
{
nature = Nature.create(name); | if (customNatureCollector != null) customNatureCollector.add(nature);
}
return nature;
}
/**
* 将字符串词性转为Enum词性
* @param name 词性名称
* @return 转换结果
*/
public static Nature convertStringToNature(String name)
{
return convertStringToNature(name, null);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\utility\LexiconUtility.java | 1 |
请完成以下Java代码 | public void setObjectIdentityPrimaryKeyQuery(String selectObjectIdentityPrimaryKey) {
this.selectObjectIdentityPrimaryKey = selectObjectIdentityPrimaryKey;
}
public void setSidPrimaryKeyQuery(String selectSidPrimaryKey) {
this.selectSidPrimaryKey = selectSidPrimaryKey;
}
public void setUpdateObjectIdentity(String updateObjectIdentity) {
this.updateObjectIdentity = updateObjectIdentity;
}
/**
* @param foreignKeysInDatabase if false this class will perform additional FK
* constrain checking, which may cause deadlocks (the default is true, so deadlocks
* are avoided but the database is expected to enforce FKs)
*/
public void setForeignKeysInDatabase(boolean foreignKeysInDatabase) {
this.foreignKeysInDatabase = foreignKeysInDatabase;
}
@Override
public void setAclClassIdSupported(boolean aclClassIdSupported) {
super.setAclClassIdSupported(aclClassIdSupported);
if (aclClassIdSupported) {
// Change the default insert if it hasn't been overridden
if (this.insertClass.equals(DEFAULT_INSERT_INTO_ACL_CLASS)) { | this.insertClass = DEFAULT_INSERT_INTO_ACL_CLASS_WITH_ID;
}
else {
log.debug("Insert class statement has already been overridden, so not overridding the default");
}
}
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
} | repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\jdbc\JdbcMutableAclService.java | 1 |
请完成以下Java代码 | private BPartner createBiller(@NonNull final I_C_Invoice invoiceRecord)
{
final IBPartnerOrgBL bpartnerOrgBL = Services.get(IBPartnerOrgBL.class);
final I_C_BPartner orgBPartner = bpartnerOrgBL.retrieveLinkedBPartner(invoiceRecord.getAD_Org_ID());
Check.assumeNotNull(orgBPartner, InvoiceToExportFactoryException.class,
"The given invoice's org needs to have a linked bPartner; AD_Org_ID={}; invoiceRecord={};", invoiceRecord.getAD_Org_ID(), invoiceRecord);
final IBPartnerDAO bPartnerDAO = Services.get(IBPartnerDAO.class);
final BPartnerLocationQuery query = BPartnerLocationQuery
.builder()
.type(Type.REMIT_TO)
.bpartnerId(de.metas.bpartner.BPartnerId.ofRepoId(orgBPartner.getC_BPartner_ID()))
.build();
final I_C_BPartner_Location remittoLocation = bPartnerDAO.retrieveBPartnerLocation(query);
final GLN gln;
if (remittoLocation == null)
{
logger.debug("The given invoice's orgBPartner has no remit-to location; -> unable to set a biller GLN; orgBPartner={}; invoiceRecord={}",
orgBPartner, invoiceRecord);
gln = null;
}
else if (Check.isBlank(remittoLocation.getGLN()))
{
logger.debug("The given invoice's orgBPartner's remit-to location has no GLN; -> unable to set a biller GLN; orgBPartner={}; invoiceRecord={}; remittoLocation={}", | orgBPartner, invoiceRecord, remittoLocation);
gln = null;
}
else
{
gln = GLN.of(remittoLocation.getGLN());
}
final BPartner biller = BPartner.builder()
.id(BPartnerId.ofRepoId(orgBPartner.getC_BPartner_ID()))
.gln(gln).build();
return biller;
}
public static final class InvoiceToExportFactoryException extends AdempiereException implements ExceptionWithOwnHeaderMessage
{
private static final long serialVersionUID = 5678496542883367180L;
public InvoiceToExportFactoryException(@NonNull final String msg)
{
super(msg);
this.markAsUserValidationError(); // propagate error to the user
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\export\InvoiceToExportFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RouteExampleController {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(RouteExampleController.class);
@GetRoute("/route-example")
public String get() {
return "get.html";
}
@PostRoute("/route-example")
public String post() {
return "post.html";
}
@PutRoute("/route-example")
public String put() {
return "put.html";
}
@DeleteRoute("/route-example")
public String delete() {
return "delete.html";
}
@Route(value = "/another-route-example", method = HttpMethod.GET)
public String anotherGet() {
return "get.html";
}
@Route(value = "/allmatch-route-example")
public String allmatch() {
return "allmatch.html";
} | @Route(value = "/triggerInternalServerError")
public void triggerInternalServerError() {
int x = 1 / 0;
}
@Route(value = "/triggerBaeldungException")
public void triggerBaeldungException() throws BaeldungException {
throw new BaeldungException("Foobar Exception to threat differently");
}
@Route(value = "/user/foo")
public void urlCoveredByNarrowedWebhook(Response response) {
response.text("Check out for the WebHook covering '/user/*' in the logs");
}
@GetRoute("/load-configuration-in-a-route")
public void loadConfigurationInARoute(Response response) {
String authors = WebContext.blade()
.env("app.authors", "Unknown authors");
log.info("[/load-configuration-in-a-route] Loading 'app.authors' from configuration, value: " + authors);
response.render("index.html");
}
@GetRoute("/template-output-test")
public void templateOutputTest(Request request, Response response) {
request.attribute("name", "Blade");
response.render("template-output-test.html");
}
} | repos\tutorials-master\web-modules\blade\src\main\java\com\baeldung\blade\sample\RouteExampleController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | class VisitController {
private final OwnerRepository owners;
public VisitController(OwnerRepository owners) {
this.owners = owners;
}
@InitBinder
public void setAllowedFields(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields("id");
}
/**
* Called before each and every @RequestMapping annotated method. 2 goals: - Make sure
* we always have fresh data - Since we do not use the session scope, make sure that
* Pet object always has an id (Even though id is not part of the form fields)
* @param petId
* @return Pet
*/
@ModelAttribute("visit")
public Visit loadPetWithVisit(@PathVariable("ownerId") int ownerId, @PathVariable("petId") int petId,
Map<String, Object> model) {
Optional<Owner> optionalOwner = owners.findById(ownerId);
Owner owner = optionalOwner.orElseThrow(() -> new IllegalArgumentException(
"Owner not found with id: " + ownerId + ". Please ensure the ID is correct "));
Pet pet = owner.getPet(petId);
if (pet == null) {
throw new IllegalArgumentException(
"Pet with id " + petId + " not found for owner with id " + ownerId + ".");
}
model.put("pet", pet);
model.put("owner", owner);
Visit visit = new Visit();
pet.addVisit(visit);
return visit;
}
// Spring MVC calls method loadPetWithVisit(...) before initNewVisitForm is
// called | @GetMapping("/owners/{ownerId}/pets/{petId}/visits/new")
public String initNewVisitForm() {
return "pets/createOrUpdateVisitForm";
}
// Spring MVC calls method loadPetWithVisit(...) before processNewVisitForm is
// called
@PostMapping("/owners/{ownerId}/pets/{petId}/visits/new")
public String processNewVisitForm(@ModelAttribute Owner owner, @PathVariable int petId, @Valid Visit visit,
BindingResult result, RedirectAttributes redirectAttributes) {
if (result.hasErrors()) {
return "pets/createOrUpdateVisitForm";
}
owner.addVisit(petId, visit);
this.owners.save(owner);
redirectAttributes.addFlashAttribute("message", "Your visit has been booked");
return "redirect:/owners/{ownerId}";
}
} | repos\spring-petclinic-main\src\main\java\org\springframework\samples\petclinic\owner\VisitController.java | 2 |
请完成以下Java代码 | public String toString() {
if (isProcessInstanceExecution()) {
return "ProcessInstance["+getToStringIdentity()+"]";
} else {
return (isEventScope? "EventScope":"")+(isConcurrent? "Concurrent" : "")+(isScope() ? "Scope" : "")+"Execution["+getToStringIdentity()+"]";
}
}
protected String getToStringIdentity() {
return Integer.toString(System.identityHashCode(this));
}
// allow for subclasses to expose a real id /////////////////////////////////
public String getId() {
return String.valueOf(System.identityHashCode(this));
}
// getters and setters //////////////////////////////////////////////////////
protected VariableStore<CoreVariableInstance> getVariableStore() {
return variableStore;
}
@Override
protected VariableInstanceFactory<CoreVariableInstance> getVariableInstanceFactory() {
return (VariableInstanceFactory) SimpleVariableInstanceFactory.INSTANCE;
}
@Override
protected List<VariableInstanceLifecycleListener<CoreVariableInstance>> getVariableInstanceLifecycleListeners() {
return Collections.emptyList();
}
public ExecutionImpl getReplacedBy() {
return (ExecutionImpl) replacedBy;
}
public void setExecutions(List<ExecutionImpl> executions) {
this.executions = executions;
}
public String getCurrentActivityName() {
String currentActivityName = null; | if (this.activity != null) {
currentActivityName = (String) activity.getProperty("name");
}
return currentActivityName;
}
public FlowElement getBpmnModelElementInstance() {
throw new UnsupportedOperationException(BpmnModelExecutionContext.class.getName() +" is unsupported in transient ExecutionImpl");
}
public BpmnModelInstance getBpmnModelInstance() {
throw new UnsupportedOperationException(BpmnModelExecutionContext.class.getName() +" is unsupported in transient ExecutionImpl");
}
public ProcessEngineServices getProcessEngineServices() {
throw new UnsupportedOperationException(ProcessEngineServicesAware.class.getName() +" is unsupported in transient ExecutionImpl");
}
public ProcessEngine getProcessEngine() {
throw new UnsupportedOperationException(ProcessEngineServicesAware.class.getName() +" is unsupported in transient ExecutionImpl");
}
public void forceUpdate() {
// nothing to do
}
public void fireHistoricProcessStartEvent() {
// do nothing
}
protected void removeVariablesLocalInternal(){
// do nothing
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\ExecutionImpl.java | 1 |
请完成以下Java代码 | public Quantity setScale(final UOMPrecision newScale, @NonNull final RoundingMode roundingMode)
{
final BigDecimal newQty = qty.setScale(newScale.toInt(), roundingMode);
return new Quantity(
newQty,
uom,
sourceQty != null ? sourceQty.setScale(newScale.toInt(), roundingMode) : newQty,
sourceUom != null ? sourceUom : uom);
}
public int intValueExact()
{
return toBigDecimal().intValueExact();
}
public boolean isWeightable()
{
return UOMType.ofNullableCodeOrOther(uom.getUOMType()).isWeight();
}
public Percent percentageOf(@NonNull final Quantity whole)
{
assertSameUOM(this, whole);
return Percent.of(toBigDecimal(), whole.toBigDecimal());
}
private void assertUOMOrSourceUOM(@NonNull final UomId uomId)
{
if (!getUomId().equals(uomId) && !getSourceUomId().equals(uomId))
{
throw new QuantitiesUOMNotMatchingExpection("UOMs are not compatible")
.appendParametersToMessage()
.setParameter("Qty.UOM", getUomId())
.setParameter("assertUOM", uomId);
}
}
@NonNull
public BigDecimal toBigDecimalAssumingUOM(@NonNull final UomId uomId)
{
assertUOMOrSourceUOM(uomId);
return getUomId().equals(uomId) ? toBigDecimal() : getSourceQty();
}
public List<Quantity> spreadEqually(final int count)
{ | if (count <= 0)
{
throw new AdempiereException("count shall be greater than zero, but it was " + count);
}
else if (count == 1)
{
return ImmutableList.of(this);
}
else // count > 1
{
final ImmutableList.Builder<Quantity> result = ImmutableList.builder();
final Quantity qtyPerPart = divide(count);
Quantity qtyRemainingToSpread = this;
for (int i = 1; i <= count; i++)
{
final boolean isLast = i == count;
if (isLast)
{
result.add(qtyRemainingToSpread);
}
else
{
result.add(qtyPerPart);
qtyRemainingToSpread = qtyRemainingToSpread.subtract(qtyPerPart);
}
}
return result.build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\Quantity.java | 1 |
请完成以下Java代码 | static Letter createLetter(String salutation, String body) {
return new Letter(salutation, body);
}
static BiFunction<String, String, Letter> SIMPLE_LETTER_CREATOR = //
(salutation, body) -> new Letter(salutation, body);
static Function<String, Function<String, Letter>> SIMPLE_CURRIED_LETTER_CREATOR = //
saluation -> body -> new Letter(saluation, body);
static Function<String, Function<String, Function<LocalDate, Function<String, Function<String, Function<String, Letter>>>>>> LETTER_CREATOR = //
returnAddress
-> closing
-> dateOfLetter
-> insideAddress
-> salutation
-> body
-> new Letter(returnAddress, insideAddress, dateOfLetter, salutation, body, closing);
static AddReturnAddress builder() {
return returnAddress
-> closing
-> dateOfLetter
-> insideAddress
-> salutation
-> body
-> new Letter(returnAddress, insideAddress, dateOfLetter, salutation, body, closing); | }
interface AddReturnAddress {
Letter.AddClosing withReturnAddress(String returnAddress);
}
interface AddClosing {
Letter.AddDateOfLetter withClosing(String closing);
}
interface AddDateOfLetter {
Letter.AddInsideAddress withDateOfLetter(LocalDate dateOfLetter);
}
interface AddInsideAddress {
Letter.AddSalutation withInsideAddress(String insideAddress);
}
interface AddSalutation {
Letter.AddBody withSalutation(String salutation);
}
interface AddBody {
Letter withBody(String body);
}
} | repos\tutorials-master\patterns-modules\design-patterns-functional\src\main\java\com\baeldung\currying\Letter.java | 1 |
请完成以下Java代码 | private JsonQuantity toJsonQuantity(@NonNull final Quantity qty)
{
return JsonQuantity.builder()
.qty(qty.toBigDecimal())
.uomCode(qty.getX12DE355().getCode())
.build();
}
private static ManufacturingOrderExportAuditItem createExportedAuditItem(@NonNull final I_PP_Order order)
{
return ManufacturingOrderExportAuditItem.builder()
.orderId(PPOrderId.ofRepoId(order.getPP_Order_ID()))
.orgId(OrgId.ofRepoIdOrAny(order.getAD_Org_ID()))
.exportStatus(APIExportStatus.Exported)
.build();
}
private static ManufacturingOrderExportAuditItem createExportErrorAuditItem(final I_PP_Order order, final AdIssueId adIssueId)
{
return ManufacturingOrderExportAuditItem.builder()
.orderId(PPOrderId.ofRepoId(order.getPP_Order_ID()))
.orgId(OrgId.ofRepoIdOrAny(order.getAD_Org_ID()))
.exportStatus(APIExportStatus.ExportError)
.issueId(adIssueId)
.build();
}
private AdIssueId createAdIssueId(final Throwable ex)
{
return errorManager.createIssue(IssueCreateRequest.builder()
.throwable(ex)
.loggerName(logger.getName())
.sourceClassname(ManufacturingOrderAPIService.class.getName())
.summary(ex.getMessage())
.build());
}
private List<I_PP_Order_BOMLine> getBOMLinesByOrderId(final PPOrderId orderId)
{
return getBOMLinesByOrderId().get(orderId);
}
private ImmutableListMultimap<PPOrderId, I_PP_Order_BOMLine> getBOMLinesByOrderId()
{
if (_bomLinesByOrderId != null)
{
return _bomLinesByOrderId;
}
final ImmutableSet<PPOrderId> orderIds = getOrders() | .stream()
.map(order -> PPOrderId.ofRepoId(order.getPP_Order_ID()))
.collect(ImmutableSet.toImmutableSet());
_bomLinesByOrderId = ppOrderBOMDAO.retrieveOrderBOMLines(orderIds, I_PP_Order_BOMLine.class)
.stream()
.collect(ImmutableListMultimap.toImmutableListMultimap(
bomLine -> PPOrderId.ofRepoId(bomLine.getPP_Order_ID()),
bomLine -> bomLine));
return _bomLinesByOrderId;
}
private Product getProductById(@NonNull final ProductId productId)
{
if (_productsById == null)
{
final HashSet<ProductId> allProductIds = new HashSet<>();
allProductIds.add(productId);
getOrders().stream()
.map(order -> ProductId.ofRepoId(order.getM_Product_ID()))
.forEach(allProductIds::add);
getBOMLinesByOrderId()
.values()
.stream()
.map(bomLine -> ProductId.ofRepoId(bomLine.getM_Product_ID()))
.forEach(allProductIds::add);
_productsById = productRepo.getByIds(allProductIds)
.stream()
.collect(GuavaCollectors.toHashMapByKey(Product::getId));
}
return _productsById.computeIfAbsent(productId, productRepo::getById);
}
private List<I_PP_Order> getOrders()
{
if (_orders == null)
{
_orders = ppOrderDAO.retrieveManufacturingOrders(query);
}
return _orders;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\rest_api\v1\ManufacturingOrdersExportCommand.java | 1 |
请完成以下Java代码 | public ExecutionEntity getExecutionEntity() {
return executionEntity;
}
@Override
public VariableMap getVariables() {
return variables;
}
@Override
public String getProcessDefinitionId() {
return executionEntity.getProcessDefinitionId();
}
@Override
public String getBusinessKey() {
return executionEntity.getBusinessKey();
}
@Override
public String getCaseInstanceId() {
return executionEntity.getCaseInstanceId();
}
@Override
public boolean isSuspended() {
return executionEntity.isSuspended();
}
@Override
public String getId() {
return executionEntity.getId();
}
@Override
public String getRootProcessInstanceId() {
return executionEntity.getRootProcessInstanceId();
}
@Override | public boolean isEnded() {
return executionEntity.isEnded();
}
@Override
public String getProcessInstanceId() {
return executionEntity.getProcessInstanceId();
}
@Override
public String getTenantId() {
return executionEntity.getTenantId();
}
@Override
public String getProcessDefinitionKey() {
return executionEntity.getProcessDefinitionKey();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ProcessInstanceWithVariablesImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ColorValue
{
public static final ColorValue RED = new ColorValue("#FF0000");
public static final ColorValue GREEN = new ColorValue("#00FF00");
public static ColorValue ofRGB(final int red, final int green, final int blue)
{
return ofHexString(toHexString(red, green, blue));
}
@JsonCreator
public static ColorValue ofHexString(final String hexString)
{
return interner.intern(new ColorValue(hexString));
}
private static Interner<ColorValue> interner = Interners.newStrongInterner();
static
{
interner.intern(RED);
interner.intern(GREEN);
}
String hexString;
private ColorValue(final String hexString)
{
this.hexString = normalizeHexString(hexString);
}
private static String normalizeHexString(@NonNull final String hexString) | {
try
{
final int i = Integer.decode(hexString);
final int red = i >> 16 & 0xFF;
final int green = i >> 8 & 0xFF;
final int blue = i & 0xFF;
return toHexString(red, green, blue);
}
catch (final Exception ex)
{
throw new AdempiereException("Invalid color hex string: " + hexString, ex);
}
}
public static String toHexString(final int red, final int green, final int blue)
{
return MFColor.toHexString(red, green, blue);
}
@JsonValue
public String toJson()
{
return hexString;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\ColorValue.java | 2 |
请完成以下Java代码 | public ResponseEntity<JsonPurchaseCandidateResponse> createCandidates(@RequestBody final JsonPurchaseCandidateCreateRequest request)
{
return ResponseEntity.ok(trxManager.call(ITrx.TRXNAME_ThreadInherited, () -> createCandidates0(request)));
}
private JsonPurchaseCandidateResponse createCandidates0(@RequestBody final JsonPurchaseCandidateCreateRequest request)
{
final ImmutableList<JsonPurchaseCandidate> candidates = request.getPurchaseCandidates()
.stream()
.map(createPurchaseCandidatesService::createCandidate)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(ImmutableList.toImmutableList());
return JsonPurchaseCandidateResponse.builder()
.purchaseCandidates(candidates)
.build(); | }
@ApiOperation("Enqueues purchase candidates for creation of purchase orders")
@PostMapping(path = "/enqueueForOrdering", consumes = "application/json", produces = "application/json")
public ResponseEntity<String> enqueue(@RequestBody @NonNull final JsonPurchaseCandidatesRequest request)
{
enqueuePurchaseCandidateService.enqueue(request);
return new ResponseEntity<>(HttpStatus.ACCEPTED);
}
@PutMapping(value = "/status", consumes = "application/json", produces = "application/json")
public JsonPurchaseCandidateResponse status(@RequestBody final JsonPurchaseCandidatesRequest request)
{
return purchaseCandidatesStatusService.getStatusForPurchaseCandidates(request);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\order\PurchaseCandidateRestController.java | 1 |
请完成以下Java代码 | public int getM_MovementLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_MovementLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** 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;
}
/** Set Scrapped Quantity.
@param ScrappedQty
The Quantity scrapped due to QA issues
*/
public void setScrappedQty (BigDecimal ScrappedQty)
{
set_Value (COLUMNNAME_ScrappedQty, ScrappedQty); | }
/** Get Scrapped Quantity.
@return The Quantity scrapped due to QA issues
*/
public BigDecimal getScrappedQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Target Quantity.
@param TargetQty
Target Movement Quantity
*/
public void setTargetQty (BigDecimal TargetQty)
{
set_Value (COLUMNNAME_TargetQty, TargetQty);
}
/** Get Target Quantity.
@return Target Movement Quantity
*/
public BigDecimal getTargetQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TargetQty);
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_M_MovementLineConfirm.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void configureDecisionRequirementsDefinitionQuery(DecisionRequirementsDefinitionQueryImpl query) {
getAuthorizationManager().configureDecisionRequirementsDefinitionQuery(query);
getTenantManager().configureQuery(query);
}
@Override
public DecisionRequirementsDefinitionEntity findLatestDefinitionByKey(String key) {
return null;
}
@Override
public DecisionRequirementsDefinitionEntity findLatestDefinitionById(String id) {
return getDbEntityManager().selectById(DecisionRequirementsDefinitionEntity.class, id);
}
@Override
public DecisionRequirementsDefinitionEntity findLatestDefinitionByKeyAndTenantId(String definitionKey, String tenantId) {
return null;
}
@Override
public DecisionRequirementsDefinitionEntity findDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId) {
return null;
} | @Override
public DecisionRequirementsDefinitionEntity findDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId) {
return null;
}
@Override
public DecisionRequirementsDefinitionEntity findDefinitionByDeploymentAndKey(String deploymentId, String definitionKey) {
return null;
}
@Override
public DecisionRequirementsDefinitionEntity getCachedResourceDefinitionEntity(String definitionId) {
return getDbEntityManager().getCachedEntity(DecisionRequirementsDefinitionEntity.class, definitionId);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\entity\repository\DecisionRequirementsDefinitionManager.java | 2 |
请完成以下Java代码 | public void setLeichMehl_PluFile_ConfigGroup_ID (final int LeichMehl_PluFile_ConfigGroup_ID)
{
if (LeichMehl_PluFile_ConfigGroup_ID < 1)
set_Value (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, null);
else
set_Value (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, LeichMehl_PluFile_ConfigGroup_ID);
}
@Override
public int getLeichMehl_PluFile_ConfigGroup_ID()
{
return get_ValueAsInt(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override | public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setPLU_File (final String PLU_File)
{
set_Value (COLUMNNAME_PLU_File, PLU_File);
}
@Override
public String getPLU_File()
{
return get_ValueAsString(COLUMNNAME_PLU_File);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_LeichMehl_ProductMapping.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
AnnotationAttributes attributes = AnnotationAttributes
.fromMap(metadata.getAnnotationAttributes(ConditionalOnJndi.class.getName()));
Assert.state(attributes != null, "'attributes' must not be null");
String[] locations = attributes.getStringArray("value");
try {
return getMatchOutcome(locations);
}
catch (NoClassDefFoundError ex) {
return ConditionOutcome
.noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class).because("JNDI class not found"));
}
}
private ConditionOutcome getMatchOutcome(String[] locations) {
if (!isJndiAvailable()) {
return ConditionOutcome
.noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class).notAvailable("JNDI environment"));
}
if (locations.length == 0) {
return ConditionOutcome
.match(ConditionMessage.forCondition(ConditionalOnJndi.class).available("JNDI environment"));
}
JndiLocator locator = getJndiLocator(locations);
String location = locator.lookupFirstLocation();
String details = "(" + StringUtils.arrayToCommaDelimitedString(locations) + ")";
if (location != null) {
return ConditionOutcome.match(ConditionMessage.forCondition(ConditionalOnJndi.class, details)
.foundExactly("\"" + location + "\""));
}
return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class, details)
.didNotFind("any matching JNDI location")
.atAll()); | }
protected boolean isJndiAvailable() {
return JndiLocatorDelegate.isDefaultJndiEnvironmentAvailable();
}
protected JndiLocator getJndiLocator(String[] locations) {
return new JndiLocator(locations);
}
protected static class JndiLocator extends JndiLocatorSupport {
private final String[] locations;
public JndiLocator(String[] locations) {
this.locations = locations;
}
public @Nullable String lookupFirstLocation() {
for (String location : this.locations) {
try {
lookup(location);
return location;
}
catch (NamingException ex) {
// Swallow and continue
}
}
return null;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\condition\OnJndiCondition.java | 2 |
请完成以下Java代码 | public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getRemote_Addr());
}
/** Set Remote Host.
@param Remote_Host
Remote host Info
*/
public void setRemote_Host (String Remote_Host)
{
set_Value (COLUMNNAME_Remote_Host, Remote_Host);
}
/** Get Remote Host.
@return Remote host Info
*/
public String getRemote_Host ()
{
return (String)get_Value(COLUMNNAME_Remote_Host);
}
/** Set User Agent.
@param UserAgent
Browser Used
*/
public void setUserAgent (String UserAgent)
{
set_Value (COLUMNNAME_UserAgent, UserAgent);
}
/** Get User Agent.
@return Browser Used
*/
public String getUserAgent ()
{
return (String)get_Value(COLUMNNAME_UserAgent);
}
public I_W_CounterCount getW_CounterCount() throws RuntimeException
{
return (I_W_CounterCount)MTable.get(getCtx(), I_W_CounterCount.Table_Name)
.getPO(getW_CounterCount_ID(), get_TrxName()); }
/** Set Counter Count.
@param W_CounterCount_ID
Web Counter Count Management
*/
public void setW_CounterCount_ID (int W_CounterCount_ID)
{
if (W_CounterCount_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, Integer.valueOf(W_CounterCount_ID));
}
/** Get Counter Count.
@return Web Counter Count Management
*/
public int getW_CounterCount_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_CounterCount_ID); | if (ii == null)
return 0;
return ii.intValue();
}
/** Set Web Counter.
@param W_Counter_ID
Individual Count hit
*/
public void setW_Counter_ID (int W_Counter_ID)
{
if (W_Counter_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_Counter_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_Counter_ID, Integer.valueOf(W_Counter_ID));
}
/** Get Web Counter.
@return Individual Count hit
*/
public int getW_Counter_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_Counter_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_W_Counter.java | 1 |
请完成以下Java代码 | private void addConnection(Connection connection) {
synchronized (this.connections) {
this.connections.add(connection);
}
}
private void removeConnection(Connection connection) {
synchronized (this.connections) {
this.connections.remove(connection);
}
}
/**
* Factory method used to create the {@link Connection}.
* @param socket the source socket
* @param inputStream the socket input stream
* @param outputStream the socket output stream
* @return a connection
* @throws IOException in case of I/O errors
*/
protected Connection createConnection(Socket socket, InputStream inputStream, OutputStream outputStream)
throws IOException {
return new Connection(socket, inputStream, outputStream);
}
/**
* {@link Runnable} to handle a single connection.
*
* @see Connection
*/
private class ConnectionHandler implements Runnable {
private final Socket socket;
private final InputStream inputStream;
ConnectionHandler(Socket socket) throws IOException {
this.socket = socket;
this.inputStream = socket.getInputStream();
}
@Override
public void run() {
try {
handle();
}
catch (ConnectionClosedException ex) {
logger.debug("LiveReload connection closed");
}
catch (Exception ex) {
if (logger.isDebugEnabled()) {
logger.debug("LiveReload error", ex); | }
}
}
private void handle() throws Exception {
try {
try (OutputStream outputStream = this.socket.getOutputStream()) {
Connection connection = createConnection(this.socket, this.inputStream, outputStream);
runConnection(connection);
}
finally {
this.inputStream.close();
}
}
finally {
this.socket.close();
}
}
private void runConnection(Connection connection) throws Exception {
try {
addConnection(connection);
connection.run();
}
finally {
removeConnection(connection);
}
}
}
/**
* {@link ThreadFactory} to create the worker threads.
*/
private static final class WorkerThreadFactory implements ThreadFactory {
private final AtomicInteger threadNumber = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
thread.setName("Live Reload #" + this.threadNumber.getAndIncrement());
return thread;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\livereload\LiveReloadServer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public long addStock(String key, Long expire, int num) {
boolean hasKey = redisTemplate.hasKey(key);
// 判断key是否存在,存在就直接更新
if (hasKey) {
return redisTemplate.opsForValue().increment(key, num);
}
Assert.notNull(expire,"初始化库存失败,库存过期时间不能为null");
RedisLock redisLock = new RedisLock(redisTemplate, key);
try {
if (redisLock.tryLock()) {
// 获取到锁后再次判断一下是否有key
hasKey = redisTemplate.hasKey(key);
if (!hasKey) {
// 初始化库存
redisTemplate.opsForValue().set(key, num, expire, TimeUnit.SECONDS);
}
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
redisLock.unlock();
}
return num;
}
/**
* 获取库存
*
* @param key 库存key
* @return -1:不限库存; 大于等于0:剩余库存
*/
public int getStock(String key) {
Integer stock = (Integer) redisTemplate.opsForValue().get(key);
return stock == null ? -1 : stock;
}
/**
* 扣库存
*
* @param key 库存key
* @param num 扣减库存数量
* @return 扣减之后剩余的库存【-3:库存未初始化; -2:库存不足; -1:不限库存; 大于等于0:扣减库存之后的剩余库存】
*/
private Long stock(String key, int num) {
// 脚本里的KEYS参数
List<String> keys = new ArrayList<>(); | keys.add(key);
// 脚本里的ARGV参数
List<String> args = new ArrayList<>();
args.add(Integer.toString(num));
long result = redisTemplate.execute(new RedisCallback<Long>() {
@Override
public Long doInRedis(RedisConnection connection) throws DataAccessException {
Object nativeConnection = connection.getNativeConnection();
// 集群模式和单机模式虽然执行脚本的方法一样,但是没有共同的接口,所以只能分开执行
// 集群模式
if (nativeConnection instanceof JedisCluster) {
return (Long) ((JedisCluster) nativeConnection).eval(STOCK_LUA, keys, args);
}
// 单机模式
else if (nativeConnection instanceof Jedis) {
return (Long) ((Jedis) nativeConnection).eval(STOCK_LUA, keys, args);
}
return UNINITIALIZED_STOCK;
}
});
return result;
}
} | repos\spring-boot-student-master\spring-boot-student-stock-redis\src\main\java\com\xiaolyuh\service\StockService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getFileType()
{
return fileType;
}
public void setFileType(String fileType)
{
this.fileType = fileType;
}
public FileInfo name(String name)
{
this.name = name;
return this;
}
/**
* The seller-provided name of the evidence file.
*
* @return name
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The seller-provided name of the evidence file.")
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public FileInfo uploadedDate(String uploadedDate)
{
this.uploadedDate = uploadedDate;
return this;
}
/**
* The timestamp in this field shows the date/time when the seller uploaded the evidential document to eBay. The timestamps returned here use the ISO-8601 24-hour date and time format, and the time zone used is Universal Coordinated Time (UTC), also known as Greenwich Mean Time (GMT), or Zulu. The ISO-8601 format looks like this: yyyy-MM-ddThh:mm.ss.sssZ. An example would be
* 2019-08-04T19:09:02.768Z.
*
* @return uploadedDate
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The timestamp in this field shows the date/time when the seller uploaded the evidential document to eBay. The timestamps returned here use the ISO-8601 24-hour date and time format, and the time zone used is Universal Coordinated Time (UTC), also known as Greenwich Mean Time (GMT), or Zulu. The ISO-8601 format looks like this: yyyy-MM-ddThh:mm.ss.sssZ. An example would be 2019-08-04T19:09:02.768Z.")
public String getUploadedDate()
{
return uploadedDate;
}
public void setUploadedDate(String uploadedDate)
{
this.uploadedDate = uploadedDate;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
FileInfo fileInfo = (FileInfo)o;
return Objects.equals(this.fileId, fileInfo.fileId) && | Objects.equals(this.fileType, fileInfo.fileType) &&
Objects.equals(this.name, fileInfo.name) &&
Objects.equals(this.uploadedDate, fileInfo.uploadedDate);
}
@Override
public int hashCode()
{
return Objects.hash(fileId, fileType, name, uploadedDate);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class FileInfo {\n");
sb.append(" fileId: ").append(toIndentedString(fileId)).append("\n");
sb.append(" fileType: ").append(toIndentedString(fileType)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" uploadedDate: ").append(toIndentedString(uploadedDate)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\FileInfo.java | 2 |
请完成以下Java代码 | public int getUpdatedBy() {
return po.getUpdatedBy(); // getUpdatedBy
}
/**************************************************************************
* Update Value or create new record.
* To reload call load() - not updated
* @return true if saved
*/
public boolean save() {
return po.save(); // save
}
/**
* Update Value or create new record.
* To reload call load() - not updated
* @param trxName transaction
* @return true if saved
*/
public boolean save(String trxName) {
return po.save(trxName); // save
}
/**
* Is there a Change to be saved?
* @return true if record changed
*/
public boolean is_Changed() {
return po.is_Changed(); // is_Change
}
/**
* Create Single/Multi Key Where Clause
* @param withValues if true uses actual values otherwise ?
* @return where clause
*/
public String get_WhereClause(boolean withValues) {
return po.get_WhereClause(withValues); // getWhereClause
}
/**************************************************************************
* Delete Current Record
* @param force delete also processed records
* @return true if deleted
*/
public boolean delete(boolean force) {
return po.delete(force); // delete
}
/**
* Delete Current Record
* @param force delete also processed records
* @param trxName transaction
*/ | public boolean delete(boolean force, String trxName) {
return po.delete(force, trxName); // delete
}
/**************************************************************************
* Lock it.
* @return true if locked
*/
public boolean lock() {
return po.lock(); // lock
}
/**
* UnLock it
* @return true if unlocked (false only if unlock fails)
*/
public boolean unlock(String trxName) {
return po.unlock(trxName); // unlock
}
/**
* Set Trx
* @param trxName transaction
*/
public void set_TrxName(String trxName) {
po.set_TrxName(trxName); // setTrx
}
/**
* Get Trx
* @return transaction
*/
public String get_TrxName() {
return po.get_TrxName(); // getTrx
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\wrapper\AbstractPOWrapper.java | 1 |
请完成以下Java代码 | public boolean hasParameters()
{
return true;
}
@Override
public Set<String> getDependsOnFieldNames()
{
return CtxNames.toNames(parameters);
}
@Override
public boolean isNumericKey()
{
return false;
}
@Override
public LookupDataSourceFetcher getLookupDataSourceFetcher()
{
return this;
}
@Override
public LookupDataSourceContext.Builder newContextForFetchingById(final Object id)
{
return LookupDataSourceContext.builder(tableName)
.putFilterById(IdsToFilter.ofSingleValue(id));
}
@Override
public LookupValue retrieveLookupValueById(final @NonNull LookupDataSourceContext evalCtx)
{
final Object id = evalCtx.getSingleIdToFilterAsObject();
if (id == null)
{
throw new IllegalStateException("No ID provided in " + evalCtx);
}
return labelsValuesLookupDataSource.findById(id);
}
@Override
public LookupDataSourceContext.Builder newContextForFetchingList()
{
return LookupDataSourceContext.builder(tableName)
.setRequiredParameters(parameters)
.requiresAD_Language()
.requiresUserRolePermissionsKey();
}
@Override
public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx) | {
final String filter = evalCtx.getFilter();
return labelsValuesLookupDataSource.findEntities(evalCtx, filter);
}
public Set<Object> normalizeStringIds(final Set<String> stringIds)
{
if (stringIds.isEmpty())
{
return ImmutableSet.of();
}
if (isLabelsValuesUseNumericKey())
{
return stringIds.stream()
.map(LabelsLookup::convertToInt)
.collect(ImmutableSet.toImmutableSet());
}
else
{
return ImmutableSet.copyOf(stringIds);
}
}
private static int convertToInt(final String stringId)
{
try
{
return Integer.parseInt(stringId);
}
catch (final Exception ex)
{
throw new AdempiereException("Failed converting `" + stringId + "` to int.", ex);
}
}
public ColumnSql getSqlForFetchingValueIdsByLinkId(@NonNull final String tableNameOrAlias)
{
final String sql = "SELECT array_agg(" + labelsValueColumnName + ")"
+ " FROM " + labelsTableName
+ " WHERE " + labelsLinkColumnName + "=" + tableNameOrAlias + "." + linkColumnName
+ " AND IsActive='Y'";
return ColumnSql.ofSql(sql, tableNameOrAlias);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\LabelsLookup.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setNetdate(XMLGregorianCalendar value) {
this.netdate = value;
}
/**
* Gets the value of the netDays property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getNetDays() {
return netDays;
}
/**
* Sets the value of the netDays property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setNetDays(BigInteger value) {
this.netDays = value;
}
/**
* Gets the value of the singlevat property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getSinglevat() {
return singlevat;
}
/**
* Sets the value of the singlevat property.
*
* @param value
* allowed object is
* {@link BigDecimal } | *
*/
public void setSinglevat(BigDecimal value) {
this.singlevat = value;
}
/**
* Gets the value of the taxfree property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTaxfree() {
return taxfree;
}
/**
* Sets the value of the taxfree property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTaxfree(String value) {
this.taxfree = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctop120VType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class BPartnerAlbertaId implements RepoIdAware
{
@JsonCreator
public static BPartnerAlbertaId ofRepoId(final int repoId)
{
return new BPartnerAlbertaId(repoId);
}
@Nullable
public static BPartnerAlbertaId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new BPartnerAlbertaId(repoId) : null;
}
public static int toRepoId(@Nullable final BPartnerAlbertaId bPartnerAlbertaId)
{
return bPartnerAlbertaId != null ? bPartnerAlbertaId.getRepoId() : -1;
} | int repoId;
private BPartnerAlbertaId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_BPartner_Alberta_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java\de\metas\vertical\healthcare\alberta\bpartner\albertabpartner\BPartnerAlbertaId.java | 2 |
请完成以下Java代码 | private static List<TransportProtos.KeyValueProto> validateKeyValueProtos(List<TransportProtos.KeyValueProto> kvList) {
kvList.forEach(keyValueProto -> {
String key = keyValueProto.getKey();
if (StringUtils.isEmpty(key)) {
throw new IllegalArgumentException("Invalid key value: " + key + "!");
}
TransportProtos.KeyValueType type = keyValueProto.getType();
switch (type) {
case BOOLEAN_V:
case LONG_V:
case DOUBLE_V:
break;
case STRING_V:
if (StringUtils.isEmpty(keyValueProto.getStringV())) {
throw new IllegalArgumentException("Value is empty for key: " + key + "!");
}
break;
case JSON_V:
try {
JsonParser.parseString(keyValueProto.getJsonV());
} catch (Exception e) {
throw new IllegalArgumentException("Can't parse value: " + keyValueProto.getJsonV() + " for key: " + key + "!");
}
break;
case UNRECOGNIZED:
throw new IllegalArgumentException("Unsupported keyValueType: " + type + "!");
}
});
return kvList;
} | public static byte[] convertToRpcRequest(TransportProtos.ToDeviceRpcRequestMsg toDeviceRpcRequestMsg, DynamicMessage.Builder rpcRequestDynamicMessageBuilder) throws AdaptorException {
rpcRequestDynamicMessageBuilder = rpcRequestDynamicMessageBuilder.getDefaultInstanceForType().newBuilderForType();
JsonObject rpcRequestJson = new JsonObject();
rpcRequestJson.addProperty("method", toDeviceRpcRequestMsg.getMethodName());
rpcRequestJson.addProperty("requestId", toDeviceRpcRequestMsg.getRequestId());
String params = toDeviceRpcRequestMsg.getParams();
try {
JsonElement paramsElement = JsonParser.parseString(params);
rpcRequestJson.add("params", paramsElement);
DynamicMessage dynamicRpcRequest = DynamicProtoUtils.jsonToDynamicMessage(rpcRequestDynamicMessageBuilder, GSON.toJson(rpcRequestJson));
return dynamicRpcRequest.toByteArray();
} catch (Exception e) {
throw new AdaptorException("Failed to convert ToDeviceRpcRequestMsg to Dynamic Rpc request message due to: ", e);
}
}
public static Descriptors.Descriptor validateDescriptor(Descriptors.Descriptor descriptor) throws AdaptorException {
if (descriptor == null) {
throw new AdaptorException("Failed to get dynamic message descriptor!");
}
return descriptor;
}
public static String dynamicMsgToJson(byte[] bytes, Descriptors.Descriptor descriptor) throws InvalidProtocolBufferException {
return DynamicProtoUtils.dynamicMsgToJson(descriptor, bytes);
}
} | repos\thingsboard-master\common\proto\src\main\java\org\thingsboard\server\common\adaptor\ProtoConverter.java | 1 |
请完成以下Java代码 | public class MiddleOfArray {
int[] middleOfArray(int[] array) {
if (ObjectUtils.isEmpty(array) || array.length < 3)
return array;
int n = array.length;
int mid = n / 2;
if (n % 2 == 0) {
int mid2 = mid - 1;
return new int[] { array[mid2], array[mid] };
} else {
return new int[] { array[mid] };
}
}
int[] middleOfArrayWithStartEndNaive(int[] array, int start, int end) {
int mid = (start + end) / 2;
int n = end - start;
if (n % 2 == 0) {
int mid2 = mid - 1;
return new int[] { array[mid2], array[mid] };
} else {
return new int[] { array[mid] };
}
}
int[] middleOfArrayWithStartEnd(int[] array, int start, int end) {
int mid = start + (end - start) / 2;
int n = end - start;
if (n % 2 == 0) {
int mid2 = mid - 1;
return new int[] { array[mid2], array[mid] };
} else {
return new int[] { array[mid] };
}
} | int[] middleOfArrayWithStartEndBitwise(int[] array, int start, int end) {
int mid = (start + end) >>> 1;
int n = end - start;
if (n % 2 == 0) {
int mid2 = mid - 1;
return new int[] { array[mid2], array[mid] };
} else {
return new int[] { array[mid] };
}
}
int medianOfArray(int[] array, int start, int end) {
Arrays.sort(array); // for safety. This can be ignored
int mid = (start + end) >>> 1;
int n = end - start;
if (n % 2 == 0) {
int mid2 = mid - 1;
return (array[mid2] + array[mid]) / 2;
} else {
return array[mid];
}
}
} | repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced-2\src\main\java\com\baeldung\arraymiddle\MiddleOfArray.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Product implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
private boolean deleted = Boolean.FALSE;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name; | }
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-crud\src\main\java\com\baeldung\softdelete\Product.java | 2 |
请完成以下Java代码 | public PageLink nextPageLink() {
return new PageLink(this.pageSize, this.page + 1, this.textSearch, this.sortOrder);
}
public Sort toSort(SortOrder sortOrder, Map<String, String> columnMap, boolean addDefaultSorting) {
if (sortOrder == null) {
return DEFAULT_SORT;
} else {
return toSort(List.of(sortOrder), columnMap, addDefaultSorting);
}
}
public Sort toSort(List<SortOrder> sortOrders, Map<String, String> columnMap, boolean addDefaultSorting) {
if (addDefaultSorting && !isDefaultSortOrderAvailable(sortOrders)) {
sortOrders = new ArrayList<>(sortOrders);
sortOrders.add(new SortOrder(DEFAULT_SORT_PROPERTY, SortOrder.Direction.ASC));
}
return Sort.by(sortOrders.stream().map(s -> toSortOrder(s, columnMap)).collect(Collectors.toList()));
}
private Sort.Order toSortOrder(SortOrder sortOrder, Map<String, String> columnMap) {
String property = sortOrder.getProperty();
if (columnMap.containsKey(property)) { | property = columnMap.get(property);
}
return new Sort.Order(Sort.Direction.fromString(sortOrder.getDirection().name()), property);
}
public boolean isDefaultSortOrderAvailable(List<SortOrder> sortOrders) {
for (SortOrder sortOrder : sortOrders) {
if (DEFAULT_SORT_PROPERTY.equals(sortOrder.getProperty())) {
return true;
}
}
return false;
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\page\PageLink.java | 1 |
请完成以下Java代码 | protected void createInstallationProperty(CommandContext commandContext) {
String installationId = UUID.randomUUID().toString();
PropertyEntity property = new PropertyEntity(INSTALLATION_PROPERTY_NAME, installationId);
commandContext.getPropertyManager().insert(property);
LOG.creatingInstallationPropertyInDatabase(property.getValue());
commandContext.getProcessEngineConfiguration().setInstallationId(installationId);
}
protected String databaseInstallationId(CommandContext commandContext) {
try {
PropertyEntity installationIdProperty = commandContext.getPropertyManager().findPropertyById(INSTALLATION_PROPERTY_NAME);
return installationIdProperty != null ? installationIdProperty.getValue() : null;
} catch (Exception e) {
LOG.couldNotSelectInstallationId(e.getMessage());
return null;
}
}
protected void checkInstallationIdLockExists(CommandContext commandContext) {
PropertyEntity installationIdProperty = commandContext.getPropertyManager().findPropertyById("installationId.lock");
if (installationIdProperty == null) {
LOG.noInstallationIdLockPropertyFound();
}
}
protected void updateTelemetryData(CommandContext commandContext) {
ProcessEngineConfigurationImpl processEngineConfiguration = commandContext.getProcessEngineConfiguration();
String installationId = processEngineConfiguration.getInstallationId();
TelemetryDataImpl telemetryData = processEngineConfiguration.getTelemetryData();
// set installationId in the telemetry data
telemetryData.setInstallation(installationId); | // set the persisted license key in the telemetry data and registry
ManagementServiceImpl managementService = (ManagementServiceImpl) processEngineConfiguration.getManagementService();
String licenseKey = managementService.getLicenseKey();
if (licenseKey != null) {
LicenseKeyDataImpl licenseKeyData = LicenseKeyDataImpl.fromRawString(licenseKey);
managementService.setLicenseKeyForDiagnostics(licenseKeyData);
telemetryData.getProduct().getInternals().setLicenseKey(licenseKeyData);
}
}
protected void acquireExclusiveInstallationIdLock(CommandContext commandContext) {
PropertyManager propertyManager = commandContext.getPropertyManager();
//exclusive lock
propertyManager.acquireExclusiveLockForInstallationId();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\BootstrapEngineCommand.java | 1 |
请完成以下Java代码 | public class FirstNonRepeatingCharacter {
public Character firstNonRepeatingCharBruteForce(String inputString) {
if (null == inputString || inputString.isEmpty()) {
return null;
}
for (Character c : inputString.toCharArray()) {
int indexOfC = inputString.indexOf(c);
if (indexOfC == inputString.lastIndexOf(c)) {
return c;
}
}
return null;
}
public Character firstNonRepeatingCharBruteForceNaive(String inputString) {
if (null == inputString || inputString.isEmpty()) {
return null;
}
for (int outer = 0; outer < inputString.length(); outer++) {
boolean repeat = false;
for (int inner = 0; inner < inputString.length(); inner++) {
if (inner != outer && inputString.charAt(outer) == inputString.charAt(inner)) {
repeat = true;
break;
}
}
if (!repeat) {
return inputString.charAt(outer);
}
}
return null;
}
public Character firstNonRepeatingCharWithMap(String inputString) {
if (null == inputString || inputString.isEmpty()) {
return null;
}
Map<Character, Integer> frequency = new HashMap<>();
for (int outer = 0; outer < inputString.length(); outer++) {
char character = inputString.charAt(outer);
frequency.put(character, frequency.getOrDefault(character, 0) + 1);
}
for (Character c : inputString.toCharArray()) { | if (frequency.get(c) == 1) {
return c;
}
}
return null;
}
public Character firstNonRepeatingCharWithArray(String inputString) {
if (null == inputString || inputString.isEmpty()) {
return null;
}
int[] frequency = new int[26];
for (int outer = 0; outer < inputString.length(); outer++) {
char character = inputString.charAt(outer);
frequency[character - 'a']++;
}
for (Character c : inputString.toCharArray()) {
if (frequency[c - 'a'] == 1) {
return c;
}
}
return null;
}
} | repos\tutorials-master\core-java-modules\core-java-string-algorithms-3\src\main\java\com\baeldung\firstnonrepeatingcharacter\FirstNonRepeatingCharacter.java | 1 |
请完成以下Java代码 | public I_PA_Ratio getPA_Ratio() throws RuntimeException
{
return (I_PA_Ratio)MTable.get(getCtx(), I_PA_Ratio.Table_Name)
.getPO(getPA_Ratio_ID(), get_TrxName()); }
/** Set Ratio.
@param PA_Ratio_ID
Performace Ratio
*/
public void setPA_Ratio_ID (int PA_Ratio_ID)
{
if (PA_Ratio_ID < 1)
set_Value (COLUMNNAME_PA_Ratio_ID, null);
else
set_Value (COLUMNNAME_PA_Ratio_ID, Integer.valueOf(PA_Ratio_ID));
}
/** Get Ratio.
@return Performace Ratio
*/
public int getPA_Ratio_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Ratio_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_R_RequestType getR_RequestType() throws RuntimeException
{ | return (I_R_RequestType)MTable.get(getCtx(), I_R_RequestType.Table_Name)
.getPO(getR_RequestType_ID(), get_TrxName()); }
/** Set Request Type.
@param R_RequestType_ID
Type of request (e.g. Inquiry, Complaint, ..)
*/
public void setR_RequestType_ID (int R_RequestType_ID)
{
if (R_RequestType_ID < 1)
set_Value (COLUMNNAME_R_RequestType_ID, null);
else
set_Value (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID));
}
/** Get Request Type.
@return Type of request (e.g. Inquiry, Complaint, ..)
*/
public int getR_RequestType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_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_PA_Measure.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static class LineAggregationKey
{
@NonNull ProductId productId;
@NonNull HUPIItemProductId hupiItemProductId;
@NonNull AttributeSetInstanceId attributeSetInstanceId;
@NonNull UomId uomId;
@Nullable DistributionNetworkAndLineId distributionNetworkAndLineId;
@Nullable OrderAndLineId salesOrderLineId;
boolean isAllowPush;
boolean isKeepTargetPlant;
public static LineAggregationKey of(final DDOrderCandidate candidate, final @NonNull AggregationConfig aggregationConfig)
{
final LineAggregationKeyBuilder lineKeyBuilder = builder()
.productId(candidate.getProductId())
.hupiItemProductId(candidate.getHupiItemProductId())
.attributeSetInstanceId(candidate.getAttributeSetInstanceId())
.uomId(candidate.getQtyEntered().getUomId())
.distributionNetworkAndLineId(candidate.getDistributionNetworkAndLineId())
.isAllowPush(candidate.isAllowPush())
.isKeepTargetPlant(candidate.isKeepTargetPlant());
if (aggregationConfig.isAggregateBySalesOrderLineId())
{
lineKeyBuilder.salesOrderLineId(candidate.getSalesOrderLineId());
}
return lineKeyBuilder
.build();
}
@Nullable
public OrderId getSalesOrderId() {return salesOrderLineId != null ? salesOrderLineId.getOrderId() : null;}
}
//
//
// ------------------------------------------------------------------------------------------
//
//
@Value
@Builder
private static class DDOrderCandidateAllocCandidate
{
@NonNull DDOrderCandidateId ddOrderCandidateId;
@NonNull Quantity qty;
public DDOrderCandidateAlloc.DDOrderCandidateAllocBuilder toDDOrderCandidateAlloc()
{
return DDOrderCandidateAlloc.builder()
.ddOrderCandidateId(ddOrderCandidateId)
.qty(qty);
}
}
@Getter
@RequiredArgsConstructor
private static class LineAggregate
{
@NonNull private final LineAggregationKey key;
@NonNull private Quantity qty;
@NonNull private final ArrayList<DDOrderCandidateAllocCandidate> allocations = new ArrayList<>(); | public LineAggregate(@NonNull final LineAggregationKey key)
{
this.key = key;
this.qty = Quantitys.zero(key.getUomId());
}
public void add(@NonNull final DDOrderCandidate candidate)
{
add(DDOrderCandidateAllocCandidate.builder()
.ddOrderCandidateId(candidate.getIdNotNull())
.qty(candidate.getQtyToProcess())
.build());
}
private void add(@NonNull final DDOrderCandidateAllocCandidate alloc)
{
this.qty = this.qty.add(alloc.getQty());
this.allocations.add(alloc);
}
public boolean isEligibleToCreate()
{
return qty.signum() != 0;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddordercandidate\DDOrderCandidateProcessCommand.java | 2 |
请完成以下Java代码 | private boolean requiresBody(HttpMethod method) {
return List.of(PUT, POST, PATCH).contains(method);
}
@lombok.Data
@lombok.Builder(builderClassName = "Builder")
public static class InstanceResponse {
private final InstanceId instanceId;
private final int status;
@Nullable
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private final String body;
@Nullable
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private final String contentType;
} | @lombok.Data
@lombok.Builder(builderClassName = "Builder")
public static class ForwardRequest {
private final URI uri;
private final HttpMethod method;
private final HttpHeaders headers;
private final BodyInserter<?, ? super ClientHttpRequest> body;
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\web\InstanceWebProxy.java | 1 |
请完成以下Java代码 | public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
if (DevToolsEnablementDeducer.shouldEnable(Thread.currentThread()) && isLocalApplication(environment)) {
if (canAddProperties(environment)) {
logger.info(LogMessage.format("Devtools property defaults active! Set '%s' to 'false' to disable",
ENABLED));
environment.getPropertySources().addLast(new MapPropertySource("devtools", PROPERTIES));
}
if (isWebApplication(environment) && !environment.containsProperty(WEB_LOGGING)) {
logger.info(LogMessage.format(
"For additional web related logging consider setting the '%s' property to 'DEBUG'",
WEB_LOGGING));
}
}
}
private boolean isLocalApplication(ConfigurableEnvironment environment) {
return environment.getPropertySources().get("remoteUrl") == null;
}
private boolean canAddProperties(Environment environment) {
if (environment.getProperty(ENABLED, Boolean.class, true)) {
return isRestarterInitialized() || isRemoteRestartEnabled(environment);
}
return false;
}
private boolean isRestarterInitialized() {
try {
Restarter restarter = Restarter.getInstance();
return (restarter != null && restarter.getInitialUrls() != null); | }
catch (Exception ex) {
return false;
}
}
private boolean isRemoteRestartEnabled(Environment environment) {
return environment.containsProperty("spring.devtools.remote.secret");
}
private boolean isWebApplication(Environment environment) {
for (String candidate : WEB_ENVIRONMENT_CLASSES) {
Class<?> environmentClass = resolveClassName(candidate, environment.getClass().getClassLoader());
if (environmentClass != null && environmentClass.isInstance(environment)) {
return true;
}
}
return false;
}
private @Nullable Class<?> resolveClassName(String candidate, ClassLoader classLoader) {
try {
return ClassUtils.resolveClassName(candidate, classLoader);
}
catch (IllegalArgumentException ex) {
return null;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\env\DevToolsPropertyDefaultsPostProcessor.java | 1 |
请完成以下Java代码 | public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override | public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_ListValue.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SelectedReceivingTarget
{
@Nullable JsonLUReceivingTarget luReceivingTarget;
@Nullable JsonTUReceivingTarget tuReceivingTarget;
@Builder
public SelectedReceivingTarget(
@Nullable final JsonLUReceivingTarget luReceivingTarget,
@Nullable final JsonTUReceivingTarget tuReceivingTarget)
{
Check.assumeSingleNonNull("Exactly one target must be set!", tuReceivingTarget, luReceivingTarget);
this.luReceivingTarget = luReceivingTarget;
this.tuReceivingTarget = tuReceivingTarget;
}
@Nullable
public JsonNewLUTarget getReceiveToNewLU()
{
return Optional.ofNullable(luReceivingTarget)
.map(JsonLUReceivingTarget::getNewLU)
.orElse(null);
}
@Nullable
public JsonHUQRCodeTarget getReceiveToQRCode() | {
return Optional.ofNullable(luReceivingTarget)
.map(JsonLUReceivingTarget::getExistingLU)
.orElse(null);
}
@Nullable
public JsonNewTUTarget getReceiveToNewTU()
{
return Optional.ofNullable(tuReceivingTarget)
.map(JsonTUReceivingTarget::getNewTU)
.orElse(null);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\commands\receive\SelectedReceivingTarget.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setJobHandlerConfiguration(String jobHandlerConfiguration) {
this.jobHandlerConfiguration = jobHandlerConfiguration;
}
@ApiModelProperty(example = "myAdvancedCfg")
public String getAdvancedJobHandlerConfiguration() {
return advancedJobHandlerConfiguration;
}
public void setAdvancedJobHandlerConfiguration(String advancedJobHandlerConfiguration) {
this.advancedJobHandlerConfiguration = advancedJobHandlerConfiguration;
}
@ApiModelProperty(example = "custom value")
public String getCustomValues() {
return customValues;
}
public void setCustomValues(String customValues) {
this.customValues = customValues;
}
@ApiModelProperty(example = "node1")
public String getLockOwner() {
return lockOwner; | }
public void setLockOwner(String lockOwner) {
this.lockOwner = lockOwner;
}
@ApiModelProperty(example = "2023-06-03T22:05:05.474+0000")
public Date getLockExpirationTime() {
return lockExpirationTime;
}
public void setLockExpirationTime(Date lockExpirationTime) {
this.lockExpirationTime = lockExpirationTime;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\management\HistoryJobResponse.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class JSONLookupValuesPage
{
private static final JSONLookupValuesPage EMPTY = new JSONLookupValuesPage();
List<JSONLookupValue> values;
@JsonInclude(JsonInclude.Include.NON_NULL)
Boolean hasMoreResults;
@JsonInclude(JsonInclude.Include.NON_NULL)
Boolean isAlwaysDisplayNewBPartner;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Nullable JsonErrorItem error;
@Builder
private JSONLookupValuesPage(
@NonNull final ImmutableList<JSONLookupValue> values,
@Nullable final Boolean hasMoreResults,
@Nullable final Boolean isAlwaysDisplayNewBPartner,
@Nullable JsonErrorItem error)
{
this.values = values;
this.hasMoreResults = hasMoreResults;
this.isAlwaysDisplayNewBPartner = isAlwaysDisplayNewBPartner;
this.error = error;
}
private JSONLookupValuesPage()
{
values = ImmutableList.of();
hasMoreResults = false;
isAlwaysDisplayNewBPartner = false;
error = null;
} | public static JSONLookupValuesPage of(
@Nullable final LookupValuesPage page,
@NonNull final String adLanguage)
{
return of(page, adLanguage, false);
}
public static JSONLookupValuesPage of(
@Nullable final LookupValuesPage page,
@NonNull final String adLanguage,
@Nullable final Boolean isAlwaysDisplayNewBPartner)
{
if (page == null || page.isEmpty())
{
return EMPTY;
}
else
{
return builder()
.values(JSONLookupValuesList.toListOfJSONLookupValues(page.getValues(), adLanguage, false))
.hasMoreResults(page.getHasMoreResults().toBooleanOrNull())
.isAlwaysDisplayNewBPartner(isAlwaysDisplayNewBPartner)
.build();
}
}
public static JSONLookupValuesPage error(@NonNull final JsonErrorItem error)
{
return builder().error(error).values(ImmutableList.of()).build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONLookupValuesPage.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public final class ItemIgnore implements Comparable<ItemIgnore> {
private final ItemType type;
private final String name;
private ItemIgnore(ItemType type, String name) {
if (type == null) {
throw new IllegalArgumentException("'type' must not be null");
}
if (name == null) {
throw new IllegalArgumentException("'name' must not be null");
}
this.type = type;
this.name = name;
}
public String getName() {
return this.name;
}
public ItemType getType() {
return this.type;
}
@Override
public int compareTo(ItemIgnore other) {
return getName().compareTo(other.getName());
}
/**
* Create an ignore for a property with the given name.
* @param name the name
* @return the item ignore
*/ | public static ItemIgnore forProperty(String name) {
return new ItemIgnore(ItemType.PROPERTY, name);
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) {
return false;
}
ItemIgnore that = (ItemIgnore) o;
return this.type == that.type && Objects.equals(this.name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(this.type, this.name);
}
@Override
public String toString() {
return "ItemIgnore{" + "type=" + this.type + ", name='" + this.name + '\'' + '}';
}
} | repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\metadata\ItemIgnore.java | 2 |
请完成以下Java代码 | public class GetProcessInstanceCommentsCmd implements Command<List<Comment>>, Serializable {
private static final long serialVersionUID = 1L;
protected String processInstanceId;
protected String type;
public GetProcessInstanceCommentsCmd(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public GetProcessInstanceCommentsCmd(String processInstanceId, String type) {
this.processInstanceId = processInstanceId;
this.type = type;
} | @Override
@SuppressWarnings("unchecked")
public List<Comment> execute(CommandContext commandContext) {
if (StringUtils.isNotBlank(type)) {
List<Comment> commentsByProcessInstanceId = commandContext
.getCommentEntityManager()
.findCommentsByProcessInstanceId(processInstanceId, type);
return commentsByProcessInstanceId;
} else {
return commandContext
.getCommentEntityManager()
.findCommentsByProcessInstanceId(processInstanceId);
}
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cmd\GetProcessInstanceCommentsCmd.java | 1 |
请完成以下Java代码 | protected class ApacheHttpComponentsExecutableHttpRequest implements ExecutableHttpRequest {
protected final HttpRequestBase request;
public ApacheHttpComponentsExecutableHttpRequest(HttpRequestBase request) {
this.request = request;
}
@Override
public HttpResponse call() {
try (CloseableHttpClient httpClient = clientBuilder.build()) {
try (CloseableHttpResponse response = httpClient.execute(request)) {
return toFlowableHttpResponse(response);
}
} catch (ClientProtocolException ex) {
throw new FlowableException("HTTP exception occurred", ex);
} catch (IOException ex) {
throw new FlowableException("IO exception occurred", ex);
}
}
}
/** | * A HttpDelete alternative that extends {@link HttpEntityEnclosingRequestBase} to allow DELETE with a request body
*
* @author ikaakkola
*/
protected static class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
public HttpDeleteWithBody(URI uri) {
super();
setURI(uri);
}
@Override
public String getMethod() {
return "DELETE";
}
}
} | repos\flowable-engine-main\modules\flowable-http-common\src\main\java\org\flowable\http\common\impl\apache\ApacheHttpComponentsFlowableHttpClient.java | 1 |
请完成以下Java代码 | public class Problem {
protected String errorMessage;
protected String resource;
protected int line;
protected int column;
public Problem(String errorMessage, String localName, int lineNumber, int columnNumber) {
this.errorMessage = errorMessage;
this.resource = localName;
this.line = lineNumber;
this.column = columnNumber;
}
public Problem(String errorMessage, BaseElement element) {
this.errorMessage = errorMessage; | this.resource = element.getId();
this.line = element.getXmlRowNumber();
this.column = element.getXmlColumnNumber();
}
public Problem(String errorMessage, GraphicInfo graphicInfo) {
this.errorMessage = errorMessage;
this.line = graphicInfo.getXmlRowNumber();
this.column = graphicInfo.getXmlColumnNumber();
}
public String toString() {
return errorMessage + (resource != null ? " | " + resource : "") + " | line " + line + " | column " + column;
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\parse\Problem.java | 1 |
请完成以下Java代码 | public void setHasRegion (boolean HasRegion)
{
set_Value (COLUMNNAME_HasRegion, Boolean.valueOf(HasRegion));
}
/** Get Land hat Regionen.
@return Country contains Regions
*/
@Override
public boolean isHasRegion ()
{
Object oo = get_Value(COLUMNNAME_HasRegion);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Reverse Local Address Lines.
@param IsAddressLinesLocalReverse
Print Local Address in reverse Order
*/
@Override
public void setIsAddressLinesLocalReverse (boolean IsAddressLinesLocalReverse)
{
set_Value (COLUMNNAME_IsAddressLinesLocalReverse, Boolean.valueOf(IsAddressLinesLocalReverse));
}
/** Get Reverse Local Address Lines.
@return Print Local Address in reverse Order
*/
@Override
public boolean isAddressLinesLocalReverse ()
{
Object oo = get_Value(COLUMNNAME_IsAddressLinesLocalReverse);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Reverse Address Lines.
@param IsAddressLinesReverse
Print Address in reverse Order
*/
@Override
public void setIsAddressLinesReverse (boolean IsAddressLinesReverse)
{
set_Value (COLUMNNAME_IsAddressLinesReverse, Boolean.valueOf(IsAddressLinesReverse));
}
/** Get Reverse Address Lines.
@return Print Address in reverse Order
*/
@Override
public boolean isAddressLinesReverse ()
{ | Object oo = get_Value(COLUMNNAME_IsAddressLinesReverse);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Media Size.
@param MediaSize
Java Media Size
*/
@Override
public void setMediaSize (java.lang.String MediaSize)
{
set_Value (COLUMNNAME_MediaSize, MediaSize);
}
/** Get Media Size.
@return Java Media Size
*/
@Override
public java.lang.String getMediaSize ()
{
return (java.lang.String)get_Value(COLUMNNAME_MediaSize);
}
/** Set Name.
@param Name Name */
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Region.
@param RegionName
Name of the Region
*/
@Override
public void setRegionName (java.lang.String RegionName)
{
set_Value (COLUMNNAME_RegionName, RegionName);
}
/** Get Region.
@return Name of the Region
*/
@Override
public java.lang.String getRegionName ()
{
return (java.lang.String)get_Value(COLUMNNAME_RegionName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Country.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable Show getShowDetails() {
return this.showDetails;
}
public void setShowDetails(@Nullable Show showDetails) {
this.showDetails = showDetails;
}
public @Nullable String getAdditionalPath() {
return this.additionalPath;
}
public void setAdditionalPath(@Nullable String additionalPath) {
this.additionalPath = additionalPath;
}
}
/**
* Health logging properties.
*/
public static class Logging { | /**
* Threshold after which a warning will be logged for slow health indicators.
*/
private Duration slowIndicatorThreshold = Duration.ofSeconds(10);
public Duration getSlowIndicatorThreshold() {
return this.slowIndicatorThreshold;
}
public void setSlowIndicatorThreshold(Duration slowIndicatorThreshold) {
this.slowIndicatorThreshold = slowIndicatorThreshold;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\autoconfigure\actuate\endpoint\HealthEndpointProperties.java | 2 |
请完成以下Java代码 | public class UserAuthSettingsEntity extends BaseSqlEntity<UserAuthSettings> implements BaseEntity<UserAuthSettings> {
@Column(name = ModelConstants.USER_AUTH_SETTINGS_USER_ID_PROPERTY, nullable = false, unique = true)
private UUID userId;
@Convert(converter = JsonConverter.class)
@Column(name = ModelConstants.USER_AUTH_SETTINGS_TWO_FA_SETTINGS)
private JsonNode twoFaSettings;
public UserAuthSettingsEntity(UserAuthSettings userAuthSettings) {
if (userAuthSettings.getId() != null) {
this.setId(userAuthSettings.getId().getId());
}
this.setCreatedTime(userAuthSettings.getCreatedTime());
if (userAuthSettings.getUserId() != null) {
this.userId = userAuthSettings.getUserId().getId();
}
if (userAuthSettings.getTwoFaSettings() != null) {
this.twoFaSettings = JacksonUtil.valueToTree(userAuthSettings.getTwoFaSettings()); | }
}
@Override
public UserAuthSettings toData() {
UserAuthSettings userAuthSettings = new UserAuthSettings();
userAuthSettings.setId(new UserAuthSettingsId(id));
userAuthSettings.setCreatedTime(createdTime);
if (userId != null) {
userAuthSettings.setUserId(new UserId(userId));
}
if (twoFaSettings != null) {
userAuthSettings.setTwoFaSettings(JacksonUtil.treeToValue(twoFaSettings, AccountTwoFaSettings.class));
}
return userAuthSettings;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\UserAuthSettingsEntity.java | 1 |
请完成以下Java代码 | private void updateRecordWithRecipient(
@NonNull final I_C_Doc_Outbound_Log docOutboundLogRecord,
@NonNull final DocOutBoundRecipients recipients)
{
final String tableName = TableRecordReference.ofReferenced(docOutboundLogRecord).getTableName();
final boolean isInvoiceEmailEnabled = I_C_Invoice.Table_Name.equals(tableName) && recipients.isInvoiceAsEmail();
docOutboundLogRecord.setIsInvoiceEmailEnabled(isInvoiceEmailEnabled);
if (recipients.getTo() != null)
{
docOutboundLogRecord.setCurrentEMailRecipient_ID(recipients.getTo().getId().getRepoId());
docOutboundLogRecord.setCurrentEMailAddress(recipients.getTo().getEmailAddress());
}
if (recipients.getCc() != null)
{
docOutboundLogRecord.setCurrentEMailCCRecipient_ID(recipients.getCc().getId().getRepoId());
docOutboundLogRecord.setCurrentEMailAddressCC(recipients.getCc().getEmailAddress());
}
}
private void shareDocumentAttachmentsWithDocoutBoundLog(
@NonNull final I_AD_Archive archiveRecord,
@NonNull final I_C_Doc_Outbound_Log docOutboundLogRecord) | {
final ITableRecordReference from = TableRecordReference.ofReferencedOrNull(archiveRecord);
if (from == null)
{
return;
}
final AttachmentEntryQuery query = AttachmentEntryQuery
.builder()
.referencedRecord(from)
.tagSetToTrue(AttachmentTags.TAGNAME_IS_DOCUMENT)
.build();
final List<AttachmentEntry> attachmentsToShare = attachmentEntryService.getByQuery(query);
attachmentEntryService.createAttachmentLinks(attachmentsToShare, ImmutableList.of(docOutboundLogRecord));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\spi\impl\DocOutboundArchiveEventListener.java | 1 |
请完成以下Java代码 | public int getAD_InfoWindow_From_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_InfoWindow_From_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_InfoWindow getAD_InfoWindow() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_InfoWindow_ID, org.compiere.model.I_AD_InfoWindow.class);
}
@Override
public void setAD_InfoWindow(org.compiere.model.I_AD_InfoWindow AD_InfoWindow)
{
set_ValueFromPO(COLUMNNAME_AD_InfoWindow_ID, org.compiere.model.I_AD_InfoWindow.class, AD_InfoWindow);
}
/** Set Info-Fenster.
@param AD_InfoWindow_ID
Info and search/select Window
*/
@Override
public void setAD_InfoWindow_ID (int AD_InfoWindow_ID)
{
if (AD_InfoWindow_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_InfoWindow_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_InfoWindow_ID, Integer.valueOf(AD_InfoWindow_ID));
}
/** Get Info-Fenster.
@return Info and search/select Window
*/
@Override
public int getAD_InfoWindow_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_InfoWindow_ID);
if (ii == null)
return 0;
return ii.intValue();
} | /**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entitäts-Art.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public void setEntityType (java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitäts-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public java.lang.String getEntityType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** Set Sql FROM.
@param FromClause
SQL FROM clause
*/
@Override
public void setFromClause (java.lang.String FromClause)
{
set_Value (COLUMNNAME_FromClause, FromClause);
}
/** Get Sql FROM.
@return SQL FROM clause
*/
@Override
public java.lang.String getFromClause ()
{
return (java.lang.String)get_Value(COLUMNNAME_FromClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_InfoWindow_From.java | 1 |
请完成以下Java代码 | public void run()
{
setBusy(true);
process.run();
setBusy(false);
}
};
worker.start();
return worker;
} // startBatch
/**
* @return Returns the AD_Form_ID.
*/
public int getAD_Form_ID ()
{
return p_AD_Form_ID;
} // getAD_Window_ID
public int getWindowNo()
{
return m_WindowNo;
}
/**
* @return Returns the manuBar
*/ | public JMenuBar getMenu()
{
return menuBar;
}
public void showFormWindow()
{
if (m_panel instanceof FormPanel2)
{
((FormPanel2)m_panel).showFormWindow(m_WindowNo, this);
}
else
{
AEnv.showCenterScreenOrMaximized(this);
}
}
} // FormFrame | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\FormFrame.java | 1 |
请完成以下Java代码 | public void setC_CompensationGroup_Schema(final de.metas.order.model.I_C_CompensationGroup_Schema C_CompensationGroup_Schema)
{
set_ValueFromPO(COLUMNNAME_C_CompensationGroup_Schema_ID, de.metas.order.model.I_C_CompensationGroup_Schema.class, C_CompensationGroup_Schema);
}
@Override
public void setC_CompensationGroup_Schema_ID (final int C_CompensationGroup_Schema_ID)
{
if (C_CompensationGroup_Schema_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_CompensationGroup_Schema_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_CompensationGroup_Schema_ID, C_CompensationGroup_Schema_ID);
}
@Override
public int getC_CompensationGroup_Schema_ID()
{
return get_ValueAsInt(COLUMNNAME_C_CompensationGroup_Schema_ID);
}
@Override
public void setC_CompensationGroup_SchemaLine_ID (final int C_CompensationGroup_SchemaLine_ID)
{
if (C_CompensationGroup_SchemaLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_CompensationGroup_SchemaLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_CompensationGroup_SchemaLine_ID, C_CompensationGroup_SchemaLine_ID);
}
@Override
public int getC_CompensationGroup_SchemaLine_ID()
{
return get_ValueAsInt(COLUMNNAME_C_CompensationGroup_SchemaLine_ID);
}
@Override
public void setC_Flatrate_Conditions_ID (final int C_Flatrate_Conditions_ID)
{
if (C_Flatrate_Conditions_ID < 1)
set_Value (COLUMNNAME_C_Flatrate_Conditions_ID, null);
else
set_Value (COLUMNNAME_C_Flatrate_Conditions_ID, C_Flatrate_Conditions_ID);
}
@Override
public int getC_Flatrate_Conditions_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Flatrate_Conditions_ID);
}
@Override
public void setCompleteOrderDiscount (final @Nullable BigDecimal CompleteOrderDiscount)
{
set_Value (COLUMNNAME_CompleteOrderDiscount, CompleteOrderDiscount);
}
@Override
public BigDecimal getCompleteOrderDiscount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_CompleteOrderDiscount);
return bd != null ? bd : BigDecimal.ZERO;
}
@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 setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
/**
* Type AD_Reference_ID=540836
* Reference name: C_CompensationGroup_SchemaLine_Type
*/
public static final int TYPE_AD_Reference_ID=540836;
/** Revenue = R */
public static final String TYPE_Revenue = "R";
/** Flatrate = F */
public static final String TYPE_Flatrate = "F";
@Override
public void setType (final @Nullable java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\order\model\X_C_CompensationGroup_SchemaLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public PaymentAllocationBuilder payableRemainingOpenAmtPolicy(@NonNull final PayableRemainingOpenAmtPolicy payableRemainingOpenAmtPolicy)
{
assertNotBuilt();
this.payableRemainingOpenAmtPolicy = payableRemainingOpenAmtPolicy;
return this;
}
public PaymentAllocationBuilder dryRun()
{
this.dryRun = true;
return this;
}
public PaymentAllocationBuilder payableDocuments(final Collection<PayableDocument> payableDocuments)
{
_payableDocuments = ImmutableList.copyOf(payableDocuments);
return this;
}
public PaymentAllocationBuilder paymentDocuments(final Collection<PaymentDocument> paymentDocuments)
{
_paymentDocuments = ImmutableList.copyOf(paymentDocuments);
return this;
}
public PaymentAllocationBuilder paymentDocument(final PaymentDocument paymentDocument)
{
return paymentDocuments(ImmutableList.of(paymentDocument));
}
@VisibleForTesting
final ImmutableList<PayableDocument> getPayableDocuments()
{ | return _payableDocuments;
}
@VisibleForTesting
final ImmutableList<PaymentDocument> getPaymentDocuments()
{
return _paymentDocuments;
}
public PaymentAllocationBuilder invoiceProcessingServiceCompanyService(@NonNull final InvoiceProcessingServiceCompanyService invoiceProcessingServiceCompanyService)
{
assertNotBuilt();
this.invoiceProcessingServiceCompanyService = invoiceProcessingServiceCompanyService;
return this;
}
/**
* @param allocatePayableAmountsAsIs if true, we allow the allocated amount to exceed the payment's amount,
* if the given payable is that big.
* We need this behavior when we want to allocate a remittance advice and know that *in sum* the payables' amounts will match the payment
*/
public PaymentAllocationBuilder allocatePayableAmountsAsIs(final boolean allocatePayableAmountsAsIs)
{
assertNotBuilt();
this.allocatePayableAmountsAsIs = allocatePayableAmountsAsIs;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\service\PaymentAllocationBuilder.java | 2 |
请完成以下Java代码 | public void setAuthorizationRedirectStrategy(ServerRedirectStrategy authorizationRedirectStrategy) {
Assert.notNull(authorizationRedirectStrategy, "authorizationRedirectStrategy cannot be null");
this.authorizationRedirectStrategy = authorizationRedirectStrategy;
}
/**
* Sets the repository used for storing {@link OAuth2AuthorizationRequest}'s.
* @param authorizationRequestRepository the repository used for storing
* {@link OAuth2AuthorizationRequest}'s
*/
public final void setAuthorizationRequestRepository(
ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository) {
Assert.notNull(authorizationRequestRepository, "authorizationRequestRepository cannot be null");
this.authorizationRequestRepository = authorizationRequestRepository;
}
/**
* The request cache to use to save the request before sending a redirect.
* @param requestCache the cache to redirect to.
*/
public void setRequestCache(ServerRequestCache requestCache) {
Assert.notNull(requestCache, "requestCache cannot be null");
this.requestCache = requestCache;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
// @formatter:off
return this.authorizationRequestResolver.resolve(exchange)
.switchIfEmpty(chain.filter(exchange).then(Mono.empty()))
.onErrorResume(ClientAuthorizationRequiredException.class,
(ex) -> this.requestCache.saveRequest(exchange).then(
this.authorizationRequestResolver.resolve(exchange, ex.getClientRegistrationId()))
)
.flatMap((clientRegistration) -> sendRedirectForAuthorization(exchange, clientRegistration));
// @formatter:on
} | private Mono<Void> sendRedirectForAuthorization(ServerWebExchange exchange,
OAuth2AuthorizationRequest authorizationRequest) {
return Mono.defer(() -> {
Mono<Void> saveAuthorizationRequest = Mono.empty();
if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(authorizationRequest.getGrantType())) {
saveAuthorizationRequest = this.authorizationRequestRepository
.saveAuthorizationRequest(authorizationRequest, exchange);
}
// @formatter:off
URI redirectUri = UriComponentsBuilder.fromUriString(authorizationRequest.getAuthorizationRequestUri())
.build(true)
.toUri();
// @formatter:on
return saveAuthorizationRequest
.then(this.authorizationRedirectStrategy.sendRedirect(exchange, redirectUri));
});
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\server\OAuth2AuthorizationRequestRedirectWebFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void customize(MongoClientSettings.Builder settingsBuilder) {
settingsBuilder.uuidRepresentation(this.uuidRepresentation);
settingsBuilder.applyConnectionString(this.connectionDetails.getConnectionString());
settingsBuilder.applyToSslSettings(this::configureSslIfNeeded);
}
private void configureSslIfNeeded(SslSettings.Builder settings) {
SslBundle sslBundle = this.connectionDetails.getSslBundle();
if (sslBundle != null) {
settings.enabled(true);
Assert.state(!sslBundle.getOptions().isSpecified(), "SSL options cannot be specified with MongoDB");
settings.context(sslBundle.createSslContext());
}
} | @Override
public int getOrder() {
return this.order;
}
/**
* Set the order value of this object.
* @param order the new order value
* @see #getOrder()
*/
public void setOrder(int order) {
this.order = order;
}
} | repos\spring-boot-4.0.1\module\spring-boot-mongodb\src\main\java\org\springframework\boot\mongodb\autoconfigure\StandardMongoClientSettingsBuilderCustomizer.java | 2 |
请完成以下Java代码 | private static @Nullable Object applyCaching(@Nullable Object response, long timeToLive) {
if (response instanceof Mono) {
return ((Mono<?>) response).cache(Duration.ofMillis(timeToLive));
}
if (response instanceof Flux) {
return ((Flux<?>) response).cache(Duration.ofMillis(timeToLive));
}
return response;
}
}
private static final class CacheKey {
private static final Class<?>[] CACHEABLE_TYPES = new Class<?>[] { ApiVersion.class, SecurityContext.class,
WebServerNamespace.class };
private final ApiVersion apiVersion;
private final @Nullable Principal principal;
private final @Nullable WebServerNamespace serverNamespace;
private CacheKey(ApiVersion apiVersion, @Nullable Principal principal,
@Nullable WebServerNamespace serverNamespace) {
this.principal = principal;
this.apiVersion = apiVersion;
this.serverNamespace = serverNamespace;
}
static boolean containsType(Class<?> type) {
return Arrays.stream(CacheKey.CACHEABLE_TYPES).anyMatch((c) -> c.isAssignableFrom(type));
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
} | CacheKey other = (CacheKey) obj;
return this.apiVersion.equals(other.apiVersion)
&& ObjectUtils.nullSafeEquals(this.principal, other.principal)
&& ObjectUtils.nullSafeEquals(this.serverNamespace, other.serverNamespace);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + this.apiVersion.hashCode();
result = prime * result + ObjectUtils.nullSafeHashCode(this.principal);
result = prime * result + ObjectUtils.nullSafeHashCode(this.serverNamespace);
return result;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\invoker\cache\CachingOperationInvoker.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static AvailableToPromiseMultiQuery forDescriptorAndAllPossibleBPartnerIds(@NonNull final MaterialDescriptor materialDescriptor)
{
final AvailableToPromiseQuery bPartnerQuery = AvailableToPromiseQuery.forMaterialDescriptor(materialDescriptor);
final AvailableToPromiseMultiQueryBuilder multiQueryBuilder = AvailableToPromiseMultiQuery.builder()
.addToPredefinedBuckets(false)
.query(bPartnerQuery);
if (bPartnerQuery.getBpartner().isSpecificBPartner())
{
final AvailableToPromiseQuery noPartnerQuery = bPartnerQuery
.toBuilder()
.bpartner(BPartnerClassifier.none())
.build();
multiQueryBuilder.query(noPartnerQuery);
}
return multiQueryBuilder.build();
}
public static final AvailableToPromiseMultiQuery of(@NonNull final AvailableToPromiseQuery query)
{
return builder()
.query(query)
.addToPredefinedBuckets(DEFAULT_addToPredefinedBuckets)
.build();
}
private final Set<AvailableToPromiseQuery> queries;
private static final boolean DEFAULT_addToPredefinedBuckets = true;
private final boolean addToPredefinedBuckets; | @Builder
private AvailableToPromiseMultiQuery(
@NonNull @Singular final ImmutableSet<AvailableToPromiseQuery> queries,
final Boolean addToPredefinedBuckets)
{
Check.assumeNotEmpty(queries, "queries is not empty");
this.queries = queries;
this.addToPredefinedBuckets = CoalesceUtil.coalesce(addToPredefinedBuckets, DEFAULT_addToPredefinedBuckets);
}
/**
* {@code true} means that the system will initially create one empty result group for the {@link AttributesKey}s of each included {@link AvailableToPromiseQuery}.
* ATP quantity that are retrieved may be added to multiple result groups, depending on those groups attributes keys
* If no ATP quantity matches a particular group, it will remain empty.<br>
* {@code false} means that the system will create result groups on the fly for the respective ATP records that it finds.
*/
public boolean isAddToPredefinedBuckets()
{
return addToPredefinedBuckets;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\atp\AvailableToPromiseMultiQuery.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public UserIdentityAvailability checkUsernameAvailability(@RequestParam(value = "username") String username)
{
Boolean isAvailable = !userRepository.existsByUsername(username);
return new UserIdentityAvailability(isAvailable);
}
@GetMapping("/user/checkEmailAvialability")
public UserIdentityAvailability checkEmailAvailability(@RequestParam(value = "email") String email)
{
Boolean isAvailable = !userRepository.existsByEmail(email);
return new UserIdentityAvailability(isAvailable);
}
@PostMapping("/users/getBySearch")
public Optional<User> getUserBySearch(@RequestParam(value = "username") String username)
{
return userRepository.findByUsername(username);
}
@GetMapping("/users/getAllUsers")
public List<String> getAllUsers(@PathVariable(value = "id") Long id)
{
return userRepository.findAllUsers();
}
@GetMapping("/users/{id}")
public UserProfile getUserProfile(@PathVariable(value = "id") Long id)
{ | User user = userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User", "username", id));
UserProfile userProfile = new UserProfile(user.getId(), user.getSurname(), user.getName(), user.getLastname(), user.getUsername(), user.getCreatedAt(), user.getPhone(), user.getEmail(), user.getPassword(), user.getCity());
userUtils.initUserAvatar(userProfile, user);
return userProfile;
}
@PostMapping("/users/saveUserProfile")
public ResponseEntity<?> saveUserProfile(@CurrentUser UserPrincipal userPrincipal, @RequestBody UserProfile userProfileForm)
{
return userService.saveUserProfile(userPrincipal, userProfileForm);
}
@PostMapping("/users/saveCity")
public Boolean saveCity(@CurrentUser UserPrincipal userPrincipal, @RequestBody String city)
{
return userService.saveCity(userPrincipal, city);
}
} | repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\controller\UserController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | static MethodInterceptor securedAuthorizationMethodInterceptor(
ObjectProvider<SecuredMethodSecurityConfiguration> securedMethodSecurityConfiguration) {
Supplier<AuthorizationManagerBeforeMethodInterceptor> supplier = () -> {
SecuredMethodSecurityConfiguration configuration = securedMethodSecurityConfiguration.getObject();
return configuration.methodInterceptor;
};
return new DeferringMethodInterceptor<>(pointcut, supplier);
}
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
EnableMethodSecurity annotation = importMetadata.getAnnotations().get(EnableMethodSecurity.class).synthesize();
this.methodInterceptor.setOrder(this.methodInterceptor.getOrder() + annotation.offset());
}
@Autowired(required = false)
void setRoleHierarchy(RoleHierarchy roleHierarchy) {
AuthoritiesAuthorizationManager authoritiesAuthorizationManager = new AuthoritiesAuthorizationManager(); | authoritiesAuthorizationManager.setRoleHierarchy(roleHierarchy);
this.authorizationManager.setAuthoritiesAuthorizationManager(authoritiesAuthorizationManager);
}
@Autowired(required = false)
void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
this.methodInterceptor.setSecurityContextHolderStrategy(securityContextHolderStrategy);
}
@Autowired(required = false)
void setEventPublisher(AuthorizationEventPublisher eventPublisher) {
this.methodInterceptor.setAuthorizationEventPublisher(eventPublisher);
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\SecuredMethodSecurityConfiguration.java | 2 |
请完成以下Java代码 | public Optional<String> getReason() {
return Optional.ofNullable(this.reason);
}
/**
* Returns an {@link Optional} {@link DistributedMember} identified as the suspect in the {@link MembershipEvent}.
*
* @return an {@link Optional} {@link DistributedMember} identified as the suspect in the {@link MembershipEvent}.
* @see org.apache.geode.distributed.DistributedMember
* @see java.util.Optional
*/
public Optional<DistributedMember> getSuspectMember() {
return Optional.ofNullable(this.suspectMember);
}
/**
* Builder method used to configure the {@link String reason} describing the suspicion of
* the {@link DistributedMember suspect member}.
*
* @param reason {@link String} describing the suspicion of the {@link DistributedMember peer member};
* may be {@literal null}.
* @return this {@link MemberSuspectEvent}.
* @see #getReason()
*/
public MemberSuspectEvent withReason(String reason) {
this.reason = reason;
return this; | }
/**
* Builder method used to configure the {@link DistributedMember peer member} that is the subject of the suspicion
* {@link MembershipEvent}.
*
* @param suspectMember {@link DistributedMember peer member} that is being suspected; may be {@literal null}.
* @return this {@link MemberSuspectEvent}.
* @see #getSuspectMember()
*/
public MemberSuspectEvent withSuspect(DistributedMember suspectMember) {
this.suspectMember = suspectMember;
return this;
}
/**
* @inheritDoc
*/
@Override
public final Type getType() {
return Type.MEMBER_SUSPECT;
}
} | repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\distributed\event\support\MemberSuspectEvent.java | 1 |
请完成以下Java代码 | public Map<String, String> getProperties() {
return commandExecutor.execute(new GetPropertiesCmd());
}
@Override
public <T> T executeCommand(Command<T> command) {
if (command == null) {
throw new ActivitiIllegalArgumentException("The command is null");
}
return commandExecutor.execute(command);
}
@Override
public <T> T executeCommand(CommandConfig config, Command<T> command) {
if (config == null) {
throw new ActivitiIllegalArgumentException("The config is null");
}
if (command == null) {
throw new ActivitiIllegalArgumentException("The command is null");
}
return commandExecutor.execute(config, command);
}
@Override
public <MapperType, ResultType> ResultType executeCustomSql(CustomSqlExecution<MapperType, ResultType> customSqlExecution) { | Class<MapperType> mapperClass = customSqlExecution.getMapperClass();
return commandExecutor.execute(new ExecuteCustomSqlCmd<>(mapperClass, customSqlExecution));
}
@Override
public List<EventLogEntry> getEventLogEntries(Long startLogNr, Long pageSize) {
return commandExecutor.execute(new GetEventLogEntriesCmd(startLogNr, pageSize));
}
@Override
public List<EventLogEntry> getEventLogEntriesByProcessInstanceId(String processInstanceId) {
return commandExecutor.execute(new GetEventLogEntriesCmd(processInstanceId));
}
@Override
public void deleteEventLogEntry(long logNr) {
commandExecutor.execute(new DeleteEventLogEntry(logNr));
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\ManagementServiceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String xxlJobList(Integer page, Integer size) {
Map<String, Object> jobInfo = Maps.newHashMap();
jobInfo.put("start", page != null ? page : 0);
jobInfo.put("length", size != null ? size : 10);
jobInfo.put("jobGroup", 2);
jobInfo.put("triggerStatus", -1);
HttpResponse execute = HttpUtil.createGet(baseUri + JOB_INFO_URI + "/pageList").form(jobInfo).execute();
log.info("【execute】= {}", execute);
return execute.body();
}
/**
* 测试手动保存任务
*/
@GetMapping("/add")
public String xxlJobAdd() {
Map<String, Object> jobInfo = Maps.newHashMap();
jobInfo.put("jobGroup", 2);
jobInfo.put("jobCron", "0 0/1 * * * ? *");
jobInfo.put("jobDesc", "手动添加的任务");
jobInfo.put("author", "admin");
jobInfo.put("executorRouteStrategy", "ROUND");
jobInfo.put("executorHandler", "demoTask");
jobInfo.put("executorParam", "手动添加的任务的参数");
jobInfo.put("executorBlockStrategy", ExecutorBlockStrategyEnum.SERIAL_EXECUTION);
jobInfo.put("glueType", GlueTypeEnum.BEAN);
HttpResponse execute = HttpUtil.createGet(baseUri + JOB_INFO_URI + "/add").form(jobInfo).execute();
log.info("【execute】= {}", execute);
return execute.body();
}
/**
* 测试手动触发一次任务
*/
@GetMapping("/trigger")
public String xxlJobTrigger() {
Map<String, Object> jobInfo = Maps.newHashMap();
jobInfo.put("id", 4);
jobInfo.put("executorParam", JSONUtil.toJsonStr(jobInfo));
HttpResponse execute = HttpUtil.createGet(baseUri + JOB_INFO_URI + "/trigger").form(jobInfo).execute();
log.info("【execute】= {}", execute);
return execute.body();
}
/**
* 测试手动删除任务
*/
@GetMapping("/remove")
public String xxlJobRemove() {
Map<String, Object> jobInfo = Maps.newHashMap();
jobInfo.put("id", 4);
HttpResponse execute = HttpUtil.createGet(baseUri + JOB_INFO_URI + "/remove").form(jobInfo).execute();
log.info("【execute】= {}", execute);
return execute.body();
} | /**
* 测试手动停止任务
*/
@GetMapping("/stop")
public String xxlJobStop() {
Map<String, Object> jobInfo = Maps.newHashMap();
jobInfo.put("id", 4);
HttpResponse execute = HttpUtil.createGet(baseUri + JOB_INFO_URI + "/stop").form(jobInfo).execute();
log.info("【execute】= {}", execute);
return execute.body();
}
/**
* 测试手动启动任务
*/
@GetMapping("/start")
public String xxlJobStart() {
Map<String, Object> jobInfo = Maps.newHashMap();
jobInfo.put("id", 4);
HttpResponse execute = HttpUtil.createGet(baseUri + JOB_INFO_URI + "/start").form(jobInfo).execute();
log.info("【execute】= {}", execute);
return execute.body();
}
} | repos\spring-boot-demo-master\demo-task-xxl-job\src\main\java\com\xkcoding\task\xxl\job\controller\ManualOperateController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public ItemHint applyPrefix(String prefix) {
return new ItemHint(ConventionUtils.toDashedCase(prefix) + "." + this.name, this.values, this.providers);
}
@Override
public int compareTo(ItemHint other) {
return getName().compareTo(other.getName());
}
public static ItemHint newHint(String name, ValueHint... values) {
return new ItemHint(name, Arrays.asList(values), Collections.emptyList());
}
@Override
public String toString() {
return "ItemHint{name='" + this.name + "', values=" + this.values + ", providers=" + this.providers + '}';
}
/**
* A hint for a value.
*/
public static class ValueHint {
private final Object value;
private final String description;
public ValueHint(Object value, String description) {
this.value = value;
this.description = description;
}
public Object getValue() {
return this.value;
}
public String getDescription() {
return this.description;
}
@Override
public String toString() {
return "ValueHint{value=" + this.value + ", description='" + this.description + '\'' + '}';
}
} | /**
* A value provider.
*/
public static class ValueProvider {
private final String name;
private final Map<String, Object> parameters;
public ValueProvider(String name, Map<String, Object> parameters) {
this.name = name;
this.parameters = parameters;
}
public String getName() {
return this.name;
}
public Map<String, Object> getParameters() {
return this.parameters;
}
@Override
public String toString() {
return "ValueProvider{name='" + this.name + "', parameters=" + this.parameters + '}';
}
}
} | repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\metadata\ItemHint.java | 2 |
请完成以下Java代码 | static class SortMapper {
protected static Map<String, Consumer<FetchAndLockBuilder>> FIELD_MAPPINGS = Map.of(
"createTime", FetchAndLockBuilder::orderByCreateTime
);
protected static Map<String, Consumer<FetchAndLockBuilder>> ORDER_MAPPINGS = Map.of(
"asc", FetchAndLockBuilder::asc,
"desc", FetchAndLockBuilder::desc
);
protected final List<SortingDto> sorting;
protected final FetchAndLockBuilder builder;
protected SortMapper(List<SortingDto> sorting, FetchAndLockBuilder builder) {
this.sorting = (sorting == null) ? Collections.emptyList() : sorting;
this.builder = builder;
}
/**
* Applies the sorting field mappings to the builder and returns it.
*/
protected FetchAndLockBuilder getBuilderWithSortConfigs() {
for (SortingDto dto : sorting) {
String sortBy = dto.getSortBy();
configureFieldOrBadRequest(sortBy, "sortBy", FIELD_MAPPINGS);
String sortOrder = dto.getSortOrder(); | if (sortOrder != null) {
configureFieldOrBadRequest(sortOrder, "sortOrder", ORDER_MAPPINGS);
}
}
return builder;
}
protected void configureFieldOrBadRequest(String key, String parameterName, Map<String, Consumer<FetchAndLockBuilder>> fieldMappings) {
if (!fieldMappings.containsKey(key)) {
throw new InvalidRequestException(BAD_REQUEST, "Cannot set query " + parameterName + " parameter to value " + key);
}
fieldMappings.get(key).accept(builder);
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\externaltask\FetchExternalTasksDto.java | 1 |
请完成以下Java代码 | public Object getCredentials() {
return this.getPassword();
}
@Override
public String getHost() {
return this.host;
}
@Override
public void setHost(String host) {
this.host = host;
}
@Override
public boolean isRememberMe() {
return this.rememberMe;
}
@Override
public void setRememberMe(boolean rememberMe) {
this.rememberMe = rememberMe;
} | public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
@Override
public void clear() {
super.clear();
this.accessToken = null;
}
} | repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\shiro\credentials\ThirdPartySupportedToken.java | 1 |
请完成以下Java代码 | private JWKSet parse(String body) {
try {
return JWKSet.parse(body);
}
catch (ParseException ex) {
throw new RuntimeException(ex);
}
}
/**
* Returns the first specified key ID (kid) for a JWK matcher.
* @param jwkMatcher The JWK matcher. Must not be {@code null}.
* @return The first key ID, {@code null} if none.
*/
protected static String getFirstSpecifiedKeyID(final JWKMatcher jwkMatcher) {
Set<String> keyIDs = jwkMatcher.getKeyIDs(); | if (keyIDs == null || keyIDs.isEmpty()) {
return null;
}
for (String id : keyIDs) {
if (id != null) {
return id;
}
}
return null; // No kid in matcher
}
void setWebClient(WebClient webClient) {
this.webClient = webClient;
}
} | repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\ReactiveRemoteJWKSource.java | 1 |
请完成以下Java代码 | public final class EnclosedInSquareBracketsConverter extends LogEventPatternConverter {
private final List<PatternFormatter> formatters;
private EnclosedInSquareBracketsConverter(List<PatternFormatter> formatters) {
super("enclosedInSquareBrackets", null);
this.formatters = formatters;
}
@Override
public void format(LogEvent event, StringBuilder toAppendTo) {
StringBuilder buf = new StringBuilder();
for (PatternFormatter formatter : this.formatters) {
formatter.format(event, buf);
}
if (buf.isEmpty()) {
return;
}
toAppendTo.append("[");
toAppendTo.append(buf); | toAppendTo.append("] ");
}
/**
* Creates a new instance of the class. Required by Log4J2.
* @param config the configuration
* @param options the options
* @return a new instance, or {@code null} if the options are invalid
*/
public static @Nullable EnclosedInSquareBracketsConverter newInstance(@Nullable Configuration config,
String[] options) {
if (options.length < 1) {
LOGGER.error("Incorrect number of options on style. Expected at least 1, received {}", options.length);
return null;
}
PatternParser parser = PatternLayout.createPatternParser(config);
List<PatternFormatter> formatters = parser.parse(options[0]);
return new EnclosedInSquareBracketsConverter(formatters);
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\log4j2\EnclosedInSquareBracketsConverter.java | 1 |
请完成以下Java代码 | public static LinkedList<Integer>[] createUsingRawArray() {
@SuppressWarnings("unchecked") LinkedList<Integer>[] groups = new LinkedList[3];
for (int i = 0; i < groups.length; i++) {
groups[i] = new LinkedList<>();
}
return groups;
}
public static ArrayList<LinkedList<Integer>> createUsingArrayList() {
ArrayList<LinkedList<Integer>> groups = new ArrayList<>();
for (int i = 0; i < 3; i++) {
groups.add(new LinkedList<>());
}
return groups;
} | public static ArrayList<LinkedList<Integer>> createUsingStreams() {
ArrayList<LinkedList<Integer>> groups = new ArrayList<>();
IntStream.range(0, 3)
.forEach(i -> groups.add(new LinkedList<>()));
return groups;
}
public static LinkedList<Integer>[] createUsingSetAll() {
@SuppressWarnings("unchecked") LinkedList<Integer>[] groups = new LinkedList[3];
Arrays.setAll(groups, i -> new LinkedList<>());
return groups;
}
} | repos\tutorials-master\core-java-modules\core-java-collections-list-8\src\main\java\com\baeldung\linkedlistarray\LinkedListArray.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Delivery {
protected String day;
protected Integer dateFrom;
protected Integer dateTo;
protected Integer timeFrom;
protected Integer timeTo;
/**
* Gets the value of the day property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDay() {
return day;
}
/**
* Sets the value of the day property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDay(String value) {
this.day = value;
}
/**
* Gets the value of the dateFrom property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getDateFrom() {
return dateFrom;
}
/**
* Sets the value of the dateFrom property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setDateFrom(Integer value) {
this.dateFrom = value;
}
/**
* Gets the value of the dateTo property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getDateTo() {
return dateTo;
}
/**
* Sets the value of the dateTo property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setDateTo(Integer value) {
this.dateTo = value;
}
/**
* Gets the value of the timeFrom property.
*
* @return
* possible object is
* {@link Integer }
* | */
public Integer getTimeFrom() {
return timeFrom;
}
/**
* Sets the value of the timeFrom property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setTimeFrom(Integer value) {
this.timeFrom = value;
}
/**
* Gets the value of the timeTo property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getTimeTo() {
return timeTo;
}
/**
* Sets the value of the timeTo property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setTimeTo(Integer value) {
this.timeTo = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\Delivery.java | 2 |
请在Spring Boot框架中完成以下Java代码 | ProblemDetail handle(IllegalArgumentException e) {
log.info(e.getMessage(), e);
return ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, e.getMessage());
}
@ExceptionHandler(NoSuchElementException.class)
ProblemDetail handle(NoSuchElementException e) {
log.info(e.getMessage(), e);
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
}
@ExceptionHandler(AccessDeniedException.class)
ProblemDetail handle(AccessDeniedException e) {
log.info(e.getMessage(), e);
return ProblemDetail.forStatusAndDetail(HttpStatus.FORBIDDEN, e.getMessage());
}
@ExceptionHandler(AuthenticationException.class)
ProblemDetail handle(AuthenticationException e) { | log.info(e.getMessage(), e);
return ProblemDetail.forStatusAndDetail(HttpStatus.UNAUTHORIZED, e.getMessage());
}
/**
* Errors that the developer did not expect are handled here and the log level is recorded as error.
*
* @param e Exception
* @return ProblemDetail
*/
@ExceptionHandler(Exception.class)
ProblemDetail handle(Exception e) {
log.error(e.getMessage(), e);
return ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR, "Please contact the administrator.");
}
} | repos\realworld-java21-springboot3-main\server\api\src\main\java\io\zhc1\realworld\config\ApplicationExceptionHandler.java | 2 |
请完成以下Java代码 | public class DelegateExpressionUtil {
public static Object resolveDelegateExpression(Expression expression,
VariableContainer variableContainer, List<FieldExtension> fieldExtensions) {
// Note: we can't cache the result of the expression, because the
// execution can change: eg. delegateExpression='${mySpringBeanFactory.randomSpringBean()}'
Object delegate = expression.getValue(variableContainer);
if (fieldExtensions != null && fieldExtensions.size() > 0) {
DelegateExpressionFieldInjectionMode injectionMode = CommandContextUtil.getCmmnEngineConfiguration().getDelegateExpressionFieldInjectionMode();
if (injectionMode == DelegateExpressionFieldInjectionMode.COMPATIBILITY) {
applyFieldExtensions(fieldExtensions, delegate, variableContainer, true);
} else if (injectionMode == DelegateExpressionFieldInjectionMode.MIXED) {
applyFieldExtensions(fieldExtensions, delegate, variableContainer, false);
}
}
return delegate;
}
protected static void applyFieldExtensions(List<FieldExtension> fieldExtensions, Object target, VariableContainer variableContainer, boolean throwExceptionOnMissingField) {
if (fieldExtensions != null) {
for (FieldExtension fieldExtension : fieldExtensions) { | applyFieldExtension(fieldExtension, target, throwExceptionOnMissingField);
}
}
}
protected static void applyFieldExtension(FieldExtension fieldExtension, Object target, boolean throwExceptionOnMissingField) {
Object value = null;
if (fieldExtension.getExpression() != null) {
ExpressionManager expressionManager = CommandContextUtil.getCmmnEngineConfiguration().getExpressionManager();
value = expressionManager.createExpression(fieldExtension.getExpression());
} else {
value = new FixedValue(fieldExtension.getStringValue());
}
ReflectUtil.invokeSetterOrField(target, fieldExtension.getFieldName(), value, throwExceptionOnMissingField);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\util\DelegateExpressionUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Optional<JsonRequestBPartnerUpsertItem> mapCreatedUpdatedBy()
{
if (rootBPartnerIdForUsers == null || (createdBy == null && updatedBy == null))
{
return Optional.empty();
}
final JsonRequestContactUpsert.JsonRequestContactUpsertBuilder requestContactUpsert = JsonRequestContactUpsert.builder();
final Optional<JsonRequestContactUpsertItem> createdByContact = DataMapper.userToBPartnerContact(createdBy);
createdByContact.ifPresent(requestContactUpsert::requestItem);
DataMapper.userToBPartnerContact(updatedBy)
.filter(updatedByContact -> createdByContact.isEmpty() || !updatedByContact.getContactIdentifier().equals(createdByContact.get().getContactIdentifier()))
.ifPresent(requestContactUpsert::requestItem);
final JsonRequestComposite jsonRequestComposite = JsonRequestComposite.builder()
.contacts(requestContactUpsert.build())
.build();
return Optional.of(JsonRequestBPartnerUpsertItem
.builder()
.bpartnerIdentifier(String.valueOf(rootBPartnerIdForUsers.getValue()))
.bpartnerComposite(jsonRequestComposite)
.build());
}
@Value
@Builder | public static class BPartnerRequestProducerResult
{
@NonNull
String patientBPartnerIdentifier;
@NonNull
String patientMainAddressIdentifier;
@NonNull
Map<String, JsonBPRelationRole> bPartnerIdentifier2RelationRole;
@NonNull
JsonRequestBPartnerUpsert jsonRequestBPartnerUpsert;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\patient\BPartnerUpsertRequestProducer.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public int getId() {
return id;
}
/**
* Sets the value of the id property.
*
*/
public void setId(int value) {
this.id = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
} | /**
* Gets the value of the passportNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPassportNumber() {
return passportNumber;
}
/**
* Sets the value of the passportNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPassportNumber(String value) {
this.passportNumber = value;
}
} | repos\spring-boot-examples-master\spring-boot-tutorial-soap-web-services\src\main\java\com\in28minutes\students\StudentDetails.java | 2 |
请完成以下Java代码 | public I_C_UOM getUom()
{
final UomId uomId = getUomId();
if (uomId == null)
{
return null;
}
final IUOMDAO uomDAO = Services.get(IUOMDAO.class);
return uomDAO.getById(uomId);
}
@NonNull
public I_C_UOM getUomNotNull()
{
return Check.assumeNotNull(getUom(), "Expecting UOM to always be present when using this method!");
}
public boolean isReceipt()
{
return getType().canReceive();
}
public boolean isIssue()
{
return getType().canIssue();
}
public boolean isHUStatusActive()
{
return huStatus != null && X_M_HU.HUSTATUS_Active.equals(huStatus.getKey());
}
@Override
public boolean hasAttributes()
{
return attributesSupplier != null;
}
@Override
public IViewRowAttributes getAttributes() throws EntityNotFoundException
{
if (attributesSupplier == null)
{
throw new EntityNotFoundException("This PPOrderLineRow does not support attributes; this=" + this); | }
final IViewRowAttributes attributes = attributesSupplier.get();
if (attributes == null)
{
throw new EntityNotFoundException("This PPOrderLineRow does not support attributes; this=" + this);
}
return attributes;
}
@Override
public HuUnitType getHUUnitTypeOrNull() {return huUnitType;}
@Override
public BPartnerId getBpartnerId() {return huBPartnerId;}
@Override
public boolean isTopLevel() {return topLevelHU;}
@Override
public Stream<HUReportAwareViewRow> streamIncludedHUReportAwareRows() {return getIncludedRows().stream().map(PPOrderLineRow::toHUReportAwareViewRow);}
private HUReportAwareViewRow toHUReportAwareViewRow() {return this;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\PPOrderLineRow.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.