instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public void addToDesadv(final I_M_InOut inOut)
{
if (Services.get(IHUInOutBL.class).isCustomerReturn(inOut))
{
// no EDI for customer return (for the time being)
return;
}
final IEDIDocumentBL ediDocumentBL = Services.get(IEDIDocumentBL.class);
if (!ediDocumentBL.updateEdiEnabled(inOut))
{
return;
}
if (inOut.getEDI_Desadv_ID() <= 0
&& Check.isNotBlank(inOut.getPOReference())) // task 08619: only try if we have a POReference and thus can succeed
{
Services.get(IDesadvBL.class).addToDesadvCreateForInOutIfNotExist(inOut);
}
}
/**
|
* Calls {@link IDesadvBL#removeInOutFromDesadv(I_M_InOut)} to detach the given inout from it's desadv (if any) when it is reversed, reactivated etc. Also see
* {@link de.metas.handlingunits.model.validator.M_InOut#assertReActivationAllowed(org.compiere.model.I_M_InOut)}. Note that this method will also be fired if the inout's <code>C_Order</code> is reactivated.
*/
@DocValidate(timings = { ModelValidator.TIMING_BEFORE_REACTIVATE,
ModelValidator.TIMING_BEFORE_REVERSEACCRUAL,
ModelValidator.TIMING_BEFORE_REVERSECORRECT,
ModelValidator.TIMING_BEFORE_VOID })
public void removeFromDesadv(final I_M_InOut inOut)
{
if (inOut.getEDI_Desadv_ID() > 0)
{
Services.get(IDesadvBL.class).removeInOutFromDesadv(inOut);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\model\validator\M_InOut.java
| 1
|
请完成以下Java代码
|
public class RelationImpl extends ExpressionImpl implements Relation {
protected static ChildElementCollection<Column> columnCollection;
protected static ChildElementCollection<Row> rowCollection;
public RelationImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public Collection<Column> getColumns() {
return columnCollection.get(this);
}
public Collection<Row> getRows() {
return rowCollection.get(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Relation.class, DMN_ELEMENT_RELATION)
.namespaceUri(LATEST_DMN_NS)
.extendsType(Expression.class)
.instanceProvider(new ModelTypeInstanceProvider<Relation>() {
public Relation newInstance(ModelTypeInstanceContext instanceContext) {
|
return new RelationImpl(instanceContext);
}
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
columnCollection = sequenceBuilder.elementCollection(Column.class)
.build();
rowCollection = sequenceBuilder.elementCollection(Row.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\RelationImpl.java
| 1
|
请完成以下Java代码
|
public String getCaseInstanceId() {
return caseInstanceId;
}
public Set<String> getCaseInstanceIds() {
return caseInstanceIds;
}
public String getStartedBy() {
return createdBy;
}
public String getSuperCaseInstanceId() {
return superCaseInstanceId;
}
public void setSuperCaseInstanceId(String superCaseInstanceId) {
this.superCaseInstanceId = superCaseInstanceId;
}
public List<String> getCaseKeyNotIn() {
return caseKeyNotIn;
}
public Date getCreatedAfter() {
return createdAfter;
}
public Date getCreatedBefore() {
return createdBefore;
}
public Date getClosedAfter() {
|
return closedAfter;
}
public Date getClosedBefore() {
return closedBefore;
}
public String getSubCaseInstanceId() {
return subCaseInstanceId;
}
public String getSuperProcessInstanceId() {
return superProcessInstanceId;
}
public String getSubProcessInstanceId() {
return subProcessInstanceId;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricCaseInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
private HUAttributeQueryFilterVO getOrCreateAttributeFilterVO(
@NonNull final Map<AttributeId, HUAttributeQueryFilterVO> targetMap,
@NonNull final I_M_Attribute attribute,
@Nullable final String attributeValueType)
{
final HUAttributeQueryFilterVO attributeFilterVO = targetMap.computeIfAbsent(
AttributeId.ofRepoId(attribute.getM_Attribute_ID()),
k -> new HUAttributeQueryFilterVO(attribute, attributeValueType));
if (attributeValueType != HUAttributeQueryFilterVO.ATTRIBUTEVALUETYPE_Unknown)
{
attributeFilterVO.assertAttributeValueType(attributeValueType);
}
return attributeFilterVO;
}
public boolean matches(@NonNull final IAttributeSet attributes)
{
// If there is no attribute restrictions we can accept this "attributes" right away
if (onlyAttributes == null || onlyAttributes.isEmpty())
{
return true;
}
for (final HUAttributeQueryFilterVO attributeFilter : onlyAttributes.values())
{
if (!attributeFilter.matches(attributes))
{
return false;
}
}
return true;
}
public void setBarcode(final String barcode)
{
this.barcode = barcode != null ? barcode.trim() : null;
}
private Collection<HUAttributeQueryFilterVO> createBarcodeHUAttributeQueryFilterVOs()
{
if (Check.isEmpty(barcode, true))
{
return ImmutableList.of();
}
|
final HashMap<AttributeId, HUAttributeQueryFilterVO> filterVOs = new HashMap<>();
for (final I_M_Attribute attribute : getBarcodeAttributes())
{
final HUAttributeQueryFilterVO barcodeAttributeFilterVO = getOrCreateAttributeFilterVO(
filterVOs,
attribute,
HUAttributeQueryFilterVO.ATTRIBUTEVALUETYPE_Unknown);
barcodeAttributeFilterVO.addValue(barcode);
}
return filterVOs.values();
}
private List<I_M_Attribute> getBarcodeAttributes()
{
final IDimensionspecDAO dimensionSpecsRepo = Services.get(IDimensionspecDAO.class);
final DimensionSpec barcodeDimSpec = dimensionSpecsRepo.retrieveForInternalNameOrNull(HUConstants.DIM_Barcode_Attributes);
if (barcodeDimSpec == null)
{
return ImmutableList.of(); // no barcode dimension spec. Nothing to do
}
return barcodeDimSpec.retrieveAttributes()
.stream()
// Barcode must be a String attribute. In the database, this is forced by a validation rule
.filter(attribute -> attribute.getAttributeValueType().equals(X_M_Attribute.ATTRIBUTEVALUETYPE_StringMax40))
.collect(ImmutableList.toImmutableList());
}
public void setAllowSql(final boolean allowSql)
{
this.allowSql = allowSql;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUQueryBuilder_Attributes.java
| 1
|
请完成以下Java代码
|
protected DmnParse createDmnParseFromResource(EngineResource resource) {
String resourceName = resource.getName();
ByteArrayInputStream inputStream = new ByteArrayInputStream(resource.getBytes());
DmnParse dmnParse = dmnParseFactory.createParse()
.sourceInputStream(inputStream)
.setSourceSystemId(resourceName)
.deployment(deployment)
.name(resourceName);
if (deploymentSettings != null) {
// Schema validation if needed
if (deploymentSettings.containsKey(DeploymentSettings.IS_DMN_XSD_VALIDATION_ENABLED)) {
dmnParse.setValidateSchema((Boolean) deploymentSettings.get(DeploymentSettings.IS_DMN_XSD_VALIDATION_ENABLED));
}
} else {
// On redeploy, we assume it is validated at the first deploy
dmnParse.setValidateSchema(false);
}
dmnParse.execute(CommandContextUtil.getDmnEngineConfiguration());
return dmnParse;
}
protected void processDI(DmnDefinition dmnDefinition, List<DecisionEntity> decisions) {
if (decisions.isEmpty()) {
return;
}
if (!dmnDefinition.getLocationMap().isEmpty()) {
for (String dmnRef : dmnDefinition.getLocationMap().keySet()) {
if (dmnDefinition.getDecisionById(dmnRef) == null && dmnDefinition.getDecisionServiceById(dmnRef) == null) {
LOGGER.warn("Invalid reference in diagram interchange definition: could not find {}", dmnRef);
}
|
}
for (DecisionService decisionService : dmnDefinition.getDecisionServices()) {
DecisionEntity decision = getDecision(decisionService.getId(), decisions);
if (decision != null) {
decision.setHasGraphicalNotation(true);
}
}
}
}
public DecisionEntity getDecision(String decisionKey, List<DecisionEntity> decisions) {
for (DecisionEntity decision : decisions) {
if (decision.getKey().equals(decisionKey)) {
return decision;
}
}
return null;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\deployer\ParsedDeploymentBuilder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ILHandlerModelInterceptor extends AbstractModelInterceptor
{
IInvoiceCandidateHandler handler;
String tableName;
boolean isDocument;
DocTimingType createInvoiceCandidatesTiming;
CandidatesAutoCreateMode initialCandidatesAutoCreateMode;
CreateCandidatesOnCommitCollector collector = new CreateCandidatesOnCommitCollector();
public ILHandlerModelInterceptor(@NonNull final IInvoiceCandidateHandler handler)
{
this.handler = handler;
this.tableName = handler.getSourceTable();
this.initialCandidatesAutoCreateMode = handler.getGeneralCandidatesAutoCreateMode();
this.createInvoiceCandidatesTiming = handler.getAutomaticallyCreateMissingCandidatesDocTiming();
this.isDocument = Services.get(IDocumentBL.class).isDocumentTable(this.tableName);
}
@Override
protected void onInit(final IModelValidationEngine engine, final I_AD_Client client)
{
final boolean interceptDocValidate = isDocument && (initialCandidatesAutoCreateMode.isDoSomething());
final boolean interceptModelChange = (!isDocument && initialCandidatesAutoCreateMode.isDoSomething());
if (interceptDocValidate)
{
engine.addDocValidate(tableName, this);
}
if (interceptModelChange)
{
engine.addModelChange(tableName, this);
}
}
@Override
public void onDocValidate(@NonNull final Object model, @NonNull final DocTimingType timing)
{
Check.assume(isDocument, "isDocument flag is set"); // shall not happen
//
// Create missing invoice candidates for given document
if (timing == createInvoiceCandidatesTiming)
{
createMissingInvoiceCandidates(model);
}
}
@Override
public void onModelChange(@NonNull final Object model, @NonNull final ModelChangeType changeType)
|
{
//
// Create missing invoice candidates for given pseudo-document
if (!isDocument && changeType.isNewOrChange() && changeType.isAfter())
{
createMissingInvoiceCandidates(model);
}
}
/**
* Creates missing invoice candidates for given model, if this is enabled.
*/
private void createMissingInvoiceCandidates(@NonNull final Object model)
{
final CandidatesAutoCreateMode modeForCurrentModel = handler.getSpecificCandidatesAutoCreateMode(model);
switch (modeForCurrentModel)
{
case DONT: // just for completeness. we actually aren't called in this case
break;
case CREATE_CANDIDATES:
CreateMissingInvoiceCandidatesWorkpackageProcessor.schedule(model);
break;
case CREATE_CANDIDATES_AND_INVOICES:
generateIcsAndInvoices(model);
break;
}
}
private void generateIcsAndInvoices(@NonNull final Object model)
{
final TableRecordReference modelReference = TableRecordReference.of(model);
collector.collect(modelReference);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\modelvalidator\ilhandler\ILHandlerModelInterceptor.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
@ApiModelProperty(example = "http://localhost:8182/runtime/executions/7")
public String getExecutionUrl() {
return executionUrl;
}
public void setExecutionUrl(String executionUrl) {
this.executionUrl = executionUrl;
}
@ApiModelProperty(example = "timer")
public String getElementId() {
return elementId;
}
public void setElementId(String elementId) {
this.elementId = elementId;
}
@ApiModelProperty(example = "Timer task")
public String getElementName() {
return elementName;
}
public void setElementName(String elementName) {
this.elementName = elementName;
}
@ApiModelProperty(example = "trigger-timer")
public String getHandlerType() {
return handlerType;
}
public void setHandlerType(String handlerType) {
this.handlerType = handlerType;
}
@ApiModelProperty(example = "3")
public Integer getRetries() {
return retries;
}
public void setRetries(Integer retries) {
this.retries = retries;
}
@ApiModelProperty(example = "null")
public String getExceptionMessage() {
return exceptionMessage;
}
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = exceptionMessage;
|
}
@ApiModelProperty(example = "2023-06-04T22:05:05.474+0000")
public Date getDueDate() {
return dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
@ApiModelProperty(example = "2023-06-03T22:05:05.474+0000")
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@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;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\management\JobResponse.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
class ApplicationConfiguration {
/**
* Register the {@link BeforeConvertCallback} used to update an {@link ImmutablePerson} before handing over the newly
* created instance to the actual mapping layer performing the conversion into the store native
* {@link org.bson.Document} representation.
*
* @return a {@link BeforeConvertCallback} for {@link ImmutablePerson}.
*/
@Bean
BeforeConvertCallback<ImmutablePerson> beforeConvertCallback() {
return (immutablePerson, collection) -> {
var randomNumber = ThreadLocalRandom.current().nextInt(1, 100);
// withRandomNumber is a so-called wither method returning a new instance of the entity with a new value assigned
return immutablePerson.withRandomNumber(randomNumber);
};
}
|
/**
* Register the {@link BeforeConvertCallback} used to update an {@link ImmutableRecord} before handing over the newly
* created instance to the actual mapping layer performing the conversion into the store native
* {@link org.bson.Document} representation.
*
* @return a {@link BeforeConvertCallback} for {@link ImmutablePerson}.
*/
@Bean
BeforeConvertCallback<ImmutableRecord> beforeRecordConvertCallback() {
return (rec, collection) -> {
var randomNumber = ThreadLocalRandom.current().nextInt(1, 100);
return new ImmutableRecord(rec.id(), randomNumber);
};
}
}
|
repos\spring-data-examples-main\mongodb\example\src\main\java\example\springdata\mongodb\immutable\ApplicationConfiguration.java
| 2
|
请完成以下Java代码
|
public void setClassname (String Classname)
{
set_Value (COLUMNNAME_Classname, Classname);
}
/** Get Classname.
@return Java Classname
*/
public String getClassname ()
{
return (String)get_Value(COLUMNNAME_Classname);
}
/** Set Beschreibung.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Direction AD_Reference_ID=540086 */
public static final int DIRECTION_AD_Reference_ID=540086;
/** Import = I */
public static final String DIRECTION_Import = "I";
/** Export = E */
public static final String DIRECTION_Export = "E";
/** Set Richtung.
@param Direction Richtung */
public void setDirection (String Direction)
{
set_Value (COLUMNNAME_Direction, Direction);
}
/** Get Richtung.
@return Richtung */
public String getDirection ()
{
return (String)get_Value(COLUMNNAME_Direction);
}
/** Set Konnektor-Typ.
@param ImpEx_ConnectorType_ID Konnektor-Typ */
public void setImpEx_ConnectorType_ID (int ImpEx_ConnectorType_ID)
{
if (ImpEx_ConnectorType_ID < 1)
set_ValueNoCheck (COLUMNNAME_ImpEx_ConnectorType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ImpEx_ConnectorType_ID, Integer.valueOf(ImpEx_ConnectorType_ID));
}
/** Get Konnektor-Typ.
@return Konnektor-Typ */
public int getImpEx_ConnectorType_ID ()
{
|
Integer ii = (Integer)get_Value(COLUMNNAME_ImpEx_ConnectorType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\impex\model\X_ImpEx_ConnectorType.java
| 1
|
请完成以下Java代码
|
public int getAD_PInstance_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_PInstance_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
|
return ii.intValue();
}
/** Set Temporal MRP & CRP.
@param T_MRP_CRP_ID Temporal MRP & CRP */
public void setT_MRP_CRP_ID (int T_MRP_CRP_ID)
{
if (T_MRP_CRP_ID < 1)
set_ValueNoCheck (COLUMNNAME_T_MRP_CRP_ID, null);
else
set_ValueNoCheck (COLUMNNAME_T_MRP_CRP_ID, Integer.valueOf(T_MRP_CRP_ID));
}
/** Get Temporal MRP & CRP.
@return Temporal MRP & CRP */
public int getT_MRP_CRP_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_T_MRP_CRP_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\eevolution\model\X_T_MRP_CRP.java
| 1
|
请完成以下Java代码
|
private static boolean isQRR(@NonNull final I_ESR_ImportLine importLine)
{
return ESRType.TYPE_QRR.getCode().equals(importLine.getType());
}
private boolean existsPostFinanceUserNumberFitsPostAcctNo(final List<I_ESR_PostFinanceUserNumber> postFinanceUserNumbers, @NonNull final String postAcctNo)
{
if (Check.isEmpty(postFinanceUserNumbers))
{
return false;
}
for (final I_ESR_PostFinanceUserNumber postFinanceUserNumber : postFinanceUserNumbers)
{
// Provide support for both rendered and unrendered esr account numbers
final String esrAcctNo = postFinanceUserNumber.getESR_RenderedAccountNo();
if (postAcctNo.equals(esrAcctNo))
{
return true;
}
if (esrAcctNo.contains("-"))
{
final String unrenderedESRAcctNo = unrenderPostAccountNo(esrAcctNo);
|
if (postAcctNo.equals(unrenderedESRAcctNo))
{
return true;
}
}
}
return false;
}
private String unrenderPostAccountNo(final String renderedPostAccountNo)
{
final String[] renderenNoComponents = renderedPostAccountNo.split("-");
Check.assume(renderenNoComponents.length == 3, renderedPostAccountNo + " contains three '-' separated parts");
final StringBuilder sb = new StringBuilder();
sb.append(renderenNoComponents[0]);
sb.append(StringUtils.lpadZero(renderenNoComponents[1], 6, "middle section of " + renderedPostAccountNo));
sb.append(renderenNoComponents[2]);
return sb.toString();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\dataimporter\ESRDataLoaderUtil.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public CommonErrorHandler errorHandler(KafkaOperations<Object, Object> template) {
return new DefaultErrorHandler(
new DeadLetterPublishingRecoverer(template), new FixedBackOff(1000L, 2));
}
@Bean
public RecordMessageConverter converter() {
return new JsonMessageConverter();
}
@KafkaListener(id = "fooGroup", topics = "topic1")
public void listen(Foo2 foo) {
logger.info("Received: " + foo);
if (foo.getFoo().startsWith("fail")) {
throw new RuntimeException("failed");
}
this.exec.execute(() -> System.out.println("Hit Enter to terminate..."));
}
@KafkaListener(id = "dltGroup", topics = "topic1-dlt")
public void dltListen(byte[] in) {
logger.info("Received from DLT: " + new String(in));
this.exec.execute(() -> System.out.println("Hit Enter to terminate..."));
|
}
@Bean
public NewTopic topic() {
return new NewTopic("topic1", 1, (short) 1);
}
@Bean
public NewTopic dlt() {
return new NewTopic("topic1-dlt", 1, (short) 1);
}
@Bean
@Profile("default") // Don't run from test(s)
public ApplicationRunner runner() {
return args -> {
System.out.println("Hit Enter to terminate...");
System.in.read();
};
}
}
|
repos\spring-kafka-main\samples\sample-01\src\main\java\com\example\Application.java
| 2
|
请完成以下Java代码
|
private void updateFlatrateTermPartner(final I_C_Flatrate_Term term)
{
final ImmutableList<I_C_Flatrate_Term> nextTerms = flatrateBL.retrieveNextFlatrateTerms(term);
updateFlatrateTermBillBPartner(term);
nextTerms.forEach(this::updateFlatrateTermBillBPartner);
}
private void updateFlatrateTermBillBPartner(final I_C_Flatrate_Term term)
{
final BPartnerId bPartnerId = BPartnerId.ofRepoId(p_billBPartnerId);
final BPartnerLocationId bPartnerLocationId = BPartnerLocationId.ofRepoId(p_billBPartnerId, p_billLocationId);
final BPartnerContactId bPartnerContactId = BPartnerContactId.ofRepoIdOrNull(p_billBPartnerId, p_billUserId);
|
final boolean termHasInvoices = C_Flatrate_Term_Change_ProcessHelper.termHasInvoices(term);
final FlatrateTermBillPartnerRequest request = FlatrateTermBillPartnerRequest.builder()
.flatrateTermId(FlatrateTermId.ofRepoId(term.getC_Flatrate_Term_ID()))
.billBPartnerId(bPartnerId)
.billLocationId(bPartnerLocationId)
.billUserId(bPartnerContactId)
.termHasInvoices(termHasInvoices)
.build();
flatrateBL.updateFlatrateTermBillBPartner(request);
}
protected abstract ImmutableList<I_C_Flatrate_Term> getFlatrateTermsToChange();
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\process\C_Flatrate_Term_Change_BillPartner_Base.java
| 1
|
请完成以下Java代码
|
void shutDownGracefully(GracefulShutdownCallback callback) {
this.webServer.shutDownGracefully(callback);
}
void stop() {
this.webServer.stop();
}
WebServer getWebServer() {
return this.webServer;
}
HttpHandler getHandler() {
return this.handler;
}
/**
* A delayed {@link HttpHandler} that doesn't initialize things too early.
*/
static final class DelayedInitializationHttpHandler implements HttpHandler {
private final Supplier<HttpHandler> handlerSupplier;
private final boolean lazyInit;
private volatile HttpHandler delegate = this::handleUninitialized;
private DelayedInitializationHttpHandler(Supplier<HttpHandler> handlerSupplier, boolean lazyInit) {
this.handlerSupplier = handlerSupplier;
this.lazyInit = lazyInit;
}
private Mono<Void> handleUninitialized(ServerHttpRequest request, ServerHttpResponse response) {
throw new IllegalStateException("The HttpHandler has not yet been initialized");
}
@Override
public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
return this.delegate.handle(request, response);
}
void initializeHandler() {
this.delegate = this.lazyInit ? new LazyHttpHandler(this.handlerSupplier) : this.handlerSupplier.get();
}
HttpHandler getHandler() {
return this.delegate;
|
}
}
/**
* {@link HttpHandler} that initializes its delegate on first request.
*/
private static final class LazyHttpHandler implements HttpHandler {
private final Mono<HttpHandler> delegate;
private LazyHttpHandler(Supplier<HttpHandler> handlerSupplier) {
this.delegate = Mono.fromSupplier(handlerSupplier);
}
@Override
public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
return this.delegate.flatMap((handler) -> handler.handle(request, response));
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\reactive\context\WebServerManager.java
| 1
|
请完成以下Java代码
|
public String getEventKey() {
return eventKey;
}
public void setEventKey(String eventKey) {
this.eventKey = eventKey;
}
@Override
public Collection<EventPayloadInstance> getPayloadInstances() {
return payloadInstances;
}
public void setPayloadInstances(Collection<EventPayloadInstance> payloadInstances) {
this.payloadInstances = payloadInstances;
}
@Override
public Collection<EventPayloadInstance> getHeaderInstances() {
return headerInstances;
}
public void setHeaderInstances(Collection<EventPayloadInstance> headerInstances) {
this.headerInstances = headerInstances;
}
@Override
public Collection<EventPayloadInstance> getCorrelationParameterInstances() {
return correlationPayloadInstances;
}
public void setCorrelationParameterInstances(Collection<EventPayloadInstance> correlationParameterInstances) {
this.correlationPayloadInstances = correlationParameterInstances;
}
|
@Override
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("EventInstance[eventKey=").append(eventKey);
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
sb.append("]");
return sb.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\runtime\EventInstanceImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private AttributesKey getAttributesKey(@NonNull final HUItemToGroup hu)
{
final IAttributeStorage attributeStorage = attributeStorageFactory.getAttributeStorage(hu.getHu());
final Set<AttributeId> attributeIds = hu.getAttributesAssumingGroupingIsEnabled();
final Predicate<I_M_Attribute> qrMatchingRelevantAttributes =
attribute -> attributeIds.contains(AttributeId.ofRepoId(attribute.getM_Attribute_ID()));
final ImmutableAttributeSet requestedAttributeSet = ImmutableAttributeSet.createSubSet(attributeStorage, qrMatchingRelevantAttributes);
return AttributesKeys
.createAttributesKeyFromAttributeSet(requestedAttributeSet)
.orElse(AttributesKey.NONE);
}
@NonNull
private static ImmutableSet<HuId> getHuIds(@NonNull final Collection<HUItemToGroup> hus)
{
return hus.stream()
.map(HUItemToGroup::getHuId)
.collect(ImmutableSet.toImmutableSet());
}
@Value(staticConstructor = "ofBuildKeyFunction")
private static class GroupBuilder
{
@NonNull Function<HUItemToGroup, GroupKey> buildKeyFunction;
@NonNull Map<GroupKey, ImmutableList.Builder<HUItemToGroup>> key2Group = new HashMap<>();
public GroupBuilder addAllToGroups(@NonNull final Collection<HUItemToGroup> items)
{
items.forEach(this::addToGroup);
return this;
}
private void addToGroup(@NonNull final HUItemToGroup huItemToGroup)
{
final GroupKey groupKey = buildKeyFunction.apply(huItemToGroup);
final ImmutableList.Builder<HUItemToGroup> huGroup = key2Group.getOrDefault(groupKey, ImmutableList.builder());
huGroup.add(huItemToGroup);
key2Group.put(groupKey, huGroup);
}
@NonNull
public ImmutableList<ImmutableList<HUItemToGroup>> buildGroups()
{
return key2Group.values()
.stream()
.map(ImmutableList.Builder::build)
.collect(ImmutableList.toImmutableList());
}
}
@Value
@Builder
private static class HUItemToGroup
{
@NonNull I_M_HU hu;
@NonNull ProductId productId;
|
@Nullable QRCodeConfiguration productQrCodeConfiguration;
@NonNull
public HuId getHuId()
{
return HuId.ofRepoId(hu.getM_HU_ID());
}
@NonNull
public Set<AttributeId> getAttributesAssumingGroupingIsEnabled()
{
Check.assume(isGroupingByMatchingAttributesEnabled(), "Assuming grouping by attributes is enabled!");
return productQrCodeConfiguration.getGroupByAttributeIds();
}
public boolean isGroupingByMatchingAttributesEnabled()
{
return productQrCodeConfiguration != null && productQrCodeConfiguration.isGroupingByAttributesEnabled();
}
}
private interface GroupKey {}
@Value
@Builder
private static class TUGroupKey implements GroupKey
{
@NonNull ProductId productId;
@NonNull HuPackingInstructionsId packingInstructionsId;
@NonNull AttributesKey attributesKey;
}
@Value(staticConstructor = "ofHuId")
private static class SingleGroupKey implements GroupKey
{
@NonNull HuId huId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\service\HUQRCodeGenerateForExistingHUsCommand.java
| 2
|
请完成以下Java代码
|
public static Integer getSumUsingCollect(List<Integer> integers) {
return integers.stream()
.collect(Collectors.summingInt(Integer::intValue));
}
public static Integer getSumUsingSum(List<Integer> integers) {
return integers.stream()
.mapToInt(Integer::intValue)
.sum();
}
public static Integer getSumOfMapValues(Map<Object, Integer> map) {
return map.values()
|
.stream()
.mapToInt(Integer::valueOf)
.sum();
}
public static Integer getSumIntegersFromString(String str) {
Integer sum = Arrays.stream(str.split(" "))
.filter((s) -> s.matches("\\d+"))
.mapToInt(Integer::valueOf)
.sum();
return sum;
}
}
|
repos\tutorials-master\core-java-modules\core-java-streams\src\main\java\com\baeldung\stream\sum\StreamSumCalculator.java
| 1
|
请完成以下Java代码
|
public String getProductValue ()
{
return (String)get_Value(COLUMNNAME_ProductValue);
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
|
}
/** Set UOM Code.
@param X12DE355
UOM EDI X12 Code
*/
public void setX12DE355 (String X12DE355)
{
set_Value (COLUMNNAME_X12DE355, X12DE355);
}
/** Get UOM Code.
@return UOM EDI X12 Code
*/
public String getX12DE355 ()
{
return (String)get_Value(COLUMNNAME_X12DE355);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_PriceList.java
| 1
|
请完成以下Java代码
|
public RouterFunctions.Builder before(Function<ServerRequest, ServerRequest> requestProcessor) {
builder.before(requestProcessor);
return this;
}
@Override
public <T extends ServerResponse, R extends ServerResponse> RouterFunctions.Builder after(
BiFunction<ServerRequest, T, R> responseProcessor) {
builder.after(responseProcessor);
return this;
}
@Override
public <T extends ServerResponse> RouterFunctions.Builder onError(Predicate<Throwable> predicate,
BiFunction<Throwable, ServerRequest, T> responseProvider) {
builder.onError(predicate, responseProvider);
return this;
}
@Override
public <T extends ServerResponse> RouterFunctions.Builder onError(Class<? extends Throwable> exceptionType,
BiFunction<Throwable, ServerRequest, T> responseProvider) {
builder.onError(exceptionType, responseProvider);
return this;
|
}
@Override
public RouterFunctions.Builder withAttribute(String name, Object value) {
builder.withAttribute(name, value);
return this;
}
@Override
public RouterFunctions.Builder withAttributes(Consumer<Map<String, Object>> attributesConsumer) {
builder.withAttributes(attributesConsumer);
return this;
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\GatewayRouterFunctionsBuilder.java
| 1
|
请完成以下Java代码
|
public void setLabelHeight (int LabelHeight)
{
set_Value (COLUMNNAME_LabelHeight, Integer.valueOf(LabelHeight));
}
/** Get Label Height.
@return Height of the label
*/
public int getLabelHeight ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_LabelHeight);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Label Width.
@param LabelWidth
Width of the Label
*/
public void setLabelWidth (int LabelWidth)
{
set_Value (COLUMNNAME_LabelWidth, Integer.valueOf(LabelWidth));
}
/** Get Label Width.
@return Width of the Label
*/
public int getLabelWidth ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_LabelWidth);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
|
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Printer Name.
@param PrinterName
Name of the Printer
*/
public void setPrinterName (String PrinterName)
{
set_Value (COLUMNNAME_PrinterName, PrinterName);
}
/** Get Printer Name.
@return Name of the Printer
*/
public String getPrinterName ()
{
return (String)get_Value(COLUMNNAME_PrinterName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintLabel.java
| 1
|
请完成以下Java代码
|
public String getDocumentInfo()
{
MDocType dt = MDocType.get(getCtx(), getC_DocType_ID());
return dt.getName() + " " + getDocumentNo();
} // getDocumentInfo
/**
* Create PDF
*
* @return File or null
*/
@Override
public File createPDF()
{
return null;
}
/**
* Get Process Message
*
* @return clear text error message
*/
@Override
public String getProcessMsg()
{
return m_processMsg;
} // getProcessMsg
/**
* Get Document Owner (Responsible)
*
* @return AD_User_ID (Created)
*/
@Override
public int getDoc_User_ID()
{
return getCreatedBy();
} // getDoc_User_ID
/**
* Get Document Approval Amount
*
* @return DR amount
*/
|
@Override
public BigDecimal getApprovalAmt()
{
return getTotalDr();
} // getApprovalAmt
/**
* Document Status is Complete or Closed
*
* @return true if CO, CL or RE
*/
@Deprecated
public boolean isComplete()
{
return Services.get(IGLJournalBL.class).isComplete(this);
} // isComplete
// metas: cg: 02476
private static void setAmtPrecision(final I_GL_Journal journal)
{
final AcctSchemaId acctSchemaId = AcctSchemaId.ofRepoIdOrNull(journal.getC_AcctSchema_ID());
if (acctSchemaId == null)
{
return;
}
final AcctSchema as = Services.get(IAcctSchemaDAO.class).getById(acctSchemaId);
final CurrencyPrecision precision = as.getStandardPrecision();
final BigDecimal controlAmt = precision.roundIfNeeded(journal.getControlAmt());
journal.setControlAmt(controlAmt);
}
} // MJournal
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\model\MJournal.java
| 1
|
请完成以下Java代码
|
public void setM_Locator_ID(int M_Locator_ID)
{
if (M_Locator_ID < 0)
throw new IllegalArgumentException("M_Locator_ID is mandatory.");
// set to 0 explicitly to reset
set_Value(COLUMNNAME_M_Locator_ID, M_Locator_ID);
} // setM_Locator_ID
/**
* Set M_LocatorTo_ID
*
* @param M_LocatorTo_ID id
*/
@Override
public void setM_LocatorTo_ID(int M_LocatorTo_ID)
{
if (M_LocatorTo_ID < 0)
throw new IllegalArgumentException("M_LocatorTo_ID is mandatory.");
|
// set to 0 explicitly to reset
set_Value(COLUMNNAME_M_LocatorTo_ID, M_LocatorTo_ID);
} // M_LocatorTo_ID
@Override
public String toString()
{
return Table_Name + "[" + get_ID()
+ ", M_Product_ID=" + getM_Product_ID()
+ ", M_ASI_ID=" + getM_AttributeSetInstance_ID()
+ ", M_ASITo_ID=" + getM_AttributeSetInstanceTo_ID()
+ ", M_Locator_ID=" + getM_Locator_ID()
+ ", M_LocatorTo_ID=" + getM_LocatorTo_ID()
+ "]";
}
} // MMovementLine
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MMovementLine.java
| 1
|
请完成以下Java代码
|
public ImmutableSet<HuId> getHuIds()
{
return InventoryLineHU.extractHuIds(streamLineHUs());
}
public Inventory assigningTo(@NonNull final UserId newResponsibleId)
{
return assigningTo(newResponsibleId, false);
}
public Inventory reassigningTo(@NonNull final UserId newResponsibleId)
{
return assigningTo(newResponsibleId, true);
}
private Inventory assigningTo(@NonNull final UserId newResponsibleId, boolean allowReassignment)
{
// no responsible change
if (UserId.equals(responsibleId, newResponsibleId))
{
return this;
}
if (!newResponsibleId.isRegularUser())
{
throw new AdempiereException("Only regular users can be assigned to an inventory");
}
if (!allowReassignment && responsibleId != null)
{
throw new AdempiereException("Inventory is already assigned");
}
return toBuilder().responsibleId(newResponsibleId).build();
}
public Inventory unassign()
{
return responsibleId == null ? this : toBuilder().responsibleId(null).build();
}
public void assertHasAccess(@NonNull final UserId calledId)
{
if (!UserId.equals(responsibleId, calledId))
{
throw new AdempiereException("No access");
|
}
}
public Stream<InventoryLine> streamLines(@Nullable final InventoryLineId onlyLineId)
{
return onlyLineId != null
? Stream.of(getLineById(onlyLineId))
: lines.stream();
}
public Set<LocatorId> getLocatorIdsEligibleForCounting(@Nullable final InventoryLineId onlyLineId)
{
return streamLines(onlyLineId)
.filter(InventoryLine::isEligibleForCounting)
.map(InventoryLine::getLocatorId)
.collect(ImmutableSet.toImmutableSet());
}
public Inventory updatingLineById(@NonNull final InventoryLineId lineId, @NonNull UnaryOperator<InventoryLine> updater)
{
final ImmutableList<InventoryLine> newLines = CollectionUtils.map(
this.lines,
line -> InventoryLineId.equals(line.getId(), lineId) ? updater.apply(line) : line
);
return this.lines == newLines
? this
: toBuilder().lines(newLines).build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\Inventory.java
| 1
|
请完成以下Java代码
|
public static Passenger from(String firstName, String lastName) {
return new Passenger(firstName, lastName);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "Passenger{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + '}';
|
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Passenger passenger = (Passenger) o;
return Objects.equals(firstName, passenger.firstName) && Objects.equals(lastName, passenger.lastName);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName);
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-2\src\main\java\com\baeldung\jpa\domain\Passenger.java
| 1
|
请完成以下Java代码
|
/* package */ class ReplenishImportHelper
{
final public boolean isValidRecordForImport(@NonNull final I_I_Replenish importRecord)
{
return (importRecord.getM_Product_ID() > 0)
&& (importRecord.getM_Warehouse_ID() > 0)
&& (importRecord.getLevel_Max() != null)
&& (importRecord.getLevel_Min() != null)
&& (!Check.isEmpty(importRecord.getReplenishType(), true));
}
final public I_M_Replenish createNewReplenish(@NonNull final I_I_Replenish importRecord)
{
final I_M_Replenish replenish = InterfaceWrapperHelper.newInstance(I_M_Replenish.class, importRecord);
setReplenishmenttValueFields(importRecord, replenish);
return replenish;
}
final public I_M_Replenish uppdateReplenish(@NonNull final I_I_Replenish importRecord)
{
final I_M_Replenish replenish = importRecord.getM_Replenish();
setReplenishmenttValueFields(importRecord, replenish);
return replenish;
}
private void setReplenishmenttValueFields(@NonNull final I_I_Replenish importRecord, @NonNull final I_M_Replenish replenish)
{
// mandatory fields
replenish.setAD_Org_ID(importRecord.getAD_Org_ID());
replenish.setM_Product_ID(importRecord.getM_Product_ID());
replenish.setM_Warehouse_ID(importRecord.getM_Warehouse_ID());
replenish.setLevel_Max(importRecord.getLevel_Max());
replenish.setLevel_Min(importRecord.getLevel_Min());
replenish.setReplenishType(importRecord.getReplenishType());
replenish.setTimeToMarket(importRecord.getTimeToMarket());
// optional fields
|
if (importRecord.getM_Locator_ID() > 0)
{
replenish.setM_Locator_ID(importRecord.getM_Locator_ID());
}
if (importRecord.getC_Period_ID() > 0)
{
replenish.setC_Period_ID(importRecord.getC_Period_ID());
replenish.setC_Calendar_ID(getCalendar(importRecord.getC_Period()));
}
}
private int getCalendar(final I_C_Period period)
{
return period.getC_Year().getC_Calendar_ID();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\replenishment\impexp\ReplenishImportHelper.java
| 1
|
请完成以下Java代码
|
public int getC_Order_MFGWarehouse_ReportLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Order_MFGWarehouse_ReportLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Product getM_Product() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class);
}
@Override
public void setM_Product(org.compiere.model.I_M_Product M_Product)
{
set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product);
}
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
@Override
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
|
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_C_Order_MFGWarehouse_ReportLine.java
| 1
|
请完成以下Java代码
|
public void save(DataOutputStream out) throws IOException
{
out.writeInt(size);
for (int i = 0; i < size; i++)
{
out.writeInt(data[i]);
}
out.writeInt(linearExpandFactor);
out.writeBoolean(exponentialExpanding);
out.writeDouble(exponentialExpandFactor);
}
@Override
public boolean load(ByteArray byteArray)
{
if (byteArray == null)
{
return false;
}
size = byteArray.nextInt();
data = new int[size];
for (int i = 0; i < size; i++)
{
data[i] = byteArray.nextInt();
}
linearExpandFactor = byteArray.nextInt();
exponentialExpanding = byteArray.nextBoolean();
exponentialExpandFactor = byteArray.nextDouble();
return true;
}
|
private void writeObject(ObjectOutputStream out) throws IOException
{
loseWeight();
out.writeInt(size);
out.writeObject(data);
out.writeInt(linearExpandFactor);
out.writeBoolean(exponentialExpanding);
out.writeDouble(exponentialExpandFactor);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
{
size = in.readInt();
data = (int[]) in.readObject();
linearExpandFactor = in.readInt();
exponentialExpanding = in.readBoolean();
exponentialExpandFactor = in.readDouble();
}
@Override
public String toString()
{
ArrayList<Integer> head = new ArrayList<Integer>(20);
for (int i = 0; i < Math.min(size, 20); ++i)
{
head.add(data[i]);
}
return head.toString();
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\datrie\IntArrayList.java
| 1
|
请完成以下Java代码
|
private static int getC_DocType_ID(final PO po)
{
int index = po.get_ColumnIndex("C_DocType_ID");
if (index != -1)
{
Integer ii = (Integer)po.get_Value(index);
// DocType does not exist - get DocTypeTarget
if (ii != null && ii <= 0)
{
index = po.get_ColumnIndex("C_DocTypeTarget_ID");
if (index > 0)
ii = (Integer)po.get_Value(index);
}
if (ii != null)
return ii;
}
return -1;
}
private static void parseField(final PO po, final String columnName, final Collection<MADBoilerPlateVar> vars)
{
final String text = po.get_ValueAsString(columnName);
if (text == null || Check.isBlank(text))
return;
//
final BoilerPlateContext attributes = BoilerPlateContext.builder()
.setSourceDocumentFromObject(po)
.build();
//
final Matcher m = MADBoilerPlate.NameTagPattern.matcher(text);
final StringBuffer sb = new StringBuffer();
while (m.find())
{
final String refName = MADBoilerPlate.getTagName(m);
//
MADBoilerPlateVar var = null;
for (final MADBoilerPlateVar v : vars)
{
if (refName.equals(v.getValue().trim()))
{
var = v;
break;
}
}
//
final String replacement;
if (var != null)
{
|
replacement = MADBoilerPlate.getPlainText(var.evaluate(attributes));
}
else
{
replacement = m.group();
}
if (replacement == null)
{
continue;
}
m.appendReplacement(sb, replacement);
}
m.appendTail(sb);
final String textParsed = sb.toString();
po.set_ValueOfColumn(columnName, textParsed);
}
private static void setDunningRunEntryNote(final I_C_DunningRunEntry dre)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(dre);
final String trxName = InterfaceWrapperHelper.getTrxName(dre);
final I_C_DunningLevel dl = dre.getC_DunningLevel();
final I_C_BPartner bp = Services.get(IBPartnerDAO.class).getById(dre.getC_BPartner_ID());
final String adLanguage = bp.getAD_Language();
final String text;
if (adLanguage != null)
{
text = InterfaceWrapperHelper.getPO(dl).get_Translation(I_C_DunningLevel.COLUMNNAME_Note, adLanguage);
}
else
{
text = dl.getNote();
}
final boolean isEmbeded = true;
final BoilerPlateContext attributes = BoilerPlateContext.builder()
.setSourceDocumentFromObject(dre)
.build();
final String textParsed = MADBoilerPlate.parseText(ctx, text, isEmbeded, attributes, trxName);
dre.setNote(textParsed);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\letters\model\LettersValidator.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
class OAuth2ErrorEncoder implements HttpMessageEncoder<OAuth2Error> {
private final HttpMessageConverter<Object> messageConverter = HttpMessageConverters.getJsonMessageConverter();
@NonNull
@Override
public List<MediaType> getStreamingMediaTypes() {
return List.of();
}
@Override
public boolean canEncode(ResolvableType elementType, MimeType mimeType) {
return getEncodableMimeTypes().contains(mimeType);
}
@NonNull
@Override
public Flux<DataBuffer> encode(Publisher<? extends OAuth2Error> error, DataBufferFactory bufferFactory,
ResolvableType elementType, MimeType mimeType, Map<String, Object> hints) {
return Mono.from(error).flatMap((data) -> {
ByteArrayHttpOutputMessage bytes = new ByteArrayHttpOutputMessage();
try {
this.messageConverter.write(data, MediaType.APPLICATION_JSON, bytes);
return Mono.just(bytes.getBody().toByteArray());
}
catch (IOException ex) {
return Mono.error(ex);
}
}).map(bufferFactory::wrap).flux();
}
@NonNull
@Override
public List<MimeType> getEncodableMimeTypes() {
return List.of(MediaType.APPLICATION_JSON);
}
private static class ByteArrayHttpOutputMessage implements HttpOutputMessage {
|
private final ByteArrayOutputStream body = new ByteArrayOutputStream();
@NonNull
@Override
public ByteArrayOutputStream getBody() {
return this.body;
}
@NonNull
@Override
public HttpHeaders getHeaders() {
return new HttpHeaders();
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\web\server\OAuth2ErrorEncoder.java
| 2
|
请完成以下Java代码
|
public CashAccount16CHIdAndCurrency getChrgsAcct() {
return chrgsAcct;
}
/**
* Sets the value of the chrgsAcct property.
*
* @param value
* allowed object is
* {@link CashAccount16CHIdAndCurrency }
*
*/
public void setChrgsAcct(CashAccount16CHIdAndCurrency value) {
this.chrgsAcct = value;
}
/**
* Gets the value of the cdtTrfTxInf property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the cdtTrfTxInf property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCdtTrfTxInf().add(newItem);
|
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CreditTransferTransactionInformation10CH }
*
*
*/
public List<CreditTransferTransactionInformation10CH> getCdtTrfTxInf() {
if (cdtTrfTxInf == null) {
cdtTrfTxInf = new ArrayList<CreditTransferTransactionInformation10CH>();
}
return this.cdtTrfTxInf;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\PaymentInstructionInformation3CH.java
| 1
|
请完成以下Java代码
|
public class MUserMail extends X_AD_UserMail
{
/**
*
*/
private static final long serialVersionUID = -1019980049099249013L;
/**
* Standard Constructor
* @param ctx context
* @param AD_UserMail_ID id
* @param trxName trx
*/
public MUserMail (Properties ctx, int AD_UserMail_ID, String trxName)
{
super (ctx, AD_UserMail_ID, trxName);
} // MUserMail
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName trx
*/
public MUserMail (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MUserMail
/**
* User Mail
* @param parent Request Mail Text
* @param AD_User_ID recipient user
* @param mail email
*/
public MUserMail (Properties ctx, int R_MailText_ID, int AD_User_ID, final EMail mail, final EMailSentStatus mailSentStatus)
{
this (ctx, 0, ITrx.TRXNAME_ThreadInherited);
setAD_User_ID(AD_User_ID);
setR_MailText_ID(R_MailText_ID);
|
//
if (mailSentStatus.isSentOK())
setMessageID(mailSentStatus.getMessageId());
else
{
setMessageID(mailSentStatus.getSentMsg());
setIsDelivered(ISDELIVERED_No);
}
} // MUserMail
/**
* New User Mail (no trx)
* @param po persistent object
* @param AD_User_ID recipient user
* @param mail email
*/
public MUserMail (Properties ctx, int AD_User_ID, EMail mail, EMailSentStatus mailSentStatus)
{
this (ctx, 0, ITrx.TRXNAME_None);
setAD_User_ID(AD_User_ID);
setSubject(mail.getSubject());
setMailText(mail.getMessageCRLF());
//
if (mailSentStatus.isSentOK())
setMessageID(mailSentStatus.getMessageId());
else
{
setMessageID(mailSentStatus.getSentMsg());
setIsDelivered(ISDELIVERED_No);
}
} // MUserMail
} // MUserMail
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MUserMail.java
| 1
|
请完成以下Java代码
|
public final class SqlParamsCollector
{
public static SqlParamsCollector newInstance()
{
return new SqlParamsCollector(new ArrayList<>());
}
/**
* Wraps the given list if not {@code null}. All changes will be directed the list.
* If the list is null, the new instance is in "not-collecting" mode.
*
* @param list may be {@code null}, but not immutable.
*/
public static SqlParamsCollector wrapNullable(@Nullable final List<Object> list)
{
if (list == null)
{
return NOT_COLLECTING;
}
return new SqlParamsCollector(list);
}
/** An {@link SqlParamsCollector} which is actually not collecting the parameters but it's automatically translating it to SQL code. */
public static SqlParamsCollector notCollecting()
{
return NOT_COLLECTING;
}
private static final SqlParamsCollector NOT_COLLECTING = new SqlParamsCollector(null);
private final List<Object> params;
private final List<Object> paramsRO;
private SqlParamsCollector(final List<Object> params)
{
this.params = params;
paramsRO = params != null ? Collections.unmodifiableList(params) : null;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.addValue(paramsRO)
.toString();
}
public boolean isCollecting()
{
return params != null;
}
/**
* Directly append all sqlParams from the given {@code sqlQueryFilter}.
*
* @param sqlQueryFilter
*
*/
public void collectAll(@NonNull final ISqlQueryFilter sqlQueryFilter)
{
final List<Object> sqlParams = sqlQueryFilter.getSqlParams(Env.getCtx());
collectAll(sqlParams);
}
/**
|
* Directly append the given {@code sqlParams}. Please prefer using {@link #placeholder(Object)} instead.<br>
* "Package" scope because currently this method is needed only by {@link SqlDefaultDocumentFilterConverter}.
*
* Please avoid using it. It's used mainly to adapt with old code
*
* @param sqlParams
*/
public void collectAll(@Nullable final Collection<? extends Object> sqlParams)
{
if (sqlParams == null || sqlParams.isEmpty())
{
return;
}
if (params == null)
{
throw new IllegalStateException("Cannot append " + sqlParams + " to not collecting params");
}
params.addAll(sqlParams);
}
public void collect(@NonNull final SqlParamsCollector from)
{
collectAll(from.params);
}
/**
* Collects given SQL value and returns an SQL placeholder, i.e. "?"
*
* In case this is in non-collecting mode, the given SQL value will be converted to SQL code and it will be returned.
* The internal list won't be affected, because it does not exist.
*/
public String placeholder(@Nullable final Object sqlValue)
{
if (params == null)
{
return DB.TO_SQL(sqlValue);
}
else
{
params.add(sqlValue);
return "?";
}
}
/** @return readonly live list */
public List<Object> toList()
{
return paramsRO;
}
/** @return read/write live list */
public List<Object> toLiveList()
{
return params;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\sql\SqlParamsCollector.java
| 1
|
请完成以下Java代码
|
public static void main(String[] args) throws IOException {
FastAutoGenerator.create(dataSourceGenerate())
// 全局配置
.globalConfig((scanner, builder) -> {
builder.author(scanner.apply("请输入作者")).fileOverride();
builder.outputDir(OUT_DIR);
})
// 包配置
.packageConfig((scanner, builder) -> {
builder
// .pathInfo(Collections.singletonMap(OutputFile.mapperXml, System.getProperty("user.dir") + "/src/main/resources/mapper"))
.parent(scanner.apply("请输入包名?"));
})
// 策略配置
.strategyConfig((scanner, builder) -> {
builder.addInclude(MyBatisPlusGenerator.getTables(scanner.apply("请输入表名,多个英文逗号分隔?所有输入 all")))
.controllerBuilder()
.enableRestStyle()
.enableHyphenStyle()
.build();
builder.serviceBuilder()
.formatServiceFileName("%sService")
.formatServiceImplFileName("%sServiceImp")
.build();
//entity的策略配置
builder.entityBuilder()
.enableLombok()
|
.enableTableFieldAnnotation()
.versionColumnName("version")
.logicDeleteColumnName("is_delete")
.columnNaming(NamingStrategy.underline_to_camel)
// .idType(IdType.AUTO)
.formatFileName("%sEntity")
.build();
// mapper xml配置
builder.mapperBuilder()
.formatMapperFileName("%sMapper")
.enableBaseColumnList()
.enableBaseResultMap()
.build();
})
.execute();
}
}
|
repos\spring-boot-quick-master\quick-sample-server\sample-server\src\main\java\com\quick\utils\MyBatisPlusGenerator.java
| 1
|
请完成以下Java代码
|
private Optional<VATCode> computeVATCode()
{
if (taxId == null)
{
return Optional.empty();
}
final boolean isSOTrx = m_docLine != null ? m_docLine.isSOTrx() : m_doc.isSOTrx();
return services.findVATCode(VATCodeMatchingRequest.builder()
.setC_AcctSchema_ID(getAcctSchemaId().getRepoId())
.setC_Tax_ID(taxId.getRepoId())
.setIsSOTrx(isSOTrx)
.setDate(this.dateAcct)
.build());
}
public void updateFAOpenItemTrxInfo()
{
if (openItemTrxInfo != null)
{
return;
}
this.openItemTrxInfo = services.computeOpenItemTrxInfo(this).orElse(null);
}
|
void setOpenItemTrxInfo(@Nullable final FAOpenItemTrxInfo openItemTrxInfo)
{
this.openItemTrxInfo = openItemTrxInfo;
}
public void updateFrom(@NonNull FactAcctChanges changes)
{
setAmtSource(changes.getAmtSourceDr(), changes.getAmtSourceCr());
setAmtAcct(changes.getAmtAcctDr(), changes.getAmtAcctCr());
updateCurrencyRate();
if (changes.getAccountId() != null)
{
this.accountId = changes.getAccountId();
}
setTaxIdAndUpdateVatCode(changes.getTaxId());
setDescription(changes.getDescription());
this.M_Product_ID = changes.getProductId();
this.userElementString1 = changes.getUserElementString1();
this.C_OrderSO_ID = changes.getSalesOrderId();
this.C_Activity_ID = changes.getActivityId();
this.appliedUserChanges = changes;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\FactLine.java
| 1
|
请完成以下Java代码
|
public class EmployeeDTO {
private int employeeId;
private String employeeName;
private DivisionDTO division;
private String employeeStartDt;
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
|
public DivisionDTO getDivision() {
return division;
}
public void setDivision(DivisionDTO division) {
this.division = division;
}
public String getEmployeeStartDt() {
return employeeStartDt;
}
public void setEmployeeStartDt(String employeeStartDt) {
this.employeeStartDt = employeeStartDt;
}
}
|
repos\tutorials-master\mapstruct\src\main\java\com\baeldung\dto\EmployeeDTO.java
| 1
|
请完成以下Java代码
|
protected HistoryEvent createHistoryEvent(DmnDecisionEvaluationEvent evaluationEvent) {
if (historyLevel == null) {
historyLevel = Context.getProcessEngineConfiguration().getHistoryLevel();
}
DmnDecision decisionTable = evaluationEvent.getDecisionResult().getDecision();
if(isDeployedDecisionTable(decisionTable) && historyLevel.isHistoryEventProduced(HistoryEventTypes.DMN_DECISION_EVALUATE, decisionTable)) {
CoreExecutionContext<? extends CoreExecution> executionContext = Context.getCoreExecutionContext();
if (executionContext != null) {
CoreExecution coreExecution = executionContext.getExecution();
if (coreExecution instanceof ExecutionEntity) {
ExecutionEntity execution = (ExecutionEntity) coreExecution;
return eventProducer.createDecisionEvaluatedEvt(execution, evaluationEvent);
}
else if (coreExecution instanceof CaseExecutionEntity) {
CaseExecutionEntity caseExecution = (CaseExecutionEntity) coreExecution;
return eventProducer.createDecisionEvaluatedEvt(caseExecution, evaluationEvent);
}
}
|
return eventProducer.createDecisionEvaluatedEvt(evaluationEvent);
} else {
return null;
}
}
protected boolean isDeployedDecisionTable(DmnDecision decision) {
if(decision instanceof DecisionDefinition) {
return ((DecisionDefinition) decision).getId() != null;
} else {
return false;
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\parser\HistoryDecisionEvaluationListener.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JsonRfq
{
@NonNull
String rfqId;
@NonNull
String productName;
@NonNull
String packingInfo;
@NonNull LocalDate dateStart;
@NonNull LocalDate dateEnd;
@NonNull LocalDate dateClose;
@NonNull
String qtyRequested;
@NonNull
|
String qtyPromised;
@NonNull
BigDecimal price;
@NonNull
String priceRendered;
@NonNull
@Singular
List<JsonRfqQty> quantities;
boolean confirmedByUser;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Nullable
@With
Long countUnconfirmed;
}
|
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\rest\rfq\JsonRfq.java
| 2
|
请完成以下Java代码
|
public int calculateUsingSwitch(int a, int b, Operator operator) {
int result = 0;
switch (operator) {
case ADD:
result = a + b;
break;
case MULTIPLY:
result = a * b;
break;
case DIVIDE:
result = a / b;
break;
case SUBTRACT:
result = a - b;
break;
case MODULO:
result = a % b;
break;
default:
result = Integer.MIN_VALUE;
}
|
return result;
}
public int calculate(int a, int b, Operator operator) {
return operator.apply(a, b);
}
public int calculateUsingFactory(int a, int b, String operation) {
Operation targetOperation = OperatorFactory.getOperation(operation)
.orElseThrow(() -> new IllegalArgumentException("Invalid Operator"));
return targetOperation.apply(a, b);
}
public int calculate(Command command) {
return command.execute();
}
}
|
repos\tutorials-master\patterns-modules\design-patterns-creational\src\main\java\com\baeldung\reducingIfElse\Calculator.java
| 1
|
请完成以下Java代码
|
public String getRemark() {
return remark;
}
/**
* Sets the value of the remark property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRemark(String value) {
this.remark = value;
}
/**
* Gets the value of the serviceAttributes property.
*
* @return
* possible object is
* {@link Long }
*
|
*/
public long getServiceAttributes() {
if (serviceAttributes == null) {
return 0L;
} else {
return serviceAttributes;
}
}
/**
* Sets the value of the serviceAttributes property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setServiceAttributes(Long value) {
this.serviceAttributes = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\RecordServiceType.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Todo {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
private boolean completed;
public Todo() {
}
public Todo(String title) {
this.title = title;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
|
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jdbc\src\main\java\com\baeldung\springmultipledatasources\todos\Todo.java
| 2
|
请完成以下Java代码
|
public int getC_Country_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Country_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Region.
@param C_Region_ID
Identifies a geographical Region
*/
@Override
public void setC_Region_ID (int C_Region_ID)
{
if (C_Region_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Region_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Region_ID, Integer.valueOf(C_Region_ID));
}
/** Get Region.
@return Identifies a geographical Region
*/
@Override
public int getC_Region_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Region_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Standard.
@param IsDefault
Default value
*/
@Override
public void setIsDefault (boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
|
}
/** Get Standard.
@return Default value
*/
@Override
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Region.java
| 1
|
请完成以下Java代码
|
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Qty Requiered.
@param QtyRequiered Qty Requiered */
@Override
public void setQtyRequiered (java.math.BigDecimal QtyRequiered)
{
set_Value (COLUMNNAME_QtyRequiered, QtyRequiered);
}
/** Get Qty Requiered.
@return Qty Requiered */
@Override
public java.math.BigDecimal getQtyRequiered ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyRequiered);
if (bd == null)
return Env.ZERO;
return bd;
}
@Override
public org.compiere.model.I_S_Resource getS_Resource() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class);
}
@Override
public void setS_Resource(org.compiere.model.I_S_Resource S_Resource)
{
set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource);
}
/** Set Ressource.
@param S_Resource_ID
Resource
*/
@Override
public void setS_Resource_ID (int S_Resource_ID)
{
if (S_Resource_ID < 1)
set_Value (COLUMNNAME_S_Resource_ID, null);
else
set_Value (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID));
}
/** Get Ressource.
@return Resource
*/
@Override
public int getS_Resource_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_Resource_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* TypeMRP AD_Reference_ID=53230
* Reference name: _MRP Type
*/
public static final int TYPEMRP_AD_Reference_ID=53230;
/** Demand = D */
|
public static final String TYPEMRP_Demand = "D";
/** Supply = S */
public static final String TYPEMRP_Supply = "S";
/** Set TypeMRP.
@param TypeMRP TypeMRP */
@Override
public void setTypeMRP (java.lang.String TypeMRP)
{
set_Value (COLUMNNAME_TypeMRP, TypeMRP);
}
/** Get TypeMRP.
@return TypeMRP */
@Override
public java.lang.String getTypeMRP ()
{
return (java.lang.String)get_Value(COLUMNNAME_TypeMRP);
}
/** Set Suchschlüssel.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
/** Set Version.
@param Version
Version of the table definition
*/
@Override
public void setVersion (java.math.BigDecimal Version)
{
set_Value (COLUMNNAME_Version, Version);
}
/** Get Version.
@return Version of the table definition
*/
@Override
public java.math.BigDecimal getVersion ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Version);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_MRP.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getMpsExpectedSendingDate() {
return mpsExpectedSendingDate;
}
/**
* Sets the value of the mpsExpectedSendingDate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMpsExpectedSendingDate(String value) {
this.mpsExpectedSendingDate = value;
}
/**
* Gets the value of the mpsExpectedSendingTime property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMpsExpectedSendingTime() {
return mpsExpectedSendingTime;
}
/**
* Sets the value of the mpsExpectedSendingTime property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMpsExpectedSendingTime(String value) {
this.mpsExpectedSendingTime = value;
}
/**
* Gets the value of the sender property.
*
* @return
* possible object is
* {@link Address }
*
*/
public Address getSender() {
return sender;
}
/**
|
* Sets the value of the sender property.
*
* @param value
* allowed object is
* {@link Address }
*
*/
public void setSender(Address value) {
this.sender = value;
}
/**
* Gets the value of the recipient property.
*
* @return
* possible object is
* {@link Address }
*
*/
public Address getRecipient() {
return recipient;
}
/**
* Sets the value of the recipient property.
*
* @param value
* allowed object is
* {@link Address }
*
*/
public void setRecipient(Address value) {
this.recipient = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\GeneralShipmentData.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void setForecastExtension(ForecastExtensionType value) {
this.forecastExtension = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ControlTotalQualifier" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="ControlTotalValue" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"controlTotalQualifier",
"controlTotalValue"
})
public static class ControlTotal {
@XmlElement(name = "ControlTotalQualifier")
protected String controlTotalQualifier;
@XmlElement(name = "ControlTotalValue")
protected String controlTotalValue;
/**
* Gets the value of the controlTotalQualifier property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getControlTotalQualifier() {
return controlTotalQualifier;
}
|
/**
* Sets the value of the controlTotalQualifier property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setControlTotalQualifier(String value) {
this.controlTotalQualifier = value;
}
/**
* Gets the value of the controlTotalValue property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getControlTotalValue() {
return controlTotalValue;
}
/**
* Sets the value of the controlTotalValue property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setControlTotalValue(String value) {
this.controlTotalValue = value;
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\DocumentExtensionType.java
| 2
|
请完成以下Java代码
|
public Class<?> getCommonPropertyType(ELContext context, Object base) {
ELResolver delegate = getElResolverDelegate();
if(delegate == null) {
return null;
} else {
return delegate.getCommonPropertyType(context, base);
}
}
public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) {
ELResolver delegate = getElResolverDelegate();
if(delegate == null) {
return Collections.<FeatureDescriptor>emptySet().iterator();
} else {
return delegate.getFeatureDescriptors(context, base);
}
}
public Class<?> getType(ELContext context, Object base, Object property) {
context.setPropertyResolved(false);
ELResolver delegate = getElResolverDelegate();
if(delegate == null) {
return null;
} else {
return delegate.getType(context, base, property);
}
}
public Object getValue(ELContext context, Object base, Object property) {
context.setPropertyResolved(false);
ELResolver delegate = getElResolverDelegate();
if(delegate == null) {
|
return null;
} else {
return delegate.getValue(context, base, property);
}
}
public boolean isReadOnly(ELContext context, Object base, Object property) {
context.setPropertyResolved(false);
ELResolver delegate = getElResolverDelegate();
if(delegate == null) {
return true;
} else {
return delegate.isReadOnly(context, base, property);
}
}
public void setValue(ELContext context, Object base, Object property, Object value) {
context.setPropertyResolved(false);
ELResolver delegate = getElResolverDelegate();
if(delegate != null) {
delegate.setValue(context, base, property, value);
}
}
public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) {
context.setPropertyResolved(false);
ELResolver delegate = getElResolverDelegate();
if(delegate == null) {
return null;
} else {
return delegate.invoke(context, base, method, paramTypes, params);
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\el\AbstractElResolverDelegate.java
| 1
|
请完成以下Java代码
|
public static HousekeeperTask deleteTelemetry(TenantId tenantId, EntityId entityId) {
return new HousekeeperTask(tenantId, entityId, HousekeeperTaskType.DELETE_TELEMETRY);
}
public static HousekeeperTask deleteEvents(TenantId tenantId, EntityId entityId) {
return new HousekeeperTask(tenantId, entityId, HousekeeperTaskType.DELETE_EVENTS);
}
public static HousekeeperTask unassignAlarms(User user) {
return new AlarmsUnassignHousekeeperTask(user);
}
public static HousekeeperTask deleteAlarms(TenantId tenantId, EntityId entityId) {
return new AlarmsDeletionHousekeeperTask(tenantId, entityId);
}
public static HousekeeperTask deleteTenantEntities(TenantId tenantId, EntityType entityType) {
return new TenantEntitiesDeletionHousekeeperTask(tenantId, entityType);
|
}
public static HousekeeperTask deleteCalculatedFields(TenantId tenantId, EntityId entityId) {
return new HousekeeperTask(tenantId, entityId, HousekeeperTaskType.DELETE_CALCULATED_FIELDS);
}
public static HousekeeperTask deleteJobs(TenantId tenantId, EntityId entityId) {
return new HousekeeperTask(tenantId, entityId, HousekeeperTaskType.DELETE_JOBS);
}
@JsonIgnore
public String getDescription() {
return taskType.getDescription() + " for " + entityId.getEntityType().getNormalName().toLowerCase() + " " + entityId.getId();
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\housekeeper\HousekeeperTask.java
| 1
|
请完成以下Java代码
|
public int getRevisionNext() {
return revision + 1;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public String getResourceName() {
return resourceName;
}
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String getCategory() {
throw new UnsupportedOperationException();
}
@Override
public CamundaFormDefinitionEntity getPreviousDefinition() {
throw new UnsupportedOperationException();
}
@Override
public void setCategory(String category) {
throw new UnsupportedOperationException();
}
@Override
public String getDiagramResourceName() {
throw new UnsupportedOperationException("deployment of diagrams not supported for Camunda Forms");
}
@Override
public void setDiagramResourceName(String diagramResourceName) {
throw new UnsupportedOperationException("deployment of diagrams not supported for Camunda Forms");
}
|
@Override
public Integer getHistoryTimeToLive() {
throw new UnsupportedOperationException("history time to live not supported for Camunda Forms");
}
@Override
public void setHistoryTimeToLive(Integer historyTimeToLive) {
throw new UnsupportedOperationException("history time to live not supported for Camunda Forms");
}
@Override
public Object getPersistentState() {
// properties of this entity are immutable
return CamundaFormDefinitionEntity.class;
}
@Override
public void updateModifiableFieldsFromEntity(CamundaFormDefinitionEntity updatingDefinition) {
throw new UnsupportedOperationException("properties of Camunda Form Definitions are immutable");
}
@Override
public String getName() {
throw new UnsupportedOperationException("name property not supported for Camunda Forms");
}
@Override
public void setName(String name) {
throw new UnsupportedOperationException("name property not supported for Camunda Forms");
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CamundaFormDefinitionEntity.java
| 1
|
请完成以下Java代码
|
public void setModule (String Module)
{
set_Value (COLUMNNAME_Module, Module);
}
/** Get Module.
@return Module */
public String getModule ()
{
return (String)get_Value(COLUMNNAME_Module);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
public I_U_WebMenu getParentMenu() throws RuntimeException
{
return (I_U_WebMenu)MTable.get(getCtx(), I_U_WebMenu.Table_Name)
.getPO(getParentMenu_ID(), get_TrxName()); }
/** Set Parent Menu.
@param ParentMenu_ID Parent Menu */
public void setParentMenu_ID (int ParentMenu_ID)
{
if (ParentMenu_ID < 1)
set_Value (COLUMNNAME_ParentMenu_ID, null);
else
set_Value (COLUMNNAME_ParentMenu_ID, Integer.valueOf(ParentMenu_ID));
}
/** Get Parent Menu.
@return Parent Menu */
public int getParentMenu_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ParentMenu_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Position.
@param Position Position */
public void setPosition (String Position)
{
set_Value (COLUMNNAME_Position, Position);
}
/** Get Position.
@return Position */
public String getPosition ()
{
return (String)get_Value(COLUMNNAME_Position);
}
/** Set Sequence.
|
@param Sequence Sequence */
public void setSequence (BigDecimal Sequence)
{
set_Value (COLUMNNAME_Sequence, Sequence);
}
/** Get Sequence.
@return Sequence */
public BigDecimal getSequence ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Sequence);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Web Menu.
@param U_WebMenu_ID Web Menu */
public void setU_WebMenu_ID (int U_WebMenu_ID)
{
if (U_WebMenu_ID < 1)
set_ValueNoCheck (COLUMNNAME_U_WebMenu_ID, null);
else
set_ValueNoCheck (COLUMNNAME_U_WebMenu_ID, Integer.valueOf(U_WebMenu_ID));
}
/** Get Web Menu.
@return Web Menu */
public int getU_WebMenu_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_U_WebMenu_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_U_WebMenu.java
| 1
|
请完成以下Java代码
|
public class PostItem {
private String title;
private String body;
private int userId;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
|
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
@Override
public String toString() {
return "PostItem{"
+ "title='" + title + '\''
+ ", body='" + body + '\''
+ ", userId=" + userId +
'}';
}
}
|
repos\tutorials-master\aws-modules\aws-lambda-modules\todo-reminder-lambda\ToDoFunction\src\main\java\com\baeldung\lambda\todo\api\PostItem.java
| 1
|
请完成以下Java代码
|
private boolean isDoInvocation(final ICalloutField calloutField)
{
if (!I_C_OrderLine.COLUMNNAME_QtyEntered.equals(calloutField.getColumnName()))
{
// execute the callout
return true;
}
final I_C_OrderLine ol = calloutField.getModel(I_C_OrderLine.class);
// don't execute the callout
if(subscriptionBL.isSubscription(ol))
{
return false;
}
//execute the callout
return true;
}
// metas
public String subscriptionLocation(final ICalloutField calloutField)
{
final I_C_OrderLine ol = calloutField.getModel(I_C_OrderLine.class);
final I_C_Order order = ol.getC_Order();
final boolean IsSOTrx = order.isSOTrx();
final boolean isSubscription = ol.isSubscription();
if (IsSOTrx && !isSubscription)
{
final IOrderLineBL orderLineBL = Services.get(IOrderLineBL.class);
final Quantity qty = orderLineBL.getQtyEntered(ol);
final BigDecimal qtyOrdered = orderLineBL.convertQtyEnteredToStockUOM(ol).toBigDecimal();
ol.setQtyOrdered(qtyOrdered);
orderLineBL.updatePrices(OrderLinePriceUpdateRequest.builder()
.orderLine(ol)
.qtyOverride(qty)
.resultUOM(ResultUOM.CONTEXT_UOM)
.updatePriceEnteredAndDiscountOnlyIfNotAlreadySet(true)
.updateLineNetAmt(true)
.build());
}
if (IsSOTrx && isSubscription)
{
final int C_BPartner_ID = order.getC_BPartner_ID();
PreparedStatement pstmt = null;
ResultSet rs = null;
final String sql = "SELECT C_BPartner_Location_ID FROM C_BPartner_Location "
|
+ " WHERE C_BPartner_ID = ? "
+ " ORDER BY IsSubscriptionToDefault DESC";
try
{
pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, C_BPartner_ID);
rs = pstmt.executeQuery();
if (rs.next())
{
final int bpartnerLocationId = rs.getInt(1);
order.setC_BPartner_Location_ID(bpartnerLocationId);
log.debug("C_BPartner_Location_ID for Subscription changed -> " + bpartnerLocationId);
}
}
catch (final SQLException e)
{
log.error(sql, e);
return e.getLocalizedMessage();
}
finally
{
DB.close(rs, pstmt);
}
}
return NO_ERROR;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\callout\OrderLine.java
| 1
|
请完成以下Java代码
|
private Optional<TsKvEntry> processMinOrMaxResult(AggregationResult aggResult) {
if (aggResult.dataType == DataType.DOUBLE || aggResult.dataType == DataType.LONG) {
if (aggResult.hasDouble) {
double currentD = aggregation == Aggregation.MIN ? Optional.ofNullable(aggResult.dValue).orElse(Double.MAX_VALUE) : Optional.ofNullable(aggResult.dValue).orElse(Double.MIN_VALUE);
double currentL = aggregation == Aggregation.MIN ? Optional.ofNullable(aggResult.lValue).orElse(Long.MAX_VALUE) : Optional.ofNullable(aggResult.lValue).orElse(Long.MIN_VALUE);
return Optional.of(new BasicTsKvEntry(ts, new DoubleDataEntry(key, aggregation == Aggregation.MIN ? Math.min(currentD, currentL) : Math.max(currentD, currentL))));
} else {
return Optional.of(new BasicTsKvEntry(ts, new LongDataEntry(key, aggResult.lValue)));
}
} else if (aggResult.dataType == DataType.STRING) {
return Optional.of(new BasicTsKvEntry(ts, new StringDataEntry(key, aggResult.sValue)));
} else if (aggResult.dataType == DataType.JSON) {
return Optional.of(new BasicTsKvEntry(ts, new JsonDataEntry(key, aggResult.jValue)));
} else {
return Optional.of(new BasicTsKvEntry(ts, new BooleanDataEntry(key, aggResult.bValue)));
|
}
}
private class AggregationResult {
DataType dataType = null;
Boolean bValue = null;
String sValue = null;
String jValue = null;
Double dValue = null;
Long lValue = null;
long count = 0;
boolean hasDouble = false;
long aggValuesLastTs = 0;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\timeseries\AggregatePartitionsFunction.java
| 1
|
请完成以下Java代码
|
public class CodeTemplateInitListener implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
try {
long startTime = System.currentTimeMillis(); // 记录开始时间
log.info(" Init Code Generate Template [ 检测如果是JAR启动,Copy模板到config目录 ] ");
this.initJarConfigCodeGeneratorTemplate();
long endTime = System.currentTimeMillis(); // 记录结束时间
log.info(" Init Code Generate Template completed in " + (endTime - startTime) + " ms"); // 计算并记录耗时
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* ::Jar包启动模式下::
* 初始化代码生成器模板文件
*/
private void initJarConfigCodeGeneratorTemplate() throws Exception {
//1.获取jar同级下的config路径
String configPath = System.getProperty("user.dir") + File.separator + "config" + File.separator;
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath*:jeecg/code-template-online/**/*");
for (Resource re : resources) {
URL url = re.getURL();
String filepath = url.getPath();
//System.out.println("native url= " + filepath);
filepath = java.net.URLDecoder.decode(filepath, "utf-8");
//System.out.println("decode url= " + filepath);
|
//2.在config下,创建jeecg/code-template-online/*模板
String createFilePath = configPath + filepath.substring(filepath.indexOf("jeecg/code-template-online"));
// 非jar模式不生成模板
// 不生成目录,只生成具体模板文件
if ((!filepath.contains(".jar!/BOOT-INF/lib/") && !filepath.contains(".jar/!BOOT-INF/lib/")) || !createFilePath.contains(".")) {
continue;
}
if (!FileUtil.exist(createFilePath)) {
log.info("create file codeTemplate = " + createFilePath);
FileUtil.writeString(IOUtils.toString(url, StandardCharsets.UTF_8), createFilePath, "UTF-8");
}
}
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\config\init\CodeTemplateInitListener.java
| 1
|
请完成以下Java代码
|
public int getC_UOM_ID()
{
calculatePrice(false);
return UomId.toRepoId(result.getPriceUomId());
}
/**
* Get Price List
*
* @return list
*/
public BigDecimal getPriceList()
{
calculatePrice(false);
return round(result.getPriceList());
}
/**
* Get Price Std
*
* @return std
*/
public BigDecimal getPriceStd()
{
calculatePrice(false);
return round(result.getPriceStd());
}
/**
* Get Price Limit
*
* @return limit
*/
public BigDecimal getPriceLimit()
{
calculatePrice(false);
return round(result.getPriceLimit());
}
/**
* Is Price List enforded?
*
* @return enforce limit
*/
public boolean isEnforcePriceLimit()
{
calculatePrice(false);
return result.getEnforcePriceLimit().isTrue();
} // isEnforcePriceLimit
/**
* Is a DiscountSchema active?
*
* @return active Discount Schema
*/
public boolean isDiscountSchema()
{
return !result.isDisallowDiscount()
&& result.isUsesDiscountSchema();
} // isDiscountSchema
/**
* Is the Price Calculated (i.e. found)?
*
* @return calculated
*/
public boolean isCalculated()
{
return result.isCalculated();
} // isCalculated
/**
* Convenience method to get priceStd with the discount already subtracted. Note that the result matches the former behavior of {@link #getPriceStd()}.
*/
|
public BigDecimal mkPriceStdMinusDiscount()
{
calculatePrice(false);
return result.getDiscount().subtractFromBase(result.getPriceStd(), result.getPrecision().toInt());
}
@Override
public String toString()
{
return "MProductPricing ["
+ pricingCtx
+ ", " + result
+ "]";
}
public void setConvertPriceToContextUOM(boolean convertPriceToContextUOM)
{
pricingCtx.setConvertPriceToContextUOM(convertPriceToContextUOM);
}
public void setReferencedObject(Object referencedObject)
{
pricingCtx.setReferencedObject(referencedObject);
}
// metas: end
public int getC_TaxCategory_ID()
{
return TaxCategoryId.toRepoId(result.getTaxCategoryId());
}
public boolean isManualPrice()
{
return pricingCtx.getManualPriceEnabled().isTrue();
}
public void setManualPrice(boolean manualPrice)
{
pricingCtx.setManualPriceEnabled(manualPrice);
}
public void throwProductNotOnPriceListException()
{
throw new ProductNotOnPriceListException(pricingCtx);
}
} // MProductPrice
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MProductPricing.java
| 1
|
请完成以下Java代码
|
public static HuPackingInstructionsItemId ofRepoId(final int repoId)
{
if (repoId == TEMPLATE_MATERIAL_ITEM.repoId)
{
return TEMPLATE_MATERIAL_ITEM;
}
if (repoId == TEMPLATE_PACKING_ITEM.repoId)
{
return TEMPLATE_PACKING_ITEM;
}
else if (repoId == VIRTUAL.repoId)
{
return VIRTUAL;
}
else
{
return new HuPackingInstructionsItemId(repoId);
}
}
public static HuPackingInstructionsItemId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static int toRepoId(final HuPackingInstructionsItemId id)
{
return id != null ? id.getRepoId() : -1;
}
public static final HuPackingInstructionsItemId TEMPLATE_MATERIAL_ITEM = new HuPackingInstructionsItemId(540004);
private static final HuPackingInstructionsItemId TEMPLATE_PACKING_ITEM = new HuPackingInstructionsItemId(100);
public static final HuPackingInstructionsItemId VIRTUAL = new HuPackingInstructionsItemId(101);
int repoId;
private HuPackingInstructionsItemId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "M_HU_PI_Item_ID");
}
@Override
@JsonValue
|
public int getRepoId()
{
return repoId;
}
public static boolean equals(final HuPackingInstructionsItemId o1, final HuPackingInstructionsItemId o2)
{
return Objects.equals(o1, o2);
}
public boolean isTemplate()
{
return isTemplateRepoId(repoId);
}
public static boolean isTemplateRepoId(final int repoId)
{
return repoId == TEMPLATE_MATERIAL_ITEM.repoId
|| repoId == TEMPLATE_PACKING_ITEM.repoId;
}
public boolean isVirtual()
{
return isVirtualRepoId(repoId);
}
public static boolean isVirtualRepoId(final int repoId)
{
return repoId == VIRTUAL.repoId;
}
public boolean isRealPackingInstructions()
{
return isRealPackingInstructionsRepoId(repoId);
}
public static boolean isRealPackingInstructionsRepoId(final int repoId)
{
return repoId > 0
&& !isTemplateRepoId(repoId)
&& !isVirtualRepoId(repoId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\HuPackingInstructionsItemId.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setLastName(String lastName) {
super.setLastName(lastName);
lastNameChanged = true;
}
@Override
public void setDisplayName(String displayName) {
super.setDisplayName(displayName);
displayNameChanged = true;
}
@Override
public void setPassword(String passWord) {
super.setPassword(passWord);
passwordChanged = true;
}
@JsonIgnore
public boolean isEmailChanged() {
return emailChanged;
}
@JsonIgnore
public boolean isFirstNameChanged() {
|
return firstNameChanged;
}
@JsonIgnore
public boolean isLastNameChanged() {
return lastNameChanged;
}
@JsonIgnore
public boolean isDisplayNameChanged() {
return displayNameChanged;
}
@JsonIgnore
public boolean isPasswordChanged() {
return passwordChanged;
}
}
|
repos\flowable-engine-main\modules\flowable-idm-rest\src\main\java\org\flowable\idm\rest\service\api\user\UserRequest.java
| 2
|
请完成以下Java代码
|
public final class GroovyFieldDeclaration implements Annotatable {
private final AnnotationContainer annotations = new AnnotationContainer();
private final int modifiers;
private final String name;
private final String returnType;
private final Object value;
private final boolean initialized;
private GroovyFieldDeclaration(Builder builder) {
this.modifiers = builder.modifiers;
this.name = builder.name;
this.returnType = builder.returnType;
this.value = builder.value;
this.initialized = builder.initialized;
}
/**
* Creates a new builder for the field with the given name.
* @param name the name
* @return the builder
*/
public static Builder field(String name) {
return new Builder(name);
}
@Override
public AnnotationContainer annotations() {
return this.annotations;
}
/**
* Return the modifiers.
* @return the modifiers
*/
public int getModifiers() {
return this.modifiers;
}
/**
* Return the name.
* @return the name
*/
public String getName() {
return this.name;
}
/**
* Return the return type.
* @return the return type
*/
public String getReturnType() {
return this.returnType;
}
/**
* Return the value.
* @return the value
*/
public Object getValue() {
return this.value;
}
/**
* Whether the field declaration is initialized.
* @return whether the field declaration is initialized
*/
|
public boolean isInitialized() {
return this.initialized;
}
/**
* Builder for {@link GroovyFieldDeclaration}.
*/
public static final class Builder {
private final String name;
private String returnType;
private int modifiers;
private Object value;
private boolean initialized;
private Builder(String name) {
this.name = name;
}
/**
* Sets the modifiers.
* @param modifiers the modifiers
* @return this for method chaining
*/
public Builder modifiers(int modifiers) {
this.modifiers = modifiers;
return this;
}
/**
* Sets the value.
* @param value the value
* @return this for method chaining
*/
public Builder value(Object value) {
this.value = value;
this.initialized = true;
return this;
}
/**
* Sets the return type.
* @param returnType the return type
* @return the field
*/
public GroovyFieldDeclaration returning(String returnType) {
this.returnType = returnType;
return new GroovyFieldDeclaration(this);
}
}
}
|
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\groovy\GroovyFieldDeclaration.java
| 1
|
请完成以下Java代码
|
public class title extends MultiPartElement implements Printable
{
/**
*
*/
private static final long serialVersionUID = 6917790537056196697L;
/**
Private initialization routine.
*/
{
setElementType("title");
setCase(LOWERCASE);
setAttributeQuote(true);
}
/**
Basic constructor. You need to set the attributes using the
set* methods.
*/
public title()
{
}
/**
This method creates a <title> tag and sets the Element value.
@param value what goes between <start_tag> <end_tag>
*/
public title(String title)
{
addElement(title);
}
/**
Sets the lang="" and xml:lang="" attributes
@param lang the lang="" and xml:lang="" attributes
*/
public Element setLang(String lang)
{
addAttribute("lang",lang);
addAttribute("xml:lang",lang);
return this;
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public title addElement(String hashcode,Element element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
|
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public title addElement(String hashcode,String element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public title addElement(Element element)
{
addElementToRegistry(element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public title addElement(String element)
{
addElementToRegistry(element);
return(this);
}
/**
Removes an Element from the element.
@param hashcode the name of the element to be removed.
*/
public title removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\title.java
| 1
|
请完成以下Java代码
|
public Stream<HUEditorRow> stream()
{
return rows.stream();
}
public Stream<HUEditorRow> streamRecursive()
{
return stream()
.flatMap(HUEditorRow::streamRecursive)
.map(HUEditorRow::cast);
}
public long size()
{
return rows.size();
}
private static ImmutableMap<DocumentId, HUEditorRow> buildRowsByIdMap(final List<HUEditorRow> rows)
{
if (rows.isEmpty())
{
return ImmutableMap.of();
}
final ImmutableMap.Builder<DocumentId, HUEditorRow> rowsById = ImmutableMap.builder();
rows.forEach(row -> indexByIdRecursively(rowsById, row));
return rowsById.build();
}
private static void indexByIdRecursively(final ImmutableMap.Builder<DocumentId, HUEditorRow> collector, final HUEditorRow row)
|
{
collector.put(row.getId(), row);
row.getIncludedRows()
.forEach(includedRow -> indexByIdRecursively(collector, includedRow));
}
private static ImmutableMap<HUEditorRowId, HUEditorRowId> buildRowId2ParentIdMap(final List<HUEditorRow> rows)
{
if (rows.isEmpty())
{
return ImmutableMap.of();
}
final ImmutableMap.Builder<HUEditorRowId, HUEditorRowId> rowId2parentId = ImmutableMap.builder();
rows.forEach(row -> buildRowId2ParentIdMap(rowId2parentId, row));
return rowId2parentId.build();
}
private static void buildRowId2ParentIdMap(final ImmutableMap.Builder<HUEditorRowId, HUEditorRowId> rowId2parentId, final HUEditorRow parentRow)
{
final HUEditorRowId parentId = parentRow.getHURowId();
parentRow.getIncludedRows()
.forEach(includedRow -> rowId2parentId.put(includedRow.getHURowId(), parentId));
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorViewBuffer_FullyCached.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
StringHttpMessageConvertersCustomizer stringHttpMessageConvertersCustomizer(
HttpMessageConvertersProperties properties) {
return new StringHttpMessageConvertersCustomizer(properties);
}
}
static class StringHttpMessageConvertersCustomizer
implements ClientHttpMessageConvertersCustomizer, ServerHttpMessageConvertersCustomizer {
StringHttpMessageConverter converter;
StringHttpMessageConvertersCustomizer(HttpMessageConvertersProperties properties) {
this.converter = new StringHttpMessageConverter(properties.getStringEncodingCharset());
this.converter.setWriteAcceptCharset(false);
}
@Override
public void customize(ClientBuilder builder) {
builder.withStringConverter(this.converter);
}
|
@Override
public void customize(ServerBuilder builder) {
builder.withStringConverter(this.converter);
}
}
static class NotReactiveWebApplicationCondition extends NoneNestedConditions {
NotReactiveWebApplicationCondition() {
super(ConfigurationPhase.PARSE_CONFIGURATION);
}
@ConditionalOnWebApplication(type = Type.REACTIVE)
private static final class ReactiveWebApplication {
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-http-converter\src\main\java\org\springframework\boot\http\converter\autoconfigure\HttpMessageConvertersAutoConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class DataEntryLayout
{
public static DataEntryLayout empty(@NonNull final AdWindowId windowId, @NonNull final AdTableId mainTableId)
{
return builder().windowId(windowId).mainTableId(mainTableId).build();
}
AdWindowId windowId;
AdTableId mainTableId;
ImmutableList<DataEntryTab> tabs;
@Builder
private DataEntryLayout(
@NonNull final AdWindowId windowId,
@NonNull final AdTableId mainTableId,
@NonNull @Singular final List<DataEntryTab> tabs)
{
this.windowId = windowId;
this.mainTableId = mainTableId;
this.tabs = ImmutableList.copyOf(tabs);
}
public boolean isEmpty()
{
return tabs.isEmpty();
}
public Optional<DataEntryTab> getFirstTabMatching(@NonNull final Predicate<DataEntryTab> predicate)
{
return tabs.stream().filter(predicate).findFirst();
}
|
public Set<DataEntrySubTabId> getSubTabIds()
{
return tabs.stream()
.flatMap(DataEntryTab::streamSubTabIds)
.collect(ImmutableSet.toImmutableSet());
}
public DataEntrySubTab getSubTabById(@NonNull final DataEntrySubTabId subTabId)
{
return tabs.stream()
.map(tab -> tab.getSubTabByIdIfPresent(subTabId).orElse(null))
.filter(Objects::nonNull)
.findFirst()
.orElseThrow(() -> new AdempiereException("@NotFound@ " + subTabId + " in " + this));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\layout\DataEntryLayout.java
| 2
|
请完成以下Java代码
|
public void setVariables(Map<String, VariableValueDto> variables) {
this.variables = variables;
}
public String getBusinessKey() {
return businessKey;
}
public void setBusinessKey(String businessKey) {
this.businessKey = businessKey;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public void setCaseInstanceId(String caseInstanceId) {
this.caseInstanceId = caseInstanceId;
}
public List<ProcessInstanceModificationInstructionDto> getStartInstructions() {
return startInstructions;
}
public void setStartInstructions(List<ProcessInstanceModificationInstructionDto> startInstructions) {
this.startInstructions = startInstructions;
}
public boolean isSkipCustomListeners() {
return skipCustomListeners;
}
public void setSkipCustomListeners(boolean skipCustomListeners) {
this.skipCustomListeners = skipCustomListeners;
}
|
public boolean isSkipIoMappings() {
return skipIoMappings;
}
public void setSkipIoMappings(boolean skipIoMappings) {
this.skipIoMappings = skipIoMappings;
}
public boolean isWithVariablesInReturn() {
return withVariablesInReturn;
}
public void setWithVariablesInReturn(boolean withVariablesInReturn) {
this.withVariablesInReturn = withVariablesInReturn;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\StartProcessInstanceDto.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable Double getValue(Meter.Type meterType) {
return this.value.getValue(meterType);
}
/**
* Return a new {@link ServiceLevelObjectiveBoundary} instance for the given double
* value.
* @param value the source value
* @return a {@link ServiceLevelObjectiveBoundary} instance
*/
public static ServiceLevelObjectiveBoundary valueOf(double value) {
return new ServiceLevelObjectiveBoundary(MeterValue.valueOf(value));
}
/**
* Return a new {@link ServiceLevelObjectiveBoundary} instance for the given String
* value.
* @param value the source value
|
* @return a {@link ServiceLevelObjectiveBoundary} instance
*/
public static ServiceLevelObjectiveBoundary valueOf(String value) {
return new ServiceLevelObjectiveBoundary(MeterValue.valueOf(value));
}
static class ServiceLevelObjectiveBoundaryHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.reflection().registerType(ServiceLevelObjectiveBoundary.class, MemberCategory.INVOKE_PUBLIC_METHODS);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\ServiceLevelObjectiveBoundary.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public SecurityManager securityManager(SessionManager sessionManager,ModularRealmAuthenticator authenticator) {
DefaultWebSecurityManager defaultSecurityManager = new DefaultWebSecurityManager();
defaultSecurityManager.setAuthenticator(authenticator);
defaultSecurityManager.setSessionManager(sessionManager);
// defaultSecurityManager.setSubjectFactory(new HeaderDefaultSubjectFactory());
return defaultSecurityManager;
}
public SimpleCookie sessionIdCookie(){
//这个参数是cookie的名称
SimpleCookie simpleCookie = new SimpleCookie("JSESSIONID");
simpleCookie.setHttpOnly(true);
simpleCookie.setSecure(true);
//maxAge=-1表示浏览器关闭时失效此Cookie
simpleCookie.setMaxAge(10800000);
return simpleCookie;
}
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
/**
* 添加jwt过滤器,并在下面注册
* 也就是将jwtFilter注册到shiro的Filter中
* 指定除了login和logout之外的请求都先经过jwtFilter
*/
Map<String, Filter> filterMap = new HashMap<>();
//这个地方其实另外两个filter可以不设置,默认就是
filterMap.put("hf", new HeaderFilter());
factoryBean.setFilters(filterMap);
factoryBean.setSecurityManager(securityManager);
factoryBean.setLoginUrl("/login");
factoryBean.setSuccessUrl("/index");
factoryBean.setUnauthorizedUrl("/unauthorized");
Map<String, String> map = new LinkedHashMap<>();
/**
|
* {@link DefaultFilter}
*/
map.put("/doLogin", "anon");
map.put("/getLogin/**", "anon");
map.put("/anno/hello1", "anon");
map.put("/vip", "roles[admin]");
map.put("/common", "roles[user]");
// 登陆鉴权
map.put("/**", "hf,authc");
// header 鉴权
factoryBean.setFilterChainDefinitionMap(map);
return factoryBean;
}
/**
* 一下三个bean是为了让@RequiresRoles({"admin"}) 生效
* 这两个是 Shiro 的注解,我们需要借助 SpringAOP 扫描到它们
*
* @return
*/
@Bean
public static LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
@Bean
public static DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
advisorAutoProxyCreator.setProxyTargetClass(true);
return advisorAutoProxyCreator;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
}
|
repos\spring-boot-quick-master\quick-shiro\src\main\java\com\shiro\quick\config\ShiroConfig.java
| 2
|
请完成以下Java代码
|
public void add(int value, char[]... keyArray)
{
add(convert(keyArray), value);
}
public void add(int value, Collection<char[]> keyArray)
{
add(convert(keyArray), value);
}
private String convert(Collection<char[]> keyArray)
{
StringBuilder sbKey = new StringBuilder(keyArray.size() * 2);
for (char[] key : keyArray)
{
sbKey.append(key[0]);
sbKey.append(key[1]);
}
return sbKey.toString();
}
static private String convert(char[]... keyArray)
{
StringBuilder sbKey = new StringBuilder(keyArray.length * 2);
for (char[] key : keyArray)
{
sbKey.append(key[0]);
sbKey.append(key[1]);
}
return sbKey.toString();
}
|
@Override
public void save(DataOutputStream out) throws Exception
{
out.writeInt(total);
Integer[] valueArray = d.getValueArray(new Integer[0]);
out.writeInt(valueArray.length);
for (Integer v : valueArray)
{
out.writeInt(v);
}
d.save(out);
}
@Override
public boolean load(ByteArray byteArray)
{
total = byteArray.nextInt();
int size = byteArray.nextInt();
Integer[] valueArray = new Integer[size];
for (int i = 0; i < valueArray.length; ++i)
{
valueArray[i] = byteArray.nextInt();
}
d.load(byteArray, valueArray);
return true;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\trigram\frequency\Probability.java
| 1
|
请完成以下Java代码
|
public LocalDate getBegin() {
return begin;
}
public void setBegin(LocalDate begin) {
this.begin = begin;
}
public LocalDate getEnd() {
return end;
}
public void setEnd(LocalDate end) {
this.end = end;
}
public Customer getCustomer() {
|
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public int getRoom() {
return room;
}
public void setRoom(int room) {
this.room = room;
}
}
|
repos\tutorials-master\javaxval\src\main\java\com\baeldung\javaxval\methodvalidation\model\Reservation.java
| 1
|
请完成以下Java代码
|
public List<InstructionForCreditorAgent1> getInstrForCdtrAgt() {
if (instrForCdtrAgt == null) {
instrForCdtrAgt = new ArrayList<InstructionForCreditorAgent1>();
}
return this.instrForCdtrAgt;
}
/**
* Gets the value of the instrForDbtrAgt property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getInstrForDbtrAgt() {
return instrForDbtrAgt;
}
/**
* Sets the value of the instrForDbtrAgt property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInstrForDbtrAgt(String value) {
this.instrForDbtrAgt = value;
}
/**
* Gets the value of the purp property.
*
* @return
* possible object is
* {@link Purpose2CHCode }
*
*/
public Purpose2CHCode getPurp() {
return purp;
}
/**
* Sets the value of the purp property.
*
* @param value
* allowed object is
* {@link Purpose2CHCode }
*
*/
public void setPurp(Purpose2CHCode value) {
this.purp = value;
}
/**
* Gets the value of the rgltryRptg property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the rgltryRptg property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRgltryRptg().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link RegulatoryReporting3 }
*
|
*
*/
public List<RegulatoryReporting3> getRgltryRptg() {
if (rgltryRptg == null) {
rgltryRptg = new ArrayList<RegulatoryReporting3>();
}
return this.rgltryRptg;
}
/**
* Gets the value of the rmtInf property.
*
* @return
* possible object is
* {@link RemittanceInformation5CH }
*
*/
public RemittanceInformation5CH getRmtInf() {
return rmtInf;
}
/**
* Sets the value of the rmtInf property.
*
* @param value
* allowed object is
* {@link RemittanceInformation5CH }
*
*/
public void setRmtInf(RemittanceInformation5CH value) {
this.rmtInf = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\CreditTransferTransactionInformation10CH.java
| 1
|
请完成以下Java代码
|
public void addPrinterHW(final PrinterHWList printerHWList)
{
log.info("Found printer HWs: " + printerHWList);
}
@Override
public PrintPackage getNextPrintPackage()
{
pollNewFiles();
return buffer.getNextPrintPackage();
}
@Override
public InputStream getPrintPackageData(final PrintPackage printPackage)
{
return buffer.getPrintPackageData(printPackage);
}
@Override
public void sendPrintPackageResponse(final PrintPackage printPackage, final PrintJobInstructionsConfirm response)
{
log.info("Got : " + response + " for " + printPackage);
}
private void pollNewFiles()
{
log.fine("Polling directory: " + directory);
final File[] files = directory.listFiles();
if (files == null || files.length == 0)
{
return;
}
for (final File file : files)
{
if (!file.isFile())
{
continue;
}
final String ext = Util.getFileExtension(file.getName());
if (!fileExtension.equals(ext))
{
continue;
}
enqueueFile(file);
}
}
private boolean enqueueFile(final File file)
{
log.info("Enqueuing " + file);
PrintPackage printPackage = null;
InputStream printPackageStream = null;
final File dataFile = new File(Util.changeFileExtension(file.getAbsolutePath(), "pdf"));
InputStream printDataStream = null;
try
{
printPackageStream = new FileInputStream(file);
printPackage = beanEncoder.decodeStream(printPackageStream, PrintPackage.class);
printPackageStream.close();
printPackageStream = null;
printDataStream = new FileInputStream(dataFile);
final byte[] data = Util.toByteArray(printDataStream);
printDataStream.close();
printDataStream = new ByteArrayInputStream(data);
|
file.delete();
dataFile.delete();
}
catch (final Exception e)
{
log.log(Level.WARNING, e.getLocalizedMessage(), e);
return false;
}
finally
{
Util.close(printPackageStream);
Util.close(printDataStream);
}
log.info("Adding package to buffer: " + printPackage);
buffer.addPrintPackage(printPackage, printDataStream);
return true;
}
@Override
public String toString()
{
return "DirectoryPrintConnectionEndpoint [directory=" + directory + ", fileExtension=" + fileExtension + ", beanEncoder=" + beanEncoder + ", buffer=" + buffer + "]";
}
@Override
public LoginResponse login(final LoginRequest loginRequest)
{
throw new UnsupportedOperationException();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\endpoint\DirectoryPrintConnectionEndpoint.java
| 1
|
请完成以下Java代码
|
public Long getNewsId() {
return newsId;
}
public void setNewsId(Long newsId) {
this.newsId = newsId;
}
public String getNewsTitle() {
return newsTitle;
}
public void setNewsTitle(String newsTitle) {
this.newsTitle = newsTitle == null ? null : newsTitle.trim();
}
public Long getNewsCategoryId() {
return newsCategoryId;
}
public void setNewsCategoryId(Long newsCategoryId) {
this.newsCategoryId = newsCategoryId;
}
public String getNewsCoverImage() {
return newsCoverImage;
}
public void setNewsCoverImage(String newsCoverImage) {
this.newsCoverImage = newsCoverImage == null ? null : newsCoverImage.trim();
}
public Byte getNewsStatus() {
return newsStatus;
}
public void setNewsStatus(Byte newsStatus) {
this.newsStatus = newsStatus;
}
public Long getNewsViews() {
return newsViews;
}
public void setNewsViews(Long newsViews) {
this.newsViews = newsViews;
}
public Byte getIsDeleted() {
return isDeleted;
}
|
public void setIsDeleted(Byte isDeleted) {
this.isDeleted = isDeleted;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getNewsContent() {
return newsContent;
}
public void setNewsContent(String newsContent) {
this.newsContent = newsContent;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", newsId=").append(newsId);
sb.append(", newsTitle=").append(newsTitle);
sb.append(", newsCategoryId=").append(newsCategoryId);
sb.append(", newsCoverImage=").append(newsCoverImage);
sb.append(", newsStatus=").append(newsStatus);
sb.append(", newsViews=").append(newsViews);
sb.append(", isDeleted=").append(isDeleted);
sb.append(", createTime=").append(createTime);
sb.append(", updateTime=").append(updateTime);
sb.append("]");
return sb.toString();
}
}
|
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\entity\News.java
| 1
|
请完成以下Java代码
|
public List<String> execute(CommandContext commandContext) {
if (executionId == null) {
throw new ActivitiIllegalArgumentException("executionId is null");
}
ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager();
ExecutionEntity execution = executionEntityManager.findById(executionId);
if (execution == null) {
throw new ActivitiObjectNotFoundException("execution " + executionId + " doesn't exist", Execution.class);
}
return findActiveActivityIds(execution);
}
|
public List<String> findActiveActivityIds(ExecutionEntity executionEntity) {
List<String> activeActivityIds = new ArrayList<String>();
collectActiveActivityIds(executionEntity, activeActivityIds);
return activeActivityIds;
}
protected void collectActiveActivityIds(ExecutionEntity executionEntity, List<String> activeActivityIds) {
if (executionEntity.isActive() && executionEntity.getActivityId() != null) {
activeActivityIds.add(executionEntity.getActivityId());
}
for (ExecutionEntity childExecution : executionEntity.getExecutions()) {
collectActiveActivityIds(childExecution, activeActivityIds);
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\FindActiveActivityIdsCmd.java
| 1
|
请完成以下Java代码
|
public double apply(double n) {
return subtract1(add3(divideBy2(multiplyBy2(multiplyBy2(2)))));
}
}
class MonadSample2 extends MonadBaseExample {
public double apply(double n) {
double n1 = multiplyBy2(n);
double n2 = multiplyBy2(n1);
double n3 = divideBy2(n2);
double n4 = add3(n3);
return subtract1(n4);
}
}
class MonadSample3 extends MonadBaseExample {
public double apply(double n) {
return Optional.of(n)
.flatMap(value -> Optional.of(multiplyBy2(value)))
.flatMap(value -> Optional.of(multiplyBy2(value)))
.flatMap(value -> Optional.of(divideBy2(value)))
.flatMap(value -> Optional.of(add3(value)))
.flatMap(value -> Optional.of(subtract1(value)))
.get();
}
}
class MonadSample4 extends MonadBaseExample {
public boolean leftIdentity() {
Function<Integer, Optional<Integer>> mapping = value -> Optional.of(value + 1);
return Optional.of(3).flatMap(mapping).equals(mapping.apply(3));
}
public boolean rightIdentity() {
return Optional.of(3).flatMap(Optional::of).equals(Optional.of(3));
}
|
public boolean associativity() {
Function<Integer, Optional<Integer>> mapping = value -> Optional.of(value + 1);
Optional<Integer> leftSide = Optional.of(3).flatMap(mapping).flatMap(Optional::of);
Optional<Integer> rightSide = Optional.of(3).flatMap(v -> mapping.apply(v).flatMap(Optional::of));
return leftSide.equals(rightSide);
}
}
class MonadSample5 extends MonadBaseExample {
public boolean fail() {
Function<Integer, Optional<Integer>> mapping = value -> Optional.of(value == null ? -1 : value + 1);
return Optional.ofNullable((Integer) null).flatMap(mapping).equals(mapping.apply(null));
}
}
|
repos\tutorials-master\core-java-modules\core-java-8\src\main\java\com\baeldung\monad\MonadSamples.java
| 1
|
请完成以下Java代码
|
public TaxRecord1 createTaxRecord1() {
return new TaxRecord1();
}
/**
* Create an instance of {@link TaxRecordDetails1 }
*
*/
public TaxRecordDetails1 createTaxRecordDetails1() {
return new TaxRecordDetails1();
}
/**
* Create an instance of {@link TechnicalInputChannel1Choice }
*
*/
public TechnicalInputChannel1Choice createTechnicalInputChannel1Choice() {
return new TechnicalInputChannel1Choice();
}
/**
* Create an instance of {@link TotalTransactions2 }
*
*/
public TotalTransactions2 createTotalTransactions2() {
return new TotalTransactions2();
}
/**
* Create an instance of {@link TotalsPerBankTransactionCode2 }
*
*/
public TotalsPerBankTransactionCode2 createTotalsPerBankTransactionCode2() {
return new TotalsPerBankTransactionCode2();
}
/**
* Create an instance of {@link TransactionAgents2 }
*
*/
public TransactionAgents2 createTransactionAgents2() {
return new TransactionAgents2();
}
/**
* Create an instance of {@link TransactionDates2 }
*
*/
public TransactionDates2 createTransactionDates2() {
return new TransactionDates2();
}
/**
* Create an instance of {@link TransactionInterest2 }
*
*/
public TransactionInterest2 createTransactionInterest2() {
return new TransactionInterest2();
}
/**
* Create an instance of {@link TransactionParty2 }
*
*/
public TransactionParty2 createTransactionParty2() {
return new TransactionParty2();
}
/**
* Create an instance of {@link TransactionPrice2Choice }
*
*/
public TransactionPrice2Choice createTransactionPrice2Choice() {
return new TransactionPrice2Choice();
|
}
/**
* Create an instance of {@link TransactionQuantities1Choice }
*
*/
public TransactionQuantities1Choice createTransactionQuantities1Choice() {
return new TransactionQuantities1Choice();
}
/**
* Create an instance of {@link TransactionReferences2 }
*
*/
public TransactionReferences2 createTransactionReferences2() {
return new TransactionReferences2();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link Document }{@code >}
*
* @param value
* Java instance representing xml element's value.
* @return
* the new instance of {@link JAXBElement }{@code <}{@link Document }{@code >}
*/
@XmlElementDecl(namespace = "urn:iso:std:iso:20022:tech:xsd:camt.053.001.02", name = "Document")
public JAXBElement<Document> createDocument(Document value) {
return new JAXBElement<Document>(_Document_QNAME, Document.class, null, value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\ObjectFactory.java
| 1
|
请完成以下Java代码
|
default boolean isPublicField() { return getDescriptor().hasCharacteristic(Characteristic.PublicField); }
default boolean isAdvancedField() { return getDescriptor().hasCharacteristic(Characteristic.AdvancedField); }
//@formatter:on
//@formatter:off
default Class<?> getValueClass() { return getDescriptor().getValueClass(); }
/** @return field's current value */
@Nullable
Object getValue();
@Nullable
Object getValueAsJsonObject(JSONOptions jsonOpts);
boolean getValueAsBoolean();
int getValueAsInt(final int defaultValueWhenNull);
DocumentZoomIntoInfo getZoomIntoInfo();
@Nullable
<T> T getValueAs(@NonNull final Class<T> returnType);
default Optional<BigDecimal> getValueAsBigDecimal() { return Optional.ofNullable(getValueAs(BigDecimal.class));}
default <T extends RepoIdAware> Optional<T> getValueAsId(Class<T> idType) { return Optional.ofNullable(getValueAs(idType));}
|
/** @return initial value / last saved value */
@Nullable
Object getInitialValue();
/** @return old value (i.e. the value as it was when the document was checked out from repository/documents collection) */
@Nullable
Object getOldValue();
//@formatter:on
/**
* @return field's valid state; never return null
*/
DocumentValidStatus getValidStatus();
/**
* @return optional WindowId to be used when zooming into
*/
Optional<WindowId> getZoomIntoWindowId();
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\IDocumentFieldView.java
| 1
|
请完成以下Java代码
|
public BigDecimal retrieveQtyOrdered(final int productId,
final int warehouseId)
{
ResultSet rs = null;
final PreparedStatement pstmt = DB.prepareStatement(
SQL_SELECT_QTY_ORDERED, null);
try
{
pstmt.setInt(1, productId);
pstmt.setInt(2, warehouseId);
rs = pstmt.executeQuery();
if (rs.next())
{
final BigDecimal qtyOrdered = rs.getBigDecimal(1);
if (qtyOrdered == null)
{
return BigDecimal.ZERO;
}
return qtyOrdered;
}
|
throw new RuntimeException(
"Unable to retrive qtyOrdererd for M_Product_ID '"
+ productId + "'");
}
catch (SQLException e)
{
throw new RuntimeException(e);
}
finally
{
DB.close(rs, pstmt);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\product\impl\StoragePA.java
| 1
|
请完成以下Java代码
|
public void setM_HU_ID (final int M_HU_ID)
{
if (M_HU_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_ID, M_HU_ID);
}
@Override
public int getM_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_ID);
}
@Override
public org.eevolution.model.I_PP_Order getPP_Order()
{
return get_ValueAsPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class);
}
@Override
public void setPP_Order(final org.eevolution.model.I_PP_Order PP_Order)
{
set_ValueFromPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class, PP_Order);
}
@Override
public void setPP_Order_ID (final int PP_Order_ID)
{
if (PP_Order_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_ID, null);
else
|
set_ValueNoCheck (COLUMNNAME_PP_Order_ID, PP_Order_ID);
}
@Override
public int getPP_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_ID);
}
@Override
public void setPP_Order_SourceHU_ID (final int PP_Order_SourceHU_ID)
{
if (PP_Order_SourceHU_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_SourceHU_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_SourceHU_ID, PP_Order_SourceHU_ID);
}
@Override
public int getPP_Order_SourceHU_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_SourceHU_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_SourceHU.java
| 1
|
请完成以下Java代码
|
public class DefaultCockpitRuntimeDelegate extends AbstractAppRuntimeDelegate<CockpitPlugin> implements CockpitRuntimeDelegate {
private Map<String, CommandExecutor> commandExecutors;
public DefaultCockpitRuntimeDelegate() {
super(CockpitPlugin.class);
this.commandExecutors = new HashMap<String, CommandExecutor>();
}
@Override
public QueryService getQueryService(String processEngineName) {
CommandExecutor commandExecutor = getCommandExecutor(processEngineName);
return new QueryServiceImpl(commandExecutor);
}
@Override
public CommandExecutor getCommandExecutor(String processEngineName) {
CommandExecutor commandExecutor = commandExecutors.get(processEngineName);
if (commandExecutor == null) {
commandExecutor = createCommandExecutor(processEngineName);
commandExecutors.put(processEngineName, commandExecutor);
}
return commandExecutor;
}
/**
* Deprecated: use {@link #getAppPluginRegistry()}
*/
@Deprecated
public PluginRegistry getPluginRegistry() {
return new DefaultPluginRegistry(pluginRegistry);
}
/**
|
* Returns the list of mapping files that should be used to create the
* session factory for this runtime.
*
* @return
*/
protected List<String> getMappingFiles() {
List<CockpitPlugin> cockpitPlugins = pluginRegistry.getPlugins();
List<String> mappingFiles = new ArrayList<String>();
for (CockpitPlugin plugin: cockpitPlugins) {
mappingFiles.addAll(plugin.getMappingFiles());
}
return mappingFiles;
}
/**
* Create command executor for the engine with the given name
*
* @param processEngineName
* @return
*/
protected CommandExecutor createCommandExecutor(String processEngineName) {
ProcessEngine processEngine = getProcessEngine(processEngineName);
if (processEngine == null) {
throw new ProcessEngineException("No process engine with name " + processEngineName + " found.");
}
ProcessEngineConfigurationImpl processEngineConfiguration = ((ProcessEngineImpl)processEngine).getProcessEngineConfiguration();
List<String> mappingFiles = getMappingFiles();
return new CommandExecutorImpl(processEngineConfiguration, mappingFiles);
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\DefaultCockpitRuntimeDelegate.java
| 1
|
请完成以下Java代码
|
public IDatabase getDatabase()
{
return database;
}
public ScriptExecutionException setDatabase(final IDatabase database)
{
addParameter("database", database);
this.database = database;
return this;
}
public IScript getScript()
{
return script;
}
public ScriptExecutionException setScript(final IScript script)
{
addParameter("script", script);
this.script = script;
return this;
}
public IScriptExecutor getExecutor()
{
|
return executor;
}
public ScriptExecutionException setExecutor(final IScriptExecutor executor)
{
addParameter("executor", executor);
this.executor = executor;
return this;
}
public ScriptExecutionException setLog(final List<String> log)
{
addParameter("log", log);
this.log = log;
return this;
}
public List<String> getLog()
{
if (log == null)
{
return Collections.emptyList();
}
return log;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\exception\ScriptExecutionException.java
| 1
|
请完成以下Java代码
|
public void setSessionAuthenticationStrategy(SessionAuthenticationStrategy sessionStrategy) {
this.sessionStrategy = sessionStrategy;
}
/**
* Sets the strategy used to handle a successful authentication. By default a
* {@link SavedRequestAwareAuthenticationSuccessHandler} is used.
*/
public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler successHandler) {
Assert.notNull(successHandler, "successHandler cannot be null");
this.successHandler = successHandler;
}
public void setAuthenticationFailureHandler(AuthenticationFailureHandler failureHandler) {
Assert.notNull(failureHandler, "failureHandler cannot be null");
this.failureHandler = failureHandler;
}
/**
* Sets the {@link SecurityContextRepository} to save the {@link SecurityContext} on
* authentication success. The default action is not to save the
* {@link SecurityContext}.
* @param securityContextRepository the {@link SecurityContextRepository} to use.
* Cannot be null.
*/
public void setSecurityContextRepository(SecurityContextRepository securityContextRepository) {
Assert.notNull(securityContextRepository, "securityContextRepository cannot be null");
this.securityContextRepository = securityContextRepository;
}
/**
* 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;
}
protected AuthenticationSuccessHandler getSuccessHandler() {
return this.successHandler;
}
protected AuthenticationFailureHandler getFailureHandler() {
return this.failureHandler;
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\AbstractAuthenticationProcessingFilter.java
| 1
|
请完成以下Java代码
|
public ProcessInstance correlateStartMessage() {
startMessageOnly();
MessageCorrelationResult result = correlateWithResult();
return result.getProcessInstance();
}
protected void ensureProcessDefinitionIdNotSet() {
if(processDefinitionId != null) {
throw LOG.exceptionCorrelateMessageWithProcessDefinitionId();
}
}
protected void ensureProcessInstanceAndTenantIdNotSet() {
if (processInstanceId != null && isTenantIdSet) {
throw LOG.exceptionCorrelateMessageWithProcessInstanceAndTenantId();
}
}
protected void ensureCorrelationVariablesNotSet() {
if (correlationProcessInstanceVariables != null || correlationLocalVariables != null) {
throw LOG.exceptionCorrelateStartMessageWithCorrelationVariables();
}
}
protected void ensureProcessDefinitionAndTenantIdNotSet() {
if (processDefinitionId != null && isTenantIdSet) {
throw LOG.exceptionCorrelateMessageWithProcessDefinitionAndTenantId();
}
}
protected <T> T execute(Command<T> command) {
if(commandExecutor != null) {
return commandExecutor.execute(command);
} else {
return command.execute(commandContext);
}
}
// getters //////////////////////////////////
public CommandExecutor getCommandExecutor() {
return commandExecutor;
}
public CommandContext getCommandContext() {
return commandContext;
}
public String getMessageName() {
return messageName;
}
public String getBusinessKey() {
return businessKey;
}
public String getProcessInstanceId() {
|
return processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public Map<String, Object> getCorrelationProcessInstanceVariables() {
return correlationProcessInstanceVariables;
}
public Map<String, Object> getCorrelationLocalVariables() {
return correlationLocalVariables;
}
public Map<String, Object> getPayloadProcessInstanceVariables() {
return payloadProcessInstanceVariables;
}
public VariableMap getPayloadProcessInstanceVariablesLocal() {
return payloadProcessInstanceVariablesLocal;
}
public VariableMap getPayloadProcessInstanceVariablesToTriggeredScope() {
return payloadProcessInstanceVariablesToTriggeredScope;
}
public boolean isExclusiveCorrelation() {
return isExclusiveCorrelation;
}
public String getTenantId() {
return tenantId;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
public boolean isExecutionsOnly() {
return executionsOnly;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\MessageCorrelationBuilderImpl.java
| 1
|
请完成以下Java代码
|
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Null Value.
@param IsNullFieldValue Null Value */
@Override
public void setIsNullFieldValue (boolean IsNullFieldValue)
{
set_Value (COLUMNNAME_IsNullFieldValue, Boolean.valueOf(IsNullFieldValue));
}
/** Get Null Value.
@return Null Value */
@Override
public boolean isNullFieldValue ()
{
Object oo = get_Value(COLUMNNAME_IsNullFieldValue);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public org.compiere.model.I_M_Attribute getM_Attribute() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Attribute_ID, org.compiere.model.I_M_Attribute.class);
}
@Override
public void setM_Attribute(org.compiere.model.I_M_Attribute M_Attribute)
{
set_ValueFromPO(COLUMNNAME_M_Attribute_ID, org.compiere.model.I_M_Attribute.class, M_Attribute);
}
/** Set Merkmal.
@param M_Attribute_ID
Product Attribute
*/
@Override
public void setM_Attribute_ID (int M_Attribute_ID)
{
if (M_Attribute_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Attribute_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Attribute_ID, Integer.valueOf(M_Attribute_ID));
}
/** Get Merkmal.
@return Product Attribute
*/
@Override
public int getM_Attribute_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Attribute_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Merkmals-Wert.
@param M_AttributeValue_ID
Product Attribute Value
*/
@Override
public void setM_AttributeValue_ID (int M_AttributeValue_ID)
|
{
if (M_AttributeValue_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_AttributeValue_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeValue_ID, Integer.valueOf(M_AttributeValue_ID));
}
/** Get Merkmals-Wert.
@return Product Attribute Value
*/
@Override
public int getM_AttributeValue_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeValue_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Suchschlüssel.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
set_ValueNoCheck (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeValue.java
| 1
|
请完成以下Java代码
|
public class CustomAuthorizationRequestResolver implements OAuth2AuthorizationRequestResolver {
private OAuth2AuthorizationRequestResolver defaultResolver;
public CustomAuthorizationRequestResolver(ClientRegistrationRepository repo, String authorizationRequestBaseUri){
defaultResolver = new DefaultOAuth2AuthorizationRequestResolver(repo, authorizationRequestBaseUri);
}
@Override
public OAuth2AuthorizationRequest resolve(HttpServletRequest request) {
OAuth2AuthorizationRequest req = defaultResolver.resolve(request);
if(req != null){
req = customizeAuthorizationRequest(req);
}
return req;
}
@Override
public OAuth2AuthorizationRequest resolve(HttpServletRequest request, String clientRegistrationId) {
OAuth2AuthorizationRequest req = defaultResolver.resolve(request, clientRegistrationId);
if(req != null){
req = customizeAuthorizationRequest(req);
}
return req;
}
|
private OAuth2AuthorizationRequest customizeAuthorizationRequest(OAuth2AuthorizationRequest req) {
Map<String,Object> extraParams = new HashMap<String,Object>();
extraParams.putAll(req.getAdditionalParameters()); //VIP note
extraParams.put("test", "extra");
System.out.println("here =====================");
return OAuth2AuthorizationRequest.from(req).additionalParameters(extraParams).build();
}
private OAuth2AuthorizationRequest customizeAuthorizationRequest1(OAuth2AuthorizationRequest req) {
return OAuth2AuthorizationRequest.from(req).state("xyz").build();
}
private OAuth2AuthorizationRequest customizeOktaReq(OAuth2AuthorizationRequest req) {
Map<String,Object> extraParams = new HashMap<String,Object>();
extraParams.putAll(req.getAdditionalParameters());
extraParams.put("idp", "https://idprovider.com");
return OAuth2AuthorizationRequest.from(req).additionalParameters(extraParams).build();
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-oauth2\src\main\java\com\baeldung\oauth2request\CustomAuthorizationRequestResolver.java
| 1
|
请完成以下Java代码
|
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<CustomProperty> getCustomProperties() {
return customProperties;
}
public void setCustomProperties(List<CustomProperty> customProperties) {
this.customProperties = customProperties;
}
public String getOperationRef() {
return operationRef;
}
public void setOperationRef(String operationRef) {
this.operationRef = operationRef;
}
public String getExtensionId() {
return extensionId;
}
public void setExtensionId(String extensionId) {
this.extensionId = extensionId;
}
public boolean isExtended() {
return extensionId != null && !extensionId.isEmpty();
}
public String getSkipExpression() {
return skipExpression;
}
public void setSkipExpression(String skipExpression) {
this.skipExpression = skipExpression;
}
|
public boolean hasBoundaryErrorEvents() {
if (this.boundaryEvents != null && !this.boundaryEvents.isEmpty()) {
return this.boundaryEvents.stream().anyMatch(boundaryEvent -> boundaryEvent.hasErrorEventDefinition());
}
return false;
}
public ServiceTask clone() {
ServiceTask clone = new ServiceTask();
clone.setValues(this);
return clone;
}
public void setValues(ServiceTask otherElement) {
super.setValues(otherElement);
setImplementation(otherElement.getImplementation());
setImplementationType(otherElement.getImplementationType());
setResultVariableName(otherElement.getResultVariableName());
setType(otherElement.getType());
setOperationRef(otherElement.getOperationRef());
setExtensionId(otherElement.getExtensionId());
setSkipExpression(otherElement.getSkipExpression());
fieldExtensions = new ArrayList<FieldExtension>();
if (otherElement.getFieldExtensions() != null && !otherElement.getFieldExtensions().isEmpty()) {
for (FieldExtension extension : otherElement.getFieldExtensions()) {
fieldExtensions.add(extension.clone());
}
}
customProperties = new ArrayList<CustomProperty>();
if (otherElement.getCustomProperties() != null && !otherElement.getCustomProperties().isEmpty()) {
for (CustomProperty property : otherElement.getCustomProperties()) {
customProperties.add(property.clone());
}
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\ServiceTask.java
| 1
|
请完成以下Java代码
|
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSimpleValue() {
return simpleValue;
}
public void setSimpleValue(String simpleValue) {
this.simpleValue = simpleValue;
}
public ComplexDataType getComplexValue() {
return complexValue;
}
public void setComplexValue(ComplexDataType complexValue) {
|
this.complexValue = complexValue;
}
public CustomProperty clone() {
CustomProperty clone = new CustomProperty();
clone.setValues(this);
return clone;
}
public void setValues(CustomProperty otherProperty) {
setName(otherProperty.getName());
setSimpleValue(otherProperty.getSimpleValue());
if (otherProperty.getComplexValue() != null && otherProperty.getComplexValue() instanceof DataGrid) {
setComplexValue(((DataGrid) otherProperty.getComplexValue()).clone());
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\CustomProperty.java
| 1
|
请完成以下Java代码
|
public class MutableAmount implements IMutable<Amount>
{
private Amount value;
public MutableAmount(@Nullable final Amount value)
{
this.value = value;
}
public static MutableAmount zero(@NonNull final CurrencyCode currencyCode) {return new MutableAmount(Amount.zero(currencyCode));}
@Override
public String toString() {return String.valueOf(value);}
public Amount toAmount() {return value;}
|
@Nullable
@Override
public Amount getValue() {return value;}
@Override
public void setValue(@Nullable final Amount value) {this.value = value;}
public void add(@NonNull final Amount other)
{
this.value = value != null
? value.add(other)
: other;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\MutableAmount.java
| 1
|
请完成以下Java代码
|
public class TreeNode {
int value;
TreeNode left;
TreeNode right;
public TreeNode(int value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TreeNode treeNode = (TreeNode) o;
return value == treeNode.value;
}
@Override
public int hashCode() {
return Objects.hash(value);
}
public void insert(int value) {
insert(this, value);
}
private void insert(TreeNode currentNode, final int value) {
if (currentNode.left == null && value < currentNode.value) {
currentNode.left = new TreeNode(value);
return;
}
if (currentNode.right == null && value > currentNode.value) {
currentNode.right = new TreeNode(value);
return;
}
if (value > currentNode.value) {
insert(currentNode.right, value);
}
if (value < currentNode.value) {
insert(currentNode.left, value);
}
}
public TreeNode parent(int target) throws NoSuchElementException {
return parent(this, new TreeNode(target));
}
private TreeNode parent(TreeNode current, TreeNode target) throws NoSuchElementException {
|
if (target.equals(current) || current == null) {
throw new NoSuchElementException(format("No parent node found for 'target.value=%s' " +
"The target is not in the tree or the target is the topmost root node.",
target.value));
}
if (target.equals(current.left) || target.equals(current.right)) {
return current;
}
return parent(target.value < current.value ? current.left : current.right, target);
}
public TreeNode iterativeParent(int target) {
return iterativeParent(this, new TreeNode(target));
}
private TreeNode iterativeParent(TreeNode current, TreeNode target) {
Deque<TreeNode> parentCandidates = new LinkedList<>();
String notFoundMessage = format("No parent node found for 'target.value=%s' " +
"The target is not in the tree or the target is the topmost root node.",
target.value);
if (target.equals(current)) {
throw new NoSuchElementException(notFoundMessage);
}
while (current != null || !parentCandidates.isEmpty()) {
while (current != null) {
parentCandidates.addFirst(current);
current = current.left;
}
current = parentCandidates.pollFirst();
if (target.equals(current.left) || target.equals(current.right)) {
return current;
}
current = current.right;
}
throw new NoSuchElementException(notFoundMessage);
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-8\src\main\java\com\baeldung\algorithms\parentnodebinarytree\TreeNode.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
SecurityFilterChain customJwtSecurityChain(HttpSecurity http, JwtAuthorizationProperties props) throws Exception {
// @formatter:off
return http
.authorizeHttpRequests( r -> r.anyRequest().authenticated())
.oauth2Login(oauth2 -> oauth2.userInfoEndpoint(ep ->
ep.oidcUserService(customOidcUserService(props))))
.build();
// @formatter:on
}
private OAuth2UserService<OidcUserRequest, OidcUser> customOidcUserService(JwtAuthorizationProperties props) {
final OidcUserService delegate = new OidcUserService();
final GroupsClaimMapper mapper = new GroupsClaimMapper(
props.getAuthoritiesPrefix(),
props.getGroupsClaim(),
|
props.getGroupToAuthorities());
return userRequest -> {
OidcUser oidcUser = delegate.loadUser(userRequest);
// Enrich standard authorities with groups
Set<GrantedAuthority> mappedAuthorities = new HashSet<>();
mappedAuthorities.addAll(oidcUser.getAuthorities());
mappedAuthorities.addAll(mapper.mapAuthorities(oidcUser));
oidcUser = new NamedOidcUser(mappedAuthorities, oidcUser.getIdToken(), oidcUser.getUserInfo(),oidcUser.getName());
return oidcUser;
};
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-azuread\src\main\java\com\baeldung\security\azuread\config\JwtAuthorizationConfiguration.java
| 2
|
请完成以下Java代码
|
public Builder type(ClassName type) {
return type(type.getName());
}
/**
* Specify the {@link Class type} of the parameter.
* @param type the type
* @return this for method chaining
*/
public Builder type(Class<?> type) {
return type(type.getCanonicalName());
}
/**
* Specify the type of the parameter.
* @param type the type
* @return this for method chaining
*/
public Builder type(String type) {
this.type = type;
return this;
}
/**
* Annotate the parameter with the specified annotation.
* @param className the class of the annotation
* @return this for method chaining
* @deprecated in favor of {@link #singleAnnotate(ClassName)} and
* {@link #repeatableAnnotate(ClassName)}
*/
@Deprecated(forRemoval = true)
public Builder annotate(ClassName className) {
return annotate(className, null);
}
/**
* Annotate the parameter with the specified annotation, customized by the
* specified consumer.
* @param className the class of the annotation
* @param annotation a consumer of the builder
* @return this for method chaining
* @deprecated in favor of {@link #singleAnnotate(ClassName, Consumer)} and
* {@link #singleAnnotate(ClassName)}
*/
@Deprecated(forRemoval = true)
@SuppressWarnings("removal")
public Builder annotate(ClassName className, Consumer<Annotation.Builder> annotation) {
this.annotations.add(className, annotation);
return this;
}
/**
* Annotate the parameter with the specified single annotation.
* @param className the class of the annotation
* @return this for method chaining
*/
public Builder singleAnnotate(ClassName className) {
return singleAnnotate(className, null);
|
}
/**
* Annotate the parameter with the specified single annotation, customized by the
* specified consumer.
* @param className the class of the annotation
* @param annotation a consumer of the builder
* @return this for method chaining
*/
public Builder singleAnnotate(ClassName className, Consumer<Annotation.Builder> annotation) {
this.annotations.addSingle(className, annotation);
return this;
}
/**
* Annotate the parameter with the specified repeatable annotation.
* @param className the class of the annotation
* @return this for method chaining
*/
public Builder repeatableAnnotate(ClassName className) {
return repeatableAnnotate(className, null);
}
/**
* Annotate the parameter with the specified repeatable annotation, customized by
* the specified consumer.
* @param className the class of the annotation
* @param annotation a consumer of the builder
* @return this for method chaining
*/
public Builder repeatableAnnotate(ClassName className, Consumer<Annotation.Builder> annotation) {
this.annotations.addRepeatable(className, annotation);
return this;
}
public Parameter build() {
return new Parameter(this);
}
}
}
|
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\Parameter.java
| 1
|
请完成以下Java代码
|
public String getValue() {
return this.value;
}
static ClientAuthenticationMethod[] methods() {
return new ClientAuthenticationMethod[] { CLIENT_SECRET_BASIC, CLIENT_SECRET_POST, CLIENT_SECRET_JWT,
PRIVATE_KEY_JWT, NONE, TLS_CLIENT_AUTH, SELF_SIGNED_TLS_CLIENT_AUTH };
}
/**
* A factory to construct a {@link ClientAuthenticationMethod} based on a string,
* returning any constant value that matches.
* @param method the client authentication method
* @return a {@link ClientAuthenticationMethod}; specifically the corresponding
* constant, if any
* @since 6.5
*/
@NonNull
public static ClientAuthenticationMethod valueOf(String method) {
for (ClientAuthenticationMethod m : methods()) {
if (m.getValue().equals(method)) {
return m;
}
}
return new ClientAuthenticationMethod(method);
}
|
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || this.getClass() != obj.getClass()) {
return false;
}
ClientAuthenticationMethod that = (ClientAuthenticationMethod) obj;
return getValue().equals(that.getValue());
}
@Override
public int hashCode() {
return getValue().hashCode();
}
@Override
public String toString() {
return this.value;
}
}
|
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\ClientAuthenticationMethod.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static class UserConfigurationAdapter{
@Bean
SecurityFilterChain userFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(requests -> requests
.antMatchers("/login", "/register", "/newuserregister" ,"/test", "/test2").permitAll()
.antMatchers("/**").hasRole("USER"))
.formLogin(login -> login
.loginPage("/login")
.loginProcessingUrl("/userloginvalidate")
.successHandler((request, response, authentication) -> {
response.sendRedirect("/"); // Redirect on success
})
.failureHandler((request, response, exception) -> {
response.sendRedirect("/login?error=true"); // Redirect on failure
}))
.logout(logout -> logout.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.deleteCookies("JSESSIONID"))
.exceptionHandling(exception -> exception
.accessDeniedPage("/403") // Custom 403 page
);
http.csrf(csrf -> csrf.disable());
return http.build();
}
|
}
@Bean
UserDetailsService userDetailsService() {
return username -> {
User user = UserService.getUserByUsername(username);
if(user == null) {
throw new UsernameNotFoundException("User with username " + username + " not found.");
}
String role = user.getRole().equals("ROLE_ADMIN") ? "ADMIN":"USER";
return org.springframework.security.core.userdetails.User
.withUsername(username)
.passwordEncoder(input->passwordEncoder().encode(input))
.password(user.getPassword())
.roles(role)
.build();
};
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
|
repos\E-commerce-project-springBoot-master2\JtProject\src\main\java\com\jtspringproject\JtSpringProject\configuration\SecurityConfiguration.java
| 2
|
请完成以下Java代码
|
class FindPanelContainer_Collapsible extends FindPanelContainer
{
private CollapsiblePanel _findPanelCollapsible;
FindPanelContainer_Collapsible(final FindPanelBuilder builder)
{
super(builder);
}
@Override
protected void init(final FindPanelBuilder builder)
{
final CollapsiblePanel findPanelCollapsible = getCollapsiblePanel();
findPanelCollapsible.setTitle(Services.get(IMsgBL.class).getMsg(Env.getCtx(), "Find"));
findPanelCollapsible.add(findPanel);
}
private synchronized final CollapsiblePanel getCollapsiblePanel()
{
if (_findPanelCollapsible == null)
{
_findPanelCollapsible = new CollapsiblePanel();
}
return _findPanelCollapsible;
}
@Override
public JComponent getComponent()
{
final CollapsiblePanel findPanelCollapsible = getCollapsiblePanel();
return findPanelCollapsible;
}
@Override
public boolean isExpanded()
{
final CollapsiblePanel findPanelCollapsible = getCollapsiblePanel();
return !findPanelCollapsible.isCollapsed();
}
@Override
public void setExpanded(final boolean expanded)
{
final CollapsiblePanel findPanelCollapsible = getCollapsiblePanel();
findPanelCollapsible.setCollapsed(!expanded);
}
@Override
public final void requestFocus()
{
final CollapsiblePanel findPanelCollapsible = getCollapsiblePanel();
if (findPanelCollapsible.isCollapsed())
{
return;
}
findPanel.requestFocus();
}
@Override
public final boolean requestFocusInWindow()
{
final CollapsiblePanel findPanelCollapsible = getCollapsiblePanel();
if (findPanelCollapsible.isCollapsed())
{
return false;
}
|
return findPanel.requestFocusInWindow();
}
/**
* @return true if it's expanded and the underlying {@link FindPanel} allows focus.
*/
@Override
public boolean isFocusable()
{
if (!isExpanded())
{
return false;
}
return findPanel.isFocusable();
}
/**
* Adds a runnable to be executed when the this panel is collapsed or expanded.
*
* @param runnable
*/
@Override
public void runOnExpandedStateChange(final Runnable runnable)
{
Check.assumeNotNull(runnable, "runnable not null");
final CollapsiblePanel findPanelCollapsible = getCollapsiblePanel();
findPanelCollapsible.addPropertyChangeListener("collapsed", new PropertyChangeListener()
{
@Override
public void propertyChange(final PropertyChangeEvent evt)
{
runnable.run();
}
});
}
private static final class CollapsiblePanel extends JXTaskPane implements IUISubClassIDAware
{
private static final long serialVersionUID = 1L;
public CollapsiblePanel()
{
super();
}
@Override
public String getUISubClassID()
{
return AdempiereTaskPaneUI.UISUBCLASSID_VPanel_FindPanel;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanelContainer_Collapsible.java
| 1
|
请完成以下Java代码
|
private static String extractRawValue(final ImpFormatColumn column, final List<String> cellRawValues)
{
if (column.isConstant())
{
return column.getConstantValue();
}
// NOTE: startNo is ONE based, so we have to convert it to 0-based index.
final int cellIndex = column.getStartNo() - 1;
if (cellIndex < 0)
{
throw new AdempiereException("Invalid StartNo for column + " + column.getName());
}
if (cellIndex >= cellRawValues.size())
{
return null;
}
return cellRawValues.get(cellIndex);
}
private static List<String> splitLineByDelimiter(
final String line,
final char cellQuote,
final char cellDelimiter)
{
if (line == null || line.isEmpty())
{
return ImmutableList.of();
}
final List<String> result = new ArrayList<>();
StringBuilder currentValue = new StringBuilder();
boolean inQuotes = false;
boolean startCollectChar = false;
boolean doubleQuotesInColumn = false;
final char[] chars = line.toCharArray();
for (final char ch : chars)
{
if (inQuotes)
{
startCollectChar = true;
if (ch == cellQuote)
{
inQuotes = false;
doubleQuotesInColumn = false;
}
else
{
// Fixed : allow "" in custom quote enclosed
if (ch == '\"')
{
if (!doubleQuotesInColumn)
{
currentValue.append(ch);
|
doubleQuotesInColumn = true;
}
}
else
{
currentValue.append(ch);
}
}
}
else
{
if (ch == cellQuote)
{
inQuotes = true;
// double quotes in column will hit this!
if (startCollectChar)
{
currentValue.append('"');
}
}
else if (ch == cellDelimiter)
{
result.add(currentValue.toString());
currentValue = new StringBuilder();
startCollectChar = false;
}
else
{
currentValue.append(ch);
}
}
}
result.add(currentValue.toString());
return result;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\parser\FlexImpDataLineParser.java
| 1
|
请完成以下Java代码
|
public void destroy() throws Exception {
xxlJobScheduler.destroy();
}
// ---------------------- XxlJobScheduler ----------------------
// conf
@Value("${xxl.job.i18n}")
private String i18n;
@Value("${xxl.job.accessToken}")
private String accessToken;
@Value("${spring.mail.from}")
private String emailFrom;
@Value("${xxl.job.triggerpool.fast.max}")
private int triggerPoolFastMax;
@Value("${xxl.job.triggerpool.slow.max}")
private int triggerPoolSlowMax;
@Value("${xxl.job.logretentiondays}")
private int logretentiondays;
// dao, service
@Resource
private XxlJobLogDao xxlJobLogDao;
@Resource
private XxlJobInfoDao xxlJobInfoDao;
@Resource
private XxlJobRegistryDao xxlJobRegistryDao;
@Resource
private XxlJobGroupDao xxlJobGroupDao;
@Resource
private XxlJobLogReportDao xxlJobLogReportDao;
@Resource
private JavaMailSender mailSender;
@Resource
private DataSource dataSource;
@Resource
private JobAlarmer jobAlarmer;
public String getI18n() {
if (!Arrays.asList("zh_CN", "zh_TC", "en").contains(i18n)) {
return "zh_CN";
}
return i18n;
}
public String getAccessToken() {
return accessToken;
}
|
public String getEmailFrom() {
return emailFrom;
}
public int getTriggerPoolFastMax() {
if (triggerPoolFastMax < 200) {
return 200;
}
return triggerPoolFastMax;
}
public int getTriggerPoolSlowMax() {
if (triggerPoolSlowMax < 100) {
return 100;
}
return triggerPoolSlowMax;
}
public int getLogretentiondays() {
if (logretentiondays < 7) {
return -1; // Limit greater than or equal to 7, otherwise close
}
return logretentiondays;
}
public XxlJobLogDao getXxlJobLogDao() {
return xxlJobLogDao;
}
public XxlJobInfoDao getXxlJobInfoDao() {
return xxlJobInfoDao;
}
public XxlJobRegistryDao getXxlJobRegistryDao() {
return xxlJobRegistryDao;
}
public XxlJobGroupDao getXxlJobGroupDao() {
return xxlJobGroupDao;
}
public XxlJobLogReportDao getXxlJobLogReportDao() {
return xxlJobLogReportDao;
}
public JavaMailSender getMailSender() {
return mailSender;
}
public DataSource getDataSource() {
return dataSource;
}
public JobAlarmer getJobAlarmer() {
return jobAlarmer;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\conf\XxlJobAdminConfig.java
| 1
|
请完成以下Java代码
|
public static final InputStream getOSS2InputStream(OSSClient client, String bucketName, String diskName, String key){
OSSObject ossObj = client.getObject(bucketName, diskName + key);
return ossObj.getObjectContent();
}
/**
* 根据key删除OSS服务器上的文件
* @param client OSS客户端
* @param bucketName bucket名称
* @param diskName 文件路径
* @param key Bucket下的文件的路径名+文件名
*/
public static void deleteFile(OSSClient client, String bucketName, String diskName, String key){
client.deleteObject(bucketName, diskName + key);
LOG.info("删除" + bucketName + "下的文件" + diskName + key + "成功");
}
/**
|
* 通过文件名判断并获取OSS服务文件上传时文件的contentType
* @param fileName 文件名
* @return 文件的contentType
*/
public static final String getContentType(String fileName){
String fileExtension = fileName.substring(fileName.lastIndexOf("."));
if("bmp".equalsIgnoreCase(fileExtension)) return "image/bmp";
if("gif".equalsIgnoreCase(fileExtension)) return "image/gif";
if("jpeg".equalsIgnoreCase(fileExtension) || "jpg".equalsIgnoreCase(fileExtension) || "png".equalsIgnoreCase(fileExtension) ) return "image/jpeg";
if("html".equalsIgnoreCase(fileExtension)) return "text/html";
if("txt".equalsIgnoreCase(fileExtension)) return "text/plain";
if("vsd".equalsIgnoreCase(fileExtension)) return "application/vnd.visio";
if("ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) return "application/vnd.ms-powerpoint";
if("doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) return "application/msword";
if("xml".equalsIgnoreCase(fileExtension)) return "text/xml";
return "text/html";
}
}
|
repos\spring-boot-quick-master\quick-oss\src\main\java\com\quick\oss\OSSUnit.java
| 1
|
请完成以下Java代码
|
private Document getDocument()
{
final Document document = _documentRef.get();
if (document == null)
{
throw new IllegalStateException("Document reference already expired");
}
return document;
}
@Override
public String getTableName()
{
final Document document = getDocument();
return document.getEntityDescriptor().getTableName();
}
@Override
public int getAD_Tab_ID()
{
final Document document = getDocument();
return document.getEntityDescriptor().getAdTabId().getRepoId();
}
@Override
public <T> T getModel(final Class<T> modelClass)
{
final Document document = getDocument();
return DocumentInterfaceWrapper.wrap(document, modelClass);
}
@Override
public <T> T getModelBeforeChanges(final Class<T> modelClass)
{
final Document document = getDocument();
return DocumentInterfaceWrapper.wrapUsingOldValues(document, modelClass);
}
@Override
public Object getValue(final String columnName)
{
final Document document = getDocument();
return InterfaceWrapperHelper.getValueOrNull(document, columnName);
}
@Override
|
public String setValue(final String columnName, final Object value)
{
final Document document = getDocument();
document.setValue(columnName, value, REASON_Value_DirectSetOnCalloutRecord);
return "";
}
@Override
public void dataRefresh()
{
final Document document = getDocument();
document.refreshFromRepository();
}
@Override
public void dataRefreshAll()
{
// NOTE: there is no "All" concept here, so we are just refreshing this document
final Document document = getDocument();
document.refreshFromRepository();
}
@Override
public void dataRefreshRecursively()
{
// TODO dataRefreshRecursively: refresh document and it's children
throw new UnsupportedOperationException();
}
@Override
public boolean dataSave(final boolean manualCmd)
{
// TODO dataSave: save document but also update the DocumentsCollection!
throw new UnsupportedOperationException();
}
@Override
public boolean isLookupValuesContainingId(@NonNull final String columnName, @NonNull final RepoIdAware id)
{
//Querying all values because getLookupValueById doesn't take validation rul into consideration.
// TODO: Implement possibility to fetch sqllookupbyid with validation rule considered.
return getDocument().getFieldLookupValues(columnName).containsId(id);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentAsCalloutRecord.java
| 1
|
请完成以下Java代码
|
public static boolean getDefaultEndElement()
{
return end_element;
}
/**
What codeset are we going to use the default is 8859_1
*/
public static String getDefaultCodeset()
{
return codeset;
}
/**
position of tag relative to start and end.
*/
public static int getDefaultPosition()
{
return position;
}
/**
Default value to set case type
*/
|
public static int getDefaultCaseType()
{
return case_type;
}
public static char getDefaultStartTag()
{
return start_tag;
}
public static char getDefaultEndTag()
{
return end_tag;
}
/**
Should we print html in a more readable format?
*/
public static boolean getDefaultPrettyPrint()
{
return pretty_print;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\ECSDefaults.java
| 1
|
请完成以下Java代码
|
public ResponseEntity<?> getExternalSystemInfo(
@PathVariable @NonNull final String externalSystemConfigType,
@PathVariable @NonNull final String externalSystemChildConfigValue)
{
final ExternalSystemType externalSystemType = externalSystemService.getExternalSystemTypeByCodeOrNameOrNull(externalSystemConfigType);
if (externalSystemType == null)
{
throw new AdempiereException("Unsupported externalSystemConfigType=" + externalSystemConfigType);
}
final JsonExternalSystemInfo systemInfo = externalSystemService.getExternalSystemInfo(externalSystemType, externalSystemChildConfigValue);
return ResponseEntity.ok().body(systemInfo);
}
private ResponseEntity<?> getResponse(@NonNull final ProcessExecutionResult processExecutionResult)
{
final ResponseEntity.BodyBuilder responseEntity;
final RunProcessResponse.RunProcessResponseBuilder responseBodyBuilder = RunProcessResponse.builder()
|
.pInstanceID(String.valueOf(processExecutionResult.getPinstanceId().getRepoId()));
if (processExecutionResult.getThrowable() != null)
{
final JsonError error = JsonError.ofSingleItem(JsonErrors.ofThrowable(processExecutionResult.getThrowable(), Env.getADLanguageOrBaseLanguage()));
responseEntity = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR);
responseBodyBuilder.errors(error);
}
else
{
responseEntity = ResponseEntity.ok();
}
return responseEntity
.contentType(MediaType.APPLICATION_JSON)
.body(responseBodyBuilder.build());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\externlasystem\ExternalSystemRestController.java
| 1
|
请完成以下Java代码
|
public void setAD_Zebra_Config_ID (final int AD_Zebra_Config_ID)
{
if (AD_Zebra_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Zebra_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Zebra_Config_ID, AD_Zebra_Config_ID);
}
@Override
public int getAD_Zebra_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Zebra_Config_ID);
}
@Override
public void setEncoding (final java.lang.String Encoding)
{
set_Value (COLUMNNAME_Encoding, Encoding);
}
@Override
public java.lang.String getEncoding()
{
return get_ValueAsString(COLUMNNAME_Encoding);
}
@Override
public void setHeader_Line1 (final java.lang.String Header_Line1)
{
set_Value (COLUMNNAME_Header_Line1, Header_Line1);
}
@Override
public java.lang.String getHeader_Line1()
{
return get_ValueAsString(COLUMNNAME_Header_Line1);
}
@Override
public void setHeader_Line2 (final java.lang.String Header_Line2)
{
set_Value (COLUMNNAME_Header_Line2, Header_Line2);
}
@Override
public java.lang.String getHeader_Line2()
{
return get_ValueAsString(COLUMNNAME_Header_Line2);
|
}
@Override
public void setIsDefault (final boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, IsDefault);
}
@Override
public boolean isDefault()
{
return get_ValueAsBoolean(COLUMNNAME_IsDefault);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setSQL_Select (final java.lang.String SQL_Select)
{
set_Value (COLUMNNAME_SQL_Select, SQL_Select);
}
@Override
public java.lang.String getSQL_Select()
{
return get_ValueAsString(COLUMNNAME_SQL_Select);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Zebra_Config.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public int create(UmsMenu umsMenu) {
umsMenu.setCreateTime(new Date());
updateLevel(umsMenu);
return menuMapper.insert(umsMenu);
}
/**
* 修改菜单层级
*/
private void updateLevel(UmsMenu umsMenu) {
if (umsMenu.getParentId() == 0) {
//没有父菜单时为一级菜单
umsMenu.setLevel(0);
} else {
//有父菜单时为父菜单的level+1
UmsMenu parentMenu = menuMapper.selectByPrimaryKey(umsMenu.getParentId());
if (parentMenu != null) {
umsMenu.setLevel(parentMenu.getLevel() + 1);
} else {
umsMenu.setLevel(0);
}
}
}
@Override
public int update(Long id, UmsMenu umsMenu) {
umsMenu.setId(id);
updateLevel(umsMenu);
return menuMapper.updateByPrimaryKeySelective(umsMenu);
}
@Override
public UmsMenu getItem(Long id) {
return menuMapper.selectByPrimaryKey(id);
}
@Override
public int delete(Long id) {
return menuMapper.deleteByPrimaryKey(id);
}
@Override
public List<UmsMenu> list(Long parentId, Integer pageSize, Integer pageNum) {
PageHelper.startPage(pageNum, pageSize);
UmsMenuExample example = new UmsMenuExample();
example.setOrderByClause("sort desc");
example.createCriteria().andParentIdEqualTo(parentId);
return menuMapper.selectByExample(example);
}
@Override
public List<UmsMenuNode> treeList() {
List<UmsMenu> menuList = menuMapper.selectByExample(new UmsMenuExample());
|
List<UmsMenuNode> result = menuList.stream()
.filter(menu -> menu.getParentId().equals(0L))
.map(menu -> covertMenuNode(menu, menuList))
.collect(Collectors.toList());
return result;
}
@Override
public int updateHidden(Long id, Integer hidden) {
UmsMenu umsMenu = new UmsMenu();
umsMenu.setId(id);
umsMenu.setHidden(hidden);
return menuMapper.updateByPrimaryKeySelective(umsMenu);
}
/**
* 将UmsMenu转化为UmsMenuNode并设置children属性
*/
private UmsMenuNode covertMenuNode(UmsMenu menu, List<UmsMenu> menuList) {
UmsMenuNode node = new UmsMenuNode();
BeanUtils.copyProperties(menu, node);
List<UmsMenuNode> children = menuList.stream()
.filter(subMenu -> subMenu.getParentId().equals(menu.getId()))
.map(subMenu -> covertMenuNode(subMenu, menuList)).collect(Collectors.toList());
node.setChildren(children);
return node;
}
}
|
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\UmsMenuServiceImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class TasksService {
@Autowired
private TasksRepository tasksRepository;
@Cacheable("tasks")
public TaskRecord getTaskById(String id) {
return tasksRepository.findById(id)
.orElseThrow(() -> new UnknownTaskException(id));
}
@Transactional
public void deleteTaskById(String id) {
var task = tasksRepository.findById(id)
.orElseThrow(() -> new UnknownTaskException(id));
tasksRepository.delete(task);
}
public List<TaskRecord> search(Optional<String> createdBy, Optional<String> status) {
if (createdBy.isPresent() && status.isPresent()) {
return tasksRepository.findByStatusAndCreatedBy(status.get(), createdBy.get());
} else if (createdBy.isPresent()) {
return tasksRepository.findByCreatedBy(createdBy.get());
} else if (status.isPresent()) {
return tasksRepository.findByStatus(status.get());
} else {
return tasksRepository.findAll();
}
}
@Transactional
public TaskRecord updateTask(String id, Optional<String> newStatus, Optional<String> newAssignedTo) {
var task = tasksRepository.findById(id)
|
.orElseThrow(() -> new UnknownTaskException(id));
newStatus.ifPresent(task::setStatus);
newAssignedTo.ifPresent(task::setAssignedTo);
return task;
}
public TaskRecord createTask(String title, String createdBy) {
var task = new TaskRecord(UUID.randomUUID()
.toString(), title, Instant.now(), createdBy, null, "PENDING");
tasksRepository.save(task);
return task;
}
}
|
repos\tutorials-master\lightrun\lightrun-tasks-service\src\main\java\com\baeldung\tasksservice\service\TasksService.java
| 2
|
请完成以下Java代码
|
protected void executeValidation(BpmnModel bpmnModel, Process process, List<ValidationError> errors) {
List<EventListener> eventListeners = process.getEventListeners();
if (eventListeners != null) {
for (EventListener eventListener : eventListeners) {
if (eventListener.getImplementationType() != null && eventListener.getImplementationType().equals(ImplementationType.IMPLEMENTATION_TYPE_INVALID_THROW_EVENT)) {
addError(errors, Problems.EVENT_LISTENER_INVALID_THROW_EVENT_TYPE, process, eventListener, "Invalid or unsupported throw event type on event listener");
} else if (eventListener.getImplementationType() == null || eventListener.getImplementationType().length() == 0) {
addError(errors, Problems.EVENT_LISTENER_IMPLEMENTATION_MISSING, process, eventListener, "Element 'class', 'delegateExpression' or 'throwEvent' is mandatory on eventListener");
} else if (eventListener.getImplementationType() != null) {
if (!ImplementationType.IMPLEMENTATION_TYPE_CLASS.equals(eventListener.getImplementationType())
|
&& !ImplementationType.IMPLEMENTATION_TYPE_DELEGATEEXPRESSION.equals(eventListener.getImplementationType())
&& !ImplementationType.IMPLEMENTATION_TYPE_THROW_SIGNAL_EVENT.equals(eventListener.getImplementationType())
&& !ImplementationType.IMPLEMENTATION_TYPE_THROW_GLOBAL_SIGNAL_EVENT.equals(eventListener.getImplementationType())
&& !ImplementationType.IMPLEMENTATION_TYPE_THROW_MESSAGE_EVENT.equals(eventListener.getImplementationType())
&& !ImplementationType.IMPLEMENTATION_TYPE_THROW_ERROR_EVENT.equals(eventListener.getImplementationType())) {
addError(errors, Problems.EVENT_LISTENER_INVALID_IMPLEMENTATION, process, eventListener, "Unsupported implementation type for event listener");
}
}
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-process-validation\src\main\java\org\flowable\validation\validator\impl\FlowableEventListenerValidator.java
| 1
|
请完成以下Java代码
|
private boolean isSameQty(final I_M_HU_PI_Item_Product piip1, final I_M_HU_PI_Item_Product piip2)
{
if (piip1.isInfiniteCapacity() != piip2.isInfiniteCapacity())
{
return false;
}
final boolean isInfiniteCapacity = piip1.isInfiniteCapacity();
if (isInfiniteCapacity)
{
return true;
}
final BigDecimal piip1Qty = piip1.getQty();
final BigDecimal piip2Qty = piip2.getQty();
return piip1Qty != null && piip1Qty.compareTo(piip2Qty) == 0;
}
@Override
public Optional<I_M_HU_PI_Item_Product> retrieveDefaultForProduct(
@NonNull final ProductId productId,
@Nullable final BPartnerId bpartnerId,
@NonNull final ZonedDateTime date)
{
final IHUPIItemProductQuery query = createHUPIItemProductQuery();
query.setBPartnerId(bpartnerId);
query.setProductId(productId);
query.setDate(date);
query.setDefaultForProduct(true);
final I_M_HU_PI_Item_Product huPIItemProduct = retrieveFirst(Env.getCtx(), query, ITrx.TRXNAME_None);
return Optional.ofNullable(huPIItemProduct);
}
|
@Override
public Optional<HUPIItemProductId> retrieveDefaultIdForProduct(
@NonNull final ProductId productId,
@Nullable final BPartnerId bpartnerId,
@NonNull final ZonedDateTime date)
{
return retrieveDefaultForProduct(productId, bpartnerId, date)
.map(huPiItemProduct -> HUPIItemProductId.ofRepoIdOrNull(huPiItemProduct.getM_HU_PI_Item_Product_ID()));
}
@Override
@Nullable
public I_M_HU_PI_Item_Product retrieveDefaultForProduct(
@NonNull final ProductId productId,
@NonNull final ZonedDateTime date)
{
final IHUPIItemProductQuery query = createHUPIItemProductQuery();
query.setProductId(productId);
query.setDate(date);
query.setDefaultForProduct(true);
return retrieveFirst(Env.getCtx(), query, ITrx.TRXNAME_None);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUPIItemProductDAO.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.