instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public void setProcessed (boolean Processed)
{
set_ValueNoCheck (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Quantity.
@param QtyEntered
The Quantity Entered is based on the selected UoM
*/
public void setQtyEntered (BigDecimal QtyEntered)
{
set_Value (COLUMNNAME_QtyEntered, QtyEntered);
}
/** Get Quantity.
@return The Quantity Entered is based on the selected UoM
*/
public BigDecimal getQtyEntered ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyEntered);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Tax Amount.
@param TaxAmt
Tax Amount for a document
*/
public void setTaxAmt (BigDecimal TaxAmt)
{
set_Value (COLUMNNAME_TaxAmt, TaxAmt);
}
/** Get Tax Amount.
@return Tax Amount for a document
*/
public BigDecimal getTaxAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TaxAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
public I_C_ElementValue getUser1() throws RuntimeException
{
return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name)
.getPO(getUser1_ID(), get_TrxName()); }
/** Set User List 1.
@param User1_ID
User defined list element #1
*/
public void setUser1_ID (int User1_ID)
{
if (User1_ID < 1)
set_Value (COLUMNNAME_User1_ID, null);
else
set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID));
}
/** Get User List 1.
@return User defined list element #1
|
*/
public int getUser1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ElementValue getUser2() throws RuntimeException
{
return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name)
.getPO(getUser2_ID(), get_TrxName()); }
/** Set User List 2.
@param User2_ID
User defined list element #2
*/
public void setUser2_ID (int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID));
}
/** Get User List 2.
@return User defined list element #2
*/
public int getUser2_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User2_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_InvoiceBatchLine.java
| 1
|
请完成以下Java代码
|
public class Task {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Async("taskExecutor")
public void doTaskOne() throws Exception {
log.info("开始做任务一");
long start = System.currentTimeMillis();
log.info(stringRedisTemplate.randomKey());
long end = System.currentTimeMillis();
log.info("完成任务一,耗时:" + (end - start) + "毫秒");
}
@Async("taskExecutor")
public void doTaskTwo() throws Exception {
log.info("开始做任务二");
long start = System.currentTimeMillis();
|
log.info(stringRedisTemplate.randomKey());
long end = System.currentTimeMillis();
log.info("完成任务二,耗时:" + (end - start) + "毫秒");
}
@Async("taskExecutor")
public void doTaskThree() throws Exception {
log.info("开始做任务三");
long start = System.currentTimeMillis();
log.info(stringRedisTemplate.randomKey());
long end = System.currentTimeMillis();
log.info("完成任务三,耗时:" + (end - start) + "毫秒");
}
}
|
repos\SpringBoot-Learning-master\1.x\Chapter4-1-4\src\main\java\com\didispace\async\Task.java
| 1
|
请完成以下Java代码
|
protected final BigDecimal convertToStorageUOM(final BigDecimal qty, final I_C_UOM uom)
{
Check.assumeNotNull(qty, "qty not null");
Check.assumeNotNull(uom, "uom not null");
final ProductId productId = getProductId();
final I_C_UOM storageUOM = getC_UOM();
final BigDecimal qtyConverted = Services.get(IUOMConversionBL.class)
.convertQty(productId, qty, uom, storageUOM);
Check.assumeNotNull(qtyConverted,
"qtyConverted not null (Qty={}, FromUOM={}, ToUOM={}, Product={}",
qty, uom, storageUOM);
return qtyConverted;
}
@Override
public boolean isEmpty()
{
return getQty().isZero();
}
public boolean isFull()
{
final BigDecimal qtyFree = getQtyFree();
return qtyFree.signum() == 0;
}
|
@Override
public final void markStaled()
{
beforeMarkingStalled();
_capacity = null;
}
/**
* This method is called when {@link #markStaled()} is executed, right before resetting the status.
*
* NOTE: To be implemented by extending classes.
*/
protected void beforeMarkingStalled()
{
// nothing
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\AbstractProductStorage.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void handlePutConfirmationToProcurementWebRequest(final PutConfirmationToProcurementWebRequest request)
{
logger.debug("Importing: {}", request);
for (final SyncConfirmation syncConfirmation : request.getSyncConfirmations())
{
try
{
confirmationsImportService.importConfirmation(syncConfirmation);
}
catch (final Exception e)
{
logger.error("Failed importing confirmation: {}", syncConfirmation, e);
}
}
}
public void handlePutRfQsRequest(@NonNull final PutRfQsRequest request)
{
logger.debug("Importing: {}", request);
if (request.isEmpty())
{
return;
}
for (final SyncRfQ syncRfq : request.getSyncRfqs())
{
try
{
rfqImportService.importRfQ(syncRfq);
}
catch (final Exception e)
{
logger.error("Failed importing RfQ: {}", syncRfq, e);
}
}
}
public void handlePutRfQCloseEventsRequest(final PutRfQCloseEventsRequest request)
|
{
logger.debug("Importing: {}", request);
if (request.isEmpty())
{
return;
}
for (final SyncRfQCloseEvent syncRfQCloseEvent : request.getSyncRfQCloseEvents())
{
try
{
rfqImportService.importRfQCloseEvent(syncRfQCloseEvent);
}
catch (final Exception e)
{
logger.error("Failed importing: {}", syncRfQCloseEvent, e);
}
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\sync\ReceiverFromMetasfreshHandler.java
| 2
|
请完成以下Java代码
|
public @Nullable Origin getOrigin() {
return this.origin;
}
@Override
public @Nullable Origin getParent() {
return (this.origin != null) ? this.origin.getParent() : null;
}
@Override
public String toString() {
return (this.origin != null) ? this.origin.toString()
: "\"" + this.propertyName + "\" from property source \"" + this.propertySource.getName() + "\"";
}
|
/**
* Get an {@link Origin} for the given {@link PropertySource} and
* {@code propertyName}. Will either return an {@link OriginLookup} result or a
* {@link PropertySourceOrigin}.
* @param propertySource the origin property source
* @param name the property name
* @return the property origin
*/
public static Origin get(PropertySource<?> propertySource, String name) {
Origin origin = OriginLookup.getOrigin(propertySource, name);
return (origin instanceof PropertySourceOrigin) ? origin
: new PropertySourceOrigin(propertySource, name, origin);
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\origin\PropertySourceOrigin.java
| 1
|
请完成以下Java代码
|
public class ShellPrompts {
private static final String DEFAULT_PROMPT = "$ ";
private final Deque<String> prompts = new ArrayDeque<>();
/**
* Push a new prompt to be used by the shell.
* @param prompt the prompt
* @see #popPrompt()
*/
public void pushPrompt(String prompt) {
this.prompts.push(prompt);
}
/**
* Pop a previously pushed prompt, returning to the previous value.
|
* @see #pushPrompt(String)
*/
public void popPrompt() {
if (!this.prompts.isEmpty()) {
this.prompts.pop();
}
}
/**
* Returns the current prompt.
* @return the current prompt
*/
public String getPrompt() {
return this.prompts.isEmpty() ? DEFAULT_PROMPT : this.prompts.peek();
}
}
|
repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\shell\ShellPrompts.java
| 1
|
请完成以下Java代码
|
private static I_SAP_GLJournal extractRecord(final DocumentTableFields docFields)
{
return InterfaceWrapperHelper.create(docFields, I_SAP_GLJournal.class);
}
@Override
public String getSummary(final DocumentTableFields docFields)
{
return extractRecord(docFields).getDocumentNo();
}
@Override
public String getDocumentInfo(final DocumentTableFields docFields)
{
return extractRecord(docFields).getDocumentNo();
}
@Override
public int getDoc_User_ID(final DocumentTableFields docFields)
{
return extractRecord(docFields).getCreatedBy();
}
@Override
public LocalDate getDocumentDate(final DocumentTableFields docFields)
{
final I_SAP_GLJournal record = extractRecord(docFields);
return TimeUtil.asLocalDate(record.getDateDoc());
}
@Override
public int getC_Currency_ID(final DocumentTableFields docFields)
{
return extractRecord(docFields).getC_Currency_ID();
}
@Override
public BigDecimal getApprovalAmt(final DocumentTableFields docFields)
{
// copy-paste from MJournal.getApprovalAmt()
return extractRecord(docFields).getTotalDr();
}
@Override
public void approveIt(final DocumentTableFields docFields)
{
approveIt(extractRecord(docFields));
}
private void approveIt(final I_SAP_GLJournal glJournal)
{
glJournal.setIsApproved(true);
}
@Override
public String completeIt(final DocumentTableFields docFields)
{
final I_SAP_GLJournal glJournalRecord = extractRecord(docFields);
|
assertPeriodOpen(glJournalRecord);
glJournalService.updateWhileSaving(
glJournalRecord,
glJournal -> {
glJournal.assertHasLines();
glJournal.updateLineAcctAmounts(glJournalService.getCurrencyConverter());
glJournal.assertTotalsBalanced();
glJournal.setProcessed(true);
}
);
glJournalRecord.setDocAction(IDocument.ACTION_None);
return IDocument.STATUS_Completed;
}
private static void assertPeriodOpen(final I_SAP_GLJournal glJournalRecord)
{
MPeriod.testPeriodOpen(Env.getCtx(), glJournalRecord.getDateAcct(), glJournalRecord.getC_DocType_ID(), glJournalRecord.getAD_Org_ID());
}
@Override
public void reactivateIt(final DocumentTableFields docFields)
{
final I_SAP_GLJournal glJournalRecord = extractRecord(docFields);
assertPeriodOpen(glJournalRecord);
glJournalService.updateWhileSaving(
glJournalRecord,
glJournal -> glJournal.setProcessed(false)
);
factAcctDAO.deleteForDocumentModel(glJournalRecord);
glJournalRecord.setPosted(false);
glJournalRecord.setProcessed(false);
glJournalRecord.setDocAction(X_GL_Journal.DOCACTION_Complete);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\document\SAPGLJournalDocumentHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Integer execute01Async() {
return this.execute01();
}
@Async
public Integer execute02Async() {
return this.execute02();
}
@Async
public Future<Integer> execute01AsyncWithFuture() {
return AsyncResult.forValue(this.execute01());
}
@Async
public Future<Integer> execute02AsyncWithFuture() {
return AsyncResult.forValue(this.execute02());
}
@Async
public ListenableFuture<Integer> execute01AsyncWithListenableFuture() {
try {
return AsyncResult.forValue(this.execute02());
} catch (Throwable ex) {
return AsyncResult.forExecutionException(ex);
}
}
public Integer execute01() {
|
logger.info("[execute01]");
sleep(10);
return 1;
}
public Integer execute02() {
logger.info("[execute02]");
sleep(5);
return 2;
}
private static void sleep(int seconds) {
try {
Thread.sleep(seconds * 1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@Async
public Integer zhaoDaoNvPengYou(Integer a, Integer b) {
throw new RuntimeException("程序员不需要女朋友");
}
}
|
repos\SpringBoot-Labs-master\lab-29\lab-29-async-demo\src\main\java\cn\iocoder\springboot\lab29\asynctask\service\DemoService.java
| 2
|
请完成以下Java代码
|
default void run(@NonNull final Consumer<IHUContext> processor)
{
run((IHUContextProcessor)huContext -> {
processor.accept(huContext);
return IHUContextProcessor.NULL_RESULT;
});
}
default <T> T call(@NonNull final Function<IHUContext, T> callable)
{
final Mutable<T> resultHolder = new Mutable<>();
run(huContext -> {
T result = callable.apply(huContext);
resultHolder.setValue(result);
});
|
return resultHolder.getValue();
}
/**
* Gets current {@link IHUTransactionAttributeBuilder}.
*
* NOTE: the {@link IHUTransactionAttributeBuilder} is available only while {@link #run(IHUContextProcessor)} is running.
* Not before and not after that.
* It shall be accessed only from {@link IHUContextProcessor#process(IHUContext)}.
* If you are accessing it outside of that scope, an exception will be thrown.
*
* @return current {@link IHUTransactionAttributeBuilder}; never return null.
*/
IHUTransactionAttributeBuilder getTrxAttributesBuilder();
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\IHUContextProcessorExecutor.java
| 1
|
请完成以下Java代码
|
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);
}
public I_GL_Fund getGL_Fund() throws RuntimeException
{
return (I_GL_Fund)MTable.get(getCtx(), I_GL_Fund.Table_Name)
.getPO(getGL_Fund_ID(), get_TrxName()); }
/** Set GL Fund.
@param GL_Fund_ID
General Ledger Funds Control
*/
public void setGL_Fund_ID (int GL_Fund_ID)
{
if (GL_Fund_ID < 1)
set_ValueNoCheck (COLUMNNAME_GL_Fund_ID, null);
else
set_ValueNoCheck (COLUMNNAME_GL_Fund_ID, Integer.valueOf(GL_Fund_ID));
}
/** Get GL Fund.
@return General Ledger Funds Control
*/
public int getGL_Fund_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GL_Fund_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Fund Restriction.
@param GL_FundRestriction_ID
Restriction of Funds
*/
public void setGL_FundRestriction_ID (int GL_FundRestriction_ID)
{
if (GL_FundRestriction_ID < 1)
set_ValueNoCheck (COLUMNNAME_GL_FundRestriction_ID, null);
else
set_ValueNoCheck (COLUMNNAME_GL_FundRestriction_ID, Integer.valueOf(GL_FundRestriction_ID));
}
/** Get Fund Restriction.
@return Restriction of Funds
*/
|
public int getGL_FundRestriction_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GL_FundRestriction_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_FundRestriction.java
| 1
|
请完成以下Java代码
|
public class RootUriTemplateHandler implements UriTemplateHandler {
private final @Nullable String rootUri;
private final UriTemplateHandler handler;
protected RootUriTemplateHandler(UriTemplateHandler handler) {
Assert.notNull(handler, "'handler' must not be null");
this.rootUri = null;
this.handler = handler;
}
RootUriTemplateHandler(String rootUri, UriTemplateHandler handler) {
Assert.notNull(rootUri, "'rootUri' must not be null");
Assert.notNull(handler, "'handler' must not be null");
this.rootUri = rootUri;
this.handler = handler;
}
@Override
public URI expand(String uriTemplate, Map<String, ?> uriVariables) {
return this.handler.expand(apply(uriTemplate), uriVariables);
}
@Override
public URI expand(String uriTemplate, @Nullable Object... uriVariables) {
return this.handler.expand(apply(uriTemplate), uriVariables);
|
}
String apply(String uriTemplate) {
String rootUri = getRootUri();
if (rootUri != null && StringUtils.startsWithIgnoreCase(uriTemplate, "/")) {
return getRootUri() + uriTemplate;
}
return uriTemplate;
}
public @Nullable String getRootUri() {
return this.rootUri;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-restclient\src\main\java\org\springframework\boot\restclient\RootUriTemplateHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isWithException() {
return withException;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getId() {
return id;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getCategory() {
return category;
}
public String getCategoryLike() {
return categoryLike;
}
public String getElementId() {
return elementId;
}
public String getElementName() {
return elementName;
}
public String getScopeId() {
return scopeId;
}
public boolean isWithoutScopeId() {
return withoutScopeId;
}
public String getSubScopeId() {
return subScopeId;
}
public String getScopeType() {
return scopeType;
}
public boolean isWithoutScopeType() {
return withoutScopeType;
}
|
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public String getCaseDefinitionKey() {
return caseDefinitionKey;
}
public String getCorrelationId() {
return correlationId;
}
public boolean isOnlyTimers() {
return onlyTimers;
}
public boolean isOnlyMessages() {
return onlyMessages;
}
public boolean isExecutable() {
return executable;
}
public boolean isOnlyExternalWorkers() {
return onlyExternalWorkers;
}
public Date getDuedateHigherThan() {
return duedateHigherThan;
}
public Date getDuedateLowerThan() {
return duedateLowerThan;
}
public Date getDuedateHigherThanOrEqual() {
return duedateHigherThanOrEqual;
}
public Date getDuedateLowerThanOrEqual() {
return duedateLowerThanOrEqual;
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\DeadLetterJobQueryImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private static DistributionDetail updateDistributionDetail(
@NonNull final DistributionDetail.DistributionDetailBuilder builder,
@NonNull final AbstractDDOrderCandidateEvent event,
@NonNull final CandidateType candidateType)
{
return builder
.ddOrderRef(DDOrderRef.ofNullableDDOrderCandidateId(event.getExistingDDOrderCandidateId()))
.distributionNetworkAndLineId(event.getDistributionNetworkAndLineId())
.qty(event.getQty())
.plantId(extractPlantId(event, candidateType))
.productPlanningId(event.getProductPlanningId())
.shipperId(event.getShipperId())
.forwardPPOrderRef(event.getForwardPPOrderRef())
.build();
}
private void handleMainDataUpdates(@NonNull final DDOrderCandidateCreatedEvent event)
{
|
if (event.isSimulated())
{
}
// final OrgId orgId = event.getEventDescriptor().getOrgId();
// final ZoneId timeZone = orgDAO.getTimeZone(orgId);
//
// final DDOrderMainDataHandler mainDataUpdater = DDOrderMainDataHandler.builder()
// .ddOrderDetailRequestHandler(ddOrderDetailRequestHandler)
// .mainDataRequestHandler(mainDataRequestHandler)
// .abstractDDOrderEvent(event)
// .ddOrderLine(ddOrderLine)
// .orgZone(timeZone)
// .build();
//
// mainDataUpdater.handleUpdate();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\ddordercandidate\DDOrderCandidateAdvisedOrCreatedHandler.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private int insertInto(String collection, List<Document> mongoDocs) {
try {
Collection<Document> inserts = mongo.insert(mongoDocs, collection);
return inserts.size();
} catch (DataIntegrityViolationException e) {
log.error("importing docs", e);
if (e.getCause() instanceof MongoBulkWriteException) {
return ((MongoBulkWriteException) e.getCause()).getWriteResult()
.getInsertedCount();
}
return 0;
}
}
private List<Document> generateMongoDocs(List<String> lines) {
return generateMongoDocs(lines, null);
}
private <T> List<Document> generateMongoDocs(List<String> lines, Class<T> type) {
ObjectMapper mapper = new ObjectMapper();
|
List<Document> docs = new ArrayList<>();
for (String json : lines) {
try {
if (type != null) {
T v = mapper.readValue(json, type);
json = mapper.writeValueAsString(v);
}
docs.add(Document.parse(json));
} catch (Throwable e) {
log.error("parsing: " + json, e);
}
}
return docs;
}
}
|
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-2\src\main\java\com\baeldung\boot\json\convertfile\service\ImportJsonService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Employee createEmployee(@RequestBody Employee employee){
return employeeRepository.save(employee);
}
// get employee by id rest api
@GetMapping("/employees/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable Long id){
Employee employee = employeeRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(" Employee not exist id: " + id));
return ResponseEntity.ok(employee);
}
//update employee rest api
@PutMapping("/employees/{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable Long id, @RequestBody Employee employeeDetails){
Employee employee1 = employeeRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(" Employee not exist with id: " + id));
employee1.setFirstName(employeeDetails.getFirstName());
employee1.setLastName(employeeDetails.getLastName());
employee1.setEmailId(employeeDetails.getEmailId());
Employee updateEmployee = employeeRepository.save(employee1);
return ResponseEntity.ok(updateEmployee);
|
}
// delete employee rest api
@DeleteMapping("/employees/{id}")
public ResponseEntity<Map<String, Boolean>> deleteEmployee(@PathVariable Long id) {
Employee employee = employeeRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Employee not exist with id: "+ id));
employeeRepository.delete(employee);
Map<String, Boolean> response = new HashMap<>();
response.put("delete", Boolean.TRUE);
return ResponseEntity.ok(response);
}
}
|
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-1.SpringBoot-React-CRUD\fullstack\backend\src\main\java\com\urunov\controller\EmployeeController.java
| 2
|
请完成以下Java代码
|
public class C_Flatrate_Term_ChangePriceQty extends JavaProcess implements IProcessPrecondition
{
@Param(parameterName = I_C_Flatrate_Term.COLUMNNAME_PriceActual, mandatory = false)
private BigDecimal priceActual;
@Param(parameterName = I_C_Flatrate_Term.COLUMNNAME_PlannedQtyPerUnit, mandatory = false)
private BigDecimal plannedQtyPerUnit;
final private ContractChangePriceQtyService contractsRepository = SpringContextHolder.instance.getBean(ContractChangePriceQtyService.class);
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
if (context.isMoreThanOneSelected())
{
|
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
if(ProcessUtil.isFlatFeeContract(context))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Not supported for FlatFee contracts");
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
final I_C_Flatrate_Term contract = getRecord(I_C_Flatrate_Term.class);
contractsRepository.changePriceIfNeeded(contract, priceActual);
contractsRepository.changeQtyIfNeeded(contract, plannedQtyPerUnit);
return "@Success@";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\process\C_Flatrate_Term_ChangePriceQty.java
| 1
|
请完成以下Java代码
|
private final class EditingCommand
{
private boolean doSelectItem = false;
private E itemToSelect = null;
private boolean doSetText = false;
private String textToSet = null;
private boolean doHighlightText = false;
private int highlightTextStartPosition = 0;
public void setItemToSelect(final E itemToSelect)
{
this.itemToSelect = itemToSelect;
this.doSelectItem = true;
}
public boolean isDoSelectItem()
{
return doSelectItem;
}
public E getItemToSelect()
{
return itemToSelect;
}
public void setTextToSet(String textToSet)
{
this.textToSet = textToSet;
this.doSetText = true;
}
public boolean isDoSetText()
{
return doSetText;
|
}
public String getTextToSet()
{
return textToSet;
}
public void setHighlightTextStartPosition(int highlightTextStartPosition)
{
this.highlightTextStartPosition = highlightTextStartPosition;
this.doHighlightText = true;
}
public boolean isDoHighlightText()
{
return doHighlightText;
}
public int getHighlightTextStartPosition()
{
return highlightTextStartPosition;
}
};
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\ComboBoxAutoCompletion.java
| 1
|
请完成以下Java代码
|
public class ImageCrawler extends WebCrawler {
private final static Pattern EXCLUSIONS = Pattern.compile(".*(\\.(css|js|xml|gif|png|mp3|mp4|zip|gz|pdf))$");
private static final Pattern IMG_PATTERNS = Pattern.compile(".*(\\.(jpg|jpeg))$");
private File saveDir;
public ImageCrawler(File saveDir) {
this.saveDir = saveDir;
}
@Override
public boolean shouldVisit(Page referringPage, WebURL url) {
String urlString = url.getURL().toLowerCase();
if (EXCLUSIONS.matcher(urlString).matches()) {
return false;
}
if (IMG_PATTERNS.matcher(urlString).matches()
|| urlString.startsWith("https://www.baeldung.com/")) {
return true;
}
|
return false;
}
@Override
public void visit(Page page) {
String url = page.getWebURL().getURL();
if (IMG_PATTERNS.matcher(url).matches()
&& page.getParseData() instanceof BinaryParseData) {
String extension = url.substring(url.lastIndexOf("."));
int contentLength = page.getContentData().length;
System.out.printf("Extension is '%s' with content length %d %n", extension, contentLength);
}
}
}
|
repos\tutorials-master\libraries-4\src\main\java\com\baeldung\crawler4j\ImageCrawler.java
| 1
|
请完成以下Java代码
|
public void setDefaultAccessDeniedHandler(ServerAccessDeniedHandler accessDeniedHandler) {
Assert.notNull(accessDeniedHandler, "accessDeniedHandler cannot be null");
this.defaultHandler = accessDeniedHandler;
}
private Mono<Boolean> isMatch(ServerWebExchange exchange, DelegateEntry entry) {
ServerWebExchangeMatcher matcher = entry.getMatcher();
return matcher.matches(exchange).map(ServerWebExchangeMatcher.MatchResult::isMatch);
}
public static class DelegateEntry {
private final ServerWebExchangeMatcher matcher;
private final ServerAccessDeniedHandler accessDeniedHandler;
|
public DelegateEntry(ServerWebExchangeMatcher matcher, ServerAccessDeniedHandler accessDeniedHandler) {
this.matcher = matcher;
this.accessDeniedHandler = accessDeniedHandler;
}
public ServerWebExchangeMatcher getMatcher() {
return this.matcher;
}
public ServerAccessDeniedHandler getAccessDeniedHandler() {
return this.accessDeniedHandler;
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\authorization\ServerWebExchangeDelegatingServerAccessDeniedHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class GreetingServiceImpl implements GreetingService {
private final PersistentEntityRegistry persistentEntityRegistry;
private final WeatherService weatherService;
@Inject
public GreetingServiceImpl(PersistentEntityRegistry persistentEntityRegistry, WeatherService weatherService) {
this.persistentEntityRegistry = persistentEntityRegistry;
this.weatherService = weatherService;
persistentEntityRegistry.register(GreetingEntity.class);
}
@Override
public ServiceCall<NotUsed, String> handleGreetFrom(String user) {
return request -> {
// Look up the hello world entity for the given ID.
|
PersistentEntityRef<GreetingCommand> ref = persistentEntityRegistry.refFor(GreetingEntity.class, user);
CompletableFuture<String> greetingResponse = ref.ask(new ReceivedGreetingCommand(user))
.toCompletableFuture();
CompletableFuture<WeatherStats> todaysWeatherInfo =
(CompletableFuture<WeatherStats>) weatherService.weatherStatsForToday().invoke();
try {
return CompletableFuture.completedFuture(greetingResponse.get() +
" Today's weather stats: " + todaysWeatherInfo.get().getMessage());
} catch (InterruptedException | ExecutionException e) {
return CompletableFuture.completedFuture("Sorry Some Error at our end, working on it");
}
};
}
}
|
repos\tutorials-master\microservices-modules\lagom\greeting-api\src\main\java\com\baeldung\lagom\helloworld\greeting\impl\GreetingServiceImpl.java
| 2
|
请完成以下Java代码
|
public void flagHeaderAggregationKeysForRecompute(@NonNull final Set<String> headerAggregationKeys)
{
invalidSchedulesRepo.invalidateForHeaderAggregationKeys(headerAggregationKeys);
}
@Override
public void notifySegmentChanged(@NonNull final IShipmentScheduleSegment segment)
{
notifySegmentsChanged(ImmutableSet.of(segment));
}
@Override
public void notifySegmentsChanged(@NonNull final Collection<IShipmentScheduleSegment> segments)
{
if (segments.isEmpty())
{
return;
}
final ImmutableList<IShipmentScheduleSegment> segmentsEffective = segments.stream()
.filter(segment -> !segment.isInvalid())
.flatMap(this::explodeByPickingBOMs)
.collect(ImmutableList.toImmutableList());
if (segmentsEffective.isEmpty())
{
return;
}
final ShipmentScheduleSegmentChangedProcessor collector = ShipmentScheduleSegmentChangedProcessor.getOrCreateIfThreadInheritedElseNull(this);
if (collector != null)
{
collector.addSegments(segmentsEffective); // they will be flagged for recompute after commit
}
else
{
final ITaskExecutorService taskExecutorService = Services.get(ITaskExecutorService.class);
taskExecutorService.submit(
() -> flagSegmentForRecompute(segmentsEffective),
this.getClass().getSimpleName());
}
}
private Stream<IShipmentScheduleSegment> explodeByPickingBOMs(final IShipmentScheduleSegment segment)
{
if (segment.isAnyProduct())
{
|
return Stream.of(segment);
}
final PickingBOMsReversedIndex pickingBOMsReversedIndex = pickingBOMService.getPickingBOMsReversedIndex();
final Set<ProductId> componentIds = ProductId.ofRepoIds(segment.getProductIds());
final ImmutableSet<ProductId> pickingBOMProductIds = pickingBOMsReversedIndex.getBOMProductIdsByComponentIds(componentIds);
if (pickingBOMProductIds.isEmpty())
{
return Stream.of(segment);
}
final ImmutableShipmentScheduleSegment pickingBOMsSegment = ImmutableShipmentScheduleSegment.builder()
.productIds(ProductId.toRepoIds(pickingBOMProductIds))
.anyBPartner()
.locatorIds(segment.getLocatorIds())
.build();
return Stream.of(segment, pickingBOMsSegment);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\invalidation\impl\ShipmentScheduleInvalidateBL.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DisplayNameQueryFilter<T> implements IQueryFilter<T>, ISqlQueryFilter
{
@NonNull
POInfo poInfo;
@NonNull
String searchTerm;
@NonNull
public static <T> DisplayNameQueryFilter<T> of(@NonNull final Class<T> modelClass, @NonNull final String searchTerm)
{
return new DisplayNameQueryFilter<>(modelClass, searchTerm);
}
private DisplayNameQueryFilter(@NonNull final Class<T> modelClass, @NonNull final String searchTerm)
{
final String tableName = InterfaceWrapperHelper.getTableName(modelClass);
this.poInfo = Optional.ofNullable(POInfo.getPOInfo(tableName))
.orElseThrow(() -> new AdempiereException("Missing POInfo for tableName = " + tableName));
this.searchTerm = searchTerm;
}
@Override
public boolean accept(final T model)
{
throw new UnsupportedOperationException();
}
@Override
public String getSql()
{
return buildDisplayNameQuerySql();
}
@Override
|
public List<Object> getSqlParams(final Properties ctx)
{
return ImmutableList.of();
}
@NonNull
private String buildDisplayNameQuerySql()
{
final String displayNameArgument = poInfo.streamColumns(POInfoColumn::isIdentifier)
.map(column -> column.isVirtualColumn() ? column.getColumnSQL() : column.getColumnName())
.collect(Collectors.joining(",", "CONCAT(", ")"));
return displayNameArgument + " ILIKE ('%" + searchTerm + "%')";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\DisplayNameQueryFilter.java
| 2
|
请完成以下Java代码
|
public IncidentQuery orderByIncidentId() {
orderBy(IncidentQueryProperty.INCIDENT_ID);
return this;
}
public IncidentQuery orderByIncidentTimestamp() {
orderBy(IncidentQueryProperty.INCIDENT_TIMESTAMP);
return this;
}
public IncidentQuery orderByIncidentType() {
orderBy(IncidentQueryProperty.INCIDENT_TYPE);
return this;
}
public IncidentQuery orderByExecutionId() {
orderBy(IncidentQueryProperty.EXECUTION_ID);
return this;
}
public IncidentQuery orderByActivityId() {
orderBy(IncidentQueryProperty.ACTIVITY_ID);
return this;
}
public IncidentQuery orderByProcessInstanceId() {
orderBy(IncidentQueryProperty.PROCESS_INSTANCE_ID);
return this;
}
public IncidentQuery orderByProcessDefinitionId() {
orderBy(IncidentQueryProperty.PROCESS_DEFINITION_ID);
return this;
}
public IncidentQuery orderByCauseIncidentId() {
orderBy(IncidentQueryProperty.CAUSE_INCIDENT_ID);
return this;
}
public IncidentQuery orderByRootCauseIncidentId() {
orderBy(IncidentQueryProperty.ROOT_CAUSE_INCIDENT_ID);
return this;
}
|
public IncidentQuery orderByConfiguration() {
orderBy(IncidentQueryProperty.CONFIGURATION);
return this;
}
public IncidentQuery orderByTenantId() {
return orderBy(IncidentQueryProperty.TENANT_ID);
}
@Override
public IncidentQuery orderByIncidentMessage() {
return orderBy(IncidentQueryProperty.INCIDENT_MESSAGE);
}
//results ////////////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getIncidentManager()
.findIncidentCountByQueryCriteria(this);
}
@Override
public List<Incident> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getIncidentManager()
.findIncidentByQueryCriteria(this, page);
}
public String[] getProcessDefinitionKeys() {
return processDefinitionKeys;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\IncidentQueryImpl.java
| 1
|
请完成以下Java代码
|
private void broadcastToChildren(TbActorId parent, Predicate<TbActorId> childFilter, TbActorMsg msg, boolean highPriority) {
Set<TbActorId> children = parentChildMap.get(parent);
if (children != null) {
children.stream().filter(childFilter).forEach(id -> {
try {
tell(id, msg, highPriority);
} catch (TbActorNotRegisteredException e) {
log.warn("Actor is missing for {}", id);
}
});
}
}
@Override
public List<TbActorId> filterChildren(TbActorId parent, Predicate<TbActorId> childFilter) {
Set<TbActorId> children = parentChildMap.get(parent);
if (children != null) {
return children.stream().filter(childFilter).collect(Collectors.toList());
} else {
return Collections.emptyList();
}
}
@Override
public void stop(TbActorRef actorRef) {
stop(actorRef.getActorId());
}
@Override
public void stop(TbActorId actorId) {
Set<TbActorId> children = parentChildMap.remove(actorId);
if (children != null) {
for (TbActorId child : children) {
stop(child);
}
}
parentChildMap.values().forEach(parentChildren -> parentChildren.remove(actorId));
TbActorMailbox mailbox = actors.remove(actorId);
if (mailbox != null) {
|
mailbox.destroy(null);
}
}
@Override
public void stop() {
dispatchers.values().forEach(dispatcher -> {
dispatcher.getExecutor().shutdown();
try {
dispatcher.getExecutor().awaitTermination(3, TimeUnit.SECONDS);
} catch (InterruptedException e) {
log.warn("[{}] Failed to stop dispatcher", dispatcher.getDispatcherId(), e);
}
});
if (scheduler != null) {
scheduler.shutdownNow();
}
actors.clear();
}
}
|
repos\thingsboard-master\common\actor\src\main\java\org\thingsboard\server\actors\DefaultTbActorSystem.java
| 1
|
请完成以下Java代码
|
public class M_ShipperTransportation
{
@DocValidate(timings = ModelValidator.TIMING_AFTER_COMPLETE)
public void processTourInstance(final I_M_ShipperTransportation shipperTransportation)
{
final I_M_Tour_Instance tourInstance = retrieveTourInstanceOrNull(shipperTransportation);
// No Tour Instance => nothing to do
if (tourInstance == null)
{
return;
}
Services.get(ITourInstanceBL.class).process(tourInstance);
}
@DocValidate(timings = { ModelValidator.TIMING_AFTER_REACTIVATE })
public void unprocessTourInstance(final I_M_ShipperTransportation shipperTransportation)
{
final I_M_Tour_Instance tourInstance = retrieveTourInstanceOrNull(shipperTransportation);
// No Tour Instance => nothing to do
if (tourInstance == null)
{
return;
}
Services.get(ITourInstanceBL.class).unprocess(tourInstance);
}
|
@DocValidate(timings = {
ModelValidator.TIMING_BEFORE_VOID,
ModelValidator.TIMING_BEFORE_REVERSECORRECT,
ModelValidator.TIMING_BEFORE_REVERSECORRECT })
public void prohibitVoidingIfTourInstanceExists(final I_M_ShipperTransportation shipperTransportation)
{
final I_M_Tour_Instance tourInstance = retrieveTourInstanceOrNull(shipperTransportation);
// No Tour Instance => nothing to do
if (tourInstance == null)
{
return;
}
throw new AdempiereException("@NotAllowed@ (@M_Tour_Instance_ID@: " + tourInstance + ")");
}
private I_M_Tour_Instance retrieveTourInstanceOrNull(final I_M_ShipperTransportation shipperTransportation)
{
final Object contextProvider = shipperTransportation;
final ITourInstanceQueryParams params = new PlainTourInstanceQueryParams();
params.setM_ShipperTransportation_ID(shipperTransportation.getM_ShipperTransportation_ID());
final I_M_Tour_Instance tourInstance = Services.get(ITourInstanceDAO.class).retrieveTourInstance(contextProvider, params);
return tourInstance;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\model\validator\M_ShipperTransportation.java
| 1
|
请完成以下Java代码
|
private @Nullable PreAuthorize findPreAuthorizeAnnotation(Method method, @Nullable Class<?> targetClass) {
Class<?> targetClassToUse = targetClass(method, targetClass);
return this.preAuthorizeScanner.scan(method, targetClassToUse);
}
/**
* Uses the provided {@link ApplicationContext} to resolve the
* {@link MethodAuthorizationDeniedHandler} from {@link PreAuthorize}.
* @param context the {@link ApplicationContext} to use
*/
void setApplicationContext(ApplicationContext context) {
Assert.notNull(context, "context cannot be null");
this.handlerResolver = (clazz) -> resolveHandler(context, clazz);
}
void setTemplateDefaults(AnnotationTemplateExpressionDefaults defaults) {
this.preAuthorizeScanner = SecurityAnnotationScanners.requireUnique(PreAuthorize.class, defaults);
}
|
private MethodAuthorizationDeniedHandler resolveHandler(ApplicationContext context,
Class<? extends MethodAuthorizationDeniedHandler> handlerClass) {
if (handlerClass == this.defaultHandler.getClass()) {
return this.defaultHandler;
}
String[] beanNames = context.getBeanNamesForType(handlerClass);
if (beanNames.length == 0) {
throw new IllegalStateException("Could not find a bean of type " + handlerClass.getName());
}
if (beanNames.length > 1) {
throw new IllegalStateException("Expected to find a single bean of type " + handlerClass.getName()
+ " but found " + Arrays.toString(beanNames));
}
return context.getBean(beanNames[0], handlerClass);
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\PreAuthorizeExpressionAttributeRegistry.java
| 1
|
请完成以下Java代码
|
public class ExtensionFileFilter extends FileFilter
implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1653311024184813302L;
/**
* Constructor
*/
public ExtensionFileFilter()
{
this ("","");
} // ExtensionFileFilter
/**
* Constructor
* @param extension extension
* @param description description
*/
public ExtensionFileFilter(String extension, String description)
{
setDescription (description);
setExtension (extension);
} // ExtensionFileFilter
/** Extension */
private String m_extension;
//
private String m_description;
/**
* Description
* @return description
*/
public String getDescription()
{
return m_description;
}
/**
* Set Description
* @param newDescription description
*/
public void setDescription(String newDescription)
{
m_description = newDescription;
} // setDescription
/**
* Extension
* @param newExtension ext
*/
public void setExtension(String newExtension)
{
m_extension = newExtension;
}
/**
* Get Extension
* @return extension
*/
public String getExtension()
{
return m_extension;
}
/**
* Accept File
* @param file file to be tested
* @return true if OK
*/
public boolean accept(File file)
{
// Need to accept directories
if (file.isDirectory())
return true;
String ext = file.getName();
int pos = ext.lastIndexOf('.');
|
// No extension
if (pos == -1)
return false;
ext = ext.substring(pos+1);
if (m_extension.equalsIgnoreCase(ext))
return true;
return false;
} // accept
/**
* Verify file name with filer
* @param file file
* @param filter filter
* @return file name
*/
public static String getFileName(File file, FileFilter filter)
{
return getFile(file, filter).getAbsolutePath();
} // getFileName
/**
* Verify file with filter
* @param file file
* @param filter filter
* @return file
*/
public static File getFile(File file, FileFilter filter)
{
String fName = file.getAbsolutePath();
if (fName == null || fName.equals(""))
fName = "Adempiere";
//
ExtensionFileFilter eff = null;
if (filter instanceof ExtensionFileFilter)
eff = (ExtensionFileFilter)filter;
else
return file;
//
int pos = fName.lastIndexOf('.');
// No extension
if (pos == -1)
{
fName += '.' + eff.getExtension();
return new File(fName);
}
String ext = fName.substring(pos+1);
// correct extension
if (ext.equalsIgnoreCase(eff.getExtension()))
return file;
fName += '.' + eff.getExtension();
return new File(fName);
} // getFile
} // ExtensionFileFilter
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\ExtensionFileFilter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class EDIExpDesadvLineWithNoPackType {
@XmlElement(name = "EDI_DesadvLine_ID")
protected EDIExpDesadvLineType ediDesadvLineID;
/**
* Gets the value of the ediDesadvLineID property.
*
* @return
* possible object is
* {@link EDIExpDesadvLineType }
*
*/
public EDIExpDesadvLineType getEDIDesadvLineID() {
return ediDesadvLineID;
|
}
/**
* Sets the value of the ediDesadvLineID property.
*
* @param value
* allowed object is
* {@link EDIExpDesadvLineType }
*
*/
public void setEDIDesadvLineID(EDIExpDesadvLineType value) {
this.ediDesadvLineID = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIExpDesadvLineWithNoPackType.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getMerchantLocationKey()
{
return merchantLocationKey;
}
public void setMerchantLocationKey(String merchantLocationKey)
{
this.merchantLocationKey = merchantLocationKey;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
PickupStep pickupStep = (PickupStep)o;
return Objects.equals(this.merchantLocationKey, pickupStep.merchantLocationKey);
}
@Override
public int hashCode()
{
return Objects.hash(merchantLocationKey);
}
@Override
public String toString()
|
{
StringBuilder sb = new StringBuilder();
sb.append("class PickupStep {\n");
sb.append(" merchantLocationKey: ").append(toIndentedString(merchantLocationKey)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\PickupStep.java
| 2
|
请完成以下Java代码
|
public de.metas.dataentry.model.I_DataEntry_Tab getDataEntry_Tab() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_DataEntry_Tab_ID, de.metas.dataentry.model.I_DataEntry_Tab.class);
}
@Override
public void setDataEntry_Tab(de.metas.dataentry.model.I_DataEntry_Tab DataEntry_Tab)
{
set_ValueFromPO(COLUMNNAME_DataEntry_Tab_ID, de.metas.dataentry.model.I_DataEntry_Tab.class, DataEntry_Tab);
}
/** Set Eingaberegister.
@param DataEntry_Tab_ID Eingaberegister */
@Override
public void setDataEntry_Tab_ID (int DataEntry_Tab_ID)
{
if (DataEntry_Tab_ID < 1)
set_ValueNoCheck (COLUMNNAME_DataEntry_Tab_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DataEntry_Tab_ID, Integer.valueOf(DataEntry_Tab_ID));
}
/** Get Eingaberegister.
@return Eingaberegister */
@Override
public int getDataEntry_Tab_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_Tab_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name Name */
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
|
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Registername.
@param TabName Registername */
@Override
public void setTabName (java.lang.String TabName)
{
set_Value (COLUMNNAME_TabName, TabName);
}
/** Get Registername.
@return Registername */
@Override
public java.lang.String getTabName ()
{
return (java.lang.String)get_Value(COLUMNNAME_TabName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_SubTab.java
| 1
|
请完成以下Java代码
|
protected String getDeploymentIdByProcessDefinition(CommandContext commandContext, String processDefinitionId) {
ProcessDefinitionEntity definition = commandContext.getProcessDefinitionManager().getCachedResourceDefinitionEntity(processDefinitionId);
if (definition == null) {
definition = commandContext.getProcessDefinitionManager().findLatestDefinitionById(processDefinitionId);
}
if (definition != null) {
return definition.getDeploymentId();
}
return null;
}
protected String getDeploymentIdByProcessDefinitionKey(CommandContext commandContext, String processDefinitionKey,
boolean tenantIdSet, String tenantId) {
ProcessDefinitionEntity definition = null;
if (tenantIdSet) {
definition = commandContext.getProcessDefinitionManager().findLatestProcessDefinitionByKeyAndTenantId(processDefinitionKey, tenantId);
} else {
// randomly use a latest process definition's deployment id from one of the tenants
List<ProcessDefinitionEntity> definitions = commandContext.getProcessDefinitionManager().findLatestProcessDefinitionsByKey(processDefinitionKey);
|
definition = definitions.isEmpty() ? null : definitions.get(0);
}
if (definition != null) {
return definition.getDeploymentId();
}
return null;
}
protected String getDeploymentIdByJobDefinition(CommandContext commandContext, String jobDefinitionId) {
JobDefinitionManager jobDefinitionManager = commandContext.getJobDefinitionManager();
JobDefinitionEntity jobDefinition = jobDefinitionManager.findById(jobDefinitionId);
if (jobDefinition != null) {
if (jobDefinition.getProcessDefinitionId() != null) {
return getDeploymentIdByProcessDefinition(commandContext, jobDefinition.getProcessDefinitionId());
}
}
return null;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractSetStateCmd.java
| 1
|
请完成以下Java代码
|
public class PartitionerTools
{
// de.metas.dlm.partitioner.PartitionerTools.dumpHistogram(records)
public static void dumpHistogram(final Map<String, Set<ITableRecordReference>> result)
{
final Set<ITableRecordReference> allRecords = result.values()
.stream()
.flatMap(records -> records.stream())
.collect(Collectors.toSet());
System.out.println("overall size=" + allRecords.size());
final PlainContextAware ctxProvider = PlainContextAware.newOutOfTrx(Env.getCtx());
allRecords.stream()
.collect(Collectors.groupingBy(ITableRecordReference::getTableName))
.forEach((t, r) -> {
System.out.println(t + ":\tsize=" + r.size() + ";\trepresentant=" + r.get(0).getModel(ctxProvider, IDLMAware.class));
});
}
public static Iterator<WorkQueue> loadQueue(final int dlm_Partition_ID, final IContextAware contextAware)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final Iterator<I_DLM_Partition_Workqueue> iterator = queryBL.createQueryBuilder(I_DLM_Partition_Workqueue.class, contextAware)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_DLM_Partition_Workqueue.COLUMN_DLM_Partition_ID, dlm_Partition_ID)
.orderBy().addColumn(I_DLM_Partition_Workqueue.COLUMNNAME_DLM_Partition_Workqueue_ID).endOrderBy()
.create()
.setOption(IQuery.OPTION_GuaranteedIteratorRequired, true)
.setOption(IQuery.OPTION_IteratorBufferSize, 5000)
.iterate(I_DLM_Partition_Workqueue.class);
return new Iterator<WorkQueue>()
{
@Override
|
public boolean hasNext()
{
return iterator.hasNext();
}
@Override
public WorkQueue next()
{
return WorkQueue.of(iterator.next());
}
@Override
public String toString()
{
return "PartitionerTools.loadQueue() [dlm_Partition_ID=" + dlm_Partition_ID + "; iterator=" + iterator + "]";
}
};
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\impl\PartitionerTools.java
| 1
|
请完成以下Java代码
|
public static XxlJobAdminConfig getAdminConfig() {
return adminConfig;
}
// ---------------------- XxlJobScheduler ----------------------
private XxlJobScheduler xxlJobScheduler;
@Override
public void afterPropertiesSet() throws Exception {
adminConfig = this;
xxlJobScheduler = new XxlJobScheduler();
xxlJobScheduler.init();
}
@Override
public void destroy() throws Exception {
xxlJobScheduler.destroy();
}
// ---------------------- XxlJobScheduler ----------------------
// conf
@Value("${xxl.job.i18n}")
private String i18n;
@Value("${xxl.job.accessToken}")
private String accessToken;
@Value("${spring.mail.from}")
private String emailFrom;
@Value("${xxl.job.triggerpool.fast.max}")
private int triggerPoolFastMax;
@Value("${xxl.job.triggerpool.slow.max}")
private int triggerPoolSlowMax;
@Value("${xxl.job.logretentiondays}")
private int logretentiondays;
// dao, service
@Resource
private XxlJobLogDao xxlJobLogDao;
@Resource
private XxlJobInfoDao xxlJobInfoDao;
@Resource
private XxlJobRegistryDao xxlJobRegistryDao;
@Resource
private XxlJobGroupDao xxlJobGroupDao;
@Resource
private XxlJobLogReportDao xxlJobLogReportDao;
@Resource
private JavaMailSender mailSender;
@Resource
private DataSource dataSource;
@Resource
private JobAlarmer jobAlarmer;
public String getI18n() {
if (!Arrays.asList("zh_CN", "zh_TC", "en").contains(i18n)) {
return "zh_CN";
}
return i18n;
}
public String getAccessToken() {
|
return accessToken;
}
public String getEmailFrom() {
return emailFrom;
}
public int getTriggerPoolFastMax() {
if (triggerPoolFastMax < 200) {
return 200;
}
return triggerPoolFastMax;
}
public int getTriggerPoolSlowMax() {
if (triggerPoolSlowMax < 100) {
return 100;
}
return triggerPoolSlowMax;
}
public int getLogretentiondays() {
if (logretentiondays < 7) {
return -1; // Limit greater than or equal to 7, otherwise close
}
return logretentiondays;
}
public XxlJobLogDao getXxlJobLogDao() {
return xxlJobLogDao;
}
public XxlJobInfoDao getXxlJobInfoDao() {
return xxlJobInfoDao;
}
public XxlJobRegistryDao getXxlJobRegistryDao() {
return xxlJobRegistryDao;
}
public XxlJobGroupDao getXxlJobGroupDao() {
return xxlJobGroupDao;
}
public XxlJobLogReportDao getXxlJobLogReportDao() {
return xxlJobLogReportDao;
}
public JavaMailSender getMailSender() {
return mailSender;
}
public DataSource getDataSource() {
return dataSource;
}
public JobAlarmer getJobAlarmer() {
return jobAlarmer;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\conf\XxlJobAdminConfig.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static class Ssl {
/**
* Whether to enable SSL support. Enabled automatically if "bundle" is provided
* unless specified otherwise.
*/
private @Nullable Boolean enabled;
/**
* SSL bundle name.
*/
private @Nullable String bundle;
public boolean isEnabled() {
return (this.enabled != null) ? this.enabled : this.bundle != null;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public @Nullable String getBundle() {
return this.bundle;
}
public void setBundle(@Nullable String bundle) {
this.bundle = bundle;
}
}
public static class Validation {
/**
|
* Whether to enable LDAP schema validation.
*/
private boolean enabled = true;
/**
* Path to the custom schema.
*/
private @Nullable Resource schema;
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public @Nullable Resource getSchema() {
return this.schema;
}
public void setSchema(@Nullable Resource schema) {
this.schema = schema;
}
}
}
|
repos\spring-boot-main\module\spring-boot-ldap\src\main\java\org\springframework\boot\ldap\autoconfigure\embedded\EmbeddedLdapProperties.java
| 2
|
请完成以下Java代码
|
public Set<String> getTargetKeyColumns()
{
return targetKeyColumns;
}
public void setTargetKeyColumns(String... columns)
{
final Set<String> s = new HashSet<String>();
for (String c : columns)
s.add(c);
this.targetKeyColumns = s;
}
public String getSql()
{
return sql;
}
public void setSql(String sql)
{
this.sql = sql;
}
public void addSourceTable(String tableName, String... columns)
{
Set<String> s = new HashSet<String>();
for (String c : columns)
s.add(c);
sourceTables.put(tableName, s);
}
public Set<String> getSourceTables()
{
return sourceTables.keySet();
}
public Set<String> getSourceColumns(String sourceTableName)
{
return sourceTables.get(sourceTableName);
}
|
public void addRelation(String sourceTableName, String targetTableName, String whereClause)
{
final MultiKey key = new MultiKey(sourceTableName, targetTableName);
relations.put(key, whereClause);
}
public String getRelationWhereClause(String sourceTableName, String targetTableName)
{
final MultiKey key = new MultiKey(sourceTableName, targetTableName);
return relations.get(key);
}
@Override
public String toString()
{
return "MViewMetadata [targetTableName=" + targetTableName + ", targetKeyColumns=" + targetKeyColumns + ", sourceTables=" + sourceTables + ", sql=" + sql + "]";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\engine\MViewMetadata.java
| 1
|
请完成以下Java代码
|
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Verarbeiten.
@return Verarbeiten */
@Override
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 Version.
@param Version
Version of the table definition
*/
@Override
public void setVersion (java.lang.String Version)
{
set_Value (COLUMNNAME_Version, Version);
}
/** Get Version.
@return Version of the table definition
*/
|
@Override
public java.lang.String getVersion ()
{
return (java.lang.String)get_Value(COLUMNNAME_Version);
}
/** Set WebUIServletListener Class.
@param WebUIServletListenerClass
Optional class to execute custom code on WebUI startup; A declared class needs to implement IWebUIServletListener
*/
@Override
public void setWebUIServletListenerClass (java.lang.String WebUIServletListenerClass)
{
set_Value (COLUMNNAME_WebUIServletListenerClass, WebUIServletListenerClass);
}
/** Get WebUIServletListener Class.
@return Optional class to execute custom code on WebUI startup; A declared class needs to implement IWebUIServletListener
*/
@Override
public java.lang.String getWebUIServletListenerClass ()
{
return (java.lang.String)get_Value(COLUMNNAME_WebUIServletListenerClass);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_EntityType.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AdjustmentType {
@XmlElement(name = "ReasonCode", required = true)
protected String reasonCode;
@XmlElement(name = "AdjustmentMonetaryAmount", required = true)
protected MonetaryAmountType adjustmentMonetaryAmount;
@XmlElement(name = "Tax")
protected TaxType tax;
/**
* Gets the value of the reasonCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReasonCode() {
return reasonCode;
}
/**
* Sets the value of the reasonCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReasonCode(String value) {
this.reasonCode = value;
}
/**
* Monetary amount of the actual adjustment.
*
* @return
* possible object is
* {@link MonetaryAmountType }
*
*/
public MonetaryAmountType getAdjustmentMonetaryAmount() {
return adjustmentMonetaryAmount;
}
/**
* Sets the value of the adjustmentMonetaryAmount property.
|
*
* @param value
* allowed object is
* {@link MonetaryAmountType }
*
*/
public void setAdjustmentMonetaryAmount(MonetaryAmountType value) {
this.adjustmentMonetaryAmount = value;
}
/**
* Taxes applied to the adjustment.
*
* @return
* possible object is
* {@link TaxType }
*
*/
public TaxType getTax() {
return tax;
}
/**
* Sets the value of the tax property.
*
* @param value
* allowed object is
* {@link TaxType }
*
*/
public void setTax(TaxType value) {
this.tax = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\AdjustmentType.java
| 2
|
请完成以下Java代码
|
public void setDecimalPointPosition (final int DecimalPointPosition)
{
set_Value (COLUMNNAME_DecimalPointPosition, DecimalPointPosition);
}
@Override
public int getDecimalPointPosition()
{
return get_ValueAsInt(COLUMNNAME_DecimalPointPosition);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setEndNo (final int EndNo)
{
set_Value (COLUMNNAME_EndNo, EndNo);
}
@Override
public int getEndNo()
|
{
return get_ValueAsInt(COLUMNNAME_EndNo);
}
@Override
public void setStartNo (final int StartNo)
{
set_Value (COLUMNNAME_StartNo, StartNo);
}
@Override
public int getStartNo()
{
return get_ValueAsInt(COLUMNNAME_StartNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ScannableCode_Format_Part.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
final Claims claims = getAllClaimsFromToken(token);
return claimsResolver.apply(claims);
}
private Claims getAllClaimsFromToken(String token) {
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
}
private Boolean isTokenExpired(String token) {
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}
private Boolean ignoreTokenExpiration(String token) {
// here you specify tokens, for that the expiration is ignored
return false;
}
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
return doGenerateToken(claims, userDetails.getUsername());
}
|
private String doGenerateToken(Map<String, Object> claims, String subject) {
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY*1000)).signWith(SignatureAlgorithm.HS512, secret).compact();
}
public Boolean canTokenBeRefreshed(String token) {
return (!isTokenExpired(token) || ignoreTokenExpiration(token));
}
public Boolean validateToken(String token, UserDetails userDetails) {
final String username = getUsernameFromToken(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}
}
|
repos\SpringBoot-Projects-FullStack-master\Advanced-SpringSecure\spring-boot-jwt-without-JPA\spring-boot-jwt\src\main\java\com\javainuse\config\JwtTokenUtil.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
public Map<String, Object> getMetadata() {
return metadata;
}
public void setMetadata(Map<String, Object> metadata) {
this.metadata = metadata;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RouteProperties that = (RouteProperties) o;
return this.order == that.order && Objects.equals(this.id, that.id)
&& Objects.equals(this.predicates, that.predicates) && Objects.equals(this.filters, that.filters)
|
&& Objects.equals(this.uri, that.uri) && Objects.equals(this.metadata, that.metadata);
}
@Override
public int hashCode() {
return Objects.hash(this.id, this.predicates, this.filters, this.uri, this.metadata, this.order);
}
@Override
public String toString() {
return "RouteDefinition{" + "id='" + id + '\'' + ", predicates=" + predicates + ", filters=" + filters
+ ", uri=" + uri + ", order=" + order + ", metadata=" + metadata + '}';
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\config\RouteProperties.java
| 2
|
请完成以下Java代码
|
public boolean isTaxIncluded ()
{
Object oo = get_Value(COLUMNNAME_IsTaxIncluded);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Preisliste.
@param M_PriceList_ID
Unique identifier of a Price List
*/
@Override
public void setM_PriceList_ID (int M_PriceList_ID)
{
if (M_PriceList_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PriceList_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PriceList_ID, Integer.valueOf(M_PriceList_ID));
}
/** Get Preisliste.
@return Unique identifier of a Price List
*/
@Override
public int getM_PriceList_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PriceList_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Preissystem.
@param M_PricingSystem_ID
Ein Preissystem enthält beliebig viele, Länder-abhängige Preislisten.
*/
@Override
public void setM_PricingSystem_ID (int M_PricingSystem_ID)
{
if (M_PricingSystem_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PricingSystem_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PricingSystem_ID, Integer.valueOf(M_PricingSystem_ID));
}
/** Get Preissystem.
@return Ein Preissystem enthält beliebig viele, Länder-abhängige Preislisten.
*/
@Override
public int getM_PricingSystem_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PricingSystem_ID);
if (ii == null)
return 0;
|
return ii.intValue();
}
/** Set Name.
@param Name Name */
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Preis Präzision.
@param PricePrecision
Precision (number of decimals) for the Price
*/
@Override
public void setPricePrecision (int PricePrecision)
{
set_Value (COLUMNNAME_PricePrecision, Integer.valueOf(PricePrecision));
}
/** Get Preis Präzision.
@return Precision (number of decimals) for the Price
*/
@Override
public int getPricePrecision ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PricePrecision);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PriceList.java
| 1
|
请完成以下Java代码
|
public class CollectionExistence {
private static MongoClient mongoClient;
private static String testCollectionName;
private static String databaseName;
public static void setUp() {
if (mongoClient == null) {
mongoClient = MongoClients.create("mongodb://localhost:27017");
}
databaseName = "baeldung";
testCollectionName = "student";
}
public static void collectionExistsSolution() {
MongoDatabase db = mongoClient.getDatabase(databaseName);
System.out.println("collectionName " + testCollectionName + db.listCollectionNames().into(new ArrayList<>()).contains(testCollectionName));
}
public static void createCollectionSolution() {
MongoDatabase database = mongoClient.getDatabase(databaseName);
try {
database.createCollection(testCollectionName);
} catch (Exception exception) {
System.err.println("Collection already Exists");
}
}
public static void listCollectionNamesSolution() {
MongoDatabase database = mongoClient.getDatabase(databaseName);
boolean collectionExists = database.listCollectionNames()
.into(new ArrayList<String>())
.contains(testCollectionName);
System.out.println("collectionExists:- " + collectionExists);
}
public static void countSolution() {
MongoDatabase database = mongoClient.getDatabase(databaseName);
|
MongoCollection<Document> collection = database.getCollection(testCollectionName);
System.out.println(collection.countDocuments());
}
public static void main(String args[]) {
//
// Connect to cluster (default is localhost:27017)
//
setUp();
//
// Check the db existence using DB class's method
//
collectionExistsSolution();
//
// Check the db existence using the createCollection method of MongoDatabase class
//
createCollectionSolution();
//
// Check the db existence using the listCollectionNames method of MongoDatabase class
//
listCollectionNamesSolution();
//
// Check the db existence using the count method of MongoDatabase class
//
countSolution();
}
}
|
repos\tutorials-master\persistence-modules\java-mongodb-3\src\main\java\com\baeldung\mongo\collectionexistence\CollectionExistence.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void createProjectLine(
@NonNull final CreateProjectRequest.ProjectLine request,
@NonNull final ProjectId projectId,
@NonNull final OrgId orgId)
{
final I_C_ProjectLine record = InterfaceWrapperHelper.newInstance(I_C_ProjectLine.class);
record.setAD_Org_ID(orgId.getRepoId());
record.setC_Project_ID(projectId.getRepoId());
record.setM_Product_ID(request.getProductId().getRepoId());
record.setPlannedQty(request.getPlannedQty().toBigDecimal());
record.setC_UOM_ID(request.getPlannedQty().getUomId().getRepoId());
save(record);
}
public ProjectLine changeProjectLine(
@NonNull final ProjectAndLineId projectLineId,
@NonNull final Consumer<ProjectLine> updater)
{
final I_C_ProjectLine record = retrieveLineRecordById(projectLineId);
final ProjectLine line = toProjectLine(record);
updater.accept(line);
updateRecord(record, line);
save(record);
return line;
}
public void linkToOrderLine(
|
@NonNull final ProjectAndLineId projectLineId,
@NonNull final OrderAndLineId orderLineId)
{
final I_C_ProjectLine record = retrieveLineRecordById(projectLineId);
record.setC_Order_ID(orderLineId.getOrderRepoId());
record.setC_OrderLine_ID(orderLineId.getOrderLineRepoId());
save(record);
}
public void markLinesAsProcessed(@NonNull final ProjectId projectId)
{
for (final I_C_ProjectLine lineRecord : queryLineRecordsByProjectId(projectId).list())
{
lineRecord.setProcessed(true);
InterfaceWrapperHelper.saveRecord(lineRecord);
}
}
public void markLinesAsNotProcessed(@NonNull final ProjectId projectId)
{
for (final I_C_ProjectLine lineRecord : queryLineRecordsByProjectId(projectId).list())
{
lineRecord.setProcessed(false);
InterfaceWrapperHelper.saveRecord(lineRecord);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\project\service\ProjectLineRepository.java
| 2
|
请完成以下Java代码
|
public void registerHints(RuntimeHints hints, ConfigurableListableBeanFactory beanFactory) {
List<Class<?>> toProxy = new ArrayList<>();
for (String name : beanFactory.getBeanDefinitionNames()) {
ResolvableType type = beanFactory.getBeanDefinition(name).getResolvableType();
if (!RepositoryFactoryBeanSupport.class.isAssignableFrom(type.toClass())) {
continue;
}
Class<?>[] generics = type.resolveGenerics();
Class<?> entity = generics[1];
AuthorizeReturnObject authorize = beanFactory.findAnnotationOnBean(name, AuthorizeReturnObject.class);
if (authorize != null) {
toProxy.add(entity);
continue;
}
Class<?> repository = generics[0];
|
for (Method method : repository.getDeclaredMethods()) {
AuthorizeReturnObject returnObject = this.scanner.scan(method, repository);
if (returnObject == null) {
continue;
}
// optimistically assume that the entity needs wrapping if any of the
// repository methods use @AuthorizeReturnObject
toProxy.add(entity);
break;
}
}
new AuthorizeReturnObjectHintsRegistrar(this.proxyFactory, toProxy).registerHints(hints, beanFactory);
}
}
|
repos\spring-security-main\data\src\main\java\org\springframework\security\data\aot\hint\AuthorizeReturnObjectDataHintsRegistrar.java
| 1
|
请完成以下Java代码
|
public ProcessInstance execute(CommandContext commandContext) {
DeploymentManager deploymentCache = commandContext.getProcessEngineConfiguration().getDeploymentManager();
ProcessDefinitionRetriever processRetriever = new ProcessDefinitionRetriever(this.tenantId, deploymentCache);
ProcessDefinition processDefinition = processRetriever.getProcessDefinition(
this.processDefinitionId,
this.processDefinitionKey
);
processInstanceHelper = commandContext.getProcessEngineConfiguration().getProcessInstanceHelper();
ProcessInstanceCreationOptions options = ProcessInstanceCreationOptions
.builder(processDefinition)
.businessKey(businessKey)
.processInstanceName(processInstanceName)
.variables(variables)
.transientVariables(transientVariables)
.linkedProcessInstanceId(linkedProcessInstanceId)
.linkedProcessInstanceType(linkedProcessInstanceType)
.build();
return createAndStartProcessInstance(options);
}
protected ProcessInstance createAndStartProcessInstance(
ProcessInstanceCreationOptions options
) {
|
return processInstanceHelper.createAndStartProcessInstance(options);
}
protected Map<String, Object> processDataObjects(Collection<ValuedDataObject> dataObjects) {
Map<String, Object> variablesMap = new HashMap<String, Object>();
// convert data objects to process variables
if (dataObjects != null) {
for (ValuedDataObject dataObject : dataObjects) {
variablesMap.put(dataObject.getName(), dataObject.getValue());
}
}
return variablesMap;
}
public String getLinkedProcessInstanceId() {
return linkedProcessInstanceId;
}
public String getLinkedProcessInstanceType() {
return linkedProcessInstanceType;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\StartProcessInstanceCmd.java
| 1
|
请完成以下Java代码
|
public String start(Model model) {
model.addAttribute("items", items);
return "pathvariables/index";
}
@GetMapping("/pathvars/single/{id}")
public String singlePathVariable(@PathVariable("id") int id, Model model) {
if (id == 1) {
model.addAttribute("item", new Item(1, "First Item"));
} else {
model.addAttribute("item", new Item(2, "Second Item"));
}
return "pathvariables/view";
}
|
@GetMapping("/pathvars/item/{itemId}/detail/{detailId}")
public String multiplePathVariable(@PathVariable("itemId") int itemId, @PathVariable("detailId") int detailId, Model model) {
for (Item item : items) {
if (item.getId() == itemId) {
model.addAttribute("item", item);
for (Detail detail : item.getDetails()) {
if (detail.getId() == detailId) {
model.addAttribute("detail", detail);
}
}
}
}
return "pathvariables/view";
}
}
|
repos\tutorials-master\spring-web-modules\spring-thymeleaf-2\src\main\java\com\baeldung\thymeleaf\pathvariables\PathVariablesController.java
| 1
|
请完成以下Java代码
|
public String getF_EMAIL() {
return F_EMAIL;
}
public void setF_EMAIL(String f_EMAIL) {
F_EMAIL = f_EMAIL;
}
public String getF_CANTONLEV() {
return F_CANTONLEV;
}
public void setF_CANTONLEV(String f_CANTONLEV) {
F_CANTONLEV = f_CANTONLEV;
}
public String getF_TAXORGCODE() {
return F_TAXORGCODE;
}
public void setF_TAXORGCODE(String f_TAXORGCODE) {
F_TAXORGCODE = f_TAXORGCODE;
}
public String getF_MEMO() {
return F_MEMO;
}
public void setF_MEMO(String f_MEMO) {
F_MEMO = f_MEMO;
}
public String getF_USING() {
return F_USING;
}
public void setF_USING(String f_USING) {
F_USING = f_USING;
}
public String getF_USINGDATE() {
return F_USINGDATE;
}
public void setF_USINGDATE(String f_USINGDATE) {
F_USINGDATE = f_USINGDATE;
|
}
public Integer getF_LEVEL() {
return F_LEVEL;
}
public void setF_LEVEL(Integer f_LEVEL) {
F_LEVEL = f_LEVEL;
}
public String getF_END() {
return F_END;
}
public void setF_END(String f_END) {
F_END = f_END;
}
public String getF_QRCANTONID() {
return F_QRCANTONID;
}
public void setF_QRCANTONID(String f_QRCANTONID) {
F_QRCANTONID = f_QRCANTONID;
}
public String getF_DECLARE() {
return F_DECLARE;
}
public void setF_DECLARE(String f_DECLARE) {
F_DECLARE = f_DECLARE;
}
public String getF_DECLAREISEND() {
return F_DECLAREISEND;
}
public void setF_DECLAREISEND(String f_DECLAREISEND) {
F_DECLAREISEND = f_DECLAREISEND;
}
}
|
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscCanton.java
| 1
|
请完成以下Java代码
|
public String[] getKeyColumns()
{
final List<String> list = new ArrayList<>();
//
for (final MColumn column : getColumns(false))
{
if (column.isKey())
{
return new String[] { column.getColumnName() };
}
if (column.isParent())
{
list.add(column.getColumnName());
}
}
return list.toArray(new String[list.size()]);
} // getKeyColumns
/**************************************************************************
* Get PO Class Instance
*
* @return PO for Record or null
* @deprecated Please consider using {@link TableModelLoader#getPO(Properties, String, int, String)} or {@link TableRecordCacheLocal#getReferencedValue(Object, Class)}.
*/
@Deprecated
public PO getPO(final int Record_ID, final String trxName)
{
final Properties ctx = getCtx();
final String tableName = getTableName();
return TableModelLoader.instance.getPO(ctx, tableName, Record_ID, trxName);
}
/**
*
* @return tableName's model class
* @deprecated Please use {@link TableModelClassLoader#getClass(String)}.
*/
@Deprecated
public static Class<?> getClass(String tableName)
{
return TableModelClassLoader.instance.getClass(tableName);
}
/**
* Before Save
*
* @param newRecord new
* @return true
*/
@Override
protected boolean beforeSave(boolean newRecord)
{
if (isView() && isDeleteable())
|
{
setIsDeleteable(false);
}
//
return true;
} // beforeSave
/**
* After Save
*
* @param newRecord new
* @param success success
* @return success
*/
@Override
protected boolean afterSave(boolean newRecord, boolean success)
{
//
// Create/Update table sequences
// NOTE: we shall do this only if it's a new table, else we will change the sequence's next value
// which could be OK on our local development database,
// but when the migration script will be executed on target customer database, their sequences will be wrongly changed (08607)
if (success && newRecord)
{
final ISequenceDAO sequenceDAO = Services.get(ISequenceDAO.class);
sequenceDAO.createTableSequenceChecker(getCtx())
.setFailOnFirstError(true)
.setSequenceRangeCheck(false)
.setTable(this)
.setTrxName(get_TrxName())
.run();
}
if (!newRecord && is_ValueChanged(COLUMNNAME_TableName))
{
final IADTableDAO adTableDAO = Services.get(IADTableDAO.class);
adTableDAO.onTableNameRename(this);
}
return success;
} // afterSave
public Query createQuery(String whereClause, String trxName)
{
return new Query(this.getCtx(), this, whereClause, trxName);
}
@Override
public String toString()
{
return "MTable[" + get_ID() + "-" + getTableName() + "]";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTable.java
| 1
|
请完成以下Java代码
|
public CRPException setS_Resource(I_S_Resource resource)
{
this.resource = resource;
resetMessageBuilt();
return this;
}
@Override
protected ITranslatableString buildMessage()
{
String msg = super.getMessage();
StringBuffer sb = new StringBuffer(msg);
//
if (this.order != null)
{
final String info;
if (order instanceof IDocument)
{
info = ((IDocument)order).getSummary();
}
else
{
|
info = "" + order.getDocumentNo() + "/" + order.getDatePromised();
}
sb.append(" @PP_Order_ID@:").append(info);
}
if (this.orderActivity != null)
{
sb.append(" @PP_Order_Node_ID@:").append(orderActivity);
}
if (this.resource != null)
{
sb.append(" @S_Resource_ID@:").append(resource.getValue()).append("_").append(resource.getName());
}
//
return TranslatableStrings.parse(sb.toString());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\exceptions\CRPException.java
| 1
|
请完成以下Java代码
|
public class CreateExternalWorkerJobBeforeContext {
protected final ExternalWorkerServiceTask externalWorkerServiceTask;
protected final DelegateExecution execution;
protected String jobCategory;
protected String jobTopicExpression;
public CreateExternalWorkerJobBeforeContext(ExternalWorkerServiceTask externalWorkerServiceTask, DelegateExecution execution, String jobCategory) {
this.externalWorkerServiceTask = externalWorkerServiceTask;
this.execution = execution;
this.jobCategory = jobCategory;
}
public ExternalWorkerServiceTask getExternalWorkerServiceTask() {
return externalWorkerServiceTask;
}
public DelegateExecution getExecution() {
return execution;
}
|
public String getJobCategory() {
return jobCategory;
}
public void setJobCategory(String jobCategory) {
this.jobCategory = jobCategory;
}
public String getJobTopicExpression() {
return jobTopicExpression;
}
public void setJobTopicExpression(String jobTopicExpression) {
this.jobTopicExpression = jobTopicExpression;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\interceptor\CreateExternalWorkerJobBeforeContext.java
| 1
|
请完成以下Java代码
|
public int getRetries() {
return retries;
}
public void setRetries(int retries) {
this.retries = retries;
}
public int getMaxIterations() {
return maxIterations;
}
public void setMaxIterations(int maxIterations) {
this.maxIterations = maxIterations;
}
public String getRepeat() {
return repeat;
}
public void setRepeat(String repeat) {
this.repeat = repeat;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = exceptionMessage;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dueDate == null) ? 0 : dueDate.hashCode());
result = prime * result + ((endDate == null) ? 0 : endDate.hashCode());
result = prime * result + ((exceptionMessage == null) ? 0 : exceptionMessage.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + maxIterations;
result = prime * result + ((repeat == null) ? 0 : repeat.hashCode());
result = prime * result + retries;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
|
if (getClass() != obj.getClass()) return false;
TimerPayload other = (TimerPayload) obj;
if (dueDate == null) {
if (other.dueDate != null) return false;
} else if (!dueDate.equals(other.dueDate)) return false;
if (endDate == null) {
if (other.endDate != null) return false;
} else if (!endDate.equals(other.endDate)) return false;
if (exceptionMessage == null) {
if (other.exceptionMessage != null) return false;
} else if (!exceptionMessage.equals(other.exceptionMessage)) return false;
if (id == null) {
if (other.id != null) return false;
} else if (!id.equals(other.id)) return false;
if (maxIterations != other.maxIterations) return false;
if (repeat == null) {
if (other.repeat != null) return false;
} else if (!repeat.equals(other.repeat)) return false;
if (retries != other.retries) return false;
return true;
}
}
|
repos\Activiti-develop\activiti-api\activiti-api-process-model\src\main\java\org\activiti\api\process\model\payloads\TimerPayload.java
| 1
|
请完成以下Java代码
|
public void setUserId(String userId) {
this.userId = userId;
}
@CamundaQueryParam("operationId")
public void setOperationId(String operationId) {
this.operationId = operationId;
}
@CamundaQueryParam("externalTaskId")
public void setExternalTaskId(String externalTaskId) {
this.externalTaskId = externalTaskId;
}
@CamundaQueryParam("operationType")
public void setOperationType(String operationType) {
this.operationType = operationType;
}
@CamundaQueryParam("entityType")
public void setEntityType(String entityType) {
this.entityType = entityType;
}
@CamundaQueryParam(value = "entityTypeIn", converter = StringArrayConverter.class)
public void setEntityTypeIn(String[] entityTypes) {
this.entityTypes = entityTypes;
}
@CamundaQueryParam("category")
public void setcategory(String category) {
this.category = category;
}
|
@CamundaQueryParam(value = "categoryIn", converter = StringArrayConverter.class)
public void setCategoryIn(String[] categories) {
this.categories = categories;
}
@CamundaQueryParam("property")
public void setProperty(String property) {
this.property = property;
}
@CamundaQueryParam(value = "afterTimestamp", converter = DateConverter.class)
public void setAfterTimestamp(Date after) {
this.afterTimestamp = after;
}
@CamundaQueryParam(value = "beforeTimestamp", converter = DateConverter.class)
public void setBeforeTimestamp(Date before) {
this.beforeTimestamp = before;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\UserOperationLogQueryDto.java
| 1
|
请完成以下Java代码
|
protected PlanItemDefinition getDefinition(CmmnElement element) {
if (isPlanItem(element)) {
PlanItem planItem = (PlanItem) element;
return planItem.getDefinition();
} else
if (isDiscretionaryItem(element)) {
DiscretionaryItem discretionaryItem = (DiscretionaryItem) element;
return discretionaryItem.getDefinition();
}
return null;
}
protected Collection<Sentry> getEntryCriterias(CmmnElement element) {
if (isPlanItem(element)) {
PlanItem planItem = (PlanItem) element;
return planItem.getEntryCriteria();
}
return new ArrayList<Sentry>();
}
protected Collection<Sentry> getExitCriterias(CmmnElement element) {
if (isPlanItem(element)) {
PlanItem planItem = (PlanItem) element;
return planItem.getExitCriteria();
}
return new ArrayList<Sentry>();
}
protected String getDesciption(CmmnElement element) {
String description = element.getDescription();
if (description == null) {
PlanItemDefinition definition = getDefinition(element);
description = definition.getDescription();
}
return description;
}
protected String getDocumentation(CmmnElement element) {
Collection<Documentation> documentations = element.getDocumentations();
if (documentations.isEmpty()) {
PlanItemDefinition definition = getDefinition(element);
documentations = definition.getDocumentations();
}
if (documentations.isEmpty()) {
|
return null;
}
StringBuilder builder = new StringBuilder();
for (Documentation doc : documentations) {
String content = doc.getTextContent();
if (content == null || content.isEmpty()) {
continue;
}
if (builder.length() != 0) {
builder.append("\n\n");
}
builder.append(content.trim());
}
return builder.toString();
}
protected boolean isPlanItem(CmmnElement element) {
return element instanceof PlanItem;
}
protected boolean isDiscretionaryItem(CmmnElement element) {
return element instanceof DiscretionaryItem;
}
protected abstract List<String> getStandardEvents(CmmnElement element);
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\handler\ItemHandler.java
| 1
|
请完成以下Spring Boot application配置
|
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.jpa.hibernate.ddl-a
|
uto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
|
repos\tutorials-master\persistence-modules\spring-jpa-2\src\main\resources\application-h2.properties
| 2
|
请完成以下Java代码
|
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@ToString.Exclude
@OneToMany(mappedBy = "author")
private List<Book> books;
|
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o))
return false;
Author author = (Author) o;
return getId() != null && Objects.equals(getId(), author.getId());
}
@Override
public int hashCode() {
return getClass().hashCode();
}
}
|
repos\tutorials-master\persistence-modules\jimmer\src\main\java\com\baeldung\jimmer\introduction\hibernate\Author.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class XmlInvoice
{
@NonNull
BigInteger requestTimestamp;
@NonNull
XMLGregorianCalendar requestDate;
@NonNull
String requestId;
public XmlInvoice withMod(@Nullable final InvoiceMod mod)
{
if (mod == null)
{
return this;
}
final XmlInvoiceBuilder builder = toBuilder();
if (mod.getRequestDate() != null)
{
builder.requestDate(mod.getRequestDate());
}
if (mod.getRequestTimestamp() != null)
{
builder.requestTimestamp(mod.getRequestTimestamp());
|
}
if (mod.getRequestId() != null)
{
builder.requestId(mod.getRequestId());
}
return builder.build();
}
@Value
@Builder
public static class InvoiceMod
{
@Nullable
BigInteger requestTimestamp;
@Nullable
XMLGregorianCalendar requestDate;
@Nullable
String requestId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_xversion\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_xversion\model\commontypes\XmlInvoice.java
| 2
|
请完成以下Java代码
|
public int getWordCount() {
return wordCount;
}
public void setWordCount(int wordCount) {
this.wordCount = wordCount;
}
public String getFileInfo() {
return "Text File Impl";
}
public String read() {
return this.getContent()
.toString();
|
}
public String read(int limit) {
return this.getContent()
.toString()
.substring(0, limit);
}
public String read(int start, int stop) {
return this.getContent()
.toString()
.substring(start, stop);
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-oop-inheritance-2\src\main\java\com\baeldung\polymorphism\TextFile.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JsonOLCandCreateBulkRequest
{
public static JsonOLCandCreateBulkRequest of(@NonNull final JsonOLCandCreateRequest request)
{
return new JsonOLCandCreateBulkRequest(ImmutableList.of(request));
}
@JsonProperty("requests")
List<JsonOLCandCreateRequest> requests;
@JsonCreator
@Builder
private JsonOLCandCreateBulkRequest(@JsonProperty("requests") @Singular final List<JsonOLCandCreateRequest> requests)
{
this.requests = ImmutableList.copyOf(requests);
}
public JsonOLCandCreateBulkRequest validate()
{
for (final JsonOLCandCreateRequest request : requests)
{
request.validate();
}
return this;
}
public JsonOLCandCreateBulkRequest withOrgSyncAdvise(@Nullable final SyncAdvise syncAdvise)
{
return syncAdvise != null
? map(request -> request.withOrgSyncAdvise(syncAdvise))
: this;
}
public JsonOLCandCreateBulkRequest withBPartnersSyncAdvise(@Nullable final SyncAdvise syncAdvise)
{
return syncAdvise != null
? map(request -> request.withBPartnersSyncAdvise(syncAdvise))
: this;
}
public JsonOLCandCreateBulkRequest withProductsSyncAdvise(@Nullable final SyncAdvise syncAdvise)
{
|
return syncAdvise != null
? map(request -> request.withProductsSyncAdvise(syncAdvise))
: this;
}
private JsonOLCandCreateBulkRequest map(@NonNull final UnaryOperator<JsonOLCandCreateRequest> mapper)
{
if (requests.isEmpty())
{
return this;
}
final ImmutableList<JsonOLCandCreateRequest> newRequests = this.requests.stream()
.map(mapper)
.collect(ImmutableList.toImmutableList());
return new JsonOLCandCreateBulkRequest(newRequests);
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-ordercandidates\src\main\java\de\metas\common\ordercandidates\v1\request\JsonOLCandCreateBulkRequest.java
| 2
|
请完成以下Java代码
|
public class Person {
Person() {
}
/**
* Also, check the {@link #move() Move} method for more movement details.
*/
public void walk() {
}
/**
* Check this {@link #move(String) Move} method for direction oriented movement.
*/
public void move() {
}
public void move(String direction) {
}
/**
* Additionally, check this {@link Animal#run(String) Run} method for direction based run.
*/
|
public void run() {
}
/**
* Also consider checking {@link com.baeldung.vehicle.Vehicle#Vehicle() Vehicle} constructor to initialize vehicle object.
*/
public void goToWork() {
}
/**
* Have a look at {@link Car#getNumberOfSeats() SeatsAvailability} method for checking the available seats needed for driving.
*/
public void drive() {
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-4\src\main\java\com\baeldung\javadocmemberreference\Person.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getProductNo(@NonNull final ProductId productId)
{
return getProductInfo(productId).getProductNo();
}
@Override
public Optional<GS1ProductCodes> getGS1ProductCodes(@NonNull final ProductId productId, @Nullable final BPartnerId customerId)
{
return getProductInfo(productId).getGs1ProductCodes().getEffectiveCodes(customerId);
}
@Override
public ProductCategoryId getProductCategoryId(@NonNull final ProductId productId)
{
return getProductInfo(productId).getProductCategoryId();
}
@Override
public ITranslatableString getProductName(@NonNull final ProductId productId)
{
return getProductInfo(productId).getName();
}
private ProductInfo getProductInfo(@NonNull final ProductId productId)
{
return productInfoCache.computeIfAbsent(productId, productService::getById);
}
@Override
public HUPIItemProduct getPackingInfo(@NonNull final HUPIItemProductId huPIItemProductId)
{
return huService.getPackingInfo(huPIItemProductId);
}
@Override
|
public String getPICaption(@NonNull final HuPackingInstructionsId piId)
{
return huService.getPI(piId).getName();
}
@Override
public String getLocatorName(@NonNull final LocatorId locatorId)
{
return locatorNamesCache.computeIfAbsent(locatorId, warehouseService::getLocatorNameById);
}
@Override
public HUQRCode getQRCodeByHUId(final HuId huId)
{
return huService.getQRCodeByHuId(huId);
}
@Override
public ScheduledPackageableLocks getLocks(final ShipmentScheduleAndJobScheduleIdSet scheduleIds)
{
return pickingJobLockService.getLocks(scheduleIds);
}
@Override
public int getSalesOrderLineSeqNo(@NonNull final OrderAndLineId orderAndLineId)
{
return orderService.getSalesOrderLineSeqNo(orderAndLineId);
}
//
//
//
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\repository\DefaultPickingJobLoaderSupportingServices.java
| 2
|
请完成以下Java代码
|
public String getToken() {
return this.token;
}
/**
* Returns the token type hint.
* @return the token type hint
*/
@Nullable
public String getTokenTypeHint() {
return this.tokenTypeHint;
}
/**
* Returns the additional parameters.
|
* @return the additional parameters
*/
public Map<String, Object> getAdditionalParameters() {
return this.additionalParameters;
}
/**
* Returns the token claims.
* @return the {@link OAuth2TokenIntrospection}
*/
public OAuth2TokenIntrospection getTokenClaims() {
return this.tokenClaims;
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2TokenIntrospectionAuthenticationToken.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
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 <V, ET extends IExpression<? extends V>> void registerGenericCompiler(final Class<ET> expressionType, final IExpressionCompiler<V, ?> compiler)
{
Check.assumeNotNull(expressionType, "Parameter expressionType is not null");
Check.assumeNotNull(compiler, "compiler not null");
compilers.put(expressionType, compiler);
}
@Override
public <V, ET extends IExpression<V>, CT extends IExpressionCompiler<V, ET>> CT getCompiler(final Class<ET> expressionType)
{
// Look for the particular compiler
final Object compilerObj = compilers.get(expressionType);
// No compiler found => fail
if (compilerObj == null)
{
throw new ExpressionCompileException("No compiler found for expressionType=" + expressionType
+ "\n Available compilers are: " + compilers.keySet());
}
// Assume this is always correct because we enforce the type when we add to map
@SuppressWarnings("unchecked")
final CT compiler = (CT)compilerObj;
return compiler;
}
@Override
public <V, ET extends IExpression<V>> ET compile(final String expressionStr, final Class<ET> expressionType)
{
final IExpressionCompiler<V, ET> compiler = getCompiler(expressionType);
return compiler.compile(ExpressionContext.EMPTY, expressionStr);
}
|
@Override
public <V, ET extends IExpression<V>> ET compileOrDefault(final String expressionStr, final ET defaultExpr, final Class<ET> expressionType)
{
if (Check.isEmpty(expressionStr, true))
{
return defaultExpr;
}
try
{
return compile(expressionStr, expressionType);
}
catch (final Exception e)
{
logger.warn(e.getLocalizedMessage(), e);
return defaultExpr;
}
}
@Override
public <V, ET extends IExpression<V>> ET compile(final String expressionStr, final Class<ET> expressionType, final ExpressionContext context)
{
final IExpressionCompiler<V, ET> compiler = getCompiler(expressionType);
return compiler.compile(context, expressionStr);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\ExpressionFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public IntegrationFlow receiveText() {
return IntegrationFlow.from(receiveTextChannel)
.channel(splitWordsChannel)
.get();
}
@Bean
public IntegrationFlow splitWords() {
return IntegrationFlow.from(splitWordsChannel)
.transform(splitWordsFunction)
.channel(toLowerCaseChannel)
.get();
}
@Bean
public IntegrationFlow toLowerCase() {
return IntegrationFlow.from(toLowerCaseChannel)
|
.split()
.transform(toLowerCase)
.aggregate(aggregatorSpec -> aggregatorSpec.releaseStrategy(listSizeReached)
.outputProcessor(buildMessageWithListPayload))
.channel(countWordsChannel)
.get();
}
@Bean
public IntegrationFlow countWords() {
return IntegrationFlow.from(countWordsChannel)
.transform(convertArrayListToCountMap)
.channel(returnResponseChannel)
.get();
}
}
|
repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\seda\springintegration\IntegrationConfiguration.java
| 2
|
请完成以下Java代码
|
public void warnResetToBuiltinCode(Integer builtinCode, int initialCode) {
logWarn("049", "You are trying to override the built-in code {} with {}. "
+ "Falling back to built-in code. If you want to override built-in error codes, "
+ "please disable the built-in error code provider.", builtinCode, initialCode);
}
public ProcessEngineException exceptionSettingJobRetriesAsyncNoJobsSpecified() {
return new ProcessEngineException(exceptionMessage(
"050",
"You must specify at least one of jobIds or jobQuery."));
}
public ProcessEngineException exceptionSettingJobRetriesAsyncNoProcessesSpecified() {
return new ProcessEngineException(exceptionMessage(
"051",
"You must specify at least one of or one of processInstanceIds, processInstanceQuery, or historicProcessInstanceQuery."));
}
public ProcessEngineException exceptionSettingJobRetriesJobsNotSpecifiedCorrectly() {
return new ProcessEngineException(exceptionMessage(
"052",
"You must specify exactly one of jobId, jobIds or jobDefinitionId as parameter. The parameter can not be null."));
}
public ProcessEngineException exceptionNoJobFoundForId(String jobId) {
|
return new ProcessEngineException(exceptionMessage(
"053",
"No job found with id '{}'.'", jobId));
}
public ProcessEngineException exceptionJobRetriesMustNotBeNegative(Integer retries) {
return new ProcessEngineException(exceptionMessage(
"054",
"The number of job retries must be a non-negative Integer, but '{}' has been provided.", retries));
}
public ProcessEngineException exceptionWhileRetrievingDiagnosticsDataRegistryNull() {
return new ProcessEngineException(
exceptionMessage("055", "Error while retrieving diagnostics data. Diagnostics registry was not initialized."));
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\CommandLogger.java
| 1
|
请完成以下Java代码
|
protected void applyFilters(EventSubscriptionQuery query) {
if (eventSubscriptionId != null) {
query.eventSubscriptionId(eventSubscriptionId);
}
if (eventName != null) {
query.eventName(eventName);
}
if (eventType != null) {
query.eventType(eventType);
}
if (executionId != null) {
query.executionId(executionId);
}
if (processInstanceId != null) {
query.processInstanceId(processInstanceId);
}
if (activityId != null) {
query.activityId(activityId);
}
if (tenantIdIn != null && !tenantIdIn.isEmpty()) {
query.tenantIdIn(tenantIdIn.toArray(new String[tenantIdIn.size()]));
|
}
if (TRUE.equals(withoutTenantId)) {
query.withoutTenantId();
}
if (TRUE.equals(includeEventSubscriptionsWithoutTenantId)) {
query.includeEventSubscriptionsWithoutTenantId();
}
}
@Override
protected void applySortBy(EventSubscriptionQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_CREATED)) {
query.orderByCreated();
} else if (sortBy.equals(SORT_BY_TENANT_ID)) {
query.orderByTenantId();
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\EventSubscriptionQueryDto.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static void createWorkpackage(@NonNull final BPartnerStatisticsUpdateRequest request)
{
for (final int bpartnerId : request.getBpartnerIds())
{
SCHEDULER.schedule(BPartnerToUpdate.builder()
.bpartnerId(bpartnerId)
.alsoResetCreditStatusFromBPGroup(request.isAlsoResetCreditStatusFromBPGroup())
.build());
}
}
@Builder
@Value
private static final class BPartnerToUpdate
{
private final int bpartnerId;
private final boolean alsoResetCreditStatusFromBPGroup;
}
private static final WorkpackagesOnCommitSchedulerTemplate<BPartnerToUpdate> SCHEDULER = new WorkpackagesOnCommitSchedulerTemplate<BPartnerToUpdate>(C_BPartner_UpdateStatsFromBPartner.class)
{
@Override
protected Properties extractCtxFromItem(final BPartnerToUpdate item)
{
return Env.getCtx();
}
@Override
protected String extractTrxNameFromItem(final BPartnerToUpdate item)
{
return ITrx.TRXNAME_ThreadInherited;
}
@Override
protected Object extractModelToEnqueueFromItem(final Collector collector, final BPartnerToUpdate item)
{
|
return TableRecordReference.of(I_C_BPartner.Table_Name, item.getBpartnerId());
}
@Override
protected Map<String, Object> extractParametersFromItem(BPartnerToUpdate item)
{
return ImmutableMap.of(PARAM_ALSO_RESET_CREDITSTATUS_FROM_BP_GROUP, item.isAlsoResetCreditStatusFromBPGroup());
}
};
@Override
public Result processWorkPackage(final I_C_Queue_WorkPackage workpackage, final String localTrxName)
{
// Services
final IBPartnerStatsDAO bpartnerStatsDAO = Services.get(IBPartnerStatsDAO.class);
final List<I_C_BPartner> bpartners = retrieveAllItems(I_C_BPartner.class);
final boolean alsoSetCreditStatusBaseOnBPGroup = getParameters().getParameterAsBool(PARAM_ALSO_RESET_CREDITSTATUS_FROM_BP_GROUP);
for (final I_C_BPartner bpartner : bpartners)
{
if (alsoSetCreditStatusBaseOnBPGroup)
{
Services.get(IBPartnerStatsBL.class).resetCreditStatusFromBPGroup(bpartner);
}
final BPartnerStats stats = Services.get(IBPartnerStatsDAO.class).getCreateBPartnerStats(bpartner);
bpartnerStatsDAO.updateBPartnerStatistics(stats);
}
return Result.SUCCESS;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\bpartner\service\async\spi\impl\C_BPartner_UpdateStatsFromBPartner.java
| 2
|
请完成以下Java代码
|
public void setAD_UserGroup_ID (int AD_UserGroup_ID)
{
if (AD_UserGroup_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_UserGroup_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_UserGroup_ID, Integer.valueOf(AD_UserGroup_ID));
}
/** Get Users Group.
@return Users Group */
@Override
public int getAD_UserGroup_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_UserGroup_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Users Group User Assignment.
@param AD_UserGroup_User_Assign_ID Users Group User Assignment */
@Override
public void setAD_UserGroup_User_Assign_ID (int AD_UserGroup_User_Assign_ID)
{
if (AD_UserGroup_User_Assign_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_UserGroup_User_Assign_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_UserGroup_User_Assign_ID, Integer.valueOf(AD_UserGroup_User_Assign_ID));
}
/** Get Users Group User Assignment.
@return Users Group User Assignment */
@Override
public int getAD_UserGroup_User_Assign_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_UserGroup_User_Assign_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Gültig ab.
@param ValidFrom
Gültig ab inklusiv (erster Tag)
*/
@Override
|
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Gültig ab inklusiv (erster Tag)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Gültig bis.
@param ValidTo
Gültig bis inklusiv (letzter Tag)
*/
@Override
public void setValidTo (java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Gültig bis.
@return Gültig bis inklusiv (letzter Tag)
*/
@Override
public java.sql.Timestamp getValidTo ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserGroup_User_Assign.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ApiResponse
{
int statusCode;
@Nullable HttpHeaders httpHeaders;
@Nullable MediaType contentType;
@NonNull @Builder.Default Charset charset = StandardCharsets.UTF_8;
@Nullable Object body;
public static ApiResponse ofException(final Throwable throwable, final String adLanguage)
{
return ApiResponse.builder()
.statusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
.contentType(MediaType.APPLICATION_JSON)
.body(JsonErrors.ofThrowable(throwable, adLanguage))
.build();
}
public boolean hasStatus2xx()
{
return getStatusCode() / 100 == HttpStatus.OK.series().value();
}
public boolean isJson()
{
return contentType != null && contentType.includes(MediaType.APPLICATION_JSON);
}
public String getBodyAsString()
{
if (body == null)
{
return null;
}
else if (isJson())
{
try
{
|
return JsonObjectMapperHolder.sharedJsonObjectMapper().writeValueAsString(body);
}
catch (JsonProcessingException e)
{
throw AdempiereException.wrapIfNeeded(e);
}
}
else if (body instanceof String)
{
return (String)body;
}
else if (body instanceof byte[])
{
return new String((byte[])body, charset);
}
else
{
return body.toString();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\audit\dto\ApiResponse.java
| 2
|
请完成以下Java代码
|
public void put(@NonNull final IView view)
{
views.put(view.getViewId(), view);
}
@Nullable
@Override
public IView getByIdOrNull(@NonNull final ViewId viewId)
{
return views.getIfPresent(viewId);
}
@Override
public void closeById(@NonNull final ViewId viewId, @NonNull final ViewCloseAction closeAction)
{
// Don't remove the view if not allowed.
// Will be removed when it will expire.
final IView view = views.getIfPresent(viewId);
if (view == null || !view.isAllowClosingPerUserRequest())
{
return;
}
//
// Notify the view that the user requested to be closed
// IMPORTANT: fire this event before removing the view from storage.
view.close(closeAction);
//
// Remove the view from storage
// => will fire #onViewRemoved
views.invalidate(viewId);
views.cleanUp(); // also cleanup to prevent views cache to grow.
}
private void onViewRemoved(final RemovalNotification<Object, Object> notification)
{
final IView view = (IView)notification.getValue();
logger.debug("View `{}` removed from cache. Cause: {}", view.getViewId(), notification.getCause());
view.afterDestroy();
|
}
@Override
public void invalidateView(final ViewId viewId)
{
final IView view = getByIdOrNull(viewId);
if (view == null)
{
return;
}
view.invalidateAll();
ViewChangesCollector.getCurrentOrAutoflush()
.collectFullyChanged(view);
}
@Override
public Stream<IView> streamAllViews()
{
return views.asMap().values().stream();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\DefaultViewsRepositoryStorage.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return MoreObjects.toStringHelper(this)
.addValue(tabCallout)
.toString();
}
protected final void handleException(final String methodName, final ICalloutRecord calloutRecord, final Exception e)
{
logger.warn("{}'s {} failed but ignored for {}", tabCallout, methodName, calloutRecord, e);
}
@Override
public void onIgnore(final ICalloutRecord calloutRecord)
{
try
{
tabCallout.onIgnore(calloutRecord);
}
catch (final Exception e)
{
handleException("onIgnore", calloutRecord, e);
}
}
@Override
public void onNew(final ICalloutRecord calloutRecord)
{
try
{
tabCallout.onNew(calloutRecord);
}
catch (final Exception e)
{
handleException("onNew", calloutRecord, e);
}
}
@Override
public void onSave(final ICalloutRecord calloutRecord)
{
try
{
tabCallout.onSave(calloutRecord);
}
catch (final Exception e)
{
handleException("onSave", calloutRecord, e);
}
}
@Override
public void onDelete(final ICalloutRecord calloutRecord)
{
try
{
tabCallout.onDelete(calloutRecord);
}
catch (final Exception e)
{
handleException("onDelete", calloutRecord, e);
}
}
|
@Override
public void onRefresh(final ICalloutRecord calloutRecord)
{
try
{
tabCallout.onRefresh(calloutRecord);
}
catch (final Exception e)
{
handleException("onRefresh", calloutRecord, e);
}
}
@Override
public void onRefreshAll(final ICalloutRecord calloutRecord)
{
try
{
tabCallout.onRefreshAll(calloutRecord);
}
catch (final Exception e)
{
handleException("onRefreshAll", calloutRecord, e);
}
}
@Override
public void onAfterQuery(final ICalloutRecord calloutRecord)
{
try
{
tabCallout.onAfterQuery(calloutRecord);
}
catch (final Exception e)
{
handleException("onAfterQuery", calloutRecord, e);
}
}
private static final class StatefulExceptionHandledTabCallout extends ExceptionHandledTabCallout implements IStatefulTabCallout
{
private StatefulExceptionHandledTabCallout(final IStatefulTabCallout tabCallout)
{
super(tabCallout);
}
@Override
public void onInit(final ICalloutRecord calloutRecord)
{
try
{
((IStatefulTabCallout)tabCallout).onInit(calloutRecord);
}
catch (final Exception e)
{
handleException("onInit", calloutRecord, e);
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\ui\spi\ExceptionHandledTabCallout.java
| 1
|
请完成以下Java代码
|
protected String doIt()
{
// NOTE: we need to clone the context which is passed to the other thread because else context (in ZK is enhanced) will be lost when this thread will end
// and as a result we will create entries with AD_Client_ID/AD_Org_ID=0
final Properties ctxToUse = (Properties)getCtx().clone();
final List<IPrintingQueueSource> sources = createPrintingQueueSources(ctxToUse);
for (final IPrintingQueueSource source : sources)
{
try
{
final ContextForAsyncProcessing printJobContext = ContextForAsyncProcessing.builder()
.adPInstanceId(getPinstanceId())
.build();
printOutputFacade.print(source,printJobContext);
}
catch (final RuntimeException ex)
{
Loggables.withLogger(logger, Level.WARN).addLog("Failed creating print job for IPrintingQueueSource={}; exception={}", source, ex);
throw ex;
}
}
return MSG_OK;
}
// each one with their own users to print user to print
|
protected List<IPrintingQueueSource> createPrintingQueueSources(final Properties ctxToUse)
{
// NOTE: we create the selection out of transaction because methods which are polling the printing queue are working out of transaction
final int selectionLength = createSelection();
if (selectionLength <= 0)
{
throw new AdempiereException("@" + MSG_INVOICE_GENERATE_NO_PRINTING_QUEUE_0P + "@");
}
final IPrintingQueueBL printingQueueBL = Services.get(IPrintingQueueBL.class);
final IPrintingQueueQuery query = printingQueueBL.createPrintingQueueQuery();
query.setFilterByProcessedQueueItems(false);
query.setOnlyAD_PInstance_ID(getPinstanceId());
return printingQueueBL.createPrintingQueueSources(ctxToUse, query);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\process\AbstractPrintJobCreate.java
| 1
|
请完成以下Java代码
|
private static String type(Resource resource) {
String ext = StringUtils.getFilenameExtension(resource.getFilename());
return (ext != null) ? ext : "jks";
}
public KeyStoreKeyFactory(Resource resource, char[] password, String type) {
this.resource = resource;
this.password = password;
this.type = type;
}
public KeyPair getKeyPair(String alias) {
return getKeyPair(alias, this.password);
}
public KeyPair getKeyPair(String alias, char[] password) {
try {
synchronized (this.lock) {
if (this.store == null) {
synchronized (this.lock) {
this.store = KeyStore.getInstance(this.type);
try (InputStream stream = this.resource.getInputStream()) {
this.store.load(stream, this.password);
}
}
}
}
RSAPrivateCrtKey key = (RSAPrivateCrtKey) this.store.getKey(alias, password);
Certificate certificate = this.store.getCertificate(alias);
PublicKey publicKey = null;
|
if (certificate != null) {
publicKey = certificate.getPublicKey();
}
else if (key != null) {
RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());
publicKey = KeyFactory.getInstance("RSA").generatePublic(spec);
}
return new KeyPair(publicKey, key);
}
catch (Exception ex) {
throw new IllegalStateException("Cannot load keys from store: " + this.resource, ex);
}
}
}
|
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\encrypt\KeyStoreKeyFactory.java
| 1
|
请完成以下Java代码
|
public class CDLDemo {
public static void main(String[] args) {
System.out.println("8.1. Producing JSONArray Directly from Comma Delimited Text: ");
jsonArrayFromCDT();
System.out.println("\n8.2. Producing Comma Delimited Text from JSONArray: ");
cDTfromJSONArray();
System.out.println("\n8.3.1. Producing JSONArray of JSONObjects Using Comma Delimited Text: ");
jaOfJOFromCDT2();
System.out.println("\n8.3.2. Producing JSONArray of JSONObjects Using Comma Delimited Text: ");
jaOfJOFromCDT2();
}
public static void jsonArrayFromCDT() {
JSONArray ja = CDL.rowToJSONArray(new JSONTokener("England, USA, Canada"));
System.out.println(ja);
}
public static void cDTfromJSONArray() {
JSONArray ja = new JSONArray("[\"England\",\"USA\",\"Canada\"]");
String cdt = CDL.rowToString(ja);
System.out.println(cdt);
}
|
public static void jaOfJOFromCDT() {
String string =
"name, city, age \n" +
"john, chicago, 22 \n" +
"gary, florida, 35 \n" +
"sal, vegas, 18";
JSONArray result = CDL.toJSONArray(string);
System.out.println(result.toString());
}
public static void jaOfJOFromCDT2() {
JSONArray ja = new JSONArray();
ja.put("name");
ja.put("city");
ja.put("age");
String string =
"john, chicago, 22 \n" +
"gary, florida, 35 \n" +
"sal, vegas, 18";
JSONArray result = CDL.toJSONArray(ja, string);
System.out.println(result.toString());
}
}
|
repos\tutorials-master\json-modules\json\src\main\java\com\baeldung\jsonjava\CDLDemo.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void forceCompletionIfNotAlreadyCompleted()
{
if (checkIfBatchIsDone())
{
return;
}
this.completableFuture.completeExceptionally(new AdempiereException("Forced exceptionally complete!")
.appendParametersToMessage()
.setParameter("AsyncBatchId", batchId.getRepoId()));
}
private synchronized boolean checkIfBatchIsDone()
{
if (wpProgress == null || !isEnqueueingDone)
{
return false;
}
if (wpProgress.isProcessedSuccessfully())
{
Loggables.withLogger(logger, Level.INFO).addLog("AsyncBatchId={} completed successfully. ", batchId.getRepoId());
this.completableFuture.complete(null);
return true;
}
else if (wpProgress.isProcessedWithError())
{
this.completableFuture.completeExceptionally(new AdempiereException("WorkPackage completed with an exception")
.appendParametersToMessage()
.setParameter("AsyncBatchId", batchId.getRepoId()));
return true;
}
return false;
}
@NonNull
private static WorkPackagesProgress getWPsProgress(@NonNull final AsyncBatchNotifyRequest request)
{
return WorkPackagesProgress.builder()
.noOfProcessedWPs(request.getNoOfProcessedWPs())
.noOfEnqueuedWPs(request.getNoOfEnqueuedWPs())
.noOfErrorWPs(request.getNoOfErrorWPs())
.build();
}
private static class WorkPackagesProgress
{
@NonNull
Integer noOfEnqueuedWPs;
@NonNull
Integer noOfProcessedWPs;
@NonNull
Integer noOfErrorWPs;
@Builder
|
public WorkPackagesProgress(
@NonNull final Integer noOfEnqueuedWPs,
@Nullable final Integer noOfProcessedWPs,
@Nullable final Integer noOfErrorWPs)
{
this.noOfEnqueuedWPs = noOfEnqueuedWPs;
this.noOfProcessedWPs = CoalesceUtil.coalesceNotNull(noOfProcessedWPs, 0);
this.noOfErrorWPs = CoalesceUtil.coalesceNotNull(noOfErrorWPs, 0);
Check.assumeGreaterThanZero(noOfEnqueuedWPs, "noOfEnqueuedWPs");
Check.assumeGreaterOrEqualToZero(this.noOfProcessedWPs, this.noOfErrorWPs);
}
public boolean isProcessedSuccessfully()
{
return noOfErrorWPs == 0 && noOfProcessedWPs >= noOfEnqueuedWPs;
}
public boolean isProcessedWithError()
{
return noOfErrorWPs > 0 && (noOfProcessedWPs + noOfErrorWPs >= noOfEnqueuedWPs);
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\service\AsyncBatchObserver.java
| 2
|
请完成以下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 setPlannedAmt (final BigDecimal PlannedAmt)
{
set_Value (COLUMNNAME_PlannedAmt, PlannedAmt);
}
@Override
public BigDecimal getPlannedAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPlannedMarginAmt (final BigDecimal PlannedMarginAmt)
{
set_Value (COLUMNNAME_PlannedMarginAmt, PlannedMarginAmt);
}
@Override
public BigDecimal getPlannedMarginAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedMarginAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPlannedPrice (final BigDecimal PlannedPrice)
{
set_Value (COLUMNNAME_PlannedPrice, PlannedPrice);
|
}
@Override
public BigDecimal getPlannedPrice()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedPrice);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPlannedQty (final BigDecimal PlannedQty)
{
set_Value (COLUMNNAME_PlannedQty, PlannedQty);
}
@Override
public BigDecimal getPlannedQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedQty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ProjectLine.java
| 1
|
请完成以下Java代码
|
private static final class Constant extends LogicExpressionResult
{
private Constant(final boolean value)
{
super(null, value, value ? ConstantLogicExpression.TRUE : ConstantLogicExpression.FALSE, null);
}
@Override
public String toString()
{
return value ? "TRUE" : "FALSE";
}
}
private static final class NamedConstant extends LogicExpressionResult
{
private transient String _toString = null; // lazy
private NamedConstant(final String name, final boolean value)
{
super(name, value, value ? ConstantLogicExpression.TRUE : ConstantLogicExpression.FALSE, null);
}
|
@Override
public String toString()
{
if (_toString == null)
{
_toString = MoreObjects.toStringHelper(value ? "TRUE" : "FALSE")
.omitNullValues()
.addValue(name)
.toString();
}
return _toString;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\LogicExpressionResult.java
| 1
|
请完成以下Java代码
|
public int getOrderRepoId()
{
return orderId.getRepoId();
}
public int getOrderLineRepoId()
{
return orderLineId.getRepoId();
}
public static boolean equals(@Nullable final OrderAndLineId o1, @Nullable final OrderAndLineId o2)
{
return Objects.equals(o1, o2);
}
@JsonValue
public String toJson()
{
|
return orderId.getRepoId() + "_" + orderLineId.getRepoId();
}
@JsonCreator
public static OrderAndLineId ofJson(@NonNull String json)
{
try
{
final int idx = json.indexOf("_");
return ofRepoIds(Integer.parseInt(json.substring(0, idx)), Integer.parseInt(json.substring(idx + 1)));
}
catch (Exception ex)
{
throw new AdempiereException("Invalid JSON: " + json, ex);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderAndLineId.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getScopeType() {
return scopeType;
}
@Override
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
@Override
public String getSubScopeId() {
return subScopeId;
}
@Override
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
@Override
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
@Override
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
@Override
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
@Override
public String getMetaInfo() {
return metaInfo;
}
@Override
public void setMetaInfo(String metaInfo) {
this.metaInfo = metaInfo;
}
// The methods below are not relevant, as getValue() is used directly to return the value set during the transaction
@Override
public String getTextValue() {
return null;
}
@Override
public void setTextValue(String textValue) {
}
@Override
public String getTextValue2() {
return null;
}
@Override
public void setTextValue2(String textValue2) {
}
@Override
public Long getLongValue() {
return null;
}
@Override
public void setLongValue(Long longValue) {
|
}
@Override
public Double getDoubleValue() {
return null;
}
@Override
public void setDoubleValue(Double doubleValue) {
}
@Override
public byte[] getBytes() {
return null;
}
@Override
public void setBytes(byte[] bytes) {
}
@Override
public Object getCachedValue() {
return null;
}
@Override
public void setCachedValue(Object cachedValue) {
}
}
|
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\TransientVariableInstance.java
| 2
|
请完成以下Java代码
|
public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_User_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID));
}
/** Get User/Contact.
@return User within the system - Internal or Business Partner Contact
*/
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_CM_ChatType getCM_ChatType() throws RuntimeException
{
return (I_CM_ChatType)MTable.get(getCtx(), I_CM_ChatType.Table_Name)
.getPO(getCM_ChatType_ID(), get_TrxName()); }
/** Set Chat Type.
@param CM_ChatType_ID
Type of discussion / chat
*/
public void setCM_ChatType_ID (int CM_ChatType_ID)
{
if (CM_ChatType_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_ChatType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CM_ChatType_ID, Integer.valueOf(CM_ChatType_ID));
}
|
/** Get Chat Type.
@return Type of discussion / chat
*/
public int getCM_ChatType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_ChatType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Self-Service.
@param IsSelfService
This is a Self-Service entry or this entry can be changed via Self-Service
*/
public void setIsSelfService (boolean IsSelfService)
{
set_Value (COLUMNNAME_IsSelfService, Boolean.valueOf(IsSelfService));
}
/** Get Self-Service.
@return This is a Self-Service entry or this entry can be changed via Self-Service
*/
public boolean isSelfService ()
{
Object oo = get_Value(COLUMNNAME_IsSelfService);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_ChatTypeUpdate.java
| 1
|
请完成以下Java代码
|
public de.metas.payment.paypal.model.I_PayPal_Order getPayPal_Order()
{
return get_ValueAsPO(COLUMNNAME_PayPal_Order_ID, de.metas.payment.paypal.model.I_PayPal_Order.class);
}
@Override
public void setPayPal_Order(final de.metas.payment.paypal.model.I_PayPal_Order PayPal_Order)
{
set_ValueFromPO(COLUMNNAME_PayPal_Order_ID, de.metas.payment.paypal.model.I_PayPal_Order.class, PayPal_Order);
}
@Override
public void setPayPal_Order_ID (final int PayPal_Order_ID)
{
if (PayPal_Order_ID < 1)
set_Value (COLUMNNAME_PayPal_Order_ID, null);
else
set_Value (COLUMNNAME_PayPal_Order_ID, PayPal_Order_ID);
}
@Override
public int getPayPal_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_PayPal_Order_ID);
}
@Override
public void setRequestBody (final @Nullable java.lang.String RequestBody)
{
set_ValueNoCheck (COLUMNNAME_RequestBody, RequestBody);
}
@Override
public java.lang.String getRequestBody()
{
return get_ValueAsString(COLUMNNAME_RequestBody);
}
@Override
public void setRequestHeaders (final @Nullable java.lang.String RequestHeaders)
{
set_ValueNoCheck (COLUMNNAME_RequestHeaders, RequestHeaders);
}
@Override
public java.lang.String getRequestHeaders()
{
return get_ValueAsString(COLUMNNAME_RequestHeaders);
}
@Override
public void setRequestMethod (final @Nullable java.lang.String RequestMethod)
{
set_ValueNoCheck (COLUMNNAME_RequestMethod, RequestMethod);
}
@Override
public java.lang.String getRequestMethod()
{
return get_ValueAsString(COLUMNNAME_RequestMethod);
}
@Override
public void setRequestPath (final @Nullable java.lang.String RequestPath)
{
set_ValueNoCheck (COLUMNNAME_RequestPath, RequestPath);
}
@Override
public java.lang.String getRequestPath()
{
return get_ValueAsString(COLUMNNAME_RequestPath);
|
}
@Override
public void setResponseBody (final @Nullable java.lang.String ResponseBody)
{
set_ValueNoCheck (COLUMNNAME_ResponseBody, ResponseBody);
}
@Override
public java.lang.String getResponseBody()
{
return get_ValueAsString(COLUMNNAME_ResponseBody);
}
@Override
public void setResponseCode (final int ResponseCode)
{
set_ValueNoCheck (COLUMNNAME_ResponseCode, ResponseCode);
}
@Override
public int getResponseCode()
{
return get_ValueAsInt(COLUMNNAME_ResponseCode);
}
@Override
public void setResponseHeaders (final @Nullable java.lang.String ResponseHeaders)
{
set_ValueNoCheck (COLUMNNAME_ResponseHeaders, ResponseHeaders);
}
@Override
public java.lang.String getResponseHeaders()
{
return get_ValueAsString(COLUMNNAME_ResponseHeaders);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java-gen\de\metas\payment\paypal\model\X_PayPal_Log.java
| 1
|
请完成以下Java代码
|
private static byte[] encrypt(byte[] text, PublicKey key, RsaAlgorithm alg, String salt, boolean gcm) {
byte[] random = KeyGenerators.secureRandom(16).generateKey();
BytesEncryptor aes = gcm ? Encryptors.stronger(new String(Hex.encode(random)), salt)
: Encryptors.standard(new String(Hex.encode(random)), salt);
try {
final Cipher cipher = Cipher.getInstance(alg.getJceName());
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] secret = cipher.doFinal(random);
ByteArrayOutputStream result = new ByteArrayOutputStream(text.length + 20);
writeInt(result, secret.length);
result.write(secret);
result.write(aes.encrypt(text));
return result.toByteArray();
}
catch (RuntimeException ex) {
throw ex;
}
catch (Exception ex) {
throw new IllegalStateException("Cannot encrypt", ex);
}
}
private static void writeInt(ByteArrayOutputStream result, int length) throws IOException {
byte[] data = new byte[2];
data[0] = (byte) ((length >> 8) & 0xFF);
data[1] = (byte) (length & 0xFF);
result.write(data);
}
private static int readInt(ByteArrayInputStream result) throws IOException {
byte[] b = new byte[2];
result.read(b);
return ((b[0] & 0xFF) << 8) | (b[1] & 0xFF);
}
private static byte[] decrypt(byte[] text, @Nullable PrivateKey key, RsaAlgorithm alg, String salt, boolean gcm) {
ByteArrayInputStream input = new ByteArrayInputStream(text);
ByteArrayOutputStream output = new ByteArrayOutputStream(text.length);
try {
int length = readInt(input);
byte[] random = new byte[length];
input.read(random);
final Cipher cipher = Cipher.getInstance(alg.getJceName());
cipher.init(Cipher.DECRYPT_MODE, key);
String secret = new String(Hex.encode(cipher.doFinal(random)));
byte[] buffer = new byte[text.length - random.length - 2];
input.read(buffer);
BytesEncryptor aes = gcm ? Encryptors.stronger(secret, salt) : Encryptors.standard(secret, salt);
output.write(aes.decrypt(buffer));
return output.toByteArray();
|
}
catch (RuntimeException ex) {
throw ex;
}
catch (Exception ex) {
throw new IllegalStateException("Cannot decrypt", ex);
}
}
private static boolean isHex(String input) {
try {
Hex.decode(input);
return true;
}
catch (Exception ex) {
return false;
}
}
public boolean canDecrypt() {
return this.privateKey != null;
}
}
|
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\encrypt\RsaSecretEncryptor.java
| 1
|
请完成以下Java代码
|
public class PageLink {
protected static final String DEFAULT_SORT_PROPERTY = "id";
private static final Sort DEFAULT_SORT = Sort.by(Sort.Direction.ASC, DEFAULT_SORT_PROPERTY);
private final String textSearch;
private final int pageSize;
private final int page;
private final SortOrder sortOrder;
public PageLink(PageLink pageLink) {
this.pageSize = pageLink.getPageSize();
this.page = pageLink.getPage();
this.textSearch = pageLink.getTextSearch();
this.sortOrder = pageLink.getSortOrder();
}
public PageLink(int pageSize) {
this(pageSize, 0);
}
public PageLink(int pageSize, int page) {
this(pageSize, page, null, null);
}
public PageLink(int pageSize, int page, String textSearch) {
this(pageSize, page, textSearch, null);
}
public PageLink(int pageSize, int page, String textSearch, SortOrder sortOrder) {
this.pageSize = pageSize;
this.page = page;
this.textSearch = textSearch;
this.sortOrder = sortOrder;
}
@JsonIgnore
public PageLink nextPageLink() {
return new PageLink(this.pageSize, this.page + 1, this.textSearch, this.sortOrder);
}
public Sort toSort(SortOrder sortOrder, Map<String, String> columnMap, boolean addDefaultSorting) {
if (sortOrder == null) {
return DEFAULT_SORT;
} else {
return toSort(List.of(sortOrder), columnMap, addDefaultSorting);
}
|
}
public Sort toSort(List<SortOrder> sortOrders, Map<String, String> columnMap, boolean addDefaultSorting) {
if (addDefaultSorting && !isDefaultSortOrderAvailable(sortOrders)) {
sortOrders = new ArrayList<>(sortOrders);
sortOrders.add(new SortOrder(DEFAULT_SORT_PROPERTY, SortOrder.Direction.ASC));
}
return Sort.by(sortOrders.stream().map(s -> toSortOrder(s, columnMap)).collect(Collectors.toList()));
}
private Sort.Order toSortOrder(SortOrder sortOrder, Map<String, String> columnMap) {
String property = sortOrder.getProperty();
if (columnMap.containsKey(property)) {
property = columnMap.get(property);
}
return new Sort.Order(Sort.Direction.fromString(sortOrder.getDirection().name()), property);
}
public boolean isDefaultSortOrderAvailable(List<SortOrder> sortOrders) {
for (SortOrder sortOrder : sortOrders) {
if (DEFAULT_SORT_PROPERTY.equals(sortOrder.getProperty())) {
return true;
}
}
return false;
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\page\PageLink.java
| 1
|
请完成以下Java代码
|
public class EventDbSchemaManager extends EngineSqlScriptBasedDbSchemaManager {
protected static final String EVENTREGISTRY_DB_SCHEMA_LOCK_NAME = "eventRegistryDbSchemaLock";
protected static final Map<String, String> changeLogVersionMap = Map.ofEntries(
Map.entry("1", "6.5.0.6"),
Map.entry("2", "6.7.2.0"),
Map.entry("3", "6.7.2.0"),
Map.entry("4", "7.1.0.0"),
Map.entry("5", "7.1.0.0")
);
public EventDbSchemaManager() {
super("eventregistry", new EngineSchemaManagerLockConfiguration(CommandContextUtil::getEventRegistryConfiguration));
}
@Override
protected String getEngineVersion() {
return EventRegistryEngine.VERSION;
}
@Override
protected String getSchemaVersionPropertyName() {
return "eventregistry.schema.version";
}
@Override
protected String getDbSchemaLockName() {
return EVENTREGISTRY_DB_SCHEMA_LOCK_NAME;
}
@Override
protected String getEngineTableName() {
return "FLW_EVENT_DEFINITION";
}
@Override
protected String getChangeLogTableName() {
|
return "FLW_EV_DATABASECHANGELOG";
}
@Override
protected String getDbVersionForChangelogVersion(String changeLogVersion) {
if (StringUtils.isNotEmpty(changeLogVersion) && changeLogVersionMap.containsKey(changeLogVersion)) {
return changeLogVersionMap.get(changeLogVersion);
}
return "6.5.0.0";
}
@Override
protected String getResourcesRootDirectory() {
return "org/flowable/eventregistry/db/";
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\db\EventDbSchemaManager.java
| 1
|
请完成以下Java代码
|
public class ProcessStartingPointcutAdvisor implements PointcutAdvisor, Serializable {
/**
* annotations that shall be scanned
*/
private Set<Class<? extends Annotation>> annotations = new HashSet<Class<? extends Annotation>>(Arrays.asList(StartProcess.class));
/**
* the {@link org.aopalliance.intercept.MethodInterceptor} that handles launching the business process.
*/
protected MethodInterceptor advice;
/**
* matches any method containing the {@link StartProcess} annotation.
*/
protected Pointcut pointcut;
/**
* the injected reference to the {@link org.camunda.bpm.engine.ProcessEngine}
*/
protected ProcessEngine processEngine;
public ProcessStartingPointcutAdvisor(ProcessEngine pe) {
this.processEngine = pe;
this.pointcut = buildPointcut();
this.advice = buildAdvise();
}
protected MethodInterceptor buildAdvise() {
return new ProcessStartingMethodInterceptor(this.processEngine);
}
public Pointcut getPointcut() {
return pointcut;
}
public Advice getAdvice() {
return advice;
}
public boolean isPerInstance() {
|
return true;
}
private Pointcut buildPointcut() {
ComposablePointcut result = null;
for (Class<? extends Annotation> publisherAnnotationType : this.annotations) {
Pointcut mpc = new MetaAnnotationMatchingPointcut(null, publisherAnnotationType);
if (result == null) {
result = new ComposablePointcut(mpc);
} else {
result.union(mpc);
}
}
return result;
}
}
|
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\components\aop\ProcessStartingPointcutAdvisor.java
| 1
|
请完成以下Java代码
|
public class AppClusterClientStateWrapVO {
/**
* {ip}@{transport_command_port}.
*/
private String id;
private Integer commandPort;
private String ip;
private ClusterClientStateVO state;
public String getId() {
return id;
}
public AppClusterClientStateWrapVO setId(String id) {
this.id = id;
return this;
}
public String getIp() {
return ip;
}
public AppClusterClientStateWrapVO setIp(String ip) {
this.ip = ip;
return this;
}
public ClusterClientStateVO getState() {
return state;
}
|
public AppClusterClientStateWrapVO setState(ClusterClientStateVO state) {
this.state = state;
return this;
}
public Integer getCommandPort() {
return commandPort;
}
public AppClusterClientStateWrapVO setCommandPort(Integer commandPort) {
this.commandPort = commandPort;
return this;
}
@Override
public String toString() {
return "AppClusterClientStateWrapVO{" +
"id='" + id + '\'' +
", commandPort=" + commandPort +
", ip='" + ip + '\'' +
", state=" + state +
'}';
}
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\state\AppClusterClientStateWrapVO.java
| 1
|
请完成以下Java代码
|
default I_AD_Table retrieveTable(final int adTableId)
{
return retrieveTable(AdTableId.ofRepoId(adTableId));
}
/**
* Return the table with the given name. Use {@link org.compiere.model.MTable} under the hood,
* because tables are a bit sensitive and using the {@link org.adempiere.ad.dao.impl.QueryBL} and {@link org.adempiere.util.proxy.Cached} does not work under all circumstances.
*
* @param tableName can be case-insensitive
*/
I_AD_Table retrieveTable(String tableName);
I_AD_Table retrieveTableOrNull(String tableName);
/**
* Retrieve all the columns of the given table
*/
List<I_AD_Column> retrieveColumnsForTable(I_AD_Table table);
/**
* Retrieve the AD_DocumentTable_Template table for the context of the given targetTable.
* This table contains all the dolumns that are supposed to belong in a table that is a document.
* The table name of this template is defined in the {@link de.metas.document.DocumentConstants}
*
* @return the Table Document Template
*/
I_AD_Table retrieveDocumentTableTemplate(I_AD_Table targetTable);
|
boolean isStandardColumn(String columnName);
Set<String> getTableNamesWithRemoteCacheInvalidation();
int getTypeaheadMinLength(String tableName);
List<I_AD_Table> retrieveAllImportTables();
List<ColumnSqlSourceDescriptor> retrieveColumnSqlSourceDescriptors();
void validate(I_AD_SQLColumn_SourceTableColumn record);
@NonNull TooltipType getTooltipTypeByTableName(@NonNull String tableName);
MinimalColumnInfo getMinimalColumnInfo(@NonNull String tableName, @NonNull String columnName);
MinimalColumnInfo getMinimalColumnInfo(@NonNull AdColumnId adColumnId);
ImmutableList<MinimalColumnInfo> getMinimalColumnInfosByIds(@NonNull Collection<AdColumnId> adColumnIds);
void updateColumnNameByAdElementId(
@NonNull AdElementId adElementId,
@Nullable String newColumnName);
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\api\IADTableDAO.java
| 1
|
请完成以下Java代码
|
public void contentsChanged(final ListDataEvent e)
{
logger.warn("Changing the content is not synchronized: " + e);
}
};
private final PropertyChangeListener groupPanelChangedListener = new PropertyChangeListener()
{
@Override
public void propertyChange(PropertyChangeEvent evt)
{
refreshUI();
}
};
public SideActionsGroupsListPanel()
{
super();
contentPanel = new JXTaskPaneContainer();
contentPanel.setScrollableWidthHint(ScrollableSizeHint.FIT);
contentPanel.setOpaque(false);
final JScrollPane contentPaneScroll = new JScrollPane();
contentPaneScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
contentPaneScroll.getViewport().add(contentPanel);
contentPaneScroll.setOpaque(false);
setLayout(new BorderLayout());
this.add(contentPaneScroll, BorderLayout.CENTER);
this.setOpaque(false);
refreshUI();
}
public void setModel(final ISideActionsGroupsListModel model)
{
if (this.model == model)
{
return;
}
if (this.model != null)
{
model.getGroups().removeListDataListener(groupsListModelListener);
}
this.model = model;
renderAll();
if (this.model != null)
{
model.getGroups().addListDataListener(groupsListModelListener);
}
}
private void renderAll()
{
final ListModel<ISideActionsGroupModel> groups = model.getGroups();
for (int i = 0; i < groups.getSize(); i++)
{
final ISideActionsGroupModel group = groups.getElementAt(i);
final SideActionsGroupPanel groupComp = createGroupComponent(group);
contentPanel.add(groupComp);
}
refreshUI();
}
|
private final SideActionsGroupPanel createGroupComponent(final ISideActionsGroupModel group)
{
final SideActionsGroupPanel groupComp = new SideActionsGroupPanel();
groupComp.setModel(group);
groupComp.addPropertyChangeListener(SideActionsGroupPanel.PROPERTY_Visible, groupPanelChangedListener);
return groupComp;
}
private void destroyGroupComponent(final SideActionsGroupPanel groupComp)
{
groupComp.removePropertyChangeListener(SideActionsGroupPanel.PROPERTY_Visible, groupPanelChangedListener);
}
protected void refreshUI()
{
autoHideIfNeeded();
contentPanel.revalidate();
}
/**
* Auto-hide if no groups or groups are not visible
*/
private final void autoHideIfNeeded()
{
boolean haveVisibleGroups = false;
for (Component groupComp : contentPanel.getComponents())
{
if (groupComp.isVisible())
{
haveVisibleGroups = true;
break;
}
}
setVisible(haveVisibleGroups);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\sideactions\swing\SideActionsGroupsListPanel.java
| 1
|
请完成以下Java代码
|
public void setC_SubscrDiscount_ID (final int C_SubscrDiscount_ID)
{
if (C_SubscrDiscount_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_SubscrDiscount_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_SubscrDiscount_ID, C_SubscrDiscount_ID);
}
@Override
public int getC_SubscrDiscount_ID()
{
return get_ValueAsInt(COLUMNNAME_C_SubscrDiscount_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
|
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void 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.contracts\src\main\java-gen\de\metas\contracts\model\X_C_SubscrDiscount.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CacheLabel
{
public static final String NO_TABLENAME_PREFIX = "$NoTableName$";
@NonNull String name;
private CacheLabel(@NonNull final String name)
{
this.name = name;
}
public static CacheLabel ofTableName(@NonNull final String tableName)
{
return new CacheLabel(tableName);
}
public static CacheLabel ofString(@NonNull final String string)
{
return new CacheLabel(string);
}
|
@Override
@Deprecated
public String toString() {return getName();}
public boolean equalsByName(@Nullable final String otherName)
{
return this.name.equals(otherName);
}
public boolean isApplicationDictionaryTableName()
{
return name.startsWith("AD_");
}
public boolean containsNoTableNameMarker()
{
return name.contains(NO_TABLENAME_PREFIX);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CacheLabel.java
| 2
|
请完成以下Java代码
|
public class DocumentationImpl extends CmmnModelElementInstanceImpl implements Documentation {
protected static Attribute<String> idAttribute;
protected static Attribute<String> textFormatAttribute;
public DocumentationImpl(ModelTypeInstanceContext context) {
super(context);
}
public String getId() {
return idAttribute.getValue(this);
}
public void setId(String id) {
idAttribute.setValue(this, id);
}
public String getTextFormat() {
return textFormatAttribute.getValue(this);
}
public void setTextFormat(String textFormat) {
textFormatAttribute.setValue(this, textFormat);
}
|
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Documentation.class, CMMN_ELEMENT_DOCUMENTATION)
.namespaceUri(CMMN11_NS)
.instanceProvider(new ModelTypeInstanceProvider<Documentation>() {
public Documentation newInstance(ModelTypeInstanceContext instanceContext) {
return new DocumentationImpl(instanceContext);
}
});
idAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_ID)
.idAttribute()
.build();
textFormatAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_TEXT_FORMAT)
.defaultValue("text/plain")
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\DocumentationImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void doFetchAlarmCount() {
result = (int) alarmService.countAlarmsByQuery(getTenantId(), getCustomerId(), query, entitiesIds);
sendWsMsg(new AlarmCountUpdate(cmdId, result));
}
private EntityDataQuery buildEntityDataQuery() {
EntityDataPageLink edpl = new EntityDataPageLink(maxEntitiesPerAlarmSubscription, 0, null,
new EntityDataSortOrder(new EntityKey(EntityKeyType.ENTITY_FIELD, ModelConstants.CREATED_TIME_PROPERTY)));
return new EntityDataQuery(query.getEntityFilter(), edpl, null, null, query.getKeyFilters());
}
private void resetInvocationCounter() {
alarmCountInvocationAttempts = 0;
}
public void createAlarmSubscriptions() {
for (EntityId entityId : entitiesIds) {
createAlarmSubscriptionForEntity(entityId);
}
}
private void createAlarmSubscriptionForEntity(EntityId entityId) {
int subIdx = sessionRef.getSessionSubIdSeq().incrementAndGet();
subToEntityIdMap.put(subIdx, entityId);
log.trace("[{}][{}][{}] Creating alarms subscription for [{}] ", serviceId, cmdId, subIdx, entityId);
TbAlarmsSubscription subscription = TbAlarmsSubscription.builder()
.serviceId(serviceId)
.sessionId(sessionRef.getSessionId())
.subscriptionId(subIdx)
|
.tenantId(sessionRef.getSecurityCtx().getTenantId())
.entityId(entityId)
.updateProcessor((sub, update) -> fetchAlarmCount())
.build();
localSubscriptionService.addSubscription(subscription, sessionRef);
}
public void clearAlarmSubscriptions() {
if (subToEntityIdMap != null) {
for (Integer subId : subToEntityIdMap.keySet()) {
localSubscriptionService.cancelSubscription(getTenantId(), getSessionId(), subId);
}
subToEntityIdMap.clear();
}
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\subscription\TbAlarmCountSubCtx.java
| 2
|
请完成以下Java代码
|
protected void removeElementProperty(String id, String propertyName, ObjectNode infoNode) {
ObjectNode bpmnNode = createOrGetBpmnNode(infoNode);
if (bpmnNode.has(id)) {
ObjectNode activityNode = (ObjectNode) bpmnNode.get(id);
if (activityNode.has(propertyName)) {
activityNode.remove(propertyName);
}
}
}
protected ObjectNode createOrGetBpmnNode(ObjectNode infoNode) {
if (!infoNode.has(BPMN_NODE)) {
infoNode.putObject(BPMN_NODE);
}
return (ObjectNode) infoNode.get(BPMN_NODE);
}
protected ObjectNode getBpmnNode(ObjectNode infoNode) {
return (ObjectNode) infoNode.get(BPMN_NODE);
}
protected void setLocalizationProperty(String language, String id, String propertyName, String propertyValue, ObjectNode infoNode) {
ObjectNode localizationNode = createOrGetLocalizationNode(infoNode);
if (!localizationNode.has(language)) {
localizationNode.putObject(language);
}
ObjectNode languageNode = (ObjectNode) localizationNode.get(language);
if (!languageNode.has(id)) {
languageNode.putObject(id);
|
}
((ObjectNode) languageNode.get(id)).put(propertyName, propertyValue);
}
protected ObjectNode createOrGetLocalizationNode(ObjectNode infoNode) {
if (!infoNode.has(LOCALIZATION_NODE)) {
infoNode.putObject(LOCALIZATION_NODE);
}
return (ObjectNode) infoNode.get(LOCALIZATION_NODE);
}
protected ObjectNode getLocalizationNode(ObjectNode infoNode) {
return (ObjectNode) infoNode.get(LOCALIZATION_NODE);
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\DynamicBpmnServiceImpl.java
| 1
|
请完成以下Java代码
|
public String route(int jobId, List<String> addressList) {
// cache clear
if (System.currentTimeMillis() > CACHE_VALID_TIME) {
jobLfuMap.clear();
CACHE_VALID_TIME = System.currentTimeMillis() + 1000*60*60*24;
}
// lfu item init
HashMap<String, Integer> lfuItemMap = jobLfuMap.get(jobId); // Key排序可以用TreeMap+构造入参Compare;Value排序暂时只能通过ArrayList;
if (lfuItemMap == null) {
lfuItemMap = new HashMap<String, Integer>();
jobLfuMap.putIfAbsent(jobId, lfuItemMap); // 避免重复覆盖
}
// put new
for (String address: addressList) {
if (!lfuItemMap.containsKey(address) || lfuItemMap.get(address) >1000000 ) {
lfuItemMap.put(address, new Random().nextInt(addressList.size())); // 初始化时主动Random一次,缓解首次压力
}
}
// remove old
List<String> delKeys = new ArrayList<>();
for (String existKey: lfuItemMap.keySet()) {
if (!addressList.contains(existKey)) {
delKeys.add(existKey);
}
}
if (delKeys.size() > 0) {
for (String delKey: delKeys) {
lfuItemMap.remove(delKey);
}
}
// load least userd count address
List<Map.Entry<String, Integer>> lfuItemList = new ArrayList<Map.Entry<String, Integer>>(lfuItemMap.entrySet());
Collections.sort(lfuItemList, new Comparator<Map.Entry<String, Integer>>() {
|
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
Map.Entry<String, Integer> addressItem = lfuItemList.get(0);
String minAddress = addressItem.getKey();
addressItem.setValue(addressItem.getValue() + 1);
return addressItem.getKey();
}
@Override
public ReturnT<String> route(TriggerParam triggerParam, List<String> addressList) {
String address = route(triggerParam.getJobId(), addressList);
return new ReturnT<String>(address);
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\route\strategy\ExecutorRouteLFU.java
| 1
|
请完成以下Java代码
|
public void log(@NonNull final PayPalCreateLogRequest log)
{
final I_PayPal_Log record = newInstanceOutOfTrx(I_PayPal_Log.class);
record.setRequestPath(log.getRequestPath());
record.setRequestMethod(log.getRequestMethod());
record.setRequestHeaders(toJson(log.getRequestHeaders()));
record.setResponseCode(log.getResponseStatusCode());
record.setResponseHeaders(toJson(log.getResponseHeaders()));
record.setResponseBody(log.getResponseBodyAsJson());
record.setC_Order_ID(OrderId.toRepoId(log.getSalesOrderId()));
record.setC_Payment_Reservation_ID(PaymentReservationId.toRepoId(log.getPaymentReservationId()));
record.setPayPal_Order_ID(PayPalOrderId.toRepoId(log.getInternalPayPalOrderId()));
saveRecord(record);
}
private String toJson(final Object obj)
{
|
if (obj == null)
{
return "";
}
try
{
return jsonObjectMapper.writeValueAsString(obj);
}
catch (JsonProcessingException ex)
{
logger.warn("Failed converting object to JSON. Returning toString(): {}", obj, ex);
return obj.toString();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\logs\PayPalLogRepository.java
| 1
|
请完成以下Java代码
|
public static void ifElseStatementsExamples() {
int count = 2; // Initial count value.
// Basic syntax. Only one statement follows. No brace usage.
if (count > 1)
System.out.println("Count is higher than 1");
// Basic syntax. More than one statement can be included. Braces are used (recommended syntax).
if (count > 1) {
System.out.println("Count is higher than 1");
System.out.println("Count is equal to: " + count);
}
// If/Else syntax. Two different courses of action can be included.
if (count > 2) {
System.out.println("Count is higher than 2");
} else {
System.out.println("Count is lower or equal than 2");
}
// If/Else/Else If syntax. Three or more courses of action can be included.
if (count > 2) {
System.out.println("Count is higher than 2");
} else if (count <= 0) {
System.out.println("Count is less or equal than zero");
} else {
System.out.println("Count is either equal to one, or two");
}
}
/**
* Ternary Operator example.
* @see ConditionalBranches#ifElseStatementsExamples()
*/
public static void ternaryExample() {
int count = 2;
System.out.println(count > 2 ? "Count is higher than 2" : "Count is lower or equal than 2");
}
/**
* Switch structure example. Shows how to replace multiple if/else statements with one structure.
*/
|
public static void switchExample() {
int count = 3;
switch (count) {
case 0:
System.out.println("Count is equal to 0");
break;
case 1:
System.out.println("Count is equal to 1");
break;
case 2:
System.out.println("Count is equal to 2");
break;
default:
System.out.println("Count is either negative, or higher than 2");
break;
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-syntax\src\main\java\com\baeldung\core\controlstructures\ConditionalBranches.java
| 1
|
请完成以下Java代码
|
public F getFirst()
{
return first;
}
public S getSecond()
{
return second;
}
@Override
public int hashCode()
{
// Note: i wanted to move ArrayKey from adempiere base to util, but i'm already kinda out of the tasks's original scope.
final int prime = 31;
int result = 1;
result = prime * result + ((first == null) ? 0 : first.hashCode());
result = prime * result + ((second == null) ? 0 : second.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (!(obj instanceof Pair))
{
return false;
}
final Pair<?, ?> other = (Pair<?, ?>)obj;
if (!Check.equals(this.first, other.first))
{
return false;
|
}
if (!Check.equals(this.second, other.second))
{
return false;
}
return true;
}
@Override
public String toString()
{
final StringBuilder builder = new StringBuilder();
builder.append("Pair [first=");
builder.append(first);
builder.append(", second=");
builder.append(second);
builder.append("]");
return builder.toString();
}
@Override
public F getLeft()
{
return getFirst();
}
@Override
public S getRight()
{
return getSecond();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\Pair.java
| 1
|
请完成以下Java代码
|
public String modelChange(PO po, int type) throws Exception
{
final int idxProcessed = po.get_ColumnIndex("Processed");
if (type == TYPE_AFTER_NEW)
{
if (idxProcessed < 0)
{
// if Processed column is missing create/link to referenceNo right now
referenceNoBL.linkReferenceNo(po, instance);
}
else if (po.get_ValueAsBoolean(idxProcessed))
{
// create/link to referenceNo only if is processed
referenceNoBL.linkReferenceNo(po, instance);
}
}
else if (type == TYPE_AFTER_CHANGE)
{
// consider it only if we have the Processed column, it was changed right and ...
if (idxProcessed >= 0 && po.is_ValueChanged(idxProcessed))
{
if (po.get_ValueAsBoolean(idxProcessed))
{
// ... Processed is true => we need to create/link to referenceNo
referenceNoBL.linkReferenceNo(po, instance);
}
else
{
// ... Processed is false => we need to unlink to referenceNo
referenceNoBL.unlinkReferenceNo(po, instance);
}
}
}
else if (type == TYPE_BEFORE_DELETE)
{
referenceNoBL.unlinkReferenceNo(po, instance);
}
return null;
}
@Override
public String docValidate(PO po, int timing)
{
final int clientId = instance.getType().getAD_Client_ID();
if (clientId != 0 && clientId != po.getAD_Client_ID())
{
// this validator does not applies for current tenant
return null;
}
if (timing == TIMING_AFTER_COMPLETE)
{
referenceNoBL.linkReferenceNo(po, instance);
}
else if (timing == TIMING_AFTER_VOID
|| timing == TIMING_AFTER_REACTIVATE
|| timing == TIMING_AFTER_REVERSEACCRUAL
|| timing == TIMING_AFTER_REVERSECORRECT)
{
referenceNoBL.unlinkReferenceNo(po, instance);
}
return null;
}
/**
* Register table doc validators. Private because it is called automatically on {@link #initialize(ModelValidationEngine, MClient)}.
*/
private void register()
{
for (int tableId : instance.getAssignedTableIds())
{
final String tableName = adTableDAO.retrieveTableName(tableId);
|
if (documentBL.isDocumentTable(tableName))
{
engine.addDocValidate(tableName, this);
logger.debug("Registered docValidate " + this);
}
else
{
engine.addModelChange(tableName, this);
logger.debug("Registered modelChange " + this);
}
}
}
public void unregister()
{
for (int tableId : instance.getAssignedTableIds())
{
final String tableName = adTableDAO.retrieveTableName(tableId);
engine.removeModelChange(tableName, this);
engine.removeDocValidate(tableName, this);
}
logger.debug("Unregistered " + this);
}
public IReferenceNoGeneratorInstance getInstance()
{
return instance;
}
@Override
public String toString()
{
return "ReferenceNoGeneratorInstanceValidator [instance=" + instance + "]";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java\de\metas\document\refid\modelvalidator\ReferenceNoGeneratorInstanceValidator.java
| 1
|
请完成以下Java代码
|
private I_M_ShipperTransportation getM_ShipperTransportation_Param()
{
if (p_IsCreateShipperTransportation)
{
return null;
}
if (p_M_ShipperTransportation != null)
{
return p_M_ShipperTransportation;
}
if (p_M_ShipperTransportation_ID <= 0)
{
throw new FillMandatoryException(PARAM_M_ShipperTransportation_ID);
}
p_M_ShipperTransportation = InterfaceWrapperHelper.create(getCtx(), p_M_ShipperTransportation_ID, I_M_ShipperTransportation.class, getTrxName());
Check.assumeNotNull(p_M_ShipperTransportation, "shipperTransportation not null");
// Make sure shipper transportation is not processed
if (p_M_ShipperTransportation.isProcessed())
{
throw new AdempiereException("@M_ShipperTransportation_ID@: @Processed@=@Y@")
.appendParametersToMessage()
.setParameter("M_ShipperTransportation_ID", p_M_ShipperTransportation_ID);
}
return p_M_ShipperTransportation;
}
private I_M_ShipperTransportation getCreateShipperTransportation(final I_M_Tour_Instance tourInstance)
{
if (_shipperTransportation != null)
{
return _shipperTransportation;
}
//
// Use the shipper transportation passed by paramters if any
_shipperTransportation = getM_ShipperTransportation_Param();
if (_shipperTransportation != null)
{
return _shipperTransportation;
}
//
// Create a new shipper transportation
_shipperTransportation = createShipperTransportation(tourInstance);
return _shipperTransportation;
}
private I_M_ShipperTransportation createShipperTransportation(final I_M_Tour_Instance tourInstance)
{
Check.assumeNotNull(tourInstance, "tourInstance not null");
final I_M_ShipperTransportation shipperTransportation = InterfaceWrapperHelper.newInstance(I_M_ShipperTransportation.class, this);
shipperTransportation.setDateDoc(tourInstance.getDeliveryDate());
|
shipperTransportation.setShipper_BPartner_ID(p_Shipper_BPartner_ID);
shipperTransportation.setShipper_Location_ID(p_Shipper_Location_ID);
final ShipperId shipperId = ShipperId.ofRepoIdOrNull(p_M_Shipper_ID);
if (shipperId != null)
{
shipperTransportationBL.setShipper(shipperTransportation, shipperId);
}
shipperTransportationBL.setC_DocType(shipperTransportation);
shipperTransportation.setIsSOTrx(true);
// 07958
// also set the tour id
shipperTransportation.setM_Tour(tourInstance.getM_Tour());
InterfaceWrapperHelper.save(shipperTransportation);
return shipperTransportation;
}
private Iterator<I_M_DeliveryDay> retrieveSelectedDeliveryDays()
{
return retrieveSelectedRecordsQueryBuilder(I_M_DeliveryDay.class)
//
.orderBy()
.clear()
.addColumn(I_M_DeliveryDay.COLUMN_SeqNo)
.endOrderBy()
//
.create()
.iterate(I_M_DeliveryDay.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\process\M_Tour_Instance_CreateFromSelectedDeliveryDays.java
| 1
|
请完成以下Java代码
|
public long findHistoricCaseInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbEntityManager().selectOne("selectHistoricCaseInstanceCountByNativeQuery", parameterMap);
}
protected void configureHistoricCaseInstanceQuery(HistoricCaseInstanceQueryImpl query) {
getTenantManager().configureQuery(query);
}
@SuppressWarnings("unchecked")
public List<String> findHistoricCaseInstanceIdsForCleanup(int batchSize, int minuteFrom, int minuteTo) {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("currentTimestamp", ClockUtil.getCurrentTime());
if (minuteTo - minuteFrom + 1 < 60) {
parameters.put("minuteFrom", minuteFrom);
parameters.put("minuteTo", minuteTo);
}
ListQueryParameterObject parameterObject = new ListQueryParameterObject(parameters, 0, batchSize);
return getDbEntityManager().selectList("selectHistoricCaseInstanceIdsForCleanup", parameterObject);
|
}
@SuppressWarnings("unchecked")
public List<CleanableHistoricCaseInstanceReportResult> findCleanableHistoricCaseInstancesReportByCriteria(CleanableHistoricCaseInstanceReportImpl query, Page page) {
query.setCurrentTimestamp(ClockUtil.getCurrentTime());
getTenantManager().configureQuery(query);
return getDbEntityManager().selectList("selectFinishedCaseInstancesReportEntities", query, page);
}
public long findCleanableHistoricCaseInstancesReportCountByCriteria(CleanableHistoricCaseInstanceReportImpl query) {
query.setCurrentTimestamp(ClockUtil.getCurrentTime());
getTenantManager().configureQuery(query);
return (Long) getDbEntityManager().selectOne("selectFinishedCaseInstancesReportEntitiesCount", query);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricCaseInstanceManager.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.