instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public AvailableForSalesLookupResult retrieveAvailableStock(@NonNull final AvailableForSalesMultiQuery availableForSalesMultiQuery)
{
final AvailableForSaleResultBuilder result = AvailableForSaleResultBuilder.createEmptyWithPredefinedBuckets(availableForSalesMultiQuery);
if (availableForSalesMultiQuery.getAvailableForSalesQueries().isEmpty())
{
return result.build(); // empty query => empty result
}
final IQuery<I_MD_Available_For_Sales_QueryResult> //
dbQuery = AvailableForSalesSqlHelper.createDBQueryForAvailableForSalesMultiQuery(availableForSalesMultiQuery);
final List<I_MD_Available_For_Sales_QueryResult> records = dbQuery.list();
final ImmutableList<AddToResultGroupRequest> requests = records
.stream()
.filter(req -> ZERO.compareTo(req.getQtyOnHandStock()) < 0 || ZERO.compareTo(req.getQtyToBeShipped()) < 0)
.map(AvailableForSalesRepository::createAddToResultGroupRequest)
.collect(ImmutableList.toImmutableList());
requests.forEach(result::addQtyToAllMatchingGroups);
return result.build();
}
@NonNull
private static AddToResultGroupRequest createAddToResultGroupRequest(final I_MD_Available_For_Sales_QueryResult result)
{
return AddToResultGroupRequest.builder()
.productId(ProductId.ofRepoId(result.getM_Product_ID()))
.storageAttributesKey(AttributesKey.ofString(result.getStorageAttributesKey()))
.qtyToBeShipped(result.getQtyToBeShipped())
.qtyOnHandStock(result.getQtyOnHandStock())
.queryNo(result.getQueryNo())
|
.warehouseId(WarehouseId.ofRepoId(result.getM_Warehouse_ID()))
.build();
}
public Set<AttributesKeyPattern> getPredefinedStorageAttributeKeys()
{
final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
final int clientId = Env.getAD_Client_ID(Env.getCtx());
final int orgId = Env.getAD_Org_ID(Env.getCtx());
final String storageAttributesKeys = sysConfigBL.getValue(
SYSCONFIG_AVAILABILITY_INFO_ATTRIBUTES_KEYS,
AttributesKey.ALL.getAsString(),
clientId, orgId);
return AttributesKeyPatternsUtil.parseCommaSeparatedString(storageAttributesKeys);
}
private static void validateResultUOM(@NonNull final I_MD_Available_For_Sales_QueryResult result, @NonNull final UomId stockUOMId)
{
if (result.getC_UOM_ID() != stockUOMId.getRepoId())
{
throw new AdempiereException("MD_Available_For_Sales_QueryResult is not in stock uom!")
.appendParametersToMessage()
.setParameter("Result.C_UOM_ID", result.getC_UOM_ID())
.setParameter("stockUOMId", stockUOMId.getRepoId());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\availableforsales\AvailableForSalesRepository.java
| 1
|
请完成以下Java代码
|
public class CycleRemovalByCountingLoopNodes {
public static <T> boolean detectAndRemoveCycle(Node<T> head) {
CycleDetectionResult<T> result = CycleDetectionByFastAndSlowIterators.detectCycle(head);
if (result.cycleExists) {
removeCycle(result.node, head);
}
return result.cycleExists;
}
private static <T> void removeCycle(Node<T> loopNodeParam, Node<T> head) {
int cycleLength = calculateCycleLength(loopNodeParam);
Node<T> cycleLengthAdvancedIterator = head;
Node<T> it = head;
for (int i = 0; i < cycleLength; i++) {
cycleLengthAdvancedIterator = cycleLengthAdvancedIterator.next;
}
|
while (it.next != cycleLengthAdvancedIterator.next) {
it = it.next;
cycleLengthAdvancedIterator = cycleLengthAdvancedIterator.next;
}
cycleLengthAdvancedIterator.next = null;
}
private static <T> int calculateCycleLength(Node<T> loopNodeParam) {
Node<T> loopNode = loopNodeParam;
int length = 1;
while (loopNode.next != loopNodeParam) {
length++;
loopNode = loopNode.next;
}
return length;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\linkedlist\CycleRemovalByCountingLoopNodes.java
| 1
|
请完成以下Java代码
|
private final ScheduledExecutorService getExecutor()
{
// NOTE: we are lazy initalizate the executor because we want to consume as few resources as possible in case
// an instance of this executor is created but nobody asked for something to be executed.
if (_executor == null)
{
final int corePoolSize = 1; // we go with only one thread
_executor = new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
// Allow the core thread to be terminated if not needed.
// In this way, after our runnable is executed we would not keep any running threads.
_executor.setKeepAliveTime(10, TimeUnit.SECONDS);
_executor.allowCoreThreadTimeOut(true);
}
return _executor;
}
/**
* @return true if the underlying runnable was already executed.
*/
public synchronized boolean isDone()
{
return done.get();
}
/**
* Try to stop any scheduled run (triggered by invoking {@link #run(long)}) and reset this helper to initial state,
* which means that next time when you will call {@link #run(long)} it will be like first time.
*/
public synchronized final void cancelAndReset()
{
// Eagerly mark as done.
final boolean alreadyDone = done.getAndSet(true);
//
|
// If not already done, try stop the current running future (if any)
if (!alreadyDone)
{
final ScheduledFuture<?> future = this.future;
if (future != null && !future.isDone())
{
// Try to cancel current execution.
// If this was not possible, then wait until it finishes.
if (!future.cancel(false))
{
try
{
future.get();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
// Create a new instance of "done" flag and set it to false.
// We do this because existing enqueued tasks will work with the old "done" reference which was set to "true".
done = new AtomicBoolean(false);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\concurrent\DelayedRunnableExecutor.java
| 1
|
请完成以下Java代码
|
public Row4<Integer, String, String, Integer> fieldsRow() {
return (Row4) super.fieldsRow();
}
@Override
public Row4<Integer, String, String, Integer> valuesRow() {
return (Row4) super.valuesRow();
}
@Override
public Field<Integer> field1() {
return Author.AUTHOR.ID;
}
@Override
public Field<String> field2() {
return Author.AUTHOR.FIRST_NAME;
}
@Override
public Field<String> field3() {
return Author.AUTHOR.LAST_NAME;
}
@Override
public Field<Integer> field4() {
return Author.AUTHOR.AGE;
}
@Override
public Integer component1() {
return getId();
}
@Override
public String component2() {
return getFirstName();
}
@Override
public String component3() {
return getLastName();
}
@Override
public Integer component4() {
return getAge();
}
@Override
public Integer value1() {
return getId();
}
@Override
public String value2() {
return getFirstName();
}
@Override
public String value3() {
return getLastName();
}
@Override
public Integer value4() {
return getAge();
}
@Override
public AuthorRecord value1(Integer value) {
|
setId(value);
return this;
}
@Override
public AuthorRecord value2(String value) {
setFirstName(value);
return this;
}
@Override
public AuthorRecord value3(String value) {
setLastName(value);
return this;
}
@Override
public AuthorRecord value4(Integer value) {
setAge(value);
return this;
}
@Override
public AuthorRecord values(Integer value1, String value2, String value3, Integer value4) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached AuthorRecord
*/
public AuthorRecord() {
super(Author.AUTHOR);
}
/**
* Create a detached, initialised AuthorRecord
*/
public AuthorRecord(Integer id, String firstName, String lastName, Integer age) {
super(Author.AUTHOR);
set(0, id);
set(1, firstName);
set(2, lastName);
set(3, age);
}
}
|
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\model\tables\records\AuthorRecord.java
| 1
|
请完成以下Java代码
|
public boolean hasAttributesSupport()
{
return true;
}
@Override
public <T> List<T> retrieveModelsByIds(
@NonNull final DocumentIdsSelection documentIds,
@NonNull final Class<T> modelClass)
{
return streamByIds(documentIds)
.map(ppOrderLineRow -> getModel(ppOrderLineRow, modelClass))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
}
/**
* loads and returns the given {@code ppOrderLineRow}'s {@code PP_Order} or {@code P_Order_BOMLine}, if available.
*/
private <T> Optional<T> getModel(
@NonNull final PPOrderLineRow ppOrderLineRow,
@NonNull final Class<T> modelClass)
{
if (I_PP_Order.class.isAssignableFrom(modelClass))
{
if (ppOrderLineRow.getOrderId() == null)
{
return Optional.empty();
}
else
{
final I_PP_Order order = Services.get(IPPOrderDAO.class).getById(ppOrderLineRow.getOrderId());
return Optional.of(InterfaceWrapperHelper.create(order, modelClass));
}
}
else if (I_PP_Order_BOMLine.class.isAssignableFrom(modelClass))
{
if (ppOrderLineRow.getOrderBOMLineId() == null)
{
return Optional.empty();
}
else
{
final I_PP_Order_BOMLine orderBOMLine = Services.get(IPPOrderBOMDAO.class).getOrderBOMLineById(ppOrderLineRow.getOrderBOMLineId());
return Optional.of(InterfaceWrapperHelper.create(orderBOMLine, modelClass));
}
}
else
{
return Optional.empty();
}
}
@Override
public Stream<PPOrderLineRow> streamByIds(final DocumentIdsSelection documentIds)
{
return getData().streamByIds(documentIds);
}
|
@Override
public void notifyRecordsChanged(
@NonNull final TableRecordReferenceSet recordRefs,
final boolean watchedByFrontend)
{
// TODO: notifyRecordsChanged: identify the sub-trees which could be affected and invalidate only those
}
@Override
public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors()
{
if (docStatus.isCompleted())
{
return additionalRelatedProcessDescriptors;
}
else
{
return ImmutableList.of();
}
}
@Override
public void invalidateAll()
{
invalidateAllNoNotify();
ViewChangesCollector.getCurrentOrAutoflush()
.collectFullyChanged(this);
}
private void invalidateAllNoNotify()
{
dataSupplier.invalidate();
}
private PPOrderLinesViewData getData()
{
return dataSupplier.getData();
}
@Override
public boolean isConsiderTableRelatedProcessDescriptors(@NonNull final ProcessHandlerType processHandlerType, final @NonNull DocumentIdsSelection selectedRowIds)
{
return ProcessHandlerType.equals(processHandlerType, HUReportProcessInstancesRepository.PROCESS_HANDLER_TYPE);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\PPOrderLinesView.java
| 1
|
请完成以下Java代码
|
class UserRegisterInteractor implements UserInputBoundary {
final UserRegisterDsGateway userDsGateway;
final UserPresenter userPresenter;
final UserFactory userFactory;
UserRegisterInteractor(UserRegisterDsGateway userRegisterDfGateway, UserPresenter userPresenter,
UserFactory userFactory) {
this.userDsGateway = userRegisterDfGateway;
this.userPresenter = userPresenter;
this.userFactory = userFactory;
}
@Override
public UserResponseModel create(UserRequestModel requestModel) {
if (userDsGateway.existsByName(requestModel.getName())) {
|
return userPresenter.prepareFailView("User already exists.");
}
User user = userFactory.create(requestModel.getName(), requestModel.getPassword());
if (!user.passwordIsValid()) {
return userPresenter.prepareFailView("User password must have more than 5 characters.");
}
LocalDateTime now = LocalDateTime.now();
UserDsRequestModel userDsModel = new UserDsRequestModel(user.getName(), user.getPassword(), now);
userDsGateway.save(userDsModel);
UserResponseModel accountResponseModel = new UserResponseModel(user.getName(), now.toString());
return userPresenter.prepareSuccessView(accountResponseModel);
}
}
|
repos\tutorials-master\patterns-modules\clean-architecture\src\main\java\com\baeldung\pattern\cleanarchitecture\usercreation\UserRegisterInteractor.java
| 1
|
请完成以下Java代码
|
public BranchAndFinancialInstitutionIdentificationSEPA3 getCdtrAgt() {
return cdtrAgt;
}
/**
* Sets the value of the cdtrAgt property.
*
* @param value
* allowed object is
* {@link BranchAndFinancialInstitutionIdentificationSEPA3 }
*
*/
public void setCdtrAgt(BranchAndFinancialInstitutionIdentificationSEPA3 value) {
this.cdtrAgt = value;
}
/**
* Gets the value of the ultmtCdtr property.
*
* @return
* possible object is
* {@link PartyIdentificationSEPA1 }
*
*/
public PartyIdentificationSEPA1 getUltmtCdtr() {
return ultmtCdtr;
}
/**
* Sets the value of the ultmtCdtr property.
*
* @param value
* allowed object is
* {@link PartyIdentificationSEPA1 }
*
*/
public void setUltmtCdtr(PartyIdentificationSEPA1 value) {
this.ultmtCdtr = value;
}
/**
* Gets the value of the chrgBr property.
*
* @return
* possible object is
* {@link ChargeBearerTypeSEPACode }
*
*/
public ChargeBearerTypeSEPACode getChrgBr() {
return chrgBr;
}
/**
* Sets the value of the chrgBr property.
*
* @param value
* allowed object is
* {@link ChargeBearerTypeSEPACode }
*
*/
public void setChrgBr(ChargeBearerTypeSEPACode value) {
this.chrgBr = value;
}
/**
* Gets the value of the cdtrSchmeId property.
*
* @return
* possible object is
* {@link PartyIdentificationSEPA3 }
*
*/
public PartyIdentificationSEPA3 getCdtrSchmeId() {
return cdtrSchmeId;
|
}
/**
* Sets the value of the cdtrSchmeId property.
*
* @param value
* allowed object is
* {@link PartyIdentificationSEPA3 }
*
*/
public void setCdtrSchmeId(PartyIdentificationSEPA3 value) {
this.cdtrSchmeId = value;
}
/**
* Gets the value of the drctDbtTxInf 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 drctDbtTxInf property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDrctDbtTxInf().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DirectDebitTransactionInformationSDD }
*
*
*/
public List<DirectDebitTransactionInformationSDD> getDrctDbtTxInf() {
if (drctDbtTxInf == null) {
drctDbtTxInf = new ArrayList<DirectDebitTransactionInformationSDD>();
}
return this.drctDbtTxInf;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\PaymentInstructionInformationSDD.java
| 1
|
请完成以下Spring Boot application配置
|
server.port=8080
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
# ;charset=<encoding> is added
spring.thymeleaf.content-type=text/html
# set to false for hot refresh
spring.thymeleaf.cache=false
#ݿ
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
#û
spring.datasource.username=root
#
spring.datasource.password=root123
#ݿ
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#Զ
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.messages.fallback-to-system-locale=false
security.basic.enabled=false
logging.level.org.springframework.security=debug
github.client.clientId=c5a0e4c011fb479ad95d
gi
|
thub.client.clientSecret=6c24ca098758a354cf952171392466d51518daf9
github.client.accessTokenUri=https://github.com/login/oauth/access_token
github.client.userAuthorizationUri=https://github.com/login/oauth/authorize
github.client.authenticationScheme=query
github.client.clientAuthenticationScheme=form
github.resource.userInfoUri=https://api.github.com/user
|
repos\spring-boot-quick-master\quick-oauth2\quick-github-oauth\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public void add(String endpoint, BootstrapConfig config) throws InvalidConfigurationException {
writeLock.lock();
try {
addToStore(endpoint, config);
} finally {
writeLock.unlock();
}
}
@Override
public BootstrapConfig remove(String endpoint) {
writeLock.lock();
try {
return super.remove(endpoint);
} finally {
writeLock.unlock();
}
}
public void addToStore(String endpoint, BootstrapConfig config) throws InvalidConfigurationException {
configChecker.verify(config);
|
// Check PSK identity uniqueness for bootstrap server:
PskByServer pskToAdd = getBootstrapPskIdentity(config);
if (pskToAdd != null) {
BootstrapConfig existingConfig = bootstrapByPskId.get(pskToAdd);
if (existingConfig != null) {
// check if this config will be replace by the new one.
BootstrapConfig previousConfig = bootstrapByEndpoint.get(endpoint);
if (previousConfig != existingConfig) {
throw new InvalidConfigurationException(
"Psk identity [%s] already used for this bootstrap server [%s]", pskToAdd.identity,
pskToAdd.serverUrl);
}
}
}
bootstrapByEndpoint.put(endpoint, config);
if (pskToAdd != null) {
bootstrapByPskId.put(pskToAdd, config);
}
}
}
|
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\bootstrap\store\LwM2MInMemoryBootstrapConfigStore.java
| 1
|
请完成以下Java代码
|
public void setResult (java.lang.String Result)
{
set_Value (COLUMNNAME_Result, Result);
}
/** Get Ergebnis.
@return Result of the action taken
*/
@Override
public java.lang.String getResult ()
{
return (java.lang.String)get_Value(COLUMNNAME_Result);
}
/** Set Status.
@param Status Status */
@Override
public void setStatus (java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
/** Get Status.
@return Status */
@Override
public java.lang.String getStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_Status);
}
/** Set Summary.
@param Summary
Textual summary of this request
*/
@Override
public void setSummary (java.lang.String Summary)
|
{
set_Value (COLUMNNAME_Summary, Summary);
}
/** Get Summary.
@return Textual summary of this request
*/
@Override
public java.lang.String getSummary ()
{
return (java.lang.String)get_Value(COLUMNNAME_Summary);
}
/** Set Suchschlüssel.
@param Value
Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@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_I_Request.java
| 1
|
请完成以下Java代码
|
public void setM_Product_ID(final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value(COLUMNNAME_M_Product_ID, null);
else
set_Value(COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setName(final java.lang.String Name)
{
set_Value(COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setValue(final @Nullable java.lang.String Value)
{
set_Value(COLUMNNAME_Value, Value);
}
|
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setWidth(final @Nullable BigDecimal Width)
{
set_Value(COLUMNNAME_Width, Width);
}
@Override
public BigDecimal getWidth()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Width);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PackagingContainer.java
| 1
|
请完成以下Java代码
|
public int getModelTableId()
{
return modelTableId;
}
@Override
public void setModelTableId(int modelTableId)
{
this.modelTableId = modelTableId;
}
@Override
public int getModelFromRecordId()
{
return modelFromRecordId;
}
@Override
public void setModelFromRecordId(int modelFromRecordId)
{
this.modelFromRecordId = modelFromRecordId;
}
@Override
public int getModelToRecordId()
{
return modelToRecordId;
}
@Override
public void setModelToRecordId(int modelToRecordId)
{
this.modelToRecordId = modelToRecordId;
}
@Override
public ISqlQueryFilter getFilter()
{
return filter;
}
@Override
public void setFilter(ISqlQueryFilter filter)
{
this.filter = filter;
}
@Override
public ISqlQueryFilter getModelFilter()
{
return modelFilter;
}
@Override
public void setModelFilter(ISqlQueryFilter modelFilter)
{
this.modelFilter = modelFilter;
|
}
@Override
public Access getRequiredAccess()
{
return requiredAccess;
}
@Override
public void setRequiredAccess(final Access requiredAccess)
{
this.requiredAccess = requiredAccess;
}
@Override
public Integer getCopies()
{
return copies;
}
@Override
public void setCopies(int copies)
{
this.copies = copies;
}
@Override
public String getAggregationKey()
{
return aggregationKey;
}
@Override
public void setAggregationKey(final String aggregationKey)
{
this.aggregationKey=aggregationKey;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\PrintingQueueQuery.java
| 1
|
请完成以下Java代码
|
public class CsrfTokenRequestAttributeHandler implements CsrfTokenRequestHandler {
private static final Log logger = LogFactory.getLog(CsrfTokenRequestAttributeHandler.class);
private String csrfRequestAttributeName = "_csrf";
/**
* The {@link CsrfToken} is available as a request attribute named
* {@code CsrfToken.class.getName()}. By default, an additional request attribute that
* is the same as {@link CsrfToken#getParameterName()} is set. This attribute allows
* overriding the additional attribute.
* @param csrfRequestAttributeName the name of an additional request attribute with
* the value of the CsrfToken. Default is {@link CsrfToken#getParameterName()}
*/
public final void setCsrfRequestAttributeName(String csrfRequestAttributeName) {
this.csrfRequestAttributeName = csrfRequestAttributeName;
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
Supplier<CsrfToken> deferredCsrfToken) {
Assert.notNull(request, "request cannot be null");
Assert.notNull(response, "response cannot be null");
Assert.notNull(deferredCsrfToken, "deferredCsrfToken cannot be null");
CsrfToken csrfToken = new SupplierCsrfToken(deferredCsrfToken);
request.setAttribute(CsrfToken.class.getName(), csrfToken);
String csrfAttrName = (this.csrfRequestAttributeName != null) ? this.csrfRequestAttributeName
: csrfToken.getParameterName();
request.setAttribute(csrfAttrName, csrfToken);
logger.trace(LogMessage.format("Wrote a CSRF token to the following request attributes: [%s, %s]", csrfAttrName,
CsrfToken.class.getName()));
}
@SuppressWarnings("serial")
private static final class SupplierCsrfToken implements CsrfToken {
private final Supplier<CsrfToken> csrfTokenSupplier;
private SupplierCsrfToken(Supplier<CsrfToken> csrfTokenSupplier) {
this.csrfTokenSupplier = csrfTokenSupplier;
}
@Override
public String getHeaderName() {
return getDelegate().getHeaderName();
}
|
@Override
public String getParameterName() {
return getDelegate().getParameterName();
}
@Override
public String getToken() {
return getDelegate().getToken();
}
private CsrfToken getDelegate() {
CsrfToken delegate = this.csrfTokenSupplier.get();
if (delegate == null) {
throw new IllegalStateException("csrfTokenSupplier returned null delegate");
}
return delegate;
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\csrf\CsrfTokenRequestAttributeHandler.java
| 1
|
请完成以下Java代码
|
public void generateIcsAndInvoices(@NonNull final List<TableRecordReference> modelReferences)
{
generateMissingInvoiceCandidatesForModel(modelReferences);
final HashSet<InvoiceCandidateId> invoiceCandidateIds = new HashSet<>();
for (final TableRecordReference modelReference : modelReferences)
{
invoiceCandidateIds.addAll(invoiceCandDAO.retrieveReferencingIds(modelReference));
}
final PInstanceId invoiceCandidatesSelectionId = DB.createT_Selection(invoiceCandidateIds, Trx.TRXNAME_None);
invoiceCandBL.enqueueForInvoicing()
.setContext(getCtx())
.setInvoicingParams(createDefaultIInvoicingParams())
.setFailIfNothingEnqueued(true)
.prepareAndEnqueueSelection(invoiceCandidatesSelectionId);
}
private void generateMissingInvoiceCandidatesForModel(@NonNull final List<TableRecordReference> modelReferences)
{
final List<Object> models = TableRecordReference.getModels(modelReferences, Object.class);
final Multimap<AsyncBatchId, Object> batchIdWithUpdatedModel =
asyncBatchBL.assignTempAsyncBatchToModelsIfMissing(
models,
Async_Constants.C_Async_Batch_InternalName_EnqueueInvoiceCandidateCreation);
for (final AsyncBatchId asyncBatchId : batchIdWithUpdatedModel.keySet())
{
final Collection<Object> modelsWithBatchId = batchIdWithUpdatedModel.get(asyncBatchId);
|
final Supplier<IEnqueueResult> action = () -> {
int counter = 0;
for (final Object modelWithBatchId : modelsWithBatchId)
{
CreateMissingInvoiceCandidatesWorkpackageProcessor.schedule(modelWithBatchId);
counter++;
}
final int finalCounter = counter; // a lambda's return value should be final
return () -> finalCounter; // return the numer of workpackages that we enqeued
};
asyncBatchService.executeBatch(action, asyncBatchId);
}
}
@NonNull
private IInvoicingParams createDefaultIInvoicingParams()
{
final PlainInvoicingParams invoicingParams = new PlainInvoicingParams();
invoicingParams.setIgnoreInvoiceSchedule(false);
invoicingParams.setDateInvoiced(LocalDate.now());
return invoicingParams;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\CreateInvoiceForModelService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ResponseEntity<List<String>> postToClients(@RequestBody MulticastMessageRepresentation message) throws FirebaseMessagingException {
MulticastMessage msg = MulticastMessage.builder()
.addAllTokens(message.getRegistrationTokens())
.putData("body", message.getData())
.build();
BatchResponse response = fcm.sendMulticast(msg);
List<String> ids = response.getResponses()
.stream()
.map(r->r.getMessageId())
.collect(Collectors.toList());
return ResponseEntity
|
.status(HttpStatus.ACCEPTED)
.body(ids);
}
@PostMapping("/subscriptions/{topic}")
public ResponseEntity<Void> createSubscription(@PathVariable("topic") String topic,@RequestBody List<String> registrationTokens) throws FirebaseMessagingException {
fcm.subscribeToTopic(registrationTokens, topic);
return ResponseEntity.ok().build();
}
@DeleteMapping("/subscriptions/{topic}/{registrationToken}")
public ResponseEntity<Void> deleteSubscription(@PathVariable String topic, @PathVariable String registrationToken) throws FirebaseMessagingException {
fcm.subscribeToTopic(Arrays.asList(registrationToken), topic);
return ResponseEntity.ok().build();
}
}
|
repos\tutorials-master\gcp-firebase\src\main\java\com\baeldung\gcp\firebase\publisher\controller\FirebasePublisherController.java
| 2
|
请完成以下Java代码
|
public void setOldAmt (final BigDecimal OldAmt)
{
set_Value (COLUMNNAME_OldAmt, OldAmt);
}
@Override
public BigDecimal getOldAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_OldAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setOldCostPrice (final BigDecimal OldCostPrice)
{
set_Value (COLUMNNAME_OldCostPrice, OldCostPrice);
}
@Override
public BigDecimal getOldCostPrice()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_OldCostPrice);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* RevaluationType AD_Reference_ID=541641
* Reference name: M_CostRevaluation_Detail_RevaluationType
*/
public static final int REVALUATIONTYPE_AD_Reference_ID=541641;
/** CurrentCostBeforeRevaluation = CCB */
public static final String REVALUATIONTYPE_CurrentCostBeforeRevaluation = "CCB";
/** CurrentCostAfterRevaluation = CCA */
|
public static final String REVALUATIONTYPE_CurrentCostAfterRevaluation = "CCA";
/** CostDetailAdjustment = CDA */
public static final String REVALUATIONTYPE_CostDetailAdjustment = "CDA";
@Override
public void setRevaluationType (final java.lang.String RevaluationType)
{
set_Value (COLUMNNAME_RevaluationType, RevaluationType);
}
@Override
public java.lang.String getRevaluationType()
{
return get_ValueAsString(COLUMNNAME_RevaluationType);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostRevaluation_Detail.java
| 1
|
请完成以下Java代码
|
public List<String> shortcutFieldOrder() {
return Arrays.asList(NAME_KEY, STRATEGY_KEY);
}
@Override
public GatewayFilter apply(Config config) {
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
return chain.filter(exchange)
.then(Mono.fromRunnable(() -> dedupe(exchange.getResponse().getHeaders(), config)));
}
@Override
public String toString() {
String name = config.getName();
return filterToStringCreator(DedupeResponseHeaderGatewayFilterFactory.this)
.append(name != null ? name : "", config.getStrategy())
.toString();
}
};
}
public enum Strategy {
/**
* Default: Retain the first value only.
*/
RETAIN_FIRST,
/**
* Retain the last value only.
*/
RETAIN_LAST,
/**
* Retain all unique values in the order of their first encounter.
*/
RETAIN_UNIQUE
}
void dedupe(HttpHeaders headers, Config config) {
String names = config.getName();
Strategy strategy = config.getStrategy();
if (headers == null || names == null || strategy == null) {
return;
}
for (String name : names.split(" ")) {
dedupe(headers, name.trim(), strategy);
}
}
private void dedupe(HttpHeaders headers, String name, Strategy strategy) {
List<String> values = headers.get(name);
if (values == null || values.size() <= 1) {
|
return;
}
switch (strategy) {
case RETAIN_FIRST:
headers.set(name, values.get(0));
break;
case RETAIN_LAST:
headers.set(name, values.get(values.size() - 1));
break;
case RETAIN_UNIQUE:
headers.put(name, new ArrayList<>(new LinkedHashSet<>(values)));
break;
default:
break;
}
}
public static class Config extends AbstractGatewayFilterFactory.NameConfig {
private Strategy strategy = Strategy.RETAIN_FIRST;
public Strategy getStrategy() {
return strategy;
}
public Config setStrategy(Strategy strategy) {
this.strategy = strategy;
return this;
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\DedupeResponseHeaderGatewayFilterFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SampleOidEntityService {
private SampleOidEntityRepository samples;
public SampleOidEntityService(SampleOidEntityRepository samplesRepository) {
super();
this.samples = samplesRepository;
}
public SampleOidEntity create(SampleOidEntity entity) {
ValidationEngine.validateAndThrow(entity);
return samples.create(entity);
}
public SampleOidEntity read(Identifier id) {
return samples.read(id);
}
public void update(SampleOidEntity entity) {
ValidationEngine.validateAndThrow(entity);
|
samples.update(entity);
}
public void delete(Identifier id) {
samples.delete(id);
}
public List<SampleOidEntity> readAll(QueryFilter filter, QueryRange range, QueryOrder order) {
return samples.readAll(filter, range, order);
}
public long count(QueryFilter filter) {
return samples.count(filter);
}
}
|
repos\tutorials-master\microservices-modules\rest-express\src\main\java\com\baeldung\restexpress\objectid\SampleOidEntityService.java
| 2
|
请完成以下Java代码
|
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProductName (final @Nullable java.lang.String ProductName)
{
throw new IllegalArgumentException ("ProductName is virtual column"); }
@Override
public java.lang.String getProductName()
{
return get_ValueAsString(COLUMNNAME_ProductName);
}
@Override
public void setProductValue (final @Nullable java.lang.String ProductValue)
{
throw new IllegalArgumentException ("ProductValue is virtual column"); }
@Override
public java.lang.String getProductValue()
{
return get_ValueAsString(COLUMNNAME_ProductValue);
}
@Override
public void setQtyLU (final @Nullable BigDecimal QtyLU)
|
{
set_Value (COLUMNNAME_QtyLU, QtyLU);
}
@Override
public BigDecimal getQtyLU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyLU);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyTU (final @Nullable BigDecimal QtyTU)
{
set_Value (COLUMNNAME_QtyTU, QtyTU);
}
@Override
public BigDecimal getQtyTU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyTU);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\shipping\model\X_M_ShippingPackage.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static <T> T getBean(HttpSecurity httpSecurity, Class<T> type) {
return httpSecurity.getSharedObject(ApplicationContext.class).getBean(type);
}
@SuppressWarnings("unchecked")
static <T> T getBean(HttpSecurity httpSecurity, ResolvableType type) {
ApplicationContext context = httpSecurity.getSharedObject(ApplicationContext.class);
String[] names = context.getBeanNamesForType(type);
if (names.length == 1) {
return (T) context.getBean(names[0]);
}
if (names.length > 1) {
throw new NoUniqueBeanDefinitionException(type, names);
}
throw new NoSuchBeanDefinitionException(type);
}
static <T> T getOptionalBean(HttpSecurity httpSecurity, Class<T> type) {
Map<String, T> beansMap = BeanFactoryUtils
.beansOfTypeIncludingAncestors(httpSecurity.getSharedObject(ApplicationContext.class), type);
|
if (beansMap.size() > 1) {
throw new NoUniqueBeanDefinitionException(type, beansMap.size(),
"Expected single matching bean of type '" + type.getName() + "' but found " + beansMap.size() + ": "
+ StringUtils.collectionToCommaDelimitedString(beansMap.keySet()));
}
return (!beansMap.isEmpty() ? beansMap.values().iterator().next() : null);
}
@SuppressWarnings("unchecked")
static <T> T getOptionalBean(HttpSecurity httpSecurity, ResolvableType type) {
ApplicationContext context = httpSecurity.getSharedObject(ApplicationContext.class);
String[] names = context.getBeanNamesForType(type);
if (names.length > 1) {
throw new NoUniqueBeanDefinitionException(type, names);
}
return (names.length == 1) ? (T) context.getBean(names[0]) : null;
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\server\authorization\OAuth2ConfigurerUtils.java
| 2
|
请完成以下Java代码
|
public int getFieldSize() {
return this.fieldNames.size();
}
@Override
public String getId() {
return this.id;
}
public void setFieldName(int index, String fieldName, Class<?> type, Class<?> parameterType) {
this.growListToContain(index, this.fieldNames);
this.growListToContain(index, this.fieldTypes);
this.growListToContain(index, this.fieldParameterTypes);
this.fieldNames.set(index, fieldName);
this.fieldTypes.set(index, type);
this.fieldParameterTypes.set(index, parameterType);
}
private void growListToContain(int index, List<?> list) {
if (!(list.size() - 1 >= index)) {
for (int i = list.size(); i <= index; i++) {
list.add(null);
}
}
}
|
@Override
public String getFieldNameAt(int index) {
return this.fieldNames.get(index);
}
@Override
public Class<?> getFieldTypeAt(int index) {
return this.fieldTypes.get(index);
}
@Override
public Class<?> getFieldParameterTypeAt(int index) {
return this.fieldParameterTypes.get(index);
}
@Override
public StructureInstance createInstance() {
return new FieldBaseStructureInstance(this);
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\data\SimpleStructureDefinition.java
| 1
|
请完成以下Java代码
|
public Map<String, ViewEditorRenderMode> getViewEditorRenderModeByFieldName()
{
return values.getViewEditorRenderModeByFieldName();
}
public boolean isPriceEditable()
{
return isFieldEditable(FIELD_Price);
}
@SuppressWarnings("SameParameterValue")
private boolean isFieldEditable(final String fieldName)
{
final ViewEditorRenderMode renderMode = getViewEditorRenderModeByFieldName().get(fieldName);
return renderMode != null && renderMode.isEditable();
}
@Override
public DocumentId getId()
{
return id;
}
@Override
public boolean isProcessed()
{
return false;
}
@Nullable
@Override
public DocumentPath getDocumentPath()
{
return null;
}
public ProductId getProductId()
{
return getProduct().getIdAs(ProductId::ofRepoId);
}
public String getProductName()
{
return getProduct().getDisplayName();
}
public boolean isQtySet()
{
final BigDecimal qty = getQty();
return qty != null && qty.signum() != 0;
}
public ProductsProposalRow withLastShipmentDays(final Integer lastShipmentDays)
{
if (Objects.equals(this.lastShipmentDays, lastShipmentDays))
{
return this;
|
}
else
{
return toBuilder().lastShipmentDays(lastShipmentDays).build();
}
}
public boolean isChanged()
{
return getProductPriceId() == null
|| !getPrice().isPriceListPriceUsed();
}
public boolean isMatching(@NonNull final ProductsProposalViewFilter filter)
{
return Check.isEmpty(filter.getProductName())
|| getProductName().toLowerCase().contains(filter.getProductName().toLowerCase());
}
public ProductsProposalRow withExistingOrderLine(@Nullable final OrderLine existingOrderLine)
{
if(existingOrderLine == null)
{
return this;
}
final Amount existingPrice = Amount.of(existingOrderLine.getPriceEntered(), existingOrderLine.getCurrency().getCurrencyCode());
return toBuilder()
.qty(existingOrderLine.isPackingMaterialWithInfiniteCapacity()
? existingOrderLine.getQtyEnteredCU()
: BigDecimal.valueOf(existingOrderLine.getQtyEnteredTU()))
.price(ProductProposalPrice.builder()
.priceListPrice(existingPrice)
.build())
.existingOrderLineId(existingOrderLine.getOrderLineId())
.description(existingOrderLine.getDescription())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\model\ProductsProposalRow.java
| 1
|
请完成以下Java代码
|
public void addColumnName(final String columnName)
{
// Make sure column was not already added
if (columnNames.contains(columnName))
{
return;
}
columnNames.add(columnName);
if (sqlReturning.length() > 0)
{
sqlReturning.append(", ");
}
sqlReturning.append(columnName);
}
public String getSqlReturning()
{
return sqlReturning.toString();
}
public boolean hasColumnNames()
{
return !columnNames.isEmpty();
}
|
@Override
public void process(final ResultSet rs) throws SQLException
{
for (final String columnName : columnNames)
{
final Object value = rs.getObject(columnName);
// NOTE: it is also setting the ID if applies
set_ValueNoCheck(columnName, value);
}
}
@Override
public String toString()
{
return "POReturningAfterInsertLoader [columnNames=" + columnNames + "]";
}
}
} // PO
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\PO.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return ObjectUtils.toString(this);
}
/** @return invoice candidate; never return <code>null</code> */
public I_C_Invoice_Candidate getC_Invoice_Candidate()
{
return ic;
}
/** @return shipment/receipt line; could be <code>null</code> */
@Nullable
public I_M_InOutLine getM_InOutLine()
{
if (iciol == null)
{
return null;
}
return iciol.getM_InOutLine();
}
public StockQtyAndUOMQty getQtysAlreadyInvoiced()
{
final StockQtyAndUOMQty zero = StockQtyAndUOMQtys.createZero(productId, icUomId);
if (iciol == null)
{
return zero;
}
else
{
final InOutLineId inoutLineId = InOutLineId.ofRepoId(iciol.getM_InOutLine_ID());
return matchInvoiceService.getMaterialQtyMatched(inoutLineId, zero);
}
}
public StockQtyAndUOMQty getQtysAlreadyShipped()
{
final I_M_InOutLine inOutLine = getM_InOutLine();
if (inOutLine == null)
{
return StockQtyAndUOMQtys.createZero(productId, icUomId);
}
final InvoicableQtyBasedOn invoicableQtyBasedOn = InvoicableQtyBasedOn.ofNullableCodeOrNominal(ic.getInvoicableQtyBasedOn());
final BigDecimal uomQty;
if (!isNull(iciol, I_C_InvoiceCandidate_InOutLine.COLUMNNAME_QtyDeliveredInUOM_Override))
{
|
uomQty = iciol.getQtyDeliveredInUOM_Override();
}
else
{
switch (invoicableQtyBasedOn)
{
case CatchWeight:
uomQty = coalesceNotNull(iciol.getQtyDeliveredInUOM_Catch(), iciol.getQtyDeliveredInUOM_Nominal());
break;
case NominalWeight:
uomQty = iciol.getQtyDeliveredInUOM_Nominal();
break;
default:
throw fail("Unexpected invoicableQtyBasedOn={}", invoicableQtyBasedOn);
}
}
final Quantity shippedUomQuantityInIcUOM = uomConversionBL.convertQuantityTo(Quantitys.of(uomQty, UomId.ofRepoId(iciol.getC_UOM_ID())),
productId,
icUomId);
final BigDecimal stockQty = inOutLine.getMovementQty();
final StockQtyAndUOMQty deliveredQty = StockQtyAndUOMQtys
.create(
stockQty,
productId,
shippedUomQuantityInIcUOM.toBigDecimal(),
shippedUomQuantityInIcUOM.getUomId());
if (inOutBL.isReturnMovementType(inOutLine.getM_InOut().getMovementType()))
{
return deliveredQty.negate();
}
return deliveredQty;
}
public boolean isShipped()
{
return getM_InOutLine() != null;
}
public I_C_InvoiceCandidate_InOutLine getC_InvoiceCandidate_InOutLine()
{
return iciol;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\impl\aggregator\standard\InvoiceCandidateWithInOutLine.java
| 1
|
请完成以下Java代码
|
public void save(OutputStream out, String comments)
{
getDelegate().save(out, comments);
}
@Override
public int hashCode()
{
return getDelegate().hashCode();
}
@Override
public void store(Writer writer, String comments) throws IOException
{
getDelegate().store(writer, comments);
}
@Override
public void store(OutputStream out, String comments) throws IOException
{
getDelegate().store(out, comments);
}
@Override
public void loadFromXML(InputStream in) throws IOException, InvalidPropertiesFormatException
{
getDelegate().loadFromXML(in);
}
@Override
public void storeToXML(OutputStream os, String comment) throws IOException
{
getDelegate().storeToXML(os, comment);
}
@Override
public void storeToXML(OutputStream os, String comment, String encoding) throws IOException
{
getDelegate().storeToXML(os, comment, encoding);
}
@Override
public String getProperty(String key)
{
return getDelegate().getProperty(key);
}
@Override
public String getProperty(String key, String defaultValue)
{
return getDelegate().getProperty(key, defaultValue);
|
}
@Override
public Enumeration<?> propertyNames()
{
return getDelegate().propertyNames();
}
@Override
public Set<String> stringPropertyNames()
{
return getDelegate().stringPropertyNames();
}
@Override
public void list(PrintStream out)
{
getDelegate().list(out);
}
@Override
public void list(PrintWriter out)
{
getDelegate().list(out);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\AbstractPropertiesProxy.java
| 1
|
请完成以下Java代码
|
public int getAD_User_Occupation_AdditionalSpecialization_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_Occupation_AdditionalSpecialization_ID);
}
@Override
public org.compiere.model.I_CRM_Occupation getCRM_Occupation()
{
return get_ValueAsPO(COLUMNNAME_CRM_Occupation_ID, org.compiere.model.I_CRM_Occupation.class);
}
@Override
public void setCRM_Occupation(final org.compiere.model.I_CRM_Occupation CRM_Occupation)
{
set_ValueFromPO(COLUMNNAME_CRM_Occupation_ID, org.compiere.model.I_CRM_Occupation.class, CRM_Occupation);
}
|
@Override
public void setCRM_Occupation_ID (final int CRM_Occupation_ID)
{
if (CRM_Occupation_ID < 1)
set_Value (COLUMNNAME_CRM_Occupation_ID, null);
else
set_Value (COLUMNNAME_CRM_Occupation_ID, CRM_Occupation_ID);
}
@Override
public int getCRM_Occupation_ID()
{
return get_ValueAsInt(COLUMNNAME_CRM_Occupation_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Occupation_AdditionalSpecialization.java
| 1
|
请完成以下Java代码
|
public class ModelInstanceValidator {
protected ModelInstanceImpl modelInstanceImpl;
protected Collection<ModelElementValidator<?>> validators;
public ModelInstanceValidator(ModelInstanceImpl modelInstanceImpl, Collection<ModelElementValidator<?>> validators) {
this.modelInstanceImpl = modelInstanceImpl;
this.validators = validators;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public ValidationResults validate() {
ValidationResultsCollectorImpl resultsCollector = new ValidationResultsCollectorImpl();
for (ModelElementValidator validator : validators) {
Class<? extends ModelElementInstance> elementType = validator.getElementType();
Collection<? extends ModelElementInstance> modelElementsByType = modelInstanceImpl.getModelElementsByType(elementType);
|
for (ModelElementInstance element : modelElementsByType) {
resultsCollector.setCurrentElement(element);
try {
validator.validate(element, resultsCollector);
}
catch(RuntimeException e) {
throw new RuntimeException("Validator " + validator + " threw an exception while validating "+element, e);
}
}
}
return resultsCollector.getResults();
}
}
|
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\validation\ModelInstanceValidator.java
| 1
|
请完成以下Java代码
|
public class SysDict implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId(type = IdType.ASSIGN_ID)
private String id;
/**
* [预留字段,暂时无用]
* 字典类型,0 string,1 number类型,2 boolean
* 前端js对stirng类型和number类型 boolean 类型敏感,需要区分。在select 标签匹配的时候会用到
* 默认为string类型
*/
private Integer type;
/**
* 字典名称
*/
private String dictName;
/**
* 字典编码
*/
private String dictCode;
/**
* 描述
*/
private String description;
/**
* 删除状态
*/
@TableLogic
private Integer delFlag;
|
/**
* 创建人
*/
private String createBy;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新人
*/
private String updateBy;
/**
* 更新时间
*/
private Date updateTime;
/**租户ID*/
private java.lang.Integer tenantId;
/** 关联的低代码应用ID */
private java.lang.String lowAppId;
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysDict.java
| 1
|
请完成以下Java代码
|
public void setNote (String Note)
{
set_Value (COLUMNNAME_Note, Note);
}
/** Get Note.
@return Optional additional user defined information
*/
public String getNote ()
{
return (String)get_Value(COLUMNNAME_Note);
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Remote Addr.
@param Remote_Addr
Remote Address
*/
public void setRemote_Addr (String Remote_Addr)
{
set_Value (COLUMNNAME_Remote_Addr, Remote_Addr);
}
|
/** Get Remote Addr.
@return Remote Address
*/
public String getRemote_Addr ()
{
return (String)get_Value(COLUMNNAME_Remote_Addr);
}
/** Set Remote Host.
@param Remote_Host
Remote host Info
*/
public void setRemote_Host (String Remote_Host)
{
set_Value (COLUMNNAME_Remote_Host, Remote_Host);
}
/** Get Remote Host.
@return Remote host Info
*/
public String getRemote_Host ()
{
return (String)get_Value(COLUMNNAME_Remote_Host);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Registration.java
| 1
|
请完成以下Java代码
|
private static boolean mergeGroups(@NonNull final ArrayList<AdWindowId> targetGroup, @NonNull final ArrayList<AdWindowId> group)
{
if (AdWindowId.equals(last(targetGroup), first(group)))
{
targetGroup.addAll(group.subList(1, group.size()));
group.clear();
return true;
}
else if (AdWindowId.equals(last(group), first(targetGroup)))
{
targetGroup.addAll(0, group.subList(0, group.size() - 1));
group.clear();
return true;
}
else
{
return false;
}
}
|
private static AdWindowId first(@NonNull final ArrayList<AdWindowId> group) { return group.get(0); }
private static AdWindowId last(@NonNull final ArrayList<AdWindowId> group) { return group.get(group.size() - 1); }
public Optional<CustomizedWindowInfo> getCustomizedWindowInfo(@NonNull final AdWindowId baseWindowId)
{
return Optional.ofNullable(effectiveCustomizedWindowInfos.get(baseWindowId));
}
public boolean isTopLevelCustomizedWindow(@NonNull final AdWindowId adWindowId)
{
final CustomizedWindowInfo customizedWindowInfo = effectiveCustomizedWindowInfos.get(adWindowId);
return customizedWindowInfo == null || AdWindowId.equals(customizedWindowInfo.getCustomizationWindowId(), adWindowId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\zoom_into\CustomizedWindowInfoMap.java
| 1
|
请完成以下Java代码
|
public int getC_Activity_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Activity_ID);
}
@Override
public void setC_CompensationGroup_Schema_ID (final int C_CompensationGroup_Schema_ID)
{
if (C_CompensationGroup_Schema_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_CompensationGroup_Schema_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_CompensationGroup_Schema_ID, C_CompensationGroup_Schema_ID);
}
@Override
public int getC_CompensationGroup_Schema_ID()
|
{
return get_ValueAsInt(COLUMNNAME_C_CompensationGroup_Schema_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\order\model\X_C_CompensationGroup_Schema.java
| 1
|
请完成以下Java代码
|
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 String postFoos() {
return "Post some Foos";
}
// with headers
@RequestMapping(value = "/foos", headers = "key=val")
@ResponseBody
public String getFoosWithHeader() {
return "Get some Foos with Header";
}
@RequestMapping(value = "/foos", headers = { "key1=val1", "key2=val2" })
@ResponseBody
public String getFoosWithHeaders() {
return "Get some Foos with Header";
}
// @RequestMapping(value = "/foos", method = RequestMethod.GET, headers = "Accept=application/json")
// @ResponseBody
// public String getFoosAsJsonFromBrowser() {
// return "Get some Foos with Header Old";
// }
@RequestMapping(value = "/foos", produces = { "application/json", "application/xml" })
@ResponseBody
public String getFoosAsJsonFromREST() {
return "Get some Foos with Header New";
}
// advanced - multiple mappings
@RequestMapping(value = { "/advanced/bars", "/advanced/foos" })
@ResponseBody
public String getFoosOrBarsByPath() {
return "Advanced - Get some Foos or Bars";
}
@RequestMapping(value = "*")
@ResponseBody
public String getFallback() {
return "Fallback for GET Requests";
}
@RequestMapping(value = "*", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public String allFallback() {
return "Fallback for All Requests";
|
}
@RequestMapping(value = "/foos/multiple", method = { RequestMethod.PUT, RequestMethod.POST })
@ResponseBody
public String putAndPostFoos() {
return "Advanced - PUT and POST within single method";
}
// --- Ambiguous Mapping
@GetMapping(value = "foos/duplicate" )
public ResponseEntity<String> duplicate() {
return new ResponseEntity<>("Duplicate", HttpStatus.OK);
}
// uncomment for exception of type java.lang.IllegalStateException: Ambiguous mapping
// @GetMapping(value = "foos/duplicate" )
// public String duplicateEx() {
// return "Duplicate";
// }
@GetMapping(value = "foos/duplicate", produces = MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<String> duplicateXml() {
return new ResponseEntity<>("<message>Duplicate</message>", HttpStatus.OK);
}
@GetMapping(value = "foos/duplicate", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> duplicateJson() {
return new ResponseEntity<>("{\"message\":\"Duplicate\"}", HttpStatus.OK);
}
}
|
repos\tutorials-master\spring-web-modules\spring-rest-http\src\main\java\com\baeldung\requestmapping\FooMappingExamplesController.java
| 1
|
请完成以下Java代码
|
private @Nullable String getValueFromExpr(SimpleEvaluationContext evalCtxt, SpelExpressionParser parser,
ServiceInstance instance, Map.Entry<String, String> entry) {
try {
Expression valueExpr = parser.parseExpression(entry.getValue());
return valueExpr.getValue(evalCtxt, instance, String.class);
}
catch (ParseException | EvaluationException e) {
if (log.isDebugEnabled()) {
log.debug("Unable to parse " + entry.getValue(), e);
}
throw e;
}
}
private static class DelegatingServiceInstance implements ServiceInstance {
final ServiceInstance delegate;
private final DiscoveryLocatorProperties properties;
private DelegatingServiceInstance(ServiceInstance delegate, DiscoveryLocatorProperties properties) {
this.delegate = delegate;
this.properties = properties;
}
@Override
public String getServiceId() {
if (properties.isLowerCaseServiceId()) {
return delegate.getServiceId().toLowerCase(Locale.ROOT);
}
return delegate.getServiceId();
}
@Override
public String getHost() {
return delegate.getHost();
}
@Override
public int getPort() {
return delegate.getPort();
}
@Override
public boolean isSecure() {
|
return delegate.isSecure();
}
@Override
public URI getUri() {
return delegate.getUri();
}
@Override
public @Nullable Map<String, String> getMetadata() {
return delegate.getMetadata();
}
@Override
public @Nullable String getScheme() {
return delegate.getScheme();
}
@Override
public String toString() {
return new ToStringCreator(this).append("delegate", delegate).append("properties", properties).toString();
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\discovery\DiscoveryClientRouteDefinitionLocator.java
| 1
|
请完成以下Java代码
|
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setExternalSystem_ID (final int ExternalSystem_ID)
{
if (ExternalSystem_ID < 1)
set_ValueNoCheck (COLUMNNAME_ExternalSystem_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID);
}
@Override
public int getExternalSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
|
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public DeploymentResponse getDeployment(@ApiParam(name = "deploymentId", value ="The id of the deployment to get.") @PathVariable String deploymentId) {
Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
if (deployment == null) {
throw new FlowableObjectNotFoundException("Could not find a deployment with id '" + deploymentId + "'.", Deployment.class);
}
if (restApiInterceptor != null) {
restApiInterceptor.accessDeploymentById(deployment);
}
return restResponseFactory.createDeploymentResponse(deployment);
}
@ApiOperation(value = "Delete a deployment", tags = { "Deployment" }, code = 204)
@ApiResponses(value = {
@ApiResponse(code = 204, message = "Indicates the deployment was found and has been deleted. Response-body is intentionally empty."),
@ApiResponse(code = 404, message = "Indicates the requested deployment was not found.")
})
@DeleteMapping(value = "/repository/deployments/{deploymentId}", produces = "application/json")
|
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteDeployment(@ApiParam(name = "deploymentId") @PathVariable String deploymentId, @RequestParam(value = "cascade", required = false, defaultValue = "false") Boolean cascade) {
Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
if (deployment == null) {
throw new FlowableObjectNotFoundException("Could not find a deployment with id '" + deploymentId + "'.", Deployment.class);
}
if (restApiInterceptor != null) {
restApiInterceptor.deleteDeployment(deployment);
}
if (cascade) {
repositoryService.deleteDeployment(deploymentId, true);
} else {
repositoryService.deleteDeployment(deploymentId);
}
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\repository\DeploymentResource.java
| 2
|
请完成以下Java代码
|
public static TriaFrequency create(String first, char delimiter, String second, String third)
{
TriaFrequency triaFrequency = new TriaFrequency(first + delimiter + second + Occurrence.RIGHT + third);
triaFrequency.first = first;
triaFrequency.second = second;
triaFrequency.third = third;
triaFrequency.delimiter = delimiter;
return triaFrequency;
}
/**
* 构造一个三阶接续,逆向
* @param second
* @param third
* @param delimiter 一般使用LEFT
* @param first
* @return
*/
public static TriaFrequency create(String second, String third, char delimiter, String first)
{
TriaFrequency triaFrequency = new TriaFrequency(second + Occurrence.RIGHT + third + delimiter + first);
triaFrequency.first = first;
triaFrequency.second = second;
triaFrequency.third = third;
triaFrequency.delimiter = delimiter;
return triaFrequency;
}
|
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append(getKey().replace(Occurrence.LEFT, '←').replace(Occurrence.RIGHT, '→'));
sb.append('=');
sb.append(" tf=");
sb.append(getValue());
sb.append(' ');
sb.append("mi=");
sb.append(mi);
sb.append(" le=");
sb.append(le);
sb.append(" re=");
sb.append(re);
return sb.toString();
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\occurrence\TriaFrequency.java
| 1
|
请完成以下Java代码
|
public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get DB-Tabelle.
@return Database Table information
*/
@Override
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Java-Klasse.
@param Classname Java-Klasse */
@Override
public void setClassname (java.lang.String Classname)
{
set_Value (COLUMNNAME_Classname, Classname);
}
/** Get Java-Klasse.
@return Java-Klasse */
@Override
public java.lang.String getClassname ()
{
return (java.lang.String)get_Value(COLUMNNAME_Classname);
}
/** Set Spaltenname.
@param ColumnName
Name der Spalte in der Datenbank
*/
@Override
public void setColumnName (java.lang.String ColumnName)
{
throw new IllegalArgumentException ("ColumnName is virtual column"); }
/** Get Spaltenname.
@return Name der Spalte in der Datenbank
*/
@Override
public java.lang.String getColumnName ()
{
return (java.lang.String)get_Value(COLUMNNAME_ColumnName);
}
/** 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);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
|
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entity Type.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public void setEntityType (java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entity Type.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public java.lang.String getEntityType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ColumnCallout.java
| 1
|
请完成以下Java代码
|
private Quantity calculateQtyToIssue(final I_PP_Order_BOMLine targetBOMLine, final IHUProductStorage from)
{
//
// Case: enforced qty to issue
if (remainingQtyToIssue != null)
{
final Quantity huStorageQty = from.getQty(remainingQtyToIssue.getUOM());
final Quantity qtyToIssue = huStorageQty.min(remainingQtyToIssue);
remainingQtyToIssue = remainingQtyToIssue.subtract(qtyToIssue);
return qtyToIssue;
}
if (considerIssueMethodForQtyToIssueCalculation)
{
//
// Case: if this is an Issue BOM Line, IssueMethod is Backflush and we did not over-issue on it yet
// => enforce the capacity to Projected Qty Required (i.e. standard Qty that needs to be issued on this line).
// initial concept: http://dewiki908/mediawiki/index.php/07433_Folie_Zuteilung_Produktion_Fertigstellung_POS_%28102170996938%29
// additional (use of projected qty required): http://dewiki908/mediawiki/index.php/07601_Calculation_of_Folie_in_Action_Receipt_%28102017845369%29
final BOMComponentIssueMethod issueMethod = BOMComponentIssueMethod.ofNullableCode(targetBOMLine.getIssueMethod());
if (BOMComponentIssueMethod.IssueOnlyForReceived.equals(issueMethod))
{
final PPOrderId ppOrderId = PPOrderId.ofRepoId(targetBOMLine.getPP_Order_ID());
|
final DraftPPOrderQuantities draftQtys = huPPOrderQtyBL.getDraftPPOrderQuantities(ppOrderId);
return ppOrderBOMBL.computeQtyToIssueBasedOnFinishedGoodReceipt(targetBOMLine, from.getC_UOM(), draftQtys);
}
}
return from.getQty();
}
private void validateSourceHUs(@NonNull final Collection<I_M_HU> sourceHUs)
{
for (final I_M_HU hu : sourceHUs)
{
if (!handlingUnitsBL.isHUHierarchyCleared(HuId.ofRepoId(hu.getM_HU_ID())))
{
throw new HUException(MSG_IssuingNotClearedHUsNotAllowed)
.markAsUserValidationError()
.setParameter("M_HU_ID", hu.getM_HU_ID());
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\hu_pporder_issue_producer\CreateDraftIssuesCommand.java
| 1
|
请完成以下Java代码
|
private void fireStockChangedEvent(
@NonNull final I_MD_Stock dataRecord,
@NonNull final BigDecimal qtyOnHandOld,
@NonNull final StockChangeSourceInfo stockChangeSourceInfo)
{
final BigDecimal qtyOnHandNew = dataRecord.getQtyOnHand();
if (qtyOnHandOld.compareTo(qtyOnHandNew) == 0)
{
return;
}
// there should be no empty parts, but let's just make sure..
final AttributesKey attributesKey = AttributesKeys.pruneEmptyParts(AttributesKey.ofString(dataRecord.getAttributesKey()));
final AttributeSetInstanceId asiId = AttributesKeys.createAttributeSetInstanceFromAttributesKey(attributesKey);
final EventDescriptor eventDescriptor = EventDescriptor
.ofClientAndOrg(
dataRecord.getAD_Client_ID(),
dataRecord.getAD_Org_ID());
final ProductDescriptor productDescriptor = ProductDescriptor
.forProductAndAttributes(
dataRecord.getM_Product_ID(),
attributesKey,
asiId.getRepoId());
final StockChangeDetails details = StockChangeDetails
.builder()
.transactionId(stockChangeSourceInfo.getTransactionId())
.resetStockPInstanceId(stockChangeSourceInfo.getResetStockAdPinstanceId())
.stockId(dataRecord.getMD_Stock_ID())
.build();
|
final StockChangedEvent event = StockChangedEvent
.builder()
.eventDescriptor(eventDescriptor)
.productDescriptor(productDescriptor)
.warehouseId(WarehouseId.ofRepoId(dataRecord.getM_Warehouse_ID()))
.qtyOnHand(qtyOnHandNew)
.qtyOnHandOld(qtyOnHandOld)
.stockChangeDetails(details)
.changeDate(TimeUtil.asInstant(dataRecord.getUpdated()))
.build();
// the event is about an I_MD_Stock record. better wait until it was committed to DB
postMaterialEventService.enqueueEventAfterNextCommit(event);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\stock\StockDataUpdateRequestHandler.java
| 1
|
请完成以下Java代码
|
public final void invalidateView(final ViewId viewId)
{
final IView view = getByIdOrNull(viewId);
if (view == null)
{
return;
}
view.invalidateAll();
}
@Override
public final PurchaseView createView(@NonNull final CreateViewRequest request)
{
final ViewId viewId = newViewId();
final List<PurchaseDemand> demands = getDemands(request);
final List<PurchaseDemandWithCandidates> purchaseDemandWithCandidatesList = purchaseDemandWithCandidatesService.getOrCreatePurchaseCandidatesGroups(demands);
final PurchaseRowsSupplier rowsSupplier = createRowsSupplier(viewId, purchaseDemandWithCandidatesList);
final PurchaseView view = PurchaseView.builder()
.viewId(viewId)
.rowsSupplier(rowsSupplier)
.additionalRelatedProcessDescriptors(getAdditionalProcessDescriptors())
.build();
return view;
}
|
protected List<RelatedProcessDescriptor> getAdditionalProcessDescriptors()
{
return ImmutableList.of();
}
private final PurchaseRowsSupplier createRowsSupplier(
final ViewId viewId,
final List<PurchaseDemandWithCandidates> purchaseDemandWithCandidatesList)
{
final PurchaseRowsSupplier rowsSupplier = PurchaseRowsLoader.builder()
.purchaseDemandWithCandidatesList(purchaseDemandWithCandidatesList)
.viewSupplier(() -> getByIdOrNull(viewId)) // needed for async stuff
.purchaseRowFactory(purchaseRowFactory)
.availabilityCheckService(availabilityCheckService)
.build()
.createPurchaseRowsSupplier();
return rowsSupplier;
}
protected final RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass)
{
final AdProcessId processId = adProcessRepo.retrieveProcessIdByClassIfUnique(processClass);
Preconditions.checkArgument(processId != null, "No AD_Process_ID found for %s", processClass);
return RelatedProcessDescriptor.builder()
.processId(processId)
.displayPlace(DisplayPlace.ViewQuickActions)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseViewFactoryTemplate.java
| 1
|
请完成以下Java代码
|
public void closeById(final ViewId viewId, final ViewCloseAction closeAction)
{
views.closeById(viewId, closeAction);
}
@Override
public Stream<IView> streamAllViews()
{
return views.streamAllViews();
}
@Override
public void invalidateView(final ViewId viewId)
{
views.invalidateView(viewId);
}
private List<RelatedProcessDescriptor> getPaymentToReconcilateProcesses()
{
|
return ImmutableList.of(
createProcessDescriptor(PaymentsToReconcileView_Reconcile.class));
}
private final RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass)
{
return RelatedProcessDescriptor.builder()
.processId(adProcessDAO.retrieveProcessIdByClass(processClass))
.anyTable()
.anyWindow()
.displayPlace(DisplayPlace.ViewQuickActions)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\BankStatementReconciliationViewFactory.java
| 1
|
请完成以下Java代码
|
public ViewRow build()
{
return new ViewRow(this);
}
private DocumentPath getDocumentPath()
{
final DocumentId documentId = getRowId();
return DocumentPath.rootDocumentPath(windowId, documentId);
}
public Builder setRowId(final DocumentId rowId)
{
this.rowId = rowId;
_rowIdEffective = null;
return this;
}
/** @return view row ID; never null */
public DocumentId getRowId()
{
if (_rowIdEffective == null)
{
if (rowId == null)
{
throw new IllegalStateException("No rowId was provided for " + this);
}
if (isRootRow())
{
_rowIdEffective = rowId;
}
else
{
// NOTE: we have to do this because usually, the root row can have the same ID as one of the included rows,
// because the root/aggregated rows are build on demand and they don't really exist in database.
// Also see https://github.com/metasfresh/metasfresh-webui-frontend/issues/835#issuecomment-307783959
_rowIdEffective = rowId.toIncludedRowId();
}
}
return _rowIdEffective;
}
public Builder setParentRowId(final DocumentId parentRowId)
{
this.parentRowId = parentRowId;
_rowIdEffective = null;
return this;
}
private DocumentId getParentRowId()
{
return parentRowId;
}
public boolean isRootRow()
{
return getParentRowId() == null;
}
private IViewRowType getType()
{
return type;
}
public Builder setType(final IViewRowType type)
{
this.type = type;
return this;
}
public Builder setProcessed(final boolean processed)
{
this.processed = processed;
return this;
}
private boolean isProcessed()
{
if (processed == null)
{
// NOTE: don't take the "Processed" field if any, because in frontend we will end up with a lot of grayed out completed sales orders, for example.
// return DisplayType.toBoolean(values.getOrDefault("Processed", false));
return false;
}
else
{
return processed.booleanValue();
}
}
public Builder putFieldValue(final String fieldName, @Nullable final Object jsonValue)
{
if (jsonValue == null || JSONNullValue.isNull(jsonValue))
|
{
values.remove(fieldName);
}
else
{
values.put(fieldName, jsonValue);
}
return this;
}
private Map<String, Object> getValues()
{
return values;
}
public LookupValue getFieldValueAsLookupValue(final String fieldName)
{
return LookupValue.cast(values.get(fieldName));
}
public Builder addIncludedRow(final IViewRow includedRow)
{
if (includedRows == null)
{
includedRows = new ArrayList<>();
}
includedRows.add(includedRow);
return this;
}
private List<IViewRow> buildIncludedRows()
{
if (includedRows == null || includedRows.isEmpty())
{
return ImmutableList.of();
}
return ImmutableList.copyOf(includedRows);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRow.java
| 1
|
请完成以下Java代码
|
public AuthenticationManager customersAuthenticationManager() {
return authentication -> {
if (isCustomer(authentication)) {
return new UsernamePasswordAuthenticationToken(
authentication.getPrincipal(),
authentication.getCredentials(),
Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
);
}
throw new UsernameNotFoundException(authentication
.getPrincipal()
.toString());
};
}
private boolean isCustomer(Authentication authentication) {
return (authentication
.getPrincipal()
.toString()
.startsWith("customer"));
}
private boolean isEmployee(Authentication authentication) {
return (authentication
.getPrincipal()
.toString()
.startsWith("employee"));
}
private AuthenticationFilter authenticationFilter() {
AuthenticationFilter filter = new AuthenticationFilter(
resolver(), authenticationConverter());
filter.setSuccessHandler((request, response, auth) -> {});
return filter;
}
|
private AuthenticationManager employeesAuthenticationManager() {
return authentication -> {
if (isEmployee(authentication)) {
return new UsernamePasswordAuthenticationToken(
authentication.getPrincipal(),
authentication.getCredentials(),
Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
);
}
throw new UsernameNotFoundException(authentication
.getPrincipal()
.toString());
};
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.addFilterBefore(authenticationFilter(), BasicAuthenticationFilter.class);
return http.build();
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\authresolver\CustomWebSecurityConfigurer.java
| 1
|
请完成以下Java代码
|
private Encoder<?> getEncoder() {
Assert.notNull(this.jsonEncoder, "jsonEncoder has not been set");
return this.jsonEncoder;
}
private Decoder<?> getDecoder() {
Assert.notNull(this.jsonDecoder, "jsonDecoder has not been set");
return this.jsonDecoder;
}
protected static class DefaultJacksonCodecs {
private static final JsonMapper JSON_MAPPER = JsonMapper.builder()
.addModule(new GraphQlJacksonModule()).build();
static Encoder<?> encoder() {
return new JacksonJsonEncoder(JSON_MAPPER, MediaType.APPLICATION_JSON);
}
static Decoder<?> decoder() {
return new JacksonJsonDecoder(JSON_MAPPER, MediaType.APPLICATION_JSON, MediaTypes.APPLICATION_GRAPHQL_RESPONSE);
}
}
|
@SuppressWarnings("removal")
protected static class DefaultJackson2Codecs {
private static final com.fasterxml.jackson.databind.ObjectMapper JSON_MAPPER =
Jackson2ObjectMapperBuilder.json().modulesToInstall(new GraphQlJackson2Module()).build();
static Encoder<?> encoder() {
return new Jackson2JsonEncoder(JSON_MAPPER, MediaType.APPLICATION_JSON);
}
static Decoder<?> decoder() {
return new Jackson2JsonDecoder(JSON_MAPPER, MediaType.APPLICATION_JSON, MediaTypes.APPLICATION_GRAPHQL_RESPONSE);
}
}
}
|
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\AbstractGraphQlClientBuilder.java
| 1
|
请完成以下Java代码
|
public int getInitialCapacity()
{
return initialCapacity;
}
@Override
public void setInitialCapacity(int initalCapacity)
{
Check.assume(initalCapacity > 0, "initialCapacity > 0");
this.initialCapacity = initalCapacity;
}
@Override
public int getMaxCapacity()
{
return maxCapacity;
}
@Override
public void setMaxCapacity(int maxCapacity)
|
{
this.maxCapacity = maxCapacity;
}
@Override
public int getExpireMinutes()
{
return expireMinutes;
}
@Override
public void setExpireMinutes(int expireMinutes)
{
this.expireMinutes = expireMinutes > 0 ? expireMinutes : EXPIREMINUTES_Never;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\impl\MutableTableCacheConfig.java
| 1
|
请完成以下Java代码
|
protected boolean isNullModel(final ModelType model)
{
return model == null;
}
@Nullable
protected IAttributeStorage getAttributeStorageForModel(final ModelType model)
{
final ArrayKey key = mkKey(model);
try
{
final IAttributeStorage result = key2storage.get(key, () -> {
final AttributeStorageType storage = createAttributeStorage(model);
Check.assumeNotNull(storage, "storage not null");
// Add listeners to our storage
addListenersToAttributeStorage(storage);
return storage;
});
if (result != null)
{
result.assertNotDisposed();
}
return result;
}
catch (final Exception e)
{
throw AdempiereException.wrapIfNeeded(e);
}
}
/**
* Create attribute storage for underlying model
*
* @return attribute storage
*/
protected abstract AttributeStorageType createAttributeStorage(final ModelType model);
@Override
public void flush()
|
{
getHUAttributesDAO().flush();
}
/**
* Method called when an {@link IAttributeStorage} is removed from cache.
* <p>
* If needed you could do some cleanup work like, {@link #removeListenersFromAttributeStorage(IAttributeStorage)}, destroy it etc.
*/
protected void onAttributeStorageRemovedFromCache(final AttributeStorageType attributeStorage)
{
// nothing on this level
}
@Override
protected void toString(final ToStringHelper stringHelper)
{
// NOTE: avoid printing the whole map because it might get to HU storages that also print factory, leading to recursive calls of the toString.
stringHelper.add("storages#", key2storage.size());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\AbstractModelAttributeStorageFactory.java
| 1
|
请完成以下Java代码
|
public int getAD_Desktop_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Desktop_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Image.
@param AD_Image_ID
Image or Icon
*/
public void setAD_Image_ID (int AD_Image_ID)
{
if (AD_Image_ID < 1)
set_Value (COLUMNNAME_AD_Image_ID, null);
else
set_Value (COLUMNNAME_AD_Image_ID, Integer.valueOf(AD_Image_ID));
}
/** Get Image.
@return Image or Icon
*/
public int getAD_Image_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Image_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 Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
|
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Desktop.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setDurationInMillis(Long durationInMillis) {
this.durationInMillis = durationInMillis;
}
public Long getWorkTimeInMillis() {
return workTimeInMillis;
}
public void setWorkTimeInMillis(Long workTimeInMillis) {
this.workTimeInMillis = workTimeInMillis;
}
public Date getClaimTime() {
return claimTime;
}
public void setClaimTime(Date claimTime) {
this.claimTime = claimTime;
}
public String getTaskDefinitionKey() {
return taskDefinitionKey;
}
public void setTaskDefinitionKey(String taskDefinitionKey) {
this.taskDefinitionKey = taskDefinitionKey;
}
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
public Integer getPriority() {
return priority;
}
public void setPriority(Integer priority) {
this.priority = priority;
}
public Date getDueDate() {
return dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
public String getParentTaskId() {
return parentTaskId;
}
public void setParentTaskId(String parentTaskId) {
this.parentTaskId = parentTaskId;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public List<RestVariable> getVariables() {
return variables;
}
public void setVariables(List<RestVariable> variables) {
this.variables = variables;
}
|
public void addVariable(RestVariable variable) {
variables.add(variable);
}
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
public String getScopeId() {
return scopeId;
}
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
public String getSubScopeId() {
return subScopeId;
}
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public String getPropagatedStageInstanceId() {
return propagatedStageInstanceId;
}
public void setPropagatedStageInstanceId(String propagatedStageInstanceId) {
this.propagatedStageInstanceId = propagatedStageInstanceId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantId() {
return tenantId;
}
public void setCategory(String category) {
this.category = category;
}
public String getCategory() {
return category;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskInstanceResponse.java
| 2
|
请完成以下Java代码
|
public void setEmail(String email) {
this.email = email;
}
public void setPosts(List<Post> posts) {
this.posts = posts;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
|
User user = (User) o;
return Objects.equals(id, user.id);
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
public String toString() {
return "User(id=" + this.getId() + ", username=" + this.getUsername() + ", email=" + this.getEmail() + ", posts=" + this.getPosts()
+ ")";
}
}
|
repos\tutorials-master\persistence-modules\spring-boot-persistence-2\src\main\java\com\baeldung\listvsset\eager\list\moderatedomain\User.java
| 1
|
请完成以下Java代码
|
public class JSONPatchMenuNodeRequest
{
public static final JSONPatchMenuNodeRequest ofChangeEvents(final List<JSONDocumentChangedEvent> events)
{
if (events == null || events.isEmpty())
{
throw new AdempiereException("No events");
}
Boolean favorite = null;
if (events != null && !events.isEmpty())
{
for (final JSONDocumentChangedEvent event : events)
{
if (!event.isReplace())
{
throw new AdempiereException("Only " + JSONOperation.replace + " are supported")
.setParameter("event", event);
}
if (PATH_Favorite.equals(event.getPath()))
{
favorite = event.getValueAsBoolean(null);
if (favorite == null)
{
throw new AdempiereException("Invalid value for " + PATH_Favorite)
.setParameter("event", event);
}
}
else
{
throw new AdempiereException("Unknown path: " + event.getPath())
.setParameter("event", event)
.setParameter("availablePaths", PATHS);
}
}
}
// Make sure we have at least on actual change
if (favorite == null)
{
|
throw new AdempiereException("None of the requested changes are supported")
.setParameter("events", events);
}
return new JSONPatchMenuNodeRequest(favorite);
}
private static final String PATH_Favorite = "favorite";
private static final Set<String> PATHS = ImmutableSet.of(PATH_Favorite);
@JsonProperty("favorite")
@JsonInclude(JsonInclude.Include.NON_NULL)
private final Boolean favorite;
@JsonCreator
private JSONPatchMenuNodeRequest(@JsonProperty("favorite") final Boolean favorite)
{
this.favorite = favorite;
}
public Boolean getFavorite()
{
return favorite;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\menu\datatypes\json\JSONPatchMenuNodeRequest.java
| 1
|
请完成以下Java代码
|
public void request(long n) {
if ( bufCount == 0 ) {
s.onComplete();
return;
}
requested += n;
if ( recurse ) {
return;
}
recurse = true;
try {
while ( requested-- > 0 && !cancelled && bufCount-- > 0 ) {
byte[] data = new byte[bufSize];
rnd.nextBytes(data);
ByteBuf buf = Unpooled.wrappedBuffer(data);
s.onNext(buf);
|
}
}
finally {
recurse = false;
}
}
@Override
public void cancel() {
cancelled = true;
}
});
}
}
}
|
repos\tutorials-master\web-modules\ratpack\src\main\java\com\baeldung\spring\EmbedRatpackStreamsApp.java
| 1
|
请完成以下Spring Boot application配置
|
logging:
level:
org:
hibernate:
SQL: DEBUG
orm:
results: DEBUG
jdbc:
bind: TRACE
type:
descriptor:
sql:
BasicBinder: TRACE
|
resource:
jdbc:
internal:
ResourceRegistryStandardImpl: TRACE
|
repos\tutorials-master\persistence-modules\hibernate-annotations-2\src\main\resources\application.yml
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Foo updateFoo(@PathVariable("id") final String id, @RequestBody final Foo foo) {
return foo;
}
@RequestMapping(method = RequestMethod.PATCH, value = "/foos/{id}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Foo patchFoo(@PathVariable("id") final String id, @RequestBody final Foo foo) {
return foo;
}
@RequestMapping(method = RequestMethod.POST, value = "/foos")
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public Foo postFoo(@RequestBody final Foo foo) {
return foo;
}
@RequestMapping(method = RequestMethod.HEAD, value = "/foos")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Foo headFoo() {
return new Foo(1, randomAlphabetic(4));
}
@RequestMapping(method = RequestMethod.GET, value = "/foos/{id}", produces = { "application/x-protobuf" })
@ResponseBody
public FooProtos.Foo findProtoById(@PathVariable final long id) {
return FooProtos.Foo.newBuilder()
.setId(1)
.setName("Foo Name")
|
.build();
}
@RequestMapping(method = RequestMethod.POST, value = "/foos/new")
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public Foo createFoo(@RequestBody final Foo foo) {
return foo;
}
@RequestMapping(method = RequestMethod.DELETE, value = "/foos/{id}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public long deleteFoo(@PathVariable final long id) {
return id;
}
@RequestMapping(method = RequestMethod.POST, value = "/foos/form")
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public String submitFoo(@RequestParam("id") String id) {
return id;
}
}
|
repos\tutorials-master\spring-web-modules\spring-rest-simple\src\main\java\com\baeldung\web\controller\FooController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public InboundEMailConfig getById(@NonNull final InboundEMailConfigId id)
{
final InboundEMailConfig config = getAllConfigsIndexById().get(id);
if (config == null)
{
throw new AdempiereException("No config found for " + id);
}
return config;
}
public List<InboundEMailConfig> getByIds(@NonNull final Collection<InboundEMailConfigId> ids)
{
if (ids.isEmpty())
{
return ImmutableList.of();
}
final Map<InboundEMailConfigId, InboundEMailConfig> allConfigsIndexById = getAllConfigsIndexById();
return ids.stream()
.map(allConfigsIndexById::get)
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList());
}
private Map<InboundEMailConfigId, InboundEMailConfig> getAllConfigsIndexById()
{
return configsCache.getOrLoad(0, this::retrieveAllConfigsIndexById);
}
private Map<InboundEMailConfigId, InboundEMailConfig> retrieveAllConfigsIndexById()
{
return Services.get(IQueryBL.class)
.createQueryBuilderOutOfTrx(I_C_InboundMailConfig.class)
.addOnlyActiveRecordsFilter()
.create()
.stream()
.map(InboundEMailConfigRepository::toInboundEMailConfig)
|
.collect(GuavaCollectors.toImmutableMapByKey(InboundEMailConfig::getId));
}
private static InboundEMailConfig toInboundEMailConfig(final I_C_InboundMailConfig record)
{
return InboundEMailConfig.builder()
.id(InboundEMailConfigId.ofRepoId(record.getC_InboundMailConfig_ID()))
.protocol(InboundEMailProtocol.forCode(record.getProtocol()))
.host(record.getHost())
.port(record.getPort())
.folder(record.getFolder())
.username(record.getUserName())
.password(record.getPassword())
.debugProtocol(record.isDebugProtocol())
.adClientId(ClientId.ofRepoId(record.getAD_Client_ID()))
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.requestTypeId(RequestTypeId.ofRepoIdOrNull(record.getR_RequestType_ID()))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.inbound.mail\src\main\java\de\metas\inbound\mail\config\InboundEMailConfigRepository.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class MscManagedProcessEngine implements Service<ProcessEngine> {
private final static Logger LOGG = Logger.getLogger(MscManagedProcessEngine.class.getName());
protected InjectedValue<MscRuntimeContainerDelegate> runtimeContainerDelegateInjector = new InjectedValue<MscRuntimeContainerDelegate>();
/** the process engine managed by this service */
protected ProcessEngine processEngine;
private ServiceController<ManagedReferenceFactory> bindingService;
// for subclasses only
protected MscManagedProcessEngine() {
}
public MscManagedProcessEngine(ProcessEngine processEngine) {
this.processEngine = processEngine;
}
public ProcessEngine getValue() throws IllegalStateException, IllegalArgumentException {
return processEngine;
}
public void start(StartContext context) throws StartException {
MscRuntimeContainerDelegate runtimeContainerDelegate = runtimeContainerDelegateInjector.getValue();
runtimeContainerDelegate.processEngineStarted(processEngine);
createProcessEngineJndiBinding(context);
}
protected void createProcessEngineJndiBinding(StartContext context) {
final ProcessEngineManagedReferenceFactory managedReferenceFactory = new ProcessEngineManagedReferenceFactory(processEngine);
final ServiceName processEngineServiceBindingServiceName = ContextNames.GLOBAL_CONTEXT_SERVICE_NAME
.append(BpmPlatform.APP_JNDI_NAME)
.append(BpmPlatform.MODULE_JNDI_NAME)
|
.append(processEngine.getName());
final String jndiName = BpmPlatform.JNDI_NAME_PREFIX
+ "/" + BpmPlatform.APP_JNDI_NAME
+ "/" + BpmPlatform.MODULE_JNDI_NAME
+ "/" +processEngine.getName();
// bind process engine service
bindingService = BindingUtil.createJndiBindings(context.getChildTarget(), processEngineServiceBindingServiceName, jndiName, managedReferenceFactory);
// log info message
LOGG.info("jndi binding for process engine " + processEngine.getName() + " is " + jndiName);
}
protected void removeProcessEngineJndiBinding() {
bindingService.setMode(Mode.REMOVE);
}
public void stop(StopContext context) {
MscRuntimeContainerDelegate runtimeContainerDelegate = runtimeContainerDelegateInjector.getValue();
runtimeContainerDelegate.processEngineStopped(processEngine);
}
public Injector<MscRuntimeContainerDelegate> getRuntimeContainerDelegateInjector() {
return runtimeContainerDelegateInjector;
}
}
|
repos\camunda-bpm-platform-master\distro\wildfly26\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\MscManagedProcessEngine.java
| 2
|
请完成以下Java代码
|
public TypedValue convertToFormValue(TypedValue modelValue) {
if(modelValue.getValue() == null) {
return Variables.stringValue("", modelValue.isTransient());
} else if(modelValue.getType() == ValueType.DATE) {
return Variables.stringValue(dateFormat.format(modelValue.getValue()), modelValue.isTransient());
}
else {
throw new ProcessEngineException("Expected value to be of type '"+ValueType.DATE+"' but got '"+modelValue.getType()+"'.");
}
}
// deprecated //////////////////////////////////////////////////////////
public Object convertFormValueToModelValue(Object propertyValue) {
if (propertyValue==null || "".equals(propertyValue)) {
return null;
|
}
try {
return dateFormat.parseObject(propertyValue.toString());
} catch (ParseException e) {
throw new ProcessEngineException("invalid date value "+propertyValue);
}
}
public String convertModelValueToFormValue(Object modelValue) {
if (modelValue==null) {
return null;
}
return dateFormat.format(modelValue);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\type\DateFormType.java
| 1
|
请完成以下Java代码
|
public int getAD_PrintFont_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_PrintFont_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Validation code.
@param Code
Validation Code
*/
public void setCode (String Code)
{
set_Value (COLUMNNAME_Code, Code);
}
/** Get Validation code.
@return Validation Code
*/
public String getCode ()
{
return (String)get_Value(COLUMNNAME_Code);
}
/** Set Default.
@param IsDefault
Default value
*/
public void setIsDefault (boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
}
/** Get Default.
@return Default value
*/
|
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
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintFont.java
| 1
|
请完成以下Java代码
|
public static <T extends Comparable> ComparableComparator<T> getInstance(Class<T> clazz)
{
return getInstance(NULLSFIRST_DEFAULT);
}
public static <T extends Comparable> ComparableComparator<T> getInstance(final Class<T> clazz, final boolean nullsFirst)
{
return getInstance(nullsFirst);
}
private final boolean nullsFirst;
public ComparableComparator()
{
this(NULLSFIRST_DEFAULT);
}
public ComparableComparator(final boolean nullsFirst)
{
this.nullsFirst = nullsFirst;
}
@Override
public int compare(T o1, T o2)
{
|
if (o1 == o2)
{
return 0;
}
if (o1 == null)
{
return nullsFirst ? -1 : +1;
}
if (o2 == null)
{
return nullsFirst ? +1 : -1;
}
@SuppressWarnings("unchecked")
final int cmp = o1.compareTo(o2);
return cmp;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\comparator\ComparableComparator.java
| 1
|
请完成以下Java代码
|
public boolean isErrorEnabled() {
return logger.isErrorEnabled();
}
@Override
public void error(String msg) {
logger.error(mdcValue(msg));
}
@Override
public void error(String format, Object arg) {
logger.error(mdcValue(format), arg);
}
@Override
public void error(String format, Object arg1, Object arg2) {
logger.error(mdcValue(format), arg1, arg2);
}
@Override
public void error(String format, Object... arguments) {
logger.error(mdcValue(format), arguments);
}
@Override
public void error(String msg, Throwable t) {
logger.error(mdcValue(msg), t);
}
@Override
public boolean isErrorEnabled(Marker marker) {
return logger.isErrorEnabled(marker);
}
@Override
public void error(Marker marker, String msg) {
logger.error(marker, mdcValue(msg));
}
@Override
public void error(Marker marker, String format, Object arg) {
logger.error(marker, mdcValue(format), arg);
}
@Override
public void error(Marker marker, String format, Object arg1, Object arg2) {
logger.error(marker, mdcValue(format), arg1, arg2);
}
@Override
public void error(Marker marker, String format, Object... arguments) {
logger.error(marker, mdcValue(format), arguments);
}
@Override
public void error(Marker marker, String msg, Throwable t) {
logger.error(marker, mdcValue(msg), t);
}
|
/**
* 输出MDC容器中的值
*
* @param msg
* @return
*/
private String mdcValue(String msg) {
try {
StringBuilder sb = new StringBuilder();
sb.append(" [");
try {
sb.append(MDC.get(MdcConstant.SESSION_KEY) + ", ");
} catch (IllegalArgumentException e) {
sb.append(" , ");
}
try {
sb.append(MDC.get(MdcConstant.REQUEST_KEY));
} catch (IllegalArgumentException e) {
sb.append(" ");
}
sb.append("] ");
sb.append(msg);
return sb.toString();
} catch (Exception e) {
return msg;
}
}
}
|
repos\spring-boot-student-master\spring-boot-student-log\src\main\java\com\xiaolyuh\core\TrackLogger.java
| 1
|
请完成以下Java代码
|
private Cache cache() {
Cache<Object, Object> cache = getCacheManager().getCache(this.getClass().getName());
return cache;
}
/**
* 创建session,保存到数据库
*
* @param session
* @return
*/
@Override
protected Serializable doCreate(Session session) {
Serializable sessionId = super.doCreate(session);
cache().put(sessionId.toString(), session);
return sessionId;
}
/**
* 获取session
*
* @param sessionId
* @return
*/
@Override
protected Session doReadSession(Serializable sessionId) {
Session session = null;
HttpServletRequest request = ServletKit.getRequest();
if (request != null) {
String uri = request.getServletPath();
if (ServletKit.isStaticFile(uri)) {
return null;
}
session = (Session) request.getAttribute("session_" + sessionId);
}
if (session == null) {
session = super.doReadSession(sessionId);
}
if (session == null) {
session = (Session) cache().get(sessionId.toString());
}
return session;
}
/**
* 更新session的最后一次访问时间
*
* @param session
*/
@Override
|
protected void doUpdate(Session session) {
HttpServletRequest request = ServletKit.getRequest();
if (request != null) {
String uri = request.getServletPath();
if (ServletKit.isStaticFile(uri)) {
return;
}
}
super.doUpdate(session);
cache().put(session.getId().toString(), session);
logger.debug("{}", session.getAttribute("shiroUserId"));
}
/**
* 删除session
*
* @param session
*/
@Override
protected void doDelete(Session session) {
super.doDelete(session);
cache().remove(session.getId().toString());
}
}
|
repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\shiro\RedisSessionDao.java
| 1
|
请完成以下Java代码
|
public void setCamundaVariable(String camundaVariable) {
camundaVariableAttribute.setValue(this, camundaVariable);
}
public String getCamundaExpression() {
return camundaExpressionAttribute.getValue(this);
}
public void setCamundaExpression(String camundaExpression) {
camundaExpressionAttribute.setValue(this, camundaExpression);
}
public String getCamundaDatePattern() {
return camundaDatePatternAttribute.getValue(this);
}
|
public void setCamundaDatePattern(String camundaDatePattern) {
camundaDatePatternAttribute.setValue(this, camundaDatePattern);
}
public String getCamundaDefault() {
return camundaDefaultAttribute.getValue(this);
}
public void setCamundaDefault(String camundaDefault) {
camundaDefaultAttribute.setValue(this, camundaDefault);
}
public Collection<CamundaValue> getCamundaValues() {
return camundaValueCollection.get(this);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaFormPropertyImpl.java
| 1
|
请完成以下Java代码
|
protected Object handleThrownException(final Throwable exception) throws Throwable {
log.debug("Exception caught during gRPC execution: ", exception);
final Class<? extends Throwable> exceptionClass = exception.getClass();
final boolean exceptionIsMapped =
this.grpcExceptionHandlerMethodResolver.isMethodMappedForException(exceptionClass);
if (!exceptionIsMapped) {
throw exception;
}
final Entry<Object, Method> methodWithInstance =
this.grpcExceptionHandlerMethodResolver.resolveMethodWithInstance(exceptionClass);
final Method mappedMethod = methodWithInstance.getValue();
final Object instanceOfMappedMethod = methodWithInstance.getKey();
final Object[] instancedParams = determineInstancedParameters(mappedMethod, exception);
return invokeMappedMethodSafely(mappedMethod, instanceOfMappedMethod, instancedParams);
}
private Object[] determineInstancedParameters(final Method mappedMethod, final Throwable exception) {
final Parameter[] parameters = mappedMethod.getParameters();
final Object[] instancedParams = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
final Class<?> parameterClass = convertToClass(parameters[i]);
if (parameterClass.isAssignableFrom(exception.getClass())) {
instancedParams[i] = exception;
break;
}
}
return instancedParams;
}
private Class<?> convertToClass(final Parameter parameter) {
|
final Type paramType = parameter.getParameterizedType();
if (paramType instanceof Class) {
return (Class<?>) paramType;
}
throw new IllegalStateException("Parameter type of method has to be from Class, it was: " + paramType);
}
private Object invokeMappedMethodSafely(
final Method mappedMethod,
final Object instanceOfMappedMethod,
final Object[] instancedParams) throws Throwable {
try {
return mappedMethod.invoke(instanceOfMappedMethod, instancedParams);
} catch (InvocationTargetException | IllegalAccessException e) {
throw e.getCause(); // throw the exception thrown by implementation
}
}
}
|
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\advice\GrpcAdviceExceptionHandler.java
| 1
|
请完成以下Java代码
|
public CreditDebitCode getCdtDbtInd() {
return cdtDbtInd;
}
/**
* Sets the value of the cdtDbtInd property.
*
* @param value
* allowed object is
* {@link CreditDebitCode }
*
*/
public void setCdtDbtInd(CreditDebitCode value) {
this.cdtDbtInd = value;
}
/**
* Gets the value of the fcstInd property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isFcstInd() {
return fcstInd;
}
/**
* Sets the value of the fcstInd property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setFcstInd(Boolean value) {
this.fcstInd = value;
}
/**
* Gets the value of the bkTxCd property.
*
* @return
* possible object is
* {@link BankTransactionCodeStructure4 }
*
*/
public BankTransactionCodeStructure4 getBkTxCd() {
return bkTxCd;
}
/**
* Sets the value of the bkTxCd property.
|
*
* @param value
* allowed object is
* {@link BankTransactionCodeStructure4 }
*
*/
public void setBkTxCd(BankTransactionCodeStructure4 value) {
this.bkTxCd = value;
}
/**
* Gets the value of the avlbty property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the avlbty property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAvlbty().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CashBalanceAvailability2 }
*
*
*/
public List<CashBalanceAvailability2> getAvlbty() {
if (avlbty == null) {
avlbty = new ArrayList<CashBalanceAvailability2>();
}
return this.avlbty;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TotalsPerBankTransactionCode2.java
| 1
|
请完成以下Java代码
|
public I_M_HU_LUTU_Configuration getCurrentLUTUConfigurationOrNull(final List<T> documentLines)
{
Check.assumeNotEmpty(documentLines, "documentLines not empty");
final T documentLine = documentLines.get(0);
return handler.getCurrentLUTUConfigurationOrNull(documentLine);
}
@Override
public List<I_M_HU_LUTU_Configuration> getCurrentLUTUConfigurationAlternatives(final List<T> documentLines)
{
Check.assumeNotEmpty(documentLines, "documentLines not empty");
final Set<Integer> seenConfigurationIds = new HashSet<>();
final List<I_M_HU_LUTU_Configuration> altConfigurations = new ArrayList<>(documentLines.size());
//
// Main configuration
final T mainDocumentLine = documentLines.get(0);
final I_M_HU_LUTU_Configuration mainConfiguration = handler.getCurrentLUTUConfigurationOrNull(mainDocumentLine);
// Skip the main configuration from returning it
if (mainConfiguration != null)
{
seenConfigurationIds.add(mainConfiguration.getM_HU_LUTU_Configuration_ID());
}
for (int i = 1; i < documentLines.size(); i++)
{
final T documentLine = documentLines.get(i);
final I_M_HU_LUTU_Configuration configuration = handler.getCurrentLUTUConfigurationOrNull(documentLine);
if (configuration == null)
{
continue;
}
final int configurationId = configuration.getM_HU_LUTU_Configuration_ID();
if (configurationId <= 0)
|
{
continue;
}
if (!seenConfigurationIds.add(configurationId))
{
continue;
}
altConfigurations.add(configuration);
}
return altConfigurations;
}
@Override
public I_M_HU_PI_Item_Product getM_HU_PI_Item_Product(final List<T> documentLines)
{
Check.assumeNotEmpty(documentLines, "documentLines not empty");
final T documentLine = documentLines.get(0);
return handler.getM_HU_PI_Item_Product(documentLine);
}
@Override
public void save(@NonNull final List<T> documentLines)
{
for (final T documentLine : documentLines)
{
handler.save(documentLine);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\CompositeDocumentLUTUConfigurationHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected void launchJobFromProperties(Properties properties) throws JobExecutionException {
JobParameters jobParameters = this.converter.getJobParameters(properties);
executeLocalJobs(jobParameters);
executeRegisteredJobs(jobParameters);
}
private boolean isLocalJob(String jobName) {
return this.jobs.stream().anyMatch((job) -> job.getName().equals(jobName));
}
private boolean isRegisteredJob(String jobName) {
return this.jobRegistry != null && this.jobRegistry.getJobNames().contains(jobName);
}
private void executeLocalJobs(JobParameters jobParameters) throws JobExecutionException {
for (Job job : this.jobs) {
if (StringUtils.hasText(this.jobName)) {
if (!this.jobName.equals(job.getName())) {
logger.debug(LogMessage.format("Skipped job: %s", job.getName()));
continue;
}
}
execute(job, jobParameters);
}
}
private void executeRegisteredJobs(JobParameters jobParameters) throws JobExecutionException {
|
if (this.jobRegistry != null && StringUtils.hasText(this.jobName)) {
if (!isLocalJob(this.jobName)) {
Job job = this.jobRegistry.getJob(this.jobName);
Assert.notNull(job, () -> "No job found with name '" + this.jobName + "'");
execute(job, jobParameters);
}
}
}
protected void execute(Job job, JobParameters jobParameters) throws JobExecutionAlreadyRunningException,
JobRestartException, JobInstanceAlreadyCompleteException, InvalidJobParametersException {
JobExecution execution = this.jobOperator.start(job, jobParameters);
if (this.publisher != null) {
this.publisher.publishEvent(new JobExecutionEvent(execution));
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-batch\src\main\java\org\springframework\boot\batch\autoconfigure\JobLauncherApplicationRunner.java
| 2
|
请完成以下Java代码
|
private JsonWorkstation toJson(final Resource workstation)
{
final ResourceId workstationId = workstation.getResourceId();
final WorkplaceId workplaceId = workstation.getWorkplaceId();
final String workplaceName = workplaceId != null ? workplaceService.getById(workplaceId).getName() : null;
return JsonWorkstation.builder()
.id(workstationId)
.name(workstation.getName())
.qrCode(workstation.toQrCode().toGlobalQRCodeJsonString())
.workplaceName(workplaceName)
.isUserAssigned(userWorkstationService.isUserAssigned(Env.getLoggedUserId(), workstationId))
.build();
}
@GetMapping
public JsonWorkstationSettings getStatus()
{
return JsonWorkstationSettings.builder()
.assignedWorkstation(userWorkstationService.getUserWorkstationId(Env.getLoggedUserId())
.map(resourceService::getById)
.map(this::toJson)
.orElse(null))
.build();
}
@PostMapping("/assign")
public JsonWorkstation assign(@RequestBody @NonNull final JsonAssignWorkstationRequest request)
|
{
final Resource workstation = getWorkstationById(request.getWorkstationIdEffective());
final UserId loggedUserId = Env.getLoggedUserId();
userWorkstationService.assign(loggedUserId, workstation.getResourceId());
Optional.ofNullable(workstation.getWorkplaceId())
.ifPresent(workplaceId -> workplaceService.assignWorkplace(loggedUserId, workplaceId));
return toJson(workstation);
}
@PostMapping("/byQRCode")
public JsonWorkstation getWorkstationByQRCode(@RequestBody @NonNull final JsonGetWorkstationByQRCodeRequest request)
{
final ResourceQRCode qrCode = ResourceQRCode.ofGlobalQRCodeJsonString(request.getQrCode());
final Resource workstation = getWorkstationById(qrCode.getResourceId());
return toJson(workstation);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\workstation\WorkstationRestController.java
| 1
|
请完成以下Java代码
|
public abstract class ModificationUtil {
public static void handleChildRemovalInScope(ExecutionEntity removedExecution) {
ActivityImpl activity = removedExecution.getActivity();
if (activity == null) {
if (removedExecution.getSuperExecution() != null) {
removedExecution = removedExecution.getSuperExecution();
activity = removedExecution.getActivity();
if (activity == null) {
return;
}
} else {
return;
}
}
ScopeImpl flowScope = activity.getFlowScope();
PvmExecutionImpl scopeExecution = removedExecution.getParentScopeExecution(false);
|
PvmExecutionImpl executionInParentScope = removedExecution.isConcurrent() ? removedExecution : removedExecution.getParent();
if (flowScope.getActivityBehavior() != null && flowScope.getActivityBehavior() instanceof ModificationObserverBehavior) {
// let child removal be handled by the scope itself
ModificationObserverBehavior behavior = (ModificationObserverBehavior) flowScope.getActivityBehavior();
behavior.destroyInnerInstance(executionInParentScope);
}
else {
if (executionInParentScope.isConcurrent()) {
executionInParentScope.remove();
scopeExecution.tryPruneLastConcurrentChild();
scopeExecution.forceUpdate();
}
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\ModificationUtil.java
| 1
|
请完成以下Java代码
|
public static DirContextOperations searchForSingleEntryInternal(DirContext ctx, SearchControls searchControls,
String base, String filter, Object[] params) throws NamingException {
final LdapName ctxBaseDn = LdapNameBuilder.newInstance(ctx.getNameInNamespace()).build();
final LdapName searchBaseDn = LdapNameBuilder.newInstance(base).build();
final NamingEnumeration<SearchResult> resultsEnum = ctx.search(searchBaseDn, filter, params,
buildControls(searchControls));
logger.trace(LogMessage.format("Searching for entry under DN '%s', base = '%s', filter = '%s'", ctxBaseDn,
searchBaseDn, filter));
Set<DirContextOperations> results = new HashSet<>();
try {
while (resultsEnum.hasMore()) {
SearchResult searchResult = resultsEnum.next();
DirContextAdapter dca = (DirContextAdapter) searchResult.getObject();
Assert.notNull(dca, "No object returned by search, DirContext is not correctly configured");
logger.debug(LogMessage.format("Found DN: %s", dca.getDn()));
results.add(dca);
}
}
catch (PartialResultException ex) {
LdapUtils.closeEnumeration(resultsEnum);
logger.trace("Ignoring PartialResultException");
}
if (results.size() != 1) {
throw new IncorrectResultSizeDataAccessException(1, results.size());
}
|
return results.iterator().next();
}
/**
* We need to make sure the search controls has the return object flag set to true, in
* order for the search to return DirContextAdapter instances.
* @param originalControls the {@link SearchControls} that might have the return
* object flag set to true
* @return a {@link SearchControls} that does have the return object flag set to true
*/
private static SearchControls buildControls(SearchControls originalControls) {
return new SearchControls(originalControls.getSearchScope(), originalControls.getCountLimit(),
originalControls.getTimeLimit(), originalControls.getReturningAttributes(), RETURN_OBJECT,
originalControls.getDerefLinkFlag());
}
/**
* Sets the search controls which will be used for search operations by the template.
* @param searchControls the SearchControls instance which will be cached in the
* template.
*/
public void setSearchControls(SearchControls searchControls) {
this.searchControls = searchControls;
}
}
|
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\SpringSecurityLdapTemplate.java
| 1
|
请完成以下Java代码
|
public void setUserElementString6 (final @Nullable java.lang.String UserElementString6)
{
set_Value (COLUMNNAME_UserElementString6, UserElementString6);
}
@Override
public java.lang.String getUserElementString6()
{
return get_ValueAsString(COLUMNNAME_UserElementString6);
}
@Override
public void setUserElementString7 (final @Nullable java.lang.String UserElementString7)
{
set_Value (COLUMNNAME_UserElementString7, UserElementString7);
}
@Override
public java.lang.String getUserElementString7()
{
return get_ValueAsString(COLUMNNAME_UserElementString7);
}
@Override
public void setVesselName (final @Nullable java.lang.String VesselName)
{
throw new IllegalArgumentException ("VesselName is virtual column"); }
@Override
public java.lang.String getVesselName()
{
return get_ValueAsString(COLUMNNAME_VesselName);
}
@Override
public void setExternalHeaderId (final @Nullable String ExternalHeaderId)
{
set_Value (COLUMNNAME_ExternalHeaderId, ExternalHeaderId);
}
@Override
public String getExternalHeaderId()
{
return get_ValueAsString(COLUMNNAME_ExternalHeaderId);
}
|
@Override
public void setExternalLineId (final @Nullable String ExternalLineId)
{
set_Value (COLUMNNAME_ExternalLineId, ExternalLineId);
}
@Override
public String getExternalLineId()
{
return get_ValueAsString(COLUMNNAME_ExternalLineId);
}
@Override
public void setExternalSystem_ID (final int ExternalSystem_ID)
{
if (ExternalSystem_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID);
}
@Override
public int getExternalSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ReceiptSchedule.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public InitHook<ResourceLoaderDependingFilter> resourceLoaderDependingInitHook() {
return filter -> {
filter.setResourceLoader(resourceLoader);
filter.setWebappProperty(properties.getWebapp());
};
}
@Bean
public LazyInitRegistration lazyInitRegistration() {
return new LazyInitRegistration();
}
@Bean
public FaviconResourceResolver faviconResourceResolver() {
return new FaviconResourceResolver();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
final String classpath = "classpath:" + properties.getWebapp().getWebjarClasspath();
WebappProperty webapp = properties.getWebapp();
String applicationPath = webapp.getApplicationPath();
registry.addResourceHandler(applicationPath + "/lib/**")
.addResourceLocations(classpath + "/lib/");
registry.addResourceHandler(applicationPath + "/api/**")
.addResourceLocations("classpath:/api/");
registry.addResourceHandler(applicationPath + "/app/**")
.addResourceLocations(classpath + "/app/");
registry.addResourceHandler(applicationPath + "/assets/**")
.addResourceLocations(classpath + "/assets/");
|
registry.addResourceHandler(applicationPath + "/favicon.ico")
.addResourceLocations(classpath + "/") // add slash to get rid of the WARN log
.resourceChain(true)
.addResolver(faviconResourceResolver());
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
WebappProperty webapp = properties.getWebapp();
if (webapp.isIndexRedirectEnabled()) {
String applicationPath = webapp.getApplicationPath();
registry.addRedirectViewController("/", applicationPath + "/app/");
}
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter-webapp-core\src\main\java\org\camunda\bpm\spring\boot\starter\webapp\CamundaBpmWebappAutoConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private CellStyle initHeaderStyle(Workbook workbook) {
CellStyle style = getBaseCellStyle(workbook);
style.setFont(getFont(workbook, FONT_SIZE_TWELVE, true));
return style;
}
/**
* init-TitleStyle
*
* @param workbook
* @return
*/
private CellStyle initTitleStyle(Workbook workbook) {
CellStyle style = getBaseCellStyle(workbook);
style.setFont(getFont(workbook, FONT_SIZE_ELEVEN, false));
// ForegroundColor
style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
return style;
}
/**
* BaseCellStyle
*
* @return
*/
private CellStyle getBaseCellStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
style.setAlignment(HorizontalAlignment.CENTER);
|
style.setVerticalAlignment(VerticalAlignment.CENTER);
style.setWrapText(true);
return style;
}
/**
* Font
*
* @param size
* @param isBold
* @return
*/
private Font getFont(Workbook workbook, short size, boolean isBold) {
Font font = workbook.createFont();
font.setFontName("宋体");
font.setBold(isBold);
font.setFontHeightInPoints(size);
return font;
}
}
|
repos\springboot-demo-master\eaypoi\src\main\java\com\et\easypoi\service\ExcelExportStyler.java
| 2
|
请完成以下Java代码
|
public final class JwtTimestampValidator implements OAuth2TokenValidator<Jwt> {
private final Log logger = LogFactory.getLog(getClass());
private static final Duration DEFAULT_MAX_CLOCK_SKEW = Duration.of(60, ChronoUnit.SECONDS);
private final Duration clockSkew;
private boolean allowEmptyExpiryClaim = true;
private boolean allowEmptyNotBeforeClaim = true;
private Clock clock = Clock.systemUTC();
/**
* A basic instance with no custom verification and the default max clock skew
*/
public JwtTimestampValidator() {
this(DEFAULT_MAX_CLOCK_SKEW);
}
public JwtTimestampValidator(Duration clockSkew) {
Assert.notNull(clockSkew, "clockSkew cannot be null");
this.clockSkew = clockSkew;
}
/**
* Whether to allow the {@code exp} header to be empty. The default value is
* {@code true}
*
* @since 7.0
*/
public void setAllowEmptyExpiryClaim(boolean allowEmptyExpiryClaim) {
this.allowEmptyExpiryClaim = allowEmptyExpiryClaim;
}
/**
* Whether to allow the {@code nbf} header to be empty. The default value is
* {@code true}
*
* @since 7.0
*/
public void setAllowEmptyNotBeforeClaim(boolean allowEmptyNotBeforeClaim) {
this.allowEmptyNotBeforeClaim = allowEmptyNotBeforeClaim;
}
@Override
public OAuth2TokenValidatorResult validate(Jwt jwt) {
Assert.notNull(jwt, "jwt cannot be null");
Instant expiry = jwt.getExpiresAt();
|
if (!this.allowEmptyExpiryClaim && ObjectUtils.isEmpty(expiry)) {
return createOAuth2Error("exp is required");
}
if (expiry != null) {
if (Instant.now(this.clock).minus(this.clockSkew).isAfter(expiry)) {
return createOAuth2Error(String.format("Jwt expired at %s", jwt.getExpiresAt()));
}
}
Instant notBefore = jwt.getNotBefore();
if (!this.allowEmptyNotBeforeClaim && ObjectUtils.isEmpty(notBefore)) {
return createOAuth2Error("nbf is required");
}
if (notBefore != null) {
if (Instant.now(this.clock).plus(this.clockSkew).isBefore(notBefore)) {
return createOAuth2Error(String.format("Jwt used before %s", jwt.getNotBefore()));
}
}
return OAuth2TokenValidatorResult.success();
}
private OAuth2TokenValidatorResult createOAuth2Error(String reason) {
this.logger.debug(reason);
return OAuth2TokenValidatorResult.failure(new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, reason,
"https://tools.ietf.org/html/rfc6750#section-3.1"));
}
/**
* Use this {@link Clock} with {@link Instant#now()} for assessing timestamp validity
* @param clock
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.clock = clock;
}
}
|
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JwtTimestampValidator.java
| 1
|
请完成以下Java代码
|
public <T> ICompositeQueryFilter<T> createCompositeQueryFilter(final Class<T> modelClass)
{
return CompositeQueryFilter.newInstance(modelClass);
}
@Override
public ICompositeQueryFilter<Object> createCompositeQueryFilter(@Nullable final String modelTableName)
{
return CompositeQueryFilter.newInstance(modelTableName);
}
@Override
public <T> ICompositeQueryUpdater<T> createCompositeQueryUpdater(final Class<T> modelClass)
{
return new CompositeQueryUpdater<>();
}
@Override
public <T> String debugAccept(final IQueryFilter<T> filter, final T model)
{
final StringBuilder sb = new StringBuilder();
sb.append("\n-------------------------------------------------------------------------------");
sb.append("\nModel: " + model);
final List<IQueryFilter<T>> filters = extractAllFilters(filter);
for (final IQueryFilter<T> f : filters)
{
final boolean accept = f.accept(model);
sb.append("\nFilter(accept=" + accept + "): " + f);
}
sb.append("\n-------------------------------------------------------------------------------");
return sb.toString();
}
private <T> List<IQueryFilter<T>> extractAllFilters(@Nullable final IQueryFilter<T> filter)
{
if (filter == null)
{
return Collections.emptyList();
}
final List<IQueryFilter<T>> result = new ArrayList<>();
result.add(filter);
if (filter instanceof ICompositeQueryFilter)
{
final ICompositeQueryFilter<T> compositeFilter = (ICompositeQueryFilter<T>)filter;
|
for (final IQueryFilter<T> f : compositeFilter.getFilters())
{
final List<IQueryFilter<T>> resultLocal = extractAllFilters(f);
result.addAll(resultLocal);
}
}
return result;
}
@Override
public <T> QueryResultPage<T> retrieveNextPage(
@NonNull final Class<T> clazz,
@NonNull final String next)
{
if (Adempiere.isUnitTestMode())
{
return POJOQuery.getPage(clazz, next);
}
return SpringContextHolder.instance
.getBean(PaginationService.class)
.loadPage(clazz, next);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\QueryBL.java
| 1
|
请完成以下Java代码
|
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 class Account {
@MongoId
private ObjectId id;
private String userEmail;
private String nickName;
private String accountDomain;
private String password;
public ObjectId getId() {
return id;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
|
public String getAccountDomain() {
return accountDomain;
}
public void setAccountDomain(String accountDomain) {
this.accountDomain = accountDomain;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Account book = (Account) o;
return Objects.equals(id, book.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
|
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb\src\main\java\com\baeldung\multipledb\model\Account.java
| 1
|
请完成以下Java代码
|
public UomId getUomId()
{
return uom == null ? null : UomId.ofRepoIdOrNull(uom.getKeyAsInt());
}
private JSONLookupValue getClearanceStatus()
{
return clearanceStatus;
}
@Nullable
public I_C_UOM getUom()
{
final UomId uomId = getUomId();
if (uomId == null)
{
return null;
}
final IUOMDAO uomDAO = Services.get(IUOMDAO.class);
return uomDAO.getById(uomId);
}
@NonNull
public I_C_UOM getUomNotNull()
{
return Check.assumeNotNull(getUom(), "Expecting UOM to always be present when using this method!");
}
public boolean isReceipt()
{
return getType().canReceive();
}
public boolean isIssue()
{
return getType().canIssue();
}
public boolean isHUStatusActive()
{
return huStatus != null && X_M_HU.HUSTATUS_Active.equals(huStatus.getKey());
|
}
@Override
public boolean hasAttributes()
{
return attributesSupplier != null;
}
@Override
public IViewRowAttributes getAttributes() throws EntityNotFoundException
{
if (attributesSupplier == null)
{
throw new EntityNotFoundException("This PPOrderLineRow does not support attributes; this=" + this);
}
final IViewRowAttributes attributes = attributesSupplier.get();
if (attributes == null)
{
throw new EntityNotFoundException("This PPOrderLineRow does not support attributes; this=" + this);
}
return attributes;
}
@Override
public HuUnitType getHUUnitTypeOrNull() {return huUnitType;}
@Override
public BPartnerId getBpartnerId() {return huBPartnerId;}
@Override
public boolean isTopLevel() {return topLevelHU;}
@Override
public Stream<HUReportAwareViewRow> streamIncludedHUReportAwareRows() {return getIncludedRows().stream().map(PPOrderLineRow::toHUReportAwareViewRow);}
private HUReportAwareViewRow toHUReportAwareViewRow() {return this;}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\PPOrderLineRow.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MailTemplateId implements RepoIdAware
{
@JsonCreator
public static MailTemplateId ofRepoId(final int repoId)
{
return new MailTemplateId(repoId);
}
public static MailTemplateId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new MailTemplateId(repoId) : null;
}
public static Optional<MailTemplateId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
int repoId;
|
private MailTemplateId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "R_MailText_ID");
}
@JsonValue
@Override
public int getRepoId()
{
return repoId;
}
public static int toRepoId(final MailTemplateId mailTemplateId)
{
return mailTemplateId != null ? mailTemplateId.getRepoId() : -1;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\templates\MailTemplateId.java
| 2
|
请完成以下Java代码
|
public void removeAttribute(String name) {
checkState();
Object oldValue = this.session.getAttribute(name);
this.session.removeAttribute(name);
if (oldValue instanceof HttpSessionBindingListener) {
try {
((HttpSessionBindingListener) oldValue).valueUnbound(new HttpSessionBindingEvent(this, name, oldValue));
}
catch (Throwable th) {
logger.error("Error invoking session binding event listener", th);
}
}
}
@Override
public void invalidate() {
checkState();
this.invalidated = true;
|
}
@Override
public boolean isNew() {
checkState();
return !this.old;
}
void markNotNew() {
this.old = true;
}
private void checkState() {
if (this.invalidated) {
throw new IllegalStateException("The HttpSession has already be invalidated.");
}
}
}
|
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\HttpSessionAdapter.java
| 1
|
请完成以下Java代码
|
public Integer getControlBehavior() {
return controlBehavior;
}
public void setControlBehavior(Integer controlBehavior) {
this.controlBehavior = controlBehavior;
}
public Integer getBurst() {
return burst;
}
public void setBurst(Integer burst) {
this.burst = burst;
}
|
public Integer getMaxQueueingTimeoutMs() {
return maxQueueingTimeoutMs;
}
public void setMaxQueueingTimeoutMs(Integer maxQueueingTimeoutMs) {
this.maxQueueingTimeoutMs = maxQueueingTimeoutMs;
}
public GatewayParamFlowItemVo getParamItem() {
return paramItem;
}
public void setParamItem(GatewayParamFlowItemVo paramItem) {
this.paramItem = paramItem;
}
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\vo\gateway\rule\UpdateFlowRuleReqVo.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setEmail(String email) {
super.setEmail(email);
emailChanged = true;
}
@Override
public void setFirstName(String firstName) {
super.setFirstName(firstName);
firstNameChanged = true;
}
@Override
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 String getBusinessKey() {
return businessKey;
}
public void setBusinessKey(String businessKey) {
this.businessKey = businessKey;
}
public Map<String, VariableValueDto> getCorrelationKeys() {
return correlationKeys;
}
public void setCorrelationKeys(Map<String, VariableValueDto> correlationKeys) {
this.correlationKeys = correlationKeys;
}
public Map<String, VariableValueDto> getLocalCorrelationKeys() {
return localCorrelationKeys;
}
public void setLocalCorrelationKeys(Map<String, VariableValueDto> localCorrelationKeys) {
this.localCorrelationKeys = localCorrelationKeys;
}
public Map<String, VariableValueDto> getProcessVariables() {
return processVariables;
}
public void setProcessVariables(Map<String, VariableValueDto> processVariables) {
this.processVariables = processVariables;
}
public Map<String, VariableValueDto> getProcessVariablesLocal() {
return processVariablesLocal;
}
public void setProcessVariablesLocal(Map<String, VariableValueDto> processVariablesLocal) {
this.processVariablesLocal = processVariablesLocal;
}
public Map<String, VariableValueDto> getProcessVariablesToTriggeredScope() {
return processVariablesToTriggeredScope;
}
public void setProcessVariablesToTriggeredScope(Map<String, VariableValueDto> processVariablesToTriggeredScope) {
this.processVariablesToTriggeredScope = processVariablesToTriggeredScope;
}
public boolean isAll() {
|
return all;
}
public void setAll(boolean all) {
this.all = all;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public boolean isResultEnabled() {
return resultEnabled;
}
public void setResultEnabled(boolean resultEnabled) {
this.resultEnabled = resultEnabled;
}
public boolean isVariablesInResultEnabled() {
return variablesInResultEnabled;
}
public void setVariablesInResultEnabled(boolean variablesInResultEnabled) {
this.variablesInResultEnabled = variablesInResultEnabled;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\message\CorrelationMessageDto.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setQUANTITY(String value) {
this.quantity = value;
}
/**
* Gets the value of the measurementunit property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMEASUREMENTUNIT() {
return measurementunit;
}
/**
* Sets the value of the measurementunit property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMEASUREMENTUNIT(String value) {
this.measurementunit = value;
}
/**
* Gets the value of the dmkdq1 property.
*
* @return
* possible object is
* {@link DMKDQ1 }
*
*/
public DMKDQ1 getDMKDQ1() {
return dmkdq1;
}
/**
* Sets the value of the dmkdq1 property.
*
* @param value
* allowed object is
* {@link DMKDQ1 }
*
*/
public void setDMKDQ1(DMKDQ1 value) {
this.dmkdq1 = value;
}
/**
* Gets the value of the dpldq1 property.
*
* @return
* possible object is
* {@link DPLDQ1 }
*
*/
public DPLDQ1 getDPLDQ1() {
return dpldq1;
}
/**
* Sets the value of the dpldq1 property.
*
* @param value
* allowed object is
* {@link DPLDQ1 }
*
*/
public void setDPLDQ1(DPLDQ1 value) {
this.dpldq1 = value;
}
/**
* Gets the value of the ddtdq1 property.
*
* @return
* possible object is
* {@link DDTDQ1 }
*
*/
public DDTDQ1 getDDTDQ1() {
return ddtdq1;
|
}
/**
* Sets the value of the ddtdq1 property.
*
* @param value
* allowed object is
* {@link DDTDQ1 }
*
*/
public void setDDTDQ1(DDTDQ1 value) {
this.ddtdq1 = value;
}
/**
* Gets the value of the dprdq1 property.
*
* @return
* possible object is
* {@link DPRDQ1 }
*
*/
public DPRDQ1 getDPRDQ1() {
return dprdq1;
}
/**
* Sets the value of the dprdq1 property.
*
* @param value
* allowed object is
* {@link DPRDQ1 }
*
*/
public void setDPRDQ1(DPRDQ1 value) {
this.dprdq1 = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DQUAN1.java
| 2
|
请完成以下Java代码
|
private List<UserNotificationRequest> createOrderCompletedEvents(
@NonNull final I_C_Order order,
@NonNull final Set<UserId> recipientUserIds,
@NonNull final ADMessageAndParams adMessageAndParams)
{
Check.assumeNotEmpty(recipientUserIds, "recipientUserIds is not empty");
return recipientUserIds.stream()
.filter(Objects::nonNull)
.map(recipientUserId -> newUserNotificationRequest()
.recipientUserId(recipientUserId)
.contentADMessage(adMessageAndParams.getAdMessage())
.contentADMessageParams(adMessageAndParams.getParams())
.targetAction(TargetRecordAction.of(TableRecordReference.of(order)))
.build())
.collect(ImmutableList.toImmutableList());
}
private UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest()
{
return UserNotificationRequest.builder()
.topic(USER_NOTIFICATIONS_TOPIC);
}
private static ADMessageAndParams extractOrderCompletedADMessageAndParams(final I_C_Order order)
{
final I_C_BPartner bpartner = Services.get(IOrderBL.class).getBPartner(order);
return ADMessageAndParams.builder()
.adMessage(order.isSOTrx() ? MSG_SalesOrderCompleted : MSG_PurchaseOrderCompleted)
.param(TableRecordReference.of(order))
.param(bpartner.getValue())
.param(bpartner.getName())
|
.build();
}
private static Set<UserId> extractRecipientUserIdsFromOrder(final I_C_Order order)
{
final Integer createdBy = InterfaceWrapperHelper.getValueOrNull(order, "CreatedBy");
final UserId recipientUserId = createdBy == null ? null : UserId.ofRepoIdOrNull(createdBy);
return recipientUserId != null ? ImmutableSet.of(recipientUserId) : ImmutableSet.of();
}
private void postNotifications(final List<UserNotificationRequest> notifications)
{
Services.get(INotificationBL.class).sendAfterCommit(notifications);
}
@Value
@Builder
public static class NotificationRequest
{
@NonNull
I_C_Order order;
@Nullable
Set<UserId> recipientUserIds;
@Nullable
ADMessageAndParams adMessageAndParams;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\event\OrderUserNotifications.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Page<QuoteDTO> findByCriteria(QuoteCriteria criteria, Pageable page) {
log.debug("find by criteria : {}, page: {}", criteria, page);
final Specification<Quote> specification = createSpecification(criteria);
return quoteRepository.findAll(specification, page)
.map(quoteMapper::toDto);
}
/**
* Return the number of matching entities in the database
* @param criteria The object which holds all the filters, which the entities should match.
* @return the number of matching entities.
*/
@Transactional(readOnly = true)
public long countByCriteria(QuoteCriteria criteria) {
log.debug("count by criteria : {}", criteria);
final Specification<Quote> specification = createSpecification(criteria);
return quoteRepository.count(specification);
}
/**
* Function to convert QuoteCriteria to a {@link Specification}
*/
private Specification<Quote> createSpecification(QuoteCriteria criteria) {
Specification<Quote> specification = Specification.where(null);
if (criteria != null) {
if (criteria.getId() != null) {
|
specification = specification.and(buildSpecification(criteria.getId(), Quote_.id));
}
if (criteria.getSymbol() != null) {
specification = specification.and(buildStringSpecification(criteria.getSymbol(), Quote_.symbol));
}
if (criteria.getPrice() != null) {
specification = specification.and(buildRangeSpecification(criteria.getPrice(), Quote_.price));
}
if (criteria.getLastTrade() != null) {
specification = specification.and(buildRangeSpecification(criteria.getLastTrade(), Quote_.lastTrade));
}
}
return specification;
}
}
|
repos\tutorials-master\jhipster-modules\jhipster-uaa\quotes\src\main\java\com\baeldung\jhipster\quotes\service\QuoteQueryService.java
| 2
|
请完成以下Java代码
|
public void setWebParam6 (String WebParam6)
{
set_Value (COLUMNNAME_WebParam6, WebParam6);
}
/** Get Web Parameter 6.
@return Web Site Parameter 6 (default footer right)
*/
public String getWebParam6 ()
{
return (String)get_Value(COLUMNNAME_WebParam6);
}
/** Set Web Store EMail.
@param WStoreEMail
EMail address used as the sender (From)
*/
public void setWStoreEMail (String WStoreEMail)
{
set_Value (COLUMNNAME_WStoreEMail, WStoreEMail);
}
/** Get Web Store EMail.
@return EMail address used as the sender (From)
*/
public String getWStoreEMail ()
{
return (String)get_Value(COLUMNNAME_WStoreEMail);
}
/** Set Web Store.
@param W_Store_ID
A Web Store of the Client
*/
public void setW_Store_ID (int W_Store_ID)
{
if (W_Store_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_Store_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_Store_ID, Integer.valueOf(W_Store_ID));
}
/** Get Web Store.
|
@return A Web Store of the Client
*/
public int getW_Store_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_Store_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set WebStore User.
@param WStoreUser
User ID of the Web Store EMail address
*/
public void setWStoreUser (String WStoreUser)
{
set_Value (COLUMNNAME_WStoreUser, WStoreUser);
}
/** Get WebStore User.
@return User ID of the Web Store EMail address
*/
public String getWStoreUser ()
{
return (String)get_Value(COLUMNNAME_WStoreUser);
}
/** Set WebStore Password.
@param WStoreUserPW
Password of the Web Store EMail address
*/
public void setWStoreUserPW (String WStoreUserPW)
{
set_Value (COLUMNNAME_WStoreUserPW, WStoreUserPW);
}
/** Get WebStore Password.
@return Password of the Web Store EMail address
*/
public String getWStoreUserPW ()
{
return (String)get_Value(COLUMNNAME_WStoreUserPW);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_Store.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setRepair_Order_ID (final int Repair_Order_ID)
{
if (Repair_Order_ID < 1)
set_Value (COLUMNNAME_Repair_Order_ID, null);
else
set_Value (COLUMNNAME_Repair_Order_ID, Repair_Order_ID);
}
@Override
public int getRepair_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_Repair_Order_ID);
}
@Override
public void setRepairOrderSummary (final @Nullable java.lang.String RepairOrderSummary)
{
set_Value (COLUMNNAME_RepairOrderSummary, RepairOrderSummary);
}
@Override
public java.lang.String getRepairOrderSummary()
{
return get_ValueAsString(COLUMNNAME_RepairOrderSummary);
}
@Override
public void setRepairServicePerformed_Product_ID (final int RepairServicePerformed_Product_ID)
{
if (RepairServicePerformed_Product_ID < 1)
set_Value (COLUMNNAME_RepairServicePerformed_Product_ID, null);
else
set_Value (COLUMNNAME_RepairServicePerformed_Product_ID, RepairServicePerformed_Product_ID);
}
@Override
public int getRepairServicePerformed_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_RepairServicePerformed_Product_ID);
}
@Override
public void setRepair_VHU_ID (final int Repair_VHU_ID)
{
if (Repair_VHU_ID < 1)
set_Value (COLUMNNAME_Repair_VHU_ID, null);
else
set_Value (COLUMNNAME_Repair_VHU_ID, Repair_VHU_ID);
}
@Override
public int getRepair_VHU_ID()
{
return get_ValueAsInt(COLUMNNAME_Repair_VHU_ID);
}
/**
* Status AD_Reference_ID=541245
* Reference name: C_Project_Repair_Task_Status
*/
public static final int STATUS_AD_Reference_ID=541245;
/** Not Started = NS */
|
public static final String STATUS_NotStarted = "NS";
/** In Progress = IP */
public static final String STATUS_InProgress = "IP";
/** Completed = CO */
public static final String STATUS_Completed = "CO";
@Override
public void setStatus (final java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return get_ValueAsString(COLUMNNAME_Status);
}
/**
* Type AD_Reference_ID=541243
* Reference name: C_Project_Repair_Task_Type
*/
public static final int TYPE_AD_Reference_ID=541243;
/** ServiceRepairOrder = W */
public static final String TYPE_ServiceRepairOrder = "W";
/** SpareParts = P */
public static final String TYPE_SpareParts = "P";
@Override
public void setType (final java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java-gen\de\metas\servicerepair\repository\model\X_C_Project_Repair_Task.java
| 2
|
请完成以下Java代码
|
public ListenerFactory getListenerFactory() {
return listenerFactory;
}
public void setListenerFactory(ListenerFactory listenerFactory) {
this.listenerFactory = listenerFactory;
}
public ExpressionManager getExpressionManager() {
return expressionManager;
}
public void setExpressionManager(ExpressionManager expressionManager) {
this.expressionManager = expressionManager;
}
public Map<String, TransitionImpl> getSequenceFlows() {
return sequenceFlows;
}
public ProcessDefinitionEntity getCurrentProcessDefinition() {
return currentProcessDefinition;
}
public void setCurrentProcessDefinition(ProcessDefinitionEntity currentProcessDefinition) {
this.currentProcessDefinition = currentProcessDefinition;
}
public FlowElement getCurrentFlowElement() {
return currentFlowElement;
}
public void setCurrentFlowElement(FlowElement currentFlowElement) {
this.currentFlowElement = currentFlowElement;
}
public ActivityImpl getCurrentActivity() {
return currentActivity;
}
public void setCurrentActivity(ActivityImpl currentActivity) {
this.currentActivity = currentActivity;
}
|
public void setCurrentSubProcess(SubProcess subProcess) {
currentSubprocessStack.push(subProcess);
}
public SubProcess getCurrentSubProcess() {
return currentSubprocessStack.peek();
}
public void removeCurrentSubProcess() {
currentSubprocessStack.pop();
}
public void setCurrentScope(ScopeImpl scope) {
currentScopeStack.push(scope);
}
public ScopeImpl getCurrentScope() {
return currentScopeStack.peek();
}
public void removeCurrentScope() {
currentScopeStack.pop();
}
public BpmnParse setSourceSystemId(String systemId) {
sourceSystemId = systemId;
return this;
}
public String getSourceSystemId() {
return this.sourceSystemId;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\BpmnParse.java
| 1
|
请完成以下Java代码
|
private Object createXMLObject(final String xml)
{
try
{
final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
final Source source = createXMLSourceFromString(xml);
final JAXBElement<?> jaxbElement = (JAXBElement<?>)unmarshaller.unmarshal(source);
final Object xmlRequestObj = jaxbElement.getValue();
return xmlRequestObj;
}
catch (JAXBException e)
{
throw new AdempiereException("Cannot convert string to xml object: " + xml, e);
}
}
private String createStringFromXMLObject(final Object xmlObject)
{
try
{
final JAXBElement<Object> jaxbElement = jaxbObjectFactory.createJAXBElement(xmlObject);
|
final Marshaller marshaller = jaxbContext.createMarshaller();
final StringWriter writer = new StringWriter();
marshaller.marshal(jaxbElement, writer);
final String xmlObjectStr = writer.toString();
return xmlObjectStr;
}
catch (JAXBException e)
{
throw new AdempiereException("Cannot convert xml object to string: " + xmlObject, e);
}
}
private Source createXMLSourceFromString(final String xmlStr)
{
final InputStream inputStream = new ByteArrayInputStream(xmlStr == null ? new byte[0] : xmlStr.getBytes(StandardCharsets.UTF_8));
return new StreamSource(inputStream);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\server\rpl\api\impl\MockedImportHelper.java
| 1
|
请完成以下Java代码
|
public List<Job> findJobsByQueryCriteria(JobQueryImpl jobQuery, Page page) {
final String query = "selectDeadLetterJobByQueryCriteria";
return getDbSqlSession().selectList(query, jobQuery, page);
}
@SuppressWarnings("unchecked")
public List<Job> findDeadLetterJobsByTypeAndProcessDefinitionKeyNoTenantId(String jobHandlerType, String processDefinitionKey) {
Map<String, String> params = new HashMap<>(2);
params.put("handlerType", jobHandlerType);
params.put("processDefinitionKey", processDefinitionKey);
return getDbSqlSession().selectList("selectDeadLetterJobByTypeAndProcessDefinitionKeyNoTenantId", params);
}
@SuppressWarnings("unchecked")
public List<Job> findDeadLetterJobsByTypeAndProcessDefinitionKeyAndTenantId(String jobHandlerType, String processDefinitionKey, String tenantId) {
Map<String, String> params = new HashMap<>(3);
params.put("handlerType", jobHandlerType);
params.put("processDefinitionKey", processDefinitionKey);
params.put("tenantId", tenantId);
return getDbSqlSession().selectList("selectDeadLetterJobByTypeAndProcessDefinitionKeyAndTenantId", params);
}
@SuppressWarnings("unchecked")
public List<Job> findDeadLetterJobsByTypeAndProcessDefinitionId(String jobHandlerType, String processDefinitionId) {
Map<String, String> params = new HashMap<>(2);
params.put("handlerType", jobHandlerType);
|
params.put("processDefinitionId", processDefinitionId);
return getDbSqlSession().selectList("selectDeadLetterJobByTypeAndProcessDefinitionId", params);
}
public long findDeadLetterJobCountByQueryCriteria(JobQueryImpl jobQuery) {
return (Long) getDbSqlSession().selectOne("selectDeadLetterJobCountByQueryCriteria", jobQuery);
}
public void updateDeadLetterJobTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().update("updateDeadLetterJobTenantIdForDeployment", params);
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\DeadLetterJobEntityManager.java
| 1
|
请完成以下Java代码
|
public I_AD_Rule retrieveByValue(final Properties ctx, final String ruleValue)
{
if (ruleValue == null)
{
return null;
}
return s_cacheByValue.getOrLoad(ruleValue, () -> {
final I_AD_Rule rule = retrieveByValue_NoCache(ctx, ruleValue);
if (rule != null)
{
s_cacheById.put(rule.getAD_Rule_ID(), rule);
}
return rule;
});
}
private final I_AD_Rule retrieveByValue_NoCache(final Properties ctx, final String ruleValue)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_AD_Rule.class, ctx, ITrx.TRXNAME_None)
.addEqualsFilter(I_AD_Rule.COLUMNNAME_Value, ruleValue)
|
.addOnlyActiveRecordsFilter()
.create()
.firstOnly(I_AD_Rule.class);
}
@Override
public List<I_AD_Rule> retrieveByEventType(final Properties ctx, final String eventType)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_AD_Rule.class, ctx, ITrx.TRXNAME_None)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_AD_Rule.COLUMNNAME_EventType, eventType)
.create()
.list(I_AD_Rule.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\script\impl\ADRuleDAO.java
| 1
|
请完成以下Java代码
|
protected AbstractResourceDefinitionManager<ProcessDefinitionEntity> getManager() {
return Context.getCommandContext().getProcessDefinitionManager();
}
@Override
protected void checkInvalidDefinitionId(String definitionId) {
ensureNotNull("Invalid process definition id", "processDefinitionId", definitionId);
}
@Override
protected void checkDefinitionFound(String definitionId, ProcessDefinitionEntity definition) {
ensureNotNull(NotFoundException.class, "no deployed process definition found with id '" + definitionId + "'", "processDefinition", definition);
}
@Override
protected void checkInvalidDefinitionByKey(String definitionKey, ProcessDefinitionEntity definition) {
ensureNotNull("no processes deployed with key '" + definitionKey + "'", "processDefinition", definition);
}
@Override
protected void checkInvalidDefinitionByKeyAndTenantId(String definitionKey, String tenantId, ProcessDefinitionEntity definition) {
ensureNotNull("no processes deployed with key '" + definitionKey + "' and tenant-id '" + tenantId + "'", "processDefinition", definition);
}
@Override
protected void checkInvalidDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId, ProcessDefinitionEntity definition) {
|
ensureNotNull("no processes deployed with key = '" + definitionKey + "', version = '" + definitionVersion
+ "' and tenant-id = '" + tenantId + "'", "processDefinition", definition);
}
@Override
protected void checkInvalidDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId,
ProcessDefinitionEntity definition) {
ensureNotNull("no processes deployed with key = '" + definitionKey + "', versionTag = '" + definitionVersionTag
+ "' and tenant-id = '" + tenantId + "'", "processDefinition", definition);
}
@Override
protected void checkInvalidDefinitionByDeploymentAndKey(String deploymentId, String definitionKey, ProcessDefinitionEntity definition) {
ensureNotNull("no processes deployed with key = '" + definitionKey + "' in deployment = '" + deploymentId + "'", "processDefinition", definition);
}
@Override
protected void checkInvalidDefinitionWasCached(String deploymentId, String definitionId, ProcessDefinitionEntity definition) {
ensureNotNull("deployment '" + deploymentId + "' didn't put process definition '" + definitionId + "' in the cache", "cachedProcessDefinition", definition);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\deploy\cache\ProcessDefinitionCache.java
| 1
|
请完成以下Java代码
|
public static User updateUser(final DataFetchingEnvironment env, @NotNull @GraphQLName(SchemaUtils.ID) final String id, @NotNull @GraphQLName(SchemaUtils.NAME) final String name, @NotNull @GraphQLName(SchemaUtils.EMAIL) final String email,
@NotNull @GraphQLName(SchemaUtils.AGE) final String age) {
final Optional<User> user = getUsers(env).stream()
.filter(c -> c.getId() == Long.parseLong(id))
.findFirst();
if (!user.isPresent()) {
return null;
}
user.get()
.setName(name);
user.get()
.setEmail(email);
user.get()
.setAge(Integer.valueOf(age));
return user.get();
|
}
@GraphQLField
public static User deleteUser(final DataFetchingEnvironment env, @NotNull @GraphQLName(SchemaUtils.ID) final String id) {
final List<User> users = getUsers(env);
final Optional<User> user = users.stream()
.filter(c -> c.getId() == Long.parseLong(id))
.findFirst();
if (!user.isPresent()) {
return null;
}
users.removeIf(c -> c.getId() == Long.parseLong(id));
return user.get();
}
}
|
repos\tutorials-master\graphql-modules\graphql-java\src\main\java\com\baeldung\graphql\mutation\UserMutation.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class HuPackingInstructionsAttributeId implements RepoIdAware
{
@JsonCreator
public static HuPackingInstructionsAttributeId ofRepoId(final int repoId)
{
return new HuPackingInstructionsAttributeId(repoId);
}
@Nullable
public static HuPackingInstructionsAttributeId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
int repoId;
private HuPackingInstructionsAttributeId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "M_HU_PI_Attribute_ID");
}
|
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static int toRepoId(final HuPackingInstructionsAttributeId id)
{
return id != null ? id.getRepoId() : -1;
}
public static boolean equals(final HuPackingInstructionsAttributeId o1, final HuPackingInstructionsAttributeId o2)
{
return Objects.equals(o1, o2);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\HuPackingInstructionsAttributeId.java
| 2
|
请完成以下Java代码
|
protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if(!isHUEditorView())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("not the HU view");
}
if (!streamSelectedHUIds(Select.ONLY_TOPLEVEL).findAny().isPresent())
{
return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(WEBUI_HU_Constants.MSG_WEBUI_ONLY_TOP_LEVEL_HU));
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
Check.assume(warehouse.isQualityReturnWarehouse(), "not a quality returns warehouse");
final List<I_M_HU> selectedTopLevelHUs = streamSelectedHUs(Select.ONLY_TOPLEVEL).collect(ImmutableList.toImmutableList());
|
if (selectedTopLevelHUs.isEmpty())
{
throw new AdempiereException("@NoSelection@");
}
movementResult = huMovementBL.moveHUsToWarehouse(selectedTopLevelHUs, WarehouseId.ofRepoId(warehouse.getM_Warehouse_ID()));
return MSG_OK;
}
@Override
protected void postProcess(final boolean success)
{
if (movementResult != null)
{
getView().invalidateAll();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_MoveToQualityWarehouse.java
| 1
|
请完成以下Java代码
|
public final class PurchaseCandidateAggregator extends MapReduceAggregator<PurchaseCandidateAggregate, PurchaseCandidate>
{
public static List<PurchaseCandidateAggregate> aggregate(@NonNull final Collection<PurchaseCandidate> candidates)
{
final PurchaseCandidateAggregator aggregator = new PurchaseCandidateAggregator();
aggregator.collectClosedGroups();
aggregator.addAll(candidates.iterator());
aggregator.closeAllGroups();
return aggregator.getClosedGroups();
}
private PurchaseCandidateAggregator()
{
setItemAggregationKeyBuilder(PurchaseCandidateAggregateKey::fromPurchaseCandidate);
collectClosedGroups();
}
|
@Override
protected PurchaseCandidateAggregate createGroup(final Object itemHashKey, final PurchaseCandidate item)
{
return PurchaseCandidateAggregate.of(PurchaseCandidateAggregateKey.cast(itemHashKey));
}
@Override
protected void closeGroup(@NonNull final PurchaseCandidateAggregate group)
{
group.calculateAndSetQtyToDeliver();
}
@Override
protected void addItemToGroup(final PurchaseCandidateAggregate group, final PurchaseCandidate item)
{
group.add(item);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\localorder\PurchaseCandidateAggregator.java
| 1
|
请完成以下Java代码
|
class DocumentAcctLogsQuerySupplier implements RelatedDocumentsQuerySupplier, RelatedDocumentsCountSupplier
{
@NonNull private final IQueryBL queryBL;
private final int adTableId;
private final int recordId;
@Builder
private DocumentAcctLogsQuerySupplier(
@NonNull final IQueryBL queryBL,
final int adTableId,
final int recordId)
{
this.queryBL = queryBL;
this.adTableId = adTableId;
this.recordId = recordId;
}
@Override
public MQuery getQuery()
|
{
final MQuery query = new MQuery(I_Document_Acct_Log.Table_Name);
query.addRestriction(I_Document_Acct_Log.COLUMNNAME_AD_Table_ID, MQuery.Operator.EQUAL, adTableId);
query.addRestriction(I_Document_Acct_Log.COLUMNNAME_Record_ID, MQuery.Operator.EQUAL, recordId);
return query;
}
@Override
public int getRecordsCount(final RelatedDocumentsPermissions permissions)
{
return queryBL.createQueryBuilder(I_Document_Acct_Log.class)
.addEqualsFilter(I_Document_Acct_Log.COLUMNNAME_AD_Table_ID, adTableId)
.addEqualsFilter(I_Document_Acct_Log.COLUMNNAME_Record_ID, recordId)
.create()
.count();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.webui\src\main\java\de\metas\acct\related_documents\DocumentAcctLogsQuerySupplier.java
| 1
|
请完成以下Java代码
|
public boolean isNamePrinted()
{
return get_ValueAsBoolean(COLUMNNAME_IsNamePrinted);
}
@Override
public void setM_Product_Category_ID (final int M_Product_Category_ID)
{
if (M_Product_Category_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_ID, null);
else
set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID);
}
@Override
public int getM_Product_Category_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
|
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public org.eevolution.model.I_PP_Product_BOM getPP_Product_BOM()
{
return get_ValueAsPO(COLUMNNAME_PP_Product_BOM_ID, org.eevolution.model.I_PP_Product_BOM.class);
}
@Override
public void setPP_Product_BOM(final org.eevolution.model.I_PP_Product_BOM PP_Product_BOM)
{
set_ValueFromPO(COLUMNNAME_PP_Product_BOM_ID, org.eevolution.model.I_PP_Product_BOM.class, PP_Product_BOM);
}
@Override
public void setPP_Product_BOM_ID (final int PP_Product_BOM_ID)
{
if (PP_Product_BOM_ID < 1)
set_Value (COLUMNNAME_PP_Product_BOM_ID, null);
else
set_Value (COLUMNNAME_PP_Product_BOM_ID, PP_Product_BOM_ID);
}
@Override
public int getPP_Product_BOM_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Product_BOM_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Order_CompensationGroup.java
| 1
|
请完成以下Java代码
|
public class ChannelDecisionManagerImpl implements ChannelDecisionManager, InitializingBean {
public static final String ANY_CHANNEL = "ANY_CHANNEL";
private List<ChannelProcessor> channelProcessors;
@Override
public void afterPropertiesSet() {
Assert.notEmpty(this.channelProcessors, "A list of ChannelProcessors is required");
}
@Override
public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config)
throws IOException, ServletException {
for (ConfigAttribute attribute : config) {
if (ANY_CHANNEL.equals(attribute.getAttribute())) {
return;
}
}
for (ChannelProcessor processor : this.channelProcessors) {
processor.decide(invocation, config);
if (invocation.getResponse().isCommitted()) {
break;
}
}
}
protected @Nullable List<ChannelProcessor> getChannelProcessors() {
return this.channelProcessors;
}
@SuppressWarnings("cast")
public void setChannelProcessors(List<?> channelProcessors) {
|
Assert.notEmpty(channelProcessors, "A list of ChannelProcessors is required");
this.channelProcessors = new ArrayList<>(channelProcessors.size());
for (Object currentObject : channelProcessors) {
Assert.isInstanceOf(ChannelProcessor.class, currentObject, () -> "ChannelProcessor "
+ currentObject.getClass().getName() + " must implement ChannelProcessor");
this.channelProcessors.add((ChannelProcessor) currentObject);
}
}
@Override
public boolean supports(ConfigAttribute attribute) {
if (ANY_CHANNEL.equals(attribute.getAttribute())) {
return true;
}
for (ChannelProcessor processor : this.channelProcessors) {
if (processor.supports(attribute)) {
return true;
}
}
return false;
}
}
|
repos\spring-security-main\access\src\main\java\org\springframework\security\web\access\channel\ChannelDecisionManagerImpl.java
| 1
|
请完成以下Java代码
|
public void setReferenceNo (final @Nullable java.lang.String ReferenceNo)
{
set_Value (COLUMNNAME_ReferenceNo, ReferenceNo);
}
@Override
public java.lang.String getReferenceNo()
{
return get_ValueAsString(COLUMNNAME_ReferenceNo);
}
@Override
public void setRoutingNo (final @Nullable java.lang.String RoutingNo)
{
set_Value (COLUMNNAME_RoutingNo, RoutingNo);
}
@Override
public java.lang.String getRoutingNo()
{
return get_ValueAsString(COLUMNNAME_RoutingNo);
}
@Override
public void setStatementDate (final @Nullable java.sql.Timestamp StatementDate)
{
set_Value (COLUMNNAME_StatementDate, StatementDate);
}
@Override
public java.sql.Timestamp getStatementDate()
{
return get_ValueAsTimestamp(COLUMNNAME_StatementDate);
}
@Override
public void setStatementLineDate (final @Nullable java.sql.Timestamp StatementLineDate)
{
set_Value (COLUMNNAME_StatementLineDate, StatementLineDate);
}
@Override
public java.sql.Timestamp getStatementLineDate()
{
return get_ValueAsTimestamp(COLUMNNAME_StatementLineDate);
}
@Override
public void setStmtAmt (final @Nullable BigDecimal StmtAmt)
{
set_Value (COLUMNNAME_StmtAmt, StmtAmt);
}
@Override
public BigDecimal getStmtAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_StmtAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
|
@Override
public void setTrxAmt (final @Nullable BigDecimal TrxAmt)
{
set_Value (COLUMNNAME_TrxAmt, TrxAmt);
}
@Override
public BigDecimal getTrxAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TrxAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* TrxType AD_Reference_ID=215
* Reference name: C_Payment Trx Type
*/
public static final int TRXTYPE_AD_Reference_ID=215;
/** Sales = S */
public static final String TRXTYPE_Sales = "S";
/** DelayedCapture = D */
public static final String TRXTYPE_DelayedCapture = "D";
/** CreditPayment = C */
public static final String TRXTYPE_CreditPayment = "C";
/** VoiceAuthorization = F */
public static final String TRXTYPE_VoiceAuthorization = "F";
/** Authorization = A */
public static final String TRXTYPE_Authorization = "A";
/** Void = V */
public static final String TRXTYPE_Void = "V";
/** Rückzahlung = R */
public static final String TRXTYPE_Rueckzahlung = "R";
@Override
public void setTrxType (final @Nullable java.lang.String TrxType)
{
set_Value (COLUMNNAME_TrxType, TrxType);
}
@Override
public java.lang.String getTrxType()
{
return get_ValueAsString(COLUMNNAME_TrxType);
}
@Override
public void setValutaDate (final @Nullable java.sql.Timestamp ValutaDate)
{
set_Value (COLUMNNAME_ValutaDate, ValutaDate);
}
@Override
public java.sql.Timestamp getValutaDate()
{
return get_ValueAsTimestamp(COLUMNNAME_ValutaDate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_I_BankStatement.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.