instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public void setQty_Planned (final @Nullable BigDecimal Qty_Planned)
{
set_Value (COLUMNNAME_Qty_Planned, Qty_Planned);
}
@Override
public BigDecimal getQty_Planned()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty_Planned);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQty_Reported (final @Nullable BigDecimal Qty_Reported)
{
set_Value (COLUMNNAME_Qty_Reported, Qty_Reported);
}
@Override
public BigDecimal getQty_Reported()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty_Reported);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
|
* Type AD_Reference_ID=540263
* Reference name: C_Flatrate_DataEntry Type
*/
public static final int TYPE_AD_Reference_ID=540263;
/** Invoicing_PeriodBased = IP */
public static final String TYPE_Invoicing_PeriodBased = "IP";
/** Correction_PeriodBased = CP */
public static final String TYPE_Correction_PeriodBased = "CP";
/** Procurement_PeriodBased = PC */
public static final String TYPE_Procurement_PeriodBased = "PC";
@Override
public void setType (final java.lang.String Type)
{
set_ValueNoCheck (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_DataEntry.java
| 1
|
请完成以下Java代码
|
public void setIncidentIds(String[] incidentIds) {
this.incidentIds = incidentIds;
}
@Override
public Incident[] getIncidents() {
return incidents;
}
public void setIncidents(Incident[] incidents) {
this.incidents = incidents;
}
public void setSubProcessInstanceId(String subProcessInstanceId) {
this.subProcessInstanceId = subProcessInstanceId;
}
public String getSubProcessInstanceId() {
return subProcessInstanceId;
}
public String toString() {
|
return this.getClass().getSimpleName()
+ "[executionId=" + executionId
+ ", targetActivityId=" + activityId
+ ", activityName=" + activityName
+ ", activityType=" + activityType
+ ", id=" + id
+ ", parentActivityInstanceId=" + parentActivityInstanceId
+ ", processInstanceId=" + processInstanceId
+ ", processDefinitionId=" + processDefinitionId
+ ", incidentIds=" + Arrays.toString(incidentIds)
+ ", incidents=" + Arrays.toString(incidents)
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TransitionInstanceImpl.java
| 1
|
请完成以下Java代码
|
public class PlainEventBusFactory implements IEventBusFactory
{
public static PlainEventBusFactory newInstance()
{
return new PlainEventBusFactory();
}
private final HashMap<Topic, EventBus> eventBuses = new HashMap<>();
public PlainEventBusFactory()
{
assertJUnitTestMode();
}
private static void assertJUnitTestMode()
{
if (!Adempiere.isUnitTestMode())
{
throw new IllegalStateException(PlainEventBusFactory.class.getName() + " shall be used only in JUnit test mode");
}
}
@Override
public IEventBus getEventBus(final Topic topic)
{
assertJUnitTestMode();
return eventBuses.computeIfAbsent(topic, this::createEventBus);
}
private EventBus createEventBus(final Topic topic)
{
final MicrometerEventBusStatsCollector micrometerEventBusStatsCollector = EventBusFactory.createMicrometerEventBusStatsCollector(topic, new SimpleMeterRegistry());
final EventBusMonitoringService eventBusMonitoringService = new EventBusMonitoringService(new MicrometerPerformanceMonitoringService(new SimpleMeterRegistry()));
final ExecutorService executor = null;
return new EventBus(topic, executor, micrometerEventBusStatsCollector, new PlainEventEnqueuer(), eventBusMonitoringService, new EventLogService(new EventLogsRepository()));
}
@Override
public IEventBus getEventBusIfExists(final Topic topic)
{
assertJUnitTestMode();
return eventBuses.get(topic);
}
@Override
public List<IEventBus> getAllEventBusInstances()
{
assertJUnitTestMode();
return ImmutableList.copyOf(eventBuses.values());
}
@Override
|
public void initEventBussesWithGlobalListeners()
{
assertJUnitTestMode();
// as of now, no unit test needs an implementation.
}
@Override
public void destroyAllEventBusses()
{
assertJUnitTestMode();
// as of now, no unit test needs an implementation.
}
@Override
public void registerGlobalEventListener(final Topic topic, final IEventListener listener)
{
assertJUnitTestMode();
// as of now, no unit test needs an implementation.
}
@Override
public void addAvailableUserNotificationsTopic(final Topic topic)
{
assertJUnitTestMode();
// as of now, no unit test needs an implementation.
}
@Override
public void registerUserNotificationsListener(final IEventListener listener)
{
assertJUnitTestMode();
// as of now, no unit test needs an implementation.
}
@Override
public void unregisterUserNotificationsListener(final IEventListener listener)
{
assertJUnitTestMode();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\impl\PlainEventBusFactory.java
| 1
|
请完成以下Java代码
|
public class Dispatcher {
private final AccessManager accessManager;
private final List<HandlerMapper> mappers;
public Dispatcher(AccessManager accessManager, Collection<HandlerMapper> mappers) {
Assert.notNull(accessManager, "'accessManager' must not be null");
Assert.notNull(mappers, "'mappers' must not be null");
this.accessManager = accessManager;
this.mappers = new ArrayList<>(mappers);
AnnotationAwareOrderComparator.sort(this.mappers);
}
/**
* Dispatch the specified request to an appropriate {@link Handler}.
* @param request the request
* @param response the response
* @return {@code true} if the request was dispatched
* @throws IOException in case of I/O errors
*/
public boolean handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException {
for (HandlerMapper mapper : this.mappers) {
Handler handler = mapper.getHandler(request);
if (handler != null) {
|
handle(handler, request, response);
return true;
}
}
return false;
}
private void handle(Handler handler, ServerHttpRequest request, ServerHttpResponse response) throws IOException {
if (!this.accessManager.isAllowed(request)) {
response.setStatusCode(HttpStatus.FORBIDDEN);
return;
}
handler.handle(request, response);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\remote\server\Dispatcher.java
| 1
|
请完成以下Java代码
|
public java.lang.String getDocumentNo()
{
return get_ValueAsString(COLUMNNAME_DocumentNo);
}
@Override
public void setHelp (final @Nullable java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
@Override
public java.lang.String getHelp()
{
return get_ValueAsString(COLUMNNAME_Help);
}
@Override
public void setIsDirectEnqueue (final boolean IsDirectEnqueue)
{
set_Value (COLUMNNAME_IsDirectEnqueue, IsDirectEnqueue);
}
@Override
public boolean isDirectEnqueue()
{
return get_ValueAsBoolean(COLUMNNAME_IsDirectEnqueue);
}
@Override
public void setIsDirectProcessQueueItem (final boolean IsDirectProcessQueueItem)
{
set_Value (COLUMNNAME_IsDirectProcessQueueItem, IsDirectProcessQueueItem);
}
@Override
public boolean isDirectProcessQueueItem()
{
return get_ValueAsBoolean(COLUMNNAME_IsDirectProcessQueueItem);
}
@Override
public void setIsFileSystem (final boolean IsFileSystem)
{
set_Value (COLUMNNAME_IsFileSystem, IsFileSystem);
}
@Override
public boolean isFileSystem()
{
return get_ValueAsBoolean(COLUMNNAME_IsFileSystem);
}
@Override
public void setIsReport (final boolean IsReport)
|
{
set_Value (COLUMNNAME_IsReport, IsReport);
}
@Override
public boolean isReport()
{
return get_ValueAsBoolean(COLUMNNAME_IsReport);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setPOReference (final @Nullable java.lang.String POReference)
{
set_Value (COLUMNNAME_POReference, POReference);
}
@Override
public java.lang.String getPOReference()
{
return get_ValueAsString(COLUMNNAME_POReference);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Archive.java
| 1
|
请完成以下Java代码
|
public class PmsProductFullReduction implements Serializable {
private Long id;
private Long productId;
private BigDecimal fullPrice;
private BigDecimal reducePrice;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
public BigDecimal getFullPrice() {
return fullPrice;
}
public void setFullPrice(BigDecimal fullPrice) {
this.fullPrice = fullPrice;
}
public BigDecimal getReducePrice() {
|
return reducePrice;
}
public void setReducePrice(BigDecimal reducePrice) {
this.reducePrice = reducePrice;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", productId=").append(productId);
sb.append(", fullPrice=").append(fullPrice);
sb.append(", reducePrice=").append(reducePrice);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductFullReduction.java
| 1
|
请完成以下Java代码
|
public IntegrationFlow fileWriter() {
return IntegrationFlow.from("holdingTank")
.bridge(e -> e.poller(Pollers.fixedRate(Duration.of(1, TimeUnit.SECONDS.toChronoUnit()), Duration.of(20, TimeUnit.SECONDS.toChronoUnit()))))
.handle(targetDirectory())
.get();
}
// @Bean
public IntegrationFlow anotherFileWriter() {
return IntegrationFlow.from("holdingTank")
.bridge(e -> e.poller(Pollers.fixedRate(Duration.of(2, TimeUnit.SECONDS.toChronoUnit()), Duration.of(10, TimeUnit.SECONDS.toChronoUnit()))))
.handle(anotherTargetDirectory())
.get();
}
public static void main(final String... args) {
|
final AbstractApplicationContext context = new AnnotationConfigApplicationContext(JavaDSLFileCopyConfig.class);
context.registerShutdownHook();
final Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a string and press <enter>: ");
while (true) {
final String input = scanner.nextLine();
if ("q".equals(input.trim())) {
context.close();
scanner.close();
break;
}
}
System.exit(0);
}
}
|
repos\tutorials-master\spring-integration\src\main\java\com\baeldung\dsl\JavaDSLFileCopyConfig.java
| 1
|
请完成以下Java代码
|
public String getCaseInstanceId() {
return caseInstanceId;
}
public void setCaseInstanceId(String caseInstanceId) {
this.caseInstanceId = caseInstanceId;
}
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public void setCaseDefinitionId(String caseDefinitionId) {
this.caseDefinitionId = caseDefinitionId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public List<String> getMoveToPlanItemDefinitionIds() {
return moveToPlanItemDefinitionIds;
}
public void setMoveToPlanItemDefinitionIds(List<String> moveToPlanItemDefinitionIds) {
this.moveToPlanItemDefinitionIds = moveToPlanItemDefinitionIds;
}
public CmmnModel getCmmnModel() {
return cmmnModel;
}
public void setCmmnModel(CmmnModel cmmnModel) {
this.cmmnModel = cmmnModel;
}
public String getNewAssigneeId() {
return newAssigneeId;
}
public void setNewAssigneeId(String newAssigneeId) {
this.newAssigneeId = newAssigneeId;
}
public Map<String, PlanItemInstanceEntity> getContinueParentPlanItemInstanceMap() {
return continueParentPlanItemInstanceMap;
}
public void setContinueParentPlanItemInstanceMap(Map<String, PlanItemInstanceEntity> continueParentPlanItemInstanceMap) {
this.continueParentPlanItemInstanceMap = continueParentPlanItemInstanceMap;
|
}
public void addContinueParentPlanItemInstance(String planItemInstanceId, PlanItemInstanceEntity continueParentPlanItemInstance) {
continueParentPlanItemInstanceMap.put(planItemInstanceId, continueParentPlanItemInstance);
}
public PlanItemInstanceEntity getContinueParentPlanItemInstance(String planItemInstanceId) {
return continueParentPlanItemInstanceMap.get(planItemInstanceId);
}
public Map<String, PlanItemMoveEntry> getMoveToPlanItemMap() {
return moveToPlanItemMap;
}
public void setMoveToPlanItemMap(Map<String, PlanItemMoveEntry> moveToPlanItemMap) {
this.moveToPlanItemMap = moveToPlanItemMap;
}
public PlanItemMoveEntry getMoveToPlanItem(String planItemId) {
return moveToPlanItemMap.get(planItemId);
}
public List<PlanItemMoveEntry> getMoveToPlanItems() {
return new ArrayList<>(moveToPlanItemMap.values());
}
public static class PlanItemMoveEntry {
protected PlanItem originalPlanItem;
protected PlanItem newPlanItem;
public PlanItemMoveEntry(PlanItem originalPlanItem, PlanItem newPlanItem) {
this.originalPlanItem = originalPlanItem;
this.newPlanItem = newPlanItem;
}
public PlanItem getOriginalPlanItem() {
return originalPlanItem;
}
public PlanItem getNewPlanItem() {
return newPlanItem;
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\MovePlanItemInstanceEntityContainer.java
| 1
|
请完成以下Java代码
|
public abstract class AbstractDunnableSource implements IDunnableSource
{
protected final transient Logger logger = LogManager.getLogger(getClass());
protected abstract Iterator<IDunnableDoc> createRawSourceIterator(IDunningContext context);
@Override
public final Iterator<IDunnableDoc> iterator(final IDunningContext context)
{
final Iterator<IDunnableDoc> sourceIterator = createRawSourceIterator(context);
final Iterator<IDunnableDoc> filteredSourceIterator = new FilterIterator<>(sourceIterator, value -> isEligible(context, value));
return filteredSourceIterator;
}
/**
*
* @param dunnableDoc
* @return true if dunnableDoc is eligible for creating a candidate
*/
protected boolean isEligible(final IDunningContext dunningContext, final IDunnableDoc dunnableDoc)
{
if (dunnableDoc.getOpenAmt().signum() == 0)
{
logger.info("Skip " + dunnableDoc + " because OpenAmt is ZERO");
return false;
}
if (dunnableDoc.isInDispute())
{
logger.info("Skip " + dunnableDoc + " because is in dispute");
return false;
}
final I_C_DunningLevel level = dunningContext.getC_DunningLevel();
final boolean isDue = dunnableDoc.getDaysDue() >= 0;
if (isDue)
|
{
if (level.isShowAllDue())
{
// Document is due, and we are asked to show all due, so there is no point to check if the days after due is valid
return true;
}
}
else
{
// Document is not due yet => not eligible for dunning
return false;
}
final int daysAfterDue = level.getDaysAfterDue().intValue();
if (dunnableDoc.getDaysDue() < daysAfterDue)
{
logger.info("Skip " + dunnableDoc + " because is not already due (DaysAfterDue:" + daysAfterDue + ")");
return false;
}
return true;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\spi\impl\AbstractDunnableSource.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AssetImportService extends BaseEntityImportService<AssetId, Asset, EntityExportData<Asset>> {
private final AssetService assetService;
@Override
protected void setOwner(TenantId tenantId, Asset asset, IdProvider idProvider) {
asset.setTenantId(tenantId);
asset.setCustomerId(idProvider.getInternalId(asset.getCustomerId()));
}
@Override
protected Asset prepare(EntitiesImportCtx ctx, Asset asset, Asset old, EntityExportData<Asset> exportData, IdProvider idProvider) {
asset.setAssetProfileId(idProvider.getInternalId(asset.getAssetProfileId()));
return asset;
}
@Override
protected Asset saveOrUpdate(EntitiesImportCtx ctx, Asset asset, EntityExportData<Asset> exportData, IdProvider idProvider, CompareResult compareResult) {
Asset savedAsset = assetService.saveAsset(asset);
if (ctx.isFinalImportAttempt() || ctx.getCurrentImportResult().isUpdatedAllExternalIds()) {
importCalculatedFields(ctx, savedAsset, exportData, idProvider);
}
return savedAsset;
}
@Override
|
protected Asset deepCopy(Asset asset) {
return new Asset(asset);
}
@Override
protected void cleanupForComparison(Asset e) {
super.cleanupForComparison(e);
if (e.getCustomerId() != null && e.getCustomerId().isNullUid()) {
e.setCustomerId(null);
}
}
@Override
public EntityType getEntityType() {
return EntityType.ASSET;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\AssetImportService.java
| 2
|
请完成以下Java代码
|
final class DDOrderLineToAllocate
{
@NonNull private final IUOMConversionBL uomConversionBL;
@NonNull private final DDOrderId ddOrderId;
@NonNull private final DDOrderLineId ddOrderLineId;
private final int ddOrderLineAlternativeId;
@Getter
@Nullable private final String description;
private final ArrayList<PickFromHU> pickFromHUs = new ArrayList<>();
@Getter
@NonNull private final ProductId productId;
@Getter
@NonNull private final AttributeSetInstanceId fromAsiId;
@Getter
@NonNull private final AttributeSetInstanceId toAsiId;
@Getter
@NonNull private final LocatorId pickFromLocatorId;
@Getter
@NonNull private final LocatorId dropToLocatorId;
@Getter
private Quantity qtyToShipScheduled;
@Getter
private Quantity qtyToShipRemaining;
@Builder
private DDOrderLineToAllocate(
final @NonNull IUOMConversionBL uomConversionBL,
//
final @NonNull DDOrderId ddOrderId,
final @NonNull DDOrderLineId ddOrderLineId,
final int ddOrderLineAlternativeId,
final @Nullable String description,
final @NonNull ProductId productId,
final @NonNull AttributeSetInstanceId fromAsiId,
final @NonNull AttributeSetInstanceId toAsiId,
final @NonNull LocatorId pickFromLocatorId,
final @NonNull LocatorId dropToLocatorId,
final @NonNull Quantity qtyToShip)
{
this.uomConversionBL = uomConversionBL;
this.ddOrderId = ddOrderId;
this.ddOrderLineId = ddOrderLineId;
this.ddOrderLineAlternativeId = ddOrderLineAlternativeId;
this.description = description;
this.productId = productId;
this.fromAsiId = fromAsiId;
this.toAsiId = toAsiId;
this.pickFromLocatorId = pickFromLocatorId;
this.dropToLocatorId = dropToLocatorId;
this.qtyToShipRemaining = qtyToShip;
this.qtyToShipScheduled = qtyToShipRemaining.toZero();
}
public DDOrderId getDDOrderId() {return ddOrderId;}
|
public DDOrderLineId getDDOrderLineId() {return ddOrderLineId;}
public int getDDOrderLineAlternativeId() {return ddOrderLineAlternativeId;}
public ImmutableList<PickFromHU> getPickFromHUs() {return ImmutableList.copyOf(pickFromHUs);}
public boolean isFullyShipped()
{
return qtyToShipRemaining.signum() <= 0;
}
public void addPickFromHU(@NonNull final PickFromHU pickFromHU)
{
this.pickFromHUs.add(pickFromHU);
qtyToShipRemaining = qtyToShipRemaining.subtract(pickFromHU.getQty());
qtyToShipScheduled = qtyToShipScheduled.add(pickFromHU.getQty());
}
//
//
//
@Value
@Builder
public static class PickFromHU
{
@NonNull I_M_HU hu;
@NonNull Quantity qty;
public HuId getHuId() {return HuId.ofRepoId(hu.getM_HU_ID());}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\generate_from_hu\DDOrderLineToAllocate.java
| 1
|
请完成以下Java代码
|
public void hit(int begin, int end, CoreDictionary.Attribute value)
{
int length = end - begin;
if (length > wordNet[begin])
{
wordNet[begin] = length;
if (config.speechTagging)
{
natureArray[begin] = value.nature[0];
}
}
}
});
LinkedList<Term> termList = new LinkedList<Term>();
posTag(sentence, wordNet, natureArray);
for (int i = 0; i < wordNet.length; )
{
Term term = new Term(new String(sentence, i, wordNet[i]), config.speechTagging ? (natureArray[i] == null ? Nature.nz : natureArray[i]) : null);
term.offset = i;
termList.add(term);
i += wordNet[i];
}
return termList;
}
@Override
public Segment enableCustomDictionary(boolean enable)
{
throw new UnsupportedOperationException("AhoCorasickDoubleArrayTrieSegment暂时不支持用户词典。");
}
public AhoCorasickDoubleArrayTrie<CoreDictionary.Attribute> getTrie()
{
return trie;
}
public void setTrie(AhoCorasickDoubleArrayTrie<CoreDictionary.Attribute> trie)
{
this.trie = trie;
}
|
public AhoCorasickDoubleArrayTrieSegment loadDictionary(String... pathArray)
{
trie = new AhoCorasickDoubleArrayTrie<CoreDictionary.Attribute>();
TreeMap<String, CoreDictionary.Attribute> map = null;
try
{
map = IOUtil.loadDictionary(pathArray);
}
catch (IOException e)
{
logger.warning("加载词典失败\n" + TextUtility.exceptionToString(e));
return this;
}
if (map != null && !map.isEmpty())
{
trie.build(map);
}
return this;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\Other\AhoCorasickDoubleArrayTrieSegment.java
| 1
|
请完成以下Java代码
|
public XhtmlFrameSetDocument appendTitle(String value)
{
title.addElement(value);
return(this);
}
/**
* Sets the codeset for this XhtmlFrameSetDocument
*/
public void setCodeset ( String codeset )
{
this.codeset = codeset;
}
/**
* Gets the codeset for this XhtmlFrameSetDocument
*
* @return the codeset
*/
public String getCodeset()
{
return this.codeset;
}
/**
Write the container to the OutputStream
*/
public void output(OutputStream out)
{
// XhtmlFrameSetDocument is just a convient wrapper for html call html.output
html.output(out);
}
/**
Write the container to the PrinteWriter
*/
public void output(PrintWriter out)
{
// XhtmlFrameSetDocument is just a convient wrapper for html call html.output
|
html.output(out);
}
/**
Override the toString() method so that it prints something meaningful.
*/
public final String toString()
{
if ( getCodeset() != null )
return (html.toString(getCodeset()));
else
return(html.toString());
}
/**
Override the toString() method so that it prints something meaningful.
*/
public final String toString(String codeset)
{
return(html.toString(codeset));
}
/**
Allows the XhtmlFrameSetDocument to be cloned. Doesn't return an instanceof XhtmlFrameSetDocument returns instance of html.
*/
public Object clone()
{
return(html.clone());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\XhtmlFrameSetDocument.java
| 1
|
请完成以下Java代码
|
public int getM_AttributeSetInstance_ID()
{
return get_ValueAsInt(COLUMNNAME_M_AttributeSetInstance_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setNote (final @Nullable java.lang.String Note)
{
set_Value (COLUMNNAME_Note, Note);
}
@Override
public java.lang.String getNote()
{
return get_ValueAsString(COLUMNNAME_Note);
}
@Override
public void setPercentage (final @Nullable BigDecimal Percentage)
{
set_Value (COLUMNNAME_Percentage, Percentage);
}
@Override
public BigDecimal getPercentage()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Percentage);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPriceActual (final @Nullable BigDecimal PriceActual)
{
set_Value (COLUMNNAME_PriceActual, PriceActual);
}
@Override
public BigDecimal getPriceActual()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceActual);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPriceEntered (final @Nullable BigDecimal PriceEntered)
{
set_Value (COLUMNNAME_PriceEntered, PriceEntered);
}
@Override
public BigDecimal getPriceEntered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceEntered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPrice_UOM_ID (final int Price_UOM_ID)
{
if (Price_UOM_ID < 1)
|
set_Value (COLUMNNAME_Price_UOM_ID, null);
else
set_Value (COLUMNNAME_Price_UOM_ID, Price_UOM_ID);
}
@Override
public int getPrice_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_Price_UOM_ID);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyEnteredInPriceUOM (final @Nullable BigDecimal QtyEnteredInPriceUOM)
{
set_Value (COLUMNNAME_QtyEnteredInPriceUOM, QtyEnteredInPriceUOM);
}
@Override
public BigDecimal getQtyEnteredInPriceUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEnteredInPriceUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Detail.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/oauth_login", "/loginFailure", "/")
.permitAll()
.anyRequest()
.authenticated()
.and()
.oauth2Login()
.loginPage("/oauth_login")
.authorizationEndpoint()
.baseUri("/oauth2/authorize-client")
.authorizationRequestRepository(authorizationRequestRepository())
.and()
.tokenEndpoint()
.accessTokenResponseClient(accessTokenResponseClient())
.and()
.defaultSuccessUrl("/loginSuccess")
.failureUrl("/loginFailure");
return http.build();
}
@Bean
public AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository() {
return new HttpSessionOAuth2AuthorizationRequestRepository();
}
@Bean
public OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient() {
DefaultAuthorizationCodeTokenResponseClient accessTokenResponseClient = new DefaultAuthorizationCodeTokenResponseClient();
return accessTokenResponseClient;
}
// additional configuration for non-Spring Boot projects
private static List<String> clients = Arrays.asList("google", "facebook");
// @Bean
public ClientRegistrationRepository clientRegistrationRepository() {
List<ClientRegistration> registrations = clients.stream()
|
.map(c -> getRegistration(c))
.filter(registration -> registration != null)
.collect(Collectors.toList());
return new InMemoryClientRegistrationRepository(registrations);
}
// @Bean
public OAuth2AuthorizedClientService authorizedClientService() {
return new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository());
}
private static String CLIENT_PROPERTY_KEY = "spring.security.oauth2.client.registration.";
@Autowired
private Environment env;
private ClientRegistration getRegistration(String client) {
String clientId = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-id");
if (clientId == null) {
return null;
}
String clientSecret = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-secret");
if (client.equals("google")) {
return CommonOAuth2Provider.GOOGLE.getBuilder(client)
.clientId(clientId)
.clientSecret(clientSecret)
.build();
}
if (client.equals("facebook")) {
return CommonOAuth2Provider.FACEBOOK.getBuilder(client)
.clientId(clientId)
.clientSecret(clientSecret)
.build();
}
return null;
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-oauth2\src\main\java\com\baeldung\oauth2\SecurityConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public int delete(List<T> list) {
if (list.isEmpty() || list.size() <= 0) {
return 0;
} else {
return (int) sessionTemplate.delete(getStatement(SQL_BATCH_DELETE_BY_IDS), list);
}
}
/**
* 根据column批量删除数据.
*/
public int delete(Map<String, Object> paramMap) {
if (paramMap == null) {
return 0;
} else {
return (int) sessionTemplate.delete(getStatement(SQL_BATCH_DELETE_BY_COLUMN), paramMap);
}
}
/**
* 分页查询数据 .
*/
public PageBean listPage(PageParam pageParam, Map<String, Object> paramMap) {
if (paramMap == null) {
paramMap = new HashMap<String, Object>();
}
// 统计总记录数
Long totalCount = sessionTemplate.selectOne(getStatement(SQL_LIST_PAGE_COUNT), paramMap);
// 校验当前页数
int currentPage = PageBean.checkCurrentPage(totalCount.intValue(), pageParam.getNumPerPage(), pageParam.getPageNum());
pageParam.setPageNum(currentPage); // 为当前页重新设值
// 校验页面输入的每页记录数numPerPage是否合法
int numPerPage = PageBean.checkNumPerPage(pageParam.getNumPerPage()); // 校验每页记录数
pageParam.setNumPerPage(numPerPage); // 重新设值
|
// 根据页面传来的分页参数构造SQL分页参数
paramMap.put("pageFirst", (pageParam.getPageNum() - 1) * pageParam.getNumPerPage());
paramMap.put("pageSize", pageParam.getNumPerPage());
paramMap.put("startRowNum", (pageParam.getPageNum() - 1) * pageParam.getNumPerPage());
paramMap.put("endRowNum", pageParam.getPageNum() * pageParam.getNumPerPage());
// 获取分页数据集
List<Object> list = sessionTemplate.selectList(getStatement(SQL_LIST_PAGE), paramMap);
Object isCount = paramMap.get("isCount"); // 是否统计当前分页条件下的数据:1:是,其他为否
if (isCount != null && "1".equals(isCount.toString())) {
Map<String, Object> countResultMap = sessionTemplate.selectOne(getStatement(SQL_COUNT_BY_PAGE_PARAM), paramMap);
return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), totalCount.intValue(), list, countResultMap);
} else {
// 构造分页对象
return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), totalCount.intValue(), list);
}
}
/**
* 函数功能说明 : 获取Mapper命名空间. 修改者名字: Along 修改日期: 2016-1-8 修改内容:
*
* @参数:@param sqlId
* @参数:@return
* @return:String
* @throws
*/
public String getStatement(String sqlId) {
String name = this.getClass().getName();
// 单线程用StringBuilder,确保速度;多线程用StringBuffer,确保安全
StringBuilder sb = new StringBuilder();
sb.append(name).append(".").append(sqlId);
return sb.toString();
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\dao\impl\PermissionBaseDaoImpl.java
| 2
|
请完成以下Java代码
|
private void validateBillPartner(
@NonNull final I_C_Flatrate_Term callOrderContract,
@NonNull final BPartnerId documentBillPartnerId,
final int documentLineSeqNo)
{
final BPartnerId contractBillPartnerId = BPartnerId.ofRepoId(callOrderContract.getBill_BPartner_ID());
if (!contractBillPartnerId.equals(documentBillPartnerId))
{
final I_C_BPartner documentBillPartner = bPartnerDAO.getById(documentBillPartnerId);
final I_C_BPartner contractPartner = bPartnerDAO.getById(contractBillPartnerId);
throw new AdempiereException(MSG_BPARTNERS_DO_NOT_MATCH,
documentBillPartner.getValue(),
contractPartner.getValue(),
documentLineSeqNo)
.markAsUserValidationError();
}
}
private boolean isCallOrderContract(@NonNull final I_C_Flatrate_Term contract)
{
return TypeConditions.CALL_ORDER.getCode().equals(contract.getType_Conditions());
}
private void validateSOTrx(
@NonNull final I_C_Flatrate_Term contract,
@NonNull final SOTrx documentSOTrx,
final int documentLineSeqNo)
{
final OrderId initiatingContractOrderId = OrderId.ofRepoIdOrNull(contract.getC_Order_Term_ID());
Check.assumeNotNull(initiatingContractOrderId, "C_Order_Term_ID cannot be null on CallOrder contracts!");
final I_C_Order initiatingContractOrder = orderBL.getById(initiatingContractOrderId);
if (initiatingContractOrder.isSOTrx() == documentSOTrx.toBoolean())
|
{
return;
}
if (initiatingContractOrder.isSOTrx())
{
throw new AdempiereException(MSG_SALES_CALL_ORDER_CONTRACT_TRX_NOT_MATCH,
contract.getDocumentNo(),
documentLineSeqNo)
.markAsUserValidationError();
}
throw new AdempiereException(MSG_PURCHASE_CALL_ORDER_CONTRACT_TRX_NOT_MATCH,
contract.getDocumentNo(),
documentLineSeqNo)
.markAsUserValidationError();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\callorder\CallOrderContractService.java
| 1
|
请完成以下Java代码
|
public String getDataState() {
return dataState;
}
public void setDataState(String dataState) {
this.dataState = dataState;
}
public String getItemSubjectRef() {
return itemSubjectRef;
}
public void setItemSubjectRef(String itemSubjectRef) {
this.itemSubjectRef = itemSubjectRef;
}
public String getDataStoreRef() {
return dataStoreRef;
}
public void setDataStoreRef(String dataStoreRef) {
this.dataStoreRef = dataStoreRef;
|
}
public DataStoreReference clone() {
DataStoreReference clone = new DataStoreReference();
clone.setValues(this);
return clone;
}
public void setValues(DataStoreReference otherElement) {
super.setValues(otherElement);
setDataState(otherElement.getDataState());
setItemSubjectRef(otherElement.getItemSubjectRef());
setDataStoreRef(otherElement.getDataStoreRef());
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\DataStoreReference.java
| 1
|
请完成以下Java代码
|
public CustomPropertiesResolver createClassDelegateCustomPropertiesResolver(ActivitiListener activitiListener) {
return classDelegateFactory.create(activitiListener.getCustomPropertiesResolverImplementation(), null);
}
@Override
public CustomPropertiesResolver createExpressionCustomPropertiesResolver(ActivitiListener activitiListener) {
return new ExpressionCustomPropertiesResolver(
expressionManager.createExpression(activitiListener.getCustomPropertiesResolverImplementation())
);
}
@Override
public CustomPropertiesResolver createDelegateExpressionCustomPropertiesResolver(
ActivitiListener activitiListener
) {
return new DelegateExpressionCustomPropertiesResolver(
expressionManager.createExpression(activitiListener.getCustomPropertiesResolverImplementation())
);
}
/**
* @param entityType
|
* the name of the entity
* @return
* @throws ActivitiIllegalArgumentException
* when the given entity name
*/
protected Class<?> getEntityType(String entityType) {
if (entityType != null) {
Class<?> entityClass = ENTITY_MAPPING.get(entityType.trim());
if (entityClass == null) {
throw new ActivitiIllegalArgumentException(
"Unsupported entity-type for an ActivitiEventListener: " + entityType
);
}
return entityClass;
}
return null;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\factory\DefaultListenerFactory.java
| 1
|
请完成以下Java代码
|
public void setDK_ParcelWidth (java.math.BigDecimal DK_ParcelWidth)
{
set_Value (COLUMNNAME_DK_ParcelWidth, DK_ParcelWidth);
}
/** Get Paketbreite.
@return Paketbreite */
@Override
public java.math.BigDecimal getDK_ParcelWidth ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DK_ParcelWidth);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Referenz.
@param DK_Reference Referenz */
@Override
public void setDK_Reference (java.lang.String DK_Reference)
{
set_Value (COLUMNNAME_DK_Reference, DK_Reference);
}
/** Get Referenz.
@return Referenz */
@Override
public java.lang.String getDK_Reference ()
|
{
return (java.lang.String)get_Value(COLUMNNAME_DK_Reference);
}
/** Set Zeile Nr..
@param Line
Einzelne Zeile in dem Dokument
*/
@Override
public void setLine (int Line)
{
set_Value (COLUMNNAME_Line, Integer.valueOf(Line));
}
/** Get Zeile Nr..
@return Einzelne Zeile in dem Dokument
*/
@Override
public int getLine ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Line);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java-gen\de\metas\shipper\gateway\derkurier\model\X_DerKurier_DeliveryOrderLine.java
| 1
|
请完成以下Java代码
|
@NonNull Set<String> commaDelimitedStringToSet(@Nullable String commaDelimitedString) {
return StringUtils.hasText(commaDelimitedString)
? Arrays.stream(commaDelimitedString.split(","))
.map(String::trim)
.filter(StringUtils::hasText)
.collect(Collectors.toSet())
: Collections.emptySet();
}
@NonNull Set<String> getActiveProfiles(@NonNull Environment environment) {
return environment != null
? toSet(environment.getActiveProfiles(), String.class)
: Collections.emptySet();
}
@NonNull Set<String> useDefaultProfilesIfEmpty(@NonNull Environment environment,
@Nullable Set<String> activeProfiles) {
Set<String> resolvedProfiles = CollectionUtils.nullSafeSet(activeProfiles).stream()
.filter(StringUtils::hasText)
.collect(Collectors.toSet());
if (resolvedProfiles.isEmpty()) {
Set<String> defaultProfiles = environment != null
? toSet(environment.getDefaultProfiles(), String.class).stream()
.filter(StringUtils::hasText)
.collect(Collectors.toSet())
: Collections.emptySet();
|
if (isNotDefaultProfileOnlySet(defaultProfiles)) {
resolvedProfiles = defaultProfiles;
}
}
return resolvedProfiles;
}
// The Set of configured Profiles cannot be null, empty or contain only the "default" Profile.
boolean isNotDefaultProfileOnlySet(@Nullable Set<String> profiles) {
return Objects.nonNull(profiles)
&& !profiles.isEmpty()
&& !Collections.singleton(RESERVED_DEFAULT_PROFILE_NAME).containsAll(profiles);
}
private static @NonNull <T> Set<T> toSet(@Nullable T[] array, @NonNull Class<T> type) {
return CollectionUtils.asSet(ArrayUtils.nullSafeArray(array, type));
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\data\AbstractCacheDataImporterExporter.java
| 1
|
请完成以下Java代码
|
public void setSkipExpression(String skipExpression) {
this.skipExpression = skipExpression;
}
public boolean isAutoStoreVariables() {
return autoStoreVariables;
}
public void setAutoStoreVariables(boolean autoStoreVariables) {
this.autoStoreVariables = autoStoreVariables;
}
public boolean isDoNotIncludeVariables() {
return doNotIncludeVariables;
}
public void setDoNotIncludeVariables(boolean doNotIncludeVariables) {
this.doNotIncludeVariables = doNotIncludeVariables;
}
@Override
public List<IOParameter> getInParameters() {
return inParameters;
}
@Override
public void addInParameter(IOParameter inParameter) {
if (inParameters == null) {
inParameters = new ArrayList<>();
}
inParameters.add(inParameter);
}
@Override
public void setInParameters(List<IOParameter> inParameters) {
this.inParameters = inParameters;
}
|
@Override
public ScriptTask clone() {
ScriptTask clone = new ScriptTask();
clone.setValues(this);
return clone;
}
public void setValues(ScriptTask otherElement) {
super.setValues(otherElement);
setScriptFormat(otherElement.getScriptFormat());
setScript(otherElement.getScript());
setResultVariable(otherElement.getResultVariable());
setSkipExpression(otherElement.getSkipExpression());
setAutoStoreVariables(otherElement.isAutoStoreVariables());
setDoNotIncludeVariables(otherElement.isDoNotIncludeVariables());
inParameters = null;
if (otherElement.getInParameters() != null && !otherElement.getInParameters().isEmpty()) {
inParameters = new ArrayList<>();
for (IOParameter parameter : otherElement.getInParameters()) {
inParameters.add(parameter.clone());
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ScriptTask.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SysUserPositionServiceImpl extends ServiceImpl<SysUserPositionMapper, SysUserPosition> implements ISysUserPositionService {
@Autowired
private SysUserPositionMapper sysUserPositionMapper;
@Autowired
private SysUserMapper userMapper;
@Override
public IPage<SysUser> getPositionUserList(Page<SysUser> page, String positionId) {
return page.setRecords(sysUserPositionMapper.getPositionUserList(page, positionId));
}
@Override
public void saveUserPosition(String userIds, String positionId) {
String[] userIdArray = userIds.split(SymbolConstant.COMMA);
//存在的用户
StringBuilder userBuilder = new StringBuilder();
for (String userId : userIdArray) {
//获取成员是否存在于职位中
Long count = sysUserPositionMapper.getUserPositionCount(userId, positionId);
if (count == 0) {
//插入到用户职位关系表里面
SysUserPosition userPosition = new SysUserPosition();
userPosition.setPositionId(positionId);
userPosition.setUserId(userId);
sysUserPositionMapper.insert(userPosition);
} else {
userBuilder.append(userId).append(SymbolConstant.COMMA);
}
}
//如果用户id存在,说明已存在用户职位关系表中,提示用户已存在
String uIds = userBuilder.toString();
if (oConvertUtils.isNotEmpty(uIds)) {
//查询用户列表
List<SysUser> sysUsers = userMapper.selectBatchIds(Arrays.asList(uIds.split(SymbolConstant.COMMA)));
String realnames = sysUsers.stream().map(SysUser::getRealname).collect(Collectors.joining(SymbolConstant.COMMA));
|
throw new JeecgBootException(realnames + "已存在该职位中");
}
}
@Override
public void removeByPositionId(String positionId) {
sysUserPositionMapper.removeByPositionId(positionId);
}
@Override
public void removePositionUser(String userIds, String positionId) {
String[] userIdArray = userIds.split(SymbolConstant.COMMA);
sysUserPositionMapper.removePositionUser(Arrays.asList(userIdArray),positionId);
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysUserPositionServiceImpl.java
| 2
|
请完成以下Java代码
|
public Builder withResetButton(final boolean withResetButton)
{
this.withResetButton = withResetButton;
return this;
}
public Builder withCustomizeButton(final boolean withCustomizeButton)
{
this.withCustomizeButton = withCustomizeButton;
return this;
}
public Builder withHistoryButton(final boolean withHistoryButton)
{
this.withHistoryButton = withHistoryButton;
return this;
}
public Builder withZoomButton(final boolean withZoomButton)
{
this.withZoomButton = withZoomButton;
return this;
}
/**
* Advice builder to create the buttons with text on them.
*/
public Builder withText()
{
return withText(true);
|
}
/**
* Advice builder to create the buttons without any text on them.
*
* NOTE: this is the default option anyway. You can call it just to explicitly state the obvious.
*/
public Builder withoutText()
{
return withText(false);
}
/**
* Advice builder to create the buttons with or without text on them.
*
* @param withText true if buttons shall have text on them
*/
public Builder withText(final boolean withText)
{
this.withText = withText;
return this;
}
public Builder withSmallButtons(final boolean withSmallButtons)
{
smallButtons = withSmallButtons;
return this;
}
}
} // ConfirmPanel
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\ConfirmPanel.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class FTSConfigId implements RepoIdAware
{
@JsonCreator
public static FTSConfigId ofRepoId(final int repoId)
{
return new FTSConfigId(repoId);
}
@Nullable
public static FTSConfigId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new FTSConfigId(repoId) : null;
}
int repoId;
|
private FTSConfigId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "ES_FTS_Config_ID");
}
@JsonValue
@Override
public int getRepoId()
{
return repoId;
}
public static int toRepoId(@Nullable final FTSConfigId id)
{
return id != null ? id.getRepoId() : -1;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\config\FTSConfigId.java
| 2
|
请完成以下Java代码
|
protected Entry<String, List<Double>> createOutputDoubleValues(Collection<Map<String, Object>> ruleResults) {
Map<String, List<Double>> distinctOutputDoubleValues = new HashMap<>();
for (Map<String, Object> ruleResult : ruleResults) {
for (Entry<String, Object> entry : ruleResult.entrySet()) {
if (distinctOutputDoubleValues.containsKey(entry.getKey()) && distinctOutputDoubleValues.get(entry.getKey()) != null) {
distinctOutputDoubleValues.get(entry.getKey()).add((Double) entry.getValue());
} else {
List<Double> valuesList = new ArrayList<>();
valuesList.add((Double) entry.getValue());
distinctOutputDoubleValues.put(entry.getKey(), valuesList);
}
}
}
// get first entry
Entry<String, List<Double>> firstEntry = null;
if (!distinctOutputDoubleValues.isEmpty()) {
firstEntry = distinctOutputDoubleValues.entrySet().iterator().next();
}
return firstEntry;
}
protected Double aggregateSum(List<Double> values) {
double aggregate = 0;
for (Double value : values) {
aggregate += value;
}
return aggregate;
}
|
protected Double aggregateMin(List<Double> values) {
return Collections.min(values);
}
protected Double aggregateMax(List<Double> values) {
return Collections.max(values);
}
protected Double aggregateCount(List<Double> values) {
return (double) values.size();
}
protected Map<String, Object> createDecisionResults(String outputName, Double outputValue) {
Map<String, Object> ruleResult = new HashMap<>();
ruleResult.put(outputName, outputValue);
return ruleResult;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\hitpolicy\HitPolicyCollect.java
| 1
|
请完成以下Java代码
|
public Builder method(String method) {
this.method = method;
return this;
}
/**
* Sets the value of the HTTP target URI of the request to which the DPoP Proof
* {@link Jwt} is attached, without query and fragment parts.
* @param targetUri the value of the HTTP target URI of the request to which the
* DPoP Proof {@link Jwt} is attached
* @return the {@link Builder}
*/
public Builder targetUri(String targetUri) {
this.targetUri = targetUri;
return this;
}
/**
* Sets the access token if the request is a Protected Resource request.
* @param accessToken the access token if the request is a Protected Resource
* request
* @return the {@link Builder}
*/
public Builder accessToken(OAuth2Token accessToken) {
this.accessToken = accessToken;
return this;
}
/**
* Builds a new {@link DPoPProofContext}.
* @return a {@link DPoPProofContext}
*/
public DPoPProofContext build() {
|
validate();
return new DPoPProofContext(this.dPoPProof, this.method, this.targetUri, this.accessToken);
}
private void validate() {
Assert.hasText(this.method, "method cannot be empty");
Assert.hasText(this.targetUri, "targetUri cannot be empty");
if (!"GET".equals(this.method) && !"HEAD".equals(this.method) && !"POST".equals(this.method)
&& !"PUT".equals(this.method) && !"PATCH".equals(this.method) && !"DELETE".equals(this.method)
&& !"OPTIONS".equals(this.method) && !"TRACE".equals(this.method)) {
throw new IllegalArgumentException("method is invalid");
}
URI uri;
try {
uri = new URI(this.targetUri);
uri.toURL();
}
catch (Exception ex) {
throw new IllegalArgumentException("targetUri must be a valid URL", ex);
}
if (uri.getQuery() != null || uri.getFragment() != null) {
throw new IllegalArgumentException("targetUri cannot contain query or fragment parts");
}
}
}
}
|
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\DPoPProofContext.java
| 1
|
请完成以下Java代码
|
final class MaturingConfigMap
{
private final ImmutableMap<MaturingConfigLineId, MaturingConfigLine> byId;
private final ImmutableListMultimap<ProductId, MaturingConfigLine> byMaturedProductId;
private final ImmutableListMultimap<ProductId, MaturingConfigLine> byFromProductId;
public MaturingConfigMap(@NonNull final List<MaturingConfigLine> maturingConfigLines)
{
byId = Maps.uniqueIndex(maturingConfigLines, MaturingConfigLine::getId);
byMaturedProductId = maturingConfigLines.stream()
.collect(ImmutableListMultimap.toImmutableListMultimap(MaturingConfigLine::getMaturedProductId, line -> line));
byFromProductId = maturingConfigLines.stream()
.collect(ImmutableListMultimap.toImmutableListMultimap(MaturingConfigLine::getFromProductId, line -> line));
}
@NonNull
public MaturingConfigLine getById(@NonNull final MaturingConfigLineId id)
|
{
final MaturingConfigLine line = byId.get(id);
if (line == null)
{
throw new AdempiereException("@NotFound@ @M_MaturingConfig_Line_ID@: " + id);
}
return line;
}
public List<MaturingConfigLine> getByMaturedProductId(@NonNull final ProductId maturedProductId)
{
return byMaturedProductId.get(maturedProductId);
}
@NonNull
public List<MaturingConfigLine> getByFromProductId(@NonNull final ProductId maturedProductId)
{
return byFromProductId.get(maturedProductId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\material\maturing\MaturingConfigMap.java
| 1
|
请完成以下Spring Boot application配置
|
spring.security.user.name=baeldung
# Encoded password with SpringBoot CLI, the decoded password is baeldungPassword
spring.security.user.password={bc
|
rypt}$2y$10$R8VIwFiQ7aUST17YqMaWJuxjkCYqk3jjPlSxyDLLzqCTOwFuJNq2a
|
repos\tutorials-master\spring-boot-modules\spring-boot-cli\src\main\resources\application.properties
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void setUrl(String url) {
this.url = url;
}
@ApiModelProperty(value = "For a single resource contains the actual URL to use for retrieving the binary resource", example = "http://localhost:8081/flowable-rest/service/cmmn-repository/deployments/10/resources/diagrams%2Fmy-process.bpmn20.xml")
public String getUrl() {
return url;
}
public void setContentUrl(String contentUrl) {
this.contentUrl = contentUrl;
}
@ApiModelProperty(example = "http://localhost:8081/flowable-rest/service/cmmn-repository/deployments/10/resourcedata/diagrams%2Fmy-process.bpmn20.xml")
public String getContentUrl() {
return contentUrl;
}
public void setMediaType(String mimeType) {
this.mediaType = mimeType;
|
}
@ApiModelProperty(example = "text/xml", value = "Contains the media-type the resource has. This is resolved using a (pluggable) MediaTypeResolver and contains, by default, a limited number of mime-type mappings.")
public String getMediaType() {
return mediaType;
}
public void setType(String type) {
this.type = type;
}
@ApiModelProperty(example = "processDefinition", value = "Type of resource", allowableValues = "resource,processDefinition,processImage")
public String getType() {
return type;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\DeploymentResourceResponse.java
| 2
|
请完成以下Java代码
|
public void setFieldNurseIdentifier(@Nullable final String fieldNurseIdentifier)
{
this.fieldNurseIdentifier = fieldNurseIdentifier;
this.fieldNurseIdentifierSet = true;
}
public void setDeactivationReason(@Nullable final String deactivationReason)
{
this.deactivationReason = deactivationReason;
this.deactivationReasonSet = true;
}
public void setDeactivationDate(@Nullable final LocalDate deactivationDate)
{
this.deactivationDate = deactivationDate;
this.deactivationDateSet = true;
}
public void setDeactivationComment(@Nullable final String deactivationComment)
{
this.deactivationComment = deactivationComment;
this.deactivationCommentSet = true;
}
public void setClassification(@Nullable final String classification)
{
this.classification = classification;
this.classificationSet = true;
}
public void setCareDegree(@Nullable final BigDecimal careDegree)
{
this.careDegree = careDegree;
this.careDegreeSet = true;
}
public void setCreatedAt(@Nullable final Instant createdAt)
{
this.createdAt = createdAt;
this.createdAtSet = true;
|
}
public void setCreatedByIdentifier(@Nullable final String createdByIdentifier)
{
this.createdByIdentifier = createdByIdentifier;
this.createdByIdentifierSet = true;
}
public void setUpdatedAt(@Nullable final Instant updatedAt)
{
this.updatedAt = updatedAt;
this.updatedAtSet = true;
}
public void setUpdateByIdentifier(@Nullable final String updateByIdentifier)
{
this.updateByIdentifier = updateByIdentifier;
this.updateByIdentifierSet = true;
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\request\alberta\JsonAlbertaPatient.java
| 1
|
请完成以下Java代码
|
protected boolean hasExcludingConditions() {
return super.hasExcludingConditions() || CompareUtil.elementIsNotContainedInArray(variableName, variableNames);
}
// results ////////////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
checkQueryOk();
ensureVariablesInitialized();
return commandContext
.getVariableInstanceManager()
.findVariableInstanceCountByQueryCriteria(this);
}
@Override
public List<VariableInstance> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
ensureVariablesInitialized();
List<VariableInstance> result = commandContext
.getVariableInstanceManager()
.findVariableInstanceByQueryCriteria(this, page);
if (result == null) {
return result;
}
// iterate over the result array to initialize the value and serialized value of the variable
for (VariableInstance variableInstance : result) {
VariableInstanceEntity variableInstanceEntity = (VariableInstanceEntity) variableInstance;
if (shouldFetchValue(variableInstanceEntity)) {
try {
variableInstanceEntity.getTypedValue(isCustomObjectDeserializationEnabled);
} catch(Exception t) {
// do not fail if one of the variables fails to load
LOG.exceptionWhileGettingValueForVariable(t);
}
}
}
return result;
}
protected boolean shouldFetchValue(VariableInstanceEntity entity) {
// do not fetch values for byte arrays eagerly (unless requested by the user)
return isByteArrayFetchingEnabled
|| !AbstractTypedValueSerializer.BINARY_VALUE_TYPES.contains(entity.getSerializer().getType().getName());
}
// getters ////////////////////////////////////////////////////
public String getVariableId() {
return variableId;
}
|
public String getVariableName() {
return variableName;
}
public String[] getVariableNames() {
return variableNames;
}
public String getVariableNameLike() {
return variableNameLike;
}
public String[] getExecutionIds() {
return executionIds;
}
public String[] getProcessInstanceIds() {
return processInstanceIds;
}
public String[] getCaseExecutionIds() {
return caseExecutionIds;
}
public String[] getCaseInstanceIds() {
return caseInstanceIds;
}
public String[] getTaskIds() {
return taskIds;
}
public String[] getBatchIds() {
return batchIds;
}
public String[] getVariableScopeIds() {
return variableScopeIds;
}
public String[] getActivityInstanceIds() {
return activityInstanceIds;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\VariableInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
public class User implements Serializable {
private static final long serialVersionUID = 3317686311392412458L;
private String username;
private String password;
private String role;
private String email;
public User(String username, String password, String role) {
this.username = username;
this.password = password;
this.role = role;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
|
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + ", role=" + role + "]";
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-springdoc\src\main\java\com\baeldung\jwt\User.java
| 1
|
请完成以下Java代码
|
private static void startAddon(final String className)
{
try
{
final Class<?> clazz = Class.forName(className);
final Class<? extends IAddOn> clazzVC = clazz
.asSubclass(IAddOn.class);
final IAddOn instance = clazzVC.newInstance();
instance.beforeConnection();
}
catch (ClassNotFoundException e)
{
MetasfreshLastError.saveError(logger, "Addon not available: " + className, e);
}
|
catch (ClassCastException e)
{
MetasfreshLastError.saveError(logger, "Addon class " + className + " doesn't implement " + IAddOn.class.getName(), e);
}
catch (InstantiationException e)
{
throw new RuntimeException(e);
}
catch (IllegalAccessException e)
{
throw new RuntimeException(e);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\addon\impl\AddonStarter.java
| 1
|
请完成以下Java代码
|
public class CustomRecursiveAction extends RecursiveAction {
final Logger logger = LoggerFactory.getLogger(CustomRecursiveAction.class);
private String workLoad = "";
private static final int THRESHOLD = 4;
public CustomRecursiveAction(String workLoad) {
this.workLoad = workLoad;
}
@Override
protected void compute() {
if (workLoad.length() > THRESHOLD) {
ForkJoinTask.invokeAll(createSubtasks());
} else {
processing(workLoad);
}
}
private Collection<CustomRecursiveAction> createSubtasks() {
|
List<CustomRecursiveAction> subtasks = new ArrayList<>();
String partOne = workLoad.substring(0, workLoad.length() / 2);
String partTwo = workLoad.substring(workLoad.length() / 2, workLoad.length());
subtasks.add(new CustomRecursiveAction(partOne));
subtasks.add(new CustomRecursiveAction(partTwo));
return subtasks;
}
private void processing(String work) {
String result = work.toUpperCase();
logger.debug("This result - (" + result + ") - was processed by " + Thread.currentThread()
.getName());
}
}
|
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced\src\main\java\com\baeldung\forkjoin\CustomRecursiveAction.java
| 1
|
请完成以下Java代码
|
public boolean executeScript(String sql, String fileName) {
BufferedReader reader = new BufferedReader(new StringReader(sql));
StringBuffer sqlBuf = new StringBuffer();
String line;
boolean statementReady = false;
boolean execOk = true;
boolean longComment = false;
try {
while ((line = reader.readLine()) != null) {
// different continuation for oracle and postgres
line = line.trim();
//Check if it's a comment
if (line.startsWith("--") || line.length() == 0){
continue;
} else if (line.endsWith(";") && !longComment) {
sqlBuf.append(' ');
sqlBuf.append(line.substring(0, line.length() - 1));
statementReady = true;
} else if(line.startsWith("/*")){
longComment = true;
} else if(line.endsWith("*/")){
longComment = false;
} else {
if(longComment)
continue;
sqlBuf.append(' ');
sqlBuf.append(line);
statementReady = false;
}
if (statementReady) {
if (sqlBuf.length() == 0)
continue;
Connection conn = DB.getConnectionRW();
conn.setAutoCommit(false);
Statement stmt = null;
try {
stmt = conn.createStatement();
stmt.execute(sqlBuf.toString());
System.out.print(".");
|
} catch (SQLException e) {
e.printStackTrace();
execOk = false;
log.error("Script: " + fileName + " - " + e.getMessage() + ". The line that caused the error is the following ==> " + sqlBuf, e);
} finally {
stmt.close();
if(execOk)
conn.commit();
else
conn.rollback();
conn.setAutoCommit(true);
conn.close();
if(!execOk)
return false;
}
sqlBuf.setLength(0);
}
}
} catch(SQLException e){
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\process\ApplyMigrationScripts.java
| 1
|
请完成以下Java代码
|
public OrderStatusResponse getOrderStatus(@NonNull final Id orderId, @NonNull final BPartnerId bpartnerId)
{
final JpaOrder jpaOrder = getJpaOrder(orderId, bpartnerId);
return createOrderStatusResponse(jpaOrder);
}
private JpaOrder getJpaOrder(@NonNull final Id orderId, @NonNull final BPartnerId bpartnerId)
{
final JpaOrder jpaOrder = jpaOrdersRepo.findByDocumentNoAndMfBpartnerId(orderId.getValueAsString(), bpartnerId.getBpartnerId());
if (jpaOrder == null)
{
throw new RuntimeException("No order found for id='" + orderId + "' and bpartnerId='" + bpartnerId + "'");
}
return jpaOrder;
}
private OrderStatusResponse createOrderStatusResponse(final JpaOrder jpaOrder)
{
|
return OrderStatusResponse.builder()
.orderId(Id.of(jpaOrder.getDocumentNo()))
.supportId(SupportIDType.of(jpaOrder.getSupportId()))
.orderStatus(jpaOrder.getOrderStatus())
.orderPackages(jpaOrder.getOrderPackages().stream()
.map(this::createOrderResponsePackage)
.collect(ImmutableList.toImmutableList()))
.build();
}
public List<OrderResponse> getOrders()
{
return jpaOrdersRepo.findAll()
.stream()
.map(this::createOrderResponse)
.collect(ImmutableList.toImmutableList());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\order\OrderService.java
| 1
|
请完成以下Java代码
|
public static void fillJsonTypes(Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap) {
convertersToBpmnMap.put(STENCIL_TASK_DECISION, DecisionTaskJsonConverter.class);
}
public static void fillBpmnTypes(
Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap
) {}
protected String getStencilId(BaseElement baseElement) {
return STENCIL_TASK_DECISION;
}
protected FlowElement convertJsonToElement(
JsonNode elementNode,
JsonNode modelNode,
Map<String, JsonNode> shapeMap
) {
ServiceTask serviceTask = new ServiceTask();
serviceTask.setType(ServiceTask.DMN_TASK);
JsonNode decisionTableReferenceNode = getProperty(PROPERTY_DECISIONTABLE_REFERENCE, elementNode);
if (
decisionTableReferenceNode != null &&
decisionTableReferenceNode.has("id") &&
!(decisionTableReferenceNode.get("id").isNull())
) {
String decisionTableId = decisionTableReferenceNode.get("id").asText();
if (decisionTableMap != null) {
String decisionTableKey = decisionTableMap.get(decisionTableId);
FieldExtension decisionTableKeyField = new FieldExtension();
decisionTableKeyField.setFieldName(PROPERTY_DECISIONTABLE_REFERENCE_KEY);
decisionTableKeyField.setStringValue(decisionTableKey);
serviceTask.getFieldExtensions().add(decisionTableKeyField);
|
}
}
return serviceTask;
}
@Override
protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) {}
@Override
public void setDecisionTableMap(Map<String, String> decisionTableMap) {
this.decisionTableMap = decisionTableMap;
}
protected void addExtensionAttributeToExtension(ExtensionElement element, String attributeName, String value) {
ExtensionAttribute extensionAttribute = new ExtensionAttribute(NAMESPACE, attributeName);
extensionAttribute.setNamespacePrefix("modeler");
extensionAttribute.setValue(value);
element.addAttribute(extensionAttribute);
}
}
|
repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\DecisionTaskJsonConverter.java
| 1
|
请完成以下Java代码
|
public class CommandInvoker extends AbstractCommandInterceptor {
private static final Logger logger = LoggerFactory.getLogger(CommandInvoker.class);
@Override
@SuppressWarnings("unchecked")
public <T> T execute(final CommandConfig config, final Command<T> command) {
final CommandContext commandContext = Context.getCommandContext();
// Execute the command.
// This will produce operations that will be put on the agenda.
commandContext
.getAgenda()
.planOperation(
new Runnable() {
@Override
public void run() {
commandContext.setResult(command.execute(commandContext));
}
}
);
// Run loop for agenda
executeOperations(commandContext);
// At the end, call the execution tree change listeners.
// TODO: optimization: only do this when the tree has actually changed (ie check dbSqlSession).
if (commandContext.hasInvolvedExecutions()) {
Context.getAgenda().planExecuteInactiveBehaviorsOperation();
executeOperations(commandContext);
}
return (T) commandContext.getResult();
}
protected void executeOperations(final CommandContext commandContext) {
while (!commandContext.getAgenda().isEmpty()) {
Runnable runnable = commandContext.getAgenda().getNextOperation();
executeOperation(runnable);
}
}
public void executeOperation(Runnable runnable) {
|
if (runnable instanceof AbstractOperation) {
AbstractOperation operation = (AbstractOperation) runnable;
// Execute the operation if the operation has no execution (i.e. it's an operation not working on a process instance)
// or the operation has an execution and it is not ended
if (operation.getExecution() == null || !operation.getExecution().isEnded()) {
if (logger.isDebugEnabled()) {
logger.debug("Executing operation {} ", operation.getClass());
}
runnable.run();
}
} else {
runnable.run();
}
}
@Override
public CommandInterceptor getNext() {
return null;
}
@Override
public void setNext(CommandInterceptor next) {
throw new UnsupportedOperationException("CommandInvoker must be the last interceptor in the chain");
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\interceptor\CommandInvoker.java
| 1
|
请完成以下Java代码
|
public class Application {
private static final Logger LOG = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
new Application().run();
}
public void run() {
CassandraConnector connector = new CassandraConnector();
connector.connect("127.0.0.1", 9042, "datacenter1");
CqlSession session = connector.getSession();
KeyspaceRepository keyspaceRepository = new KeyspaceRepository(session);
keyspaceRepository.createKeyspace("testKeyspace", 1);
keyspaceRepository.useKeyspace("testKeyspace");
ProductRepository productRepository = new ProductRepository(session);
productRepository.createProductTable("testKeyspace");
productRepository.createProductByIdTable("testKeyspace");
productRepository.createProductByIdTable("testKeyspace");
Product product = getProduct();
productRepository.insertProductBatch(product);
Product productV1 = getProduct();
Product productV2 = getProduct();
|
productRepository.insertProductVariantBatch(productV1, productV2);
List<Product> products = productRepository.selectAllProduct("testKeyspace");
products.forEach(x -> LOG.info(x.toString()));
connector.close();
}
private Product getProduct() {
Product product = new Product();
product.setProductName("Banana");
product.setDescription("Banana");
product.setPrice(12f);
return product;
}
}
|
repos\tutorials-master\persistence-modules\java-cassandra\src\main\java\com\baeldung\cassandra\batch\Application.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public at.erpel.schemas._1p0.documents.extensions.edifact.CustomerExtensionType getCustomerExtension() {
return customerExtension;
}
/**
* Sets the value of the customerExtension property.
*
* @param value
* allowed object is
* {@link at.erpel.schemas._1p0.documents.extensions.edifact.CustomerExtensionType }
*
*/
public void setCustomerExtension(at.erpel.schemas._1p0.documents.extensions.edifact.CustomerExtensionType value) {
this.customerExtension = value;
}
/**
* Gets the value of the erpelCustomerExtension property.
*
* @return
* possible object is
* {@link CustomType }
*
*/
public CustomType getErpelCustomerExtension() {
|
return erpelCustomerExtension;
}
/**
* Sets the value of the erpelCustomerExtension property.
*
* @param value
* allowed object is
* {@link CustomType }
*
*/
public void setErpelCustomerExtension(CustomType value) {
this.erpelCustomerExtension = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ext\CustomerExtensionType.java
| 2
|
请完成以下Java代码
|
public Optional<V> get(K key) {
this.lock.readLock().lock();
try {
LinkedListNode<CacheElement<K, V>> linkedListNode = this.linkedListNodeMap.get(key);
if (linkedListNode != null && !linkedListNode.isEmpty()) {
linkedListNodeMap.put(key, this.doublyLinkedList.moveToFront(linkedListNode));
return Optional.of(linkedListNode.getElement().getValue());
}
return Optional.empty();
} finally {
this.lock.readLock().unlock();
}
}
@Override
public int size() {
this.lock.readLock().lock();
try {
return doublyLinkedList.size();
} finally {
this.lock.readLock().unlock();
}
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public void clear() {
this.lock.writeLock().lock();
try {
linkedListNodeMap.clear();
doublyLinkedList.clear();
|
} finally {
this.lock.writeLock().unlock();
}
}
private boolean evictElement() {
this.lock.writeLock().lock();
try {
LinkedListNode<CacheElement<K, V>> linkedListNode = doublyLinkedList.removeTail();
if (linkedListNode.isEmpty()) {
return false;
}
linkedListNodeMap.remove(linkedListNode.getElement().getKey());
return true;
} finally {
this.lock.writeLock().unlock();
}
}
}
|
repos\tutorials-master\data-structures\src\main\java\com\baeldung\lrucache\LRUCache.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class BPartnerId
{
public static BPartnerId of(final int bpartnerId, final int bpartnerLocationId)
{
return new BPartnerId(bpartnerId, bpartnerLocationId);
}
public static BPartnerId of(final int bpartnerId)
{
final int bpartnerLocationId = -1;
return new BPartnerId(bpartnerId, bpartnerLocationId);
}
@JsonProperty("bpartnerId")
private final int bpartnerId;
|
@JsonProperty("bpartnerLocationId")
private final int bpartnerLocationId;
@JsonCreator
private BPartnerId(
@JsonProperty("bpartnerId") final int bpartnerId,
@JsonProperty("bpartnerLocationId") final int bpartnerLocationId)
{
if (bpartnerId < 1)
{
throw new IllegalArgumentException("bpartnerId shall be > 0");
}
this.bpartnerId = bpartnerId;
this.bpartnerLocationId = bpartnerLocationId > 0 ? bpartnerLocationId : -1;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\types\BPartnerId.java
| 2
|
请完成以下Java代码
|
public class RuleNodeDebugEventFilter extends DebugEventFilter {
@Schema(description = "String value representing msg direction type (incoming to entity or outcoming from entity)", allowableValues = {"IN", "OUT"})
protected String msgDirectionType;
@Schema(description = "String value representing the entity id in the event body (originator of the message)", example = "de9d54a0-2b7a-11ec-a3cc-23386423d98f")
protected String entityId;
@Schema(description = "String value representing the entity type", allowableValues = "DEVICE")
protected String entityType;
@Schema(description = "String value representing the message id in the rule engine", example = "de9d54a0-2b7a-11ec-a3cc-23386423d98f")
protected String msgId;
@Schema(description = "String value representing the message type", example = "POST_TELEMETRY_REQUEST")
protected String msgType;
@Schema(description = "String value representing the type of message routing", example = "Success")
protected String relationType;
@Schema(description = "The case insensitive 'contains' filter based on data (key and value) for the message.", example = "humidity")
|
protected String dataSearch;
@Schema(description = "The case insensitive 'contains' filter based on metadata (key and value) for the message.", example = "deviceName")
protected String metadataSearch;
@Override
public EventType getEventType() {
return EventType.DEBUG_RULE_NODE;
}
@Override
public boolean isNotEmpty() {
return super.isNotEmpty() || !StringUtils.isEmpty(msgDirectionType) || !StringUtils.isEmpty(entityId)
|| !StringUtils.isEmpty(entityType) || !StringUtils.isEmpty(msgId) || !StringUtils.isEmpty(msgType) ||
!StringUtils.isEmpty(relationType) || !StringUtils.isEmpty(dataSearch) || !StringUtils.isEmpty(metadataSearch);
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\event\RuleNodeDebugEventFilter.java
| 1
|
请完成以下Java代码
|
public String toStringX()
{
return "MElementValue[" + get_ID() + "," + getValue() + " - " + getName() + "]";
}
@Override
protected boolean beforeSave(boolean newRecord)
{
//
// Transform to summary level account
if (!newRecord && isSummary() && is_ValueChanged(COLUMNNAME_IsSummary))
{
//
// Check if we have accounting facts
boolean match = new Query(getCtx(), I_Fact_Acct.Table_Name, I_Fact_Acct.COLUMNNAME_Account_ID + "=?", ITrx.TRXNAME_ThreadInherited)
.setParameters(getC_ElementValue_ID())
.anyMatch();
if (match)
{
throw new AdempiereException("@AlreadyPostedTo@");
}
//
// Check Valid Combinations - teo_sarca FR [ 1883533 ]
String whereClause = MAccount.COLUMNNAME_Account_ID + "=?";
POResultSet<MAccount> rs = new Query(getCtx(), MAccount.Table_Name, whereClause, ITrx.TRXNAME_ThreadInherited)
.setParameters(getC_ElementValue_ID())
.scroll();
try
{
while (rs.hasNext())
{
rs.next().deleteEx(true);
}
}
finally
{
DB.close(rs);
}
}
return true;
} // beforeSave
|
@Override
protected boolean afterSave(boolean newRecord, boolean success)
{
// Value/Name change
if (!newRecord && (is_ValueChanged(COLUMNNAME_Value) || is_ValueChanged(COLUMNNAME_Name)))
{
MAccount.updateValueDescription(getCtx(), "Account_ID=" + getC_ElementValue_ID(), get_TrxName());
if ("Y".equals(Env.getContext(getCtx(), Env.CTXNAME_AcctSchemaElementPrefix + AcctSchemaElementType.UserList1.getCode())))
{
MAccount.updateValueDescription(getCtx(), "User1_ID=" + getC_ElementValue_ID(), get_TrxName());
}
if ("Y".equals(Env.getContext(getCtx(), Env.CTXNAME_AcctSchemaElementPrefix + AcctSchemaElementType.UserList2.getCode())))
{
MAccount.updateValueDescription(getCtx(), "User2_ID=" + getC_ElementValue_ID(), get_TrxName());
}
}
return success;
} // afterSave
} // MElementValue
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MElementValue.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void create(App resources) {
// 验证应用名称是否存在恶意攻击payload,https://github.com/elunez/eladmin/issues/873
String appName = resources.getName();
if (appName.contains(";") || appName.contains("|") || appName.contains("&")) {
throw new IllegalArgumentException("非法的应用名称,请勿包含[; | &]等特殊字符");
}
verification(resources);
appRepository.save(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(App resources) {
// 验证应用名称是否存在恶意攻击payload,https://github.com/elunez/eladmin/issues/873
String appName = resources.getName();
if (appName.contains(";") || appName.contains("|") || appName.contains("&")) {
throw new IllegalArgumentException("非法的应用名称,请勿包含[; | &]等特殊字符");
}
verification(resources);
App app = appRepository.findById(resources.getId()).orElseGet(App::new);
ValidationUtil.isNull(app.getId(),"App","id",resources.getId());
app.copy(resources);
appRepository.save(app);
}
private void verification(App resources){
String opt = "/opt";
String home = "/home";
if (!(resources.getUploadPath().startsWith(opt) || resources.getUploadPath().startsWith(home))) {
throw new BadRequestException("文件只能上传在opt目录或者home目录 ");
}
if (!(resources.getDeployPath().startsWith(opt) || resources.getDeployPath().startsWith(home))) {
throw new BadRequestException("文件只能部署在opt目录或者home目录 ");
}
if (!(resources.getBackupPath().startsWith(opt) || resources.getBackupPath().startsWith(home))) {
throw new BadRequestException("文件只能备份在opt目录或者home目录 ");
}
}
@Override
@Transactional(rollbackFor = Exception.class)
|
public void delete(Set<Long> ids) {
for (Long id : ids) {
appRepository.deleteById(id);
}
}
@Override
public void download(List<AppDto> queryAll, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (AppDto appDto : queryAll) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("应用名称", appDto.getName());
map.put("端口", appDto.getPort());
map.put("上传目录", appDto.getUploadPath());
map.put("部署目录", appDto.getDeployPath());
map.put("备份目录", appDto.getBackupPath());
map.put("启动脚本", appDto.getStartScript());
map.put("部署脚本", appDto.getDeployScript());
map.put("创建日期", appDto.getCreateTime());
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\service\impl\AppServiceImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class GeodeConfiguration {
// TODO: Replace with the SDG `@EnableCachingDefineRegions annotation declared above (and currently commented out,
// because...) once DATAGEODE-219 is resolved. :(
// tag::region[]
@Bean("YellowPages")
public ClientRegionFactoryBean<Object, Object> yellowPagesRegion(GemFireCache gemfireCache) {
ClientRegionFactoryBean<Object, Object> clientRegion = new ClientRegionFactoryBean<>();
clientRegion.setCache(gemfireCache);
clientRegion.setClose(false);
clientRegion.setShortcut(ClientRegionShortcut.CACHING_PROXY);
clientRegion.setRegionConfigurers(
interestRegisteringRegionConfigurer(),
subscriptionCacheListenerRegionConfigurer()
);
return clientRegion;
}
// end::region[]
// tag::interest-registration[]
@Bean
RegionConfigurer interestRegisteringRegionConfigurer() {
return new RegionConfigurer() {
@Override
@SuppressWarnings("unchecked")
public void configure(String beanName, ClientRegionFactoryBean<?, ?> clientRegion) {
Interest interest = new RegexInterest(".*", InterestResultPolicy.NONE,
false, true);
clientRegion.setInterests(ArrayUtils.asArray(interest));
}
};
}
// end::interest-registration[]
|
// tag::subscription-cache-listener[]
@Bean
RegionConfigurer subscriptionCacheListenerRegionConfigurer() {
return new RegionConfigurer() {
@Override
@SuppressWarnings("unchecked")
public void configure(String beanName, ClientRegionFactoryBean<?, ?> clientRegion) {
CacheListener subscriptionCacheListener =
new AbstractCommonEventProcessingCacheListener() {
@Override
protected void processEntryEvent(EntryEvent event, EntryEventType eventType) {
if (event.isOriginRemote()) {
System.err.printf("[%1$s] EntryEvent for [%2$s] with value [%3$s]%n",
event.getKey(), event.getOperation(), event.getNewValue());
}
}
};
clientRegion.setCacheListeners(ArrayUtils.asArray(subscriptionCacheListener));
}
};
}
// end::subscription-cache-listener[]
}
// end::class[]
|
repos\spring-boot-data-geode-main\spring-geode-samples\caching\near\src\main\java\example\app\caching\near\client\config\GeodeConfiguration.java
| 2
|
请完成以下Java代码
|
public String getName() {
return this.name;
}
/**
* Returns an {@link Optional} {@link String} containing {@link User User's} password.
*
* @return an {@link Optional} {@link String} containing {@link User User's} password.
* @see java.util.Optional
*/
public Optional<String> getPassword() {
return Optional.ofNullable(this.password).filter(StringUtils::hasText);
}
/**
* Returns an {@link Optional} {@link Role} for this {@link User}.
*
* @return an {@link Optional} {@link Role} for this {@link User}.
* @see org.springframework.geode.core.env.support.User.Role
* @see java.util.Optional
*/
public Optional<Role> getRole() {
return Optional.ofNullable(this.role);
}
/**
* Builder method used to set this {@link User User's} {@link String password}.
*
* @param password {@link String} containing this {@link User User's} password.
* @return this {@link User}.
*/
public User withPassword(String password) {
this.password = password;
return this;
}
/**
* Builder method used to set this {@link User User's} {@link Role}.
*
* @param role assigned {@link Role} of this {@link User}.
* @return this {@link User}.
* @see org.springframework.geode.core.env.support.User
*/
public User withRole(Role role) {
this.role = role;
return this;
}
@Override
@SuppressWarnings("all")
public int compareTo(User other) {
return this.getName().compareTo(other.getName());
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
|
if (!(obj instanceof User)) {
return false;
}
User that = (User) obj;
return this.getName().equals(that.getName());
}
@Override
public int hashCode() {
int hashValue = 17;
hashValue = 37 * hashValue + ObjectUtils.nullSafeHashCode(getName());
return hashValue;
}
@Override
public String toString() {
return getName();
}
public enum Role {
CLUSTER_OPERATOR,
DEVELOPER;
public static Role of(String name) {
return Arrays.stream(values())
.filter(role -> role.name().equalsIgnoreCase(String.valueOf(name).trim()))
.findFirst()
.orElse(null);
}
public boolean isClusterOperator() {
return CLUSTER_OPERATOR.equals(this);
}
public boolean isDeveloper() {
return DEVELOPER.equals(this);
}
@Override
public String toString() {
return name().toLowerCase();
}
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\env\support\User.java
| 1
|
请完成以下Java代码
|
public void setMD_Cockpit(final de.metas.material.cockpit.model.I_MD_Cockpit MD_Cockpit)
{
set_ValueFromPO(COLUMNNAME_MD_Cockpit_ID, de.metas.material.cockpit.model.I_MD_Cockpit.class, MD_Cockpit);
}
@Override
public void setMD_Cockpit_ID (final int MD_Cockpit_ID)
{
if (MD_Cockpit_ID < 1)
set_Value (COLUMNNAME_MD_Cockpit_ID, null);
else
set_Value (COLUMNNAME_MD_Cockpit_ID, MD_Cockpit_ID);
}
@Override
public int getMD_Cockpit_ID()
{
return get_ValueAsInt(COLUMNNAME_MD_Cockpit_ID);
}
@Override
public void setM_Warehouse_ID (final int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_Value (COLUMNNAME_M_Warehouse_ID, null);
else
set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID);
}
@Override
|
public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
@Override
public void setQtyPending (final BigDecimal QtyPending)
{
set_Value (COLUMNNAME_QtyPending, QtyPending);
}
@Override
public BigDecimal getQtyPending()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPending);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_MD_Cockpit_DDOrder_Detail.java
| 1
|
请完成以下Java代码
|
public String sendCmd(@NonNull final String cmd)
{
try (final Socket clientSocket = new Socket(hostName, port);
final OutputStream out = clientSocket.getOutputStream();)
{
clientSocket.setSoTimeout(readTimeoutMillis);
logger.debug("Writing cmd to the socket: {}", cmd);
out.write(cmd.getBytes(ICmd.DEFAULT_CMD_CHARSET));
out.flush();
return readSocketResponse(clientSocket.getInputStream());
}
catch (final UnknownHostException e)
{
throw new EndPointException("Caught UnknownHostException: " + e.getLocalizedMessage(), e);
}
catch (final IOException e)
{
throw new EndPointException("Caught IOException: " + e.getLocalizedMessage(), e);
}
}
@Nullable
String readSocketResponse(@NonNull final InputStream in) throws IOException
{
final StringBuilder sb = new StringBuilder();
int i;
try
{
while ((i = in.read()) != -1)
{
sb.append((char)i);
}
}
catch (final SocketTimeoutException e)
{
// if the device doesn't send "EOF", then there is nothing we can do here
// ..because at this place here we don't know how the response is terminated.
// so we just wait for the respective timeout
}
return sb.toString();
}
|
public TcpConnectionEndPoint setHost(final String hostName)
{
this.hostName = hostName;
return this;
}
public TcpConnectionEndPoint setPort(final int port)
{
this.port = port;
return this;
}
/**
* Timeout for this endpoint for each read, before considering the result to be <code>null</code>. The default is 500ms.
*/
public TcpConnectionEndPoint setReadTimeoutMillis(final int readTimeoutMillis)
{
this.readTimeoutMillis = readTimeoutMillis;
return this;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("hostName", hostName)
.add("port", port)
.toString();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\endpoint\TcpConnectionEndPoint.java
| 1
|
请完成以下Java代码
|
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Coordinates getCoordinates() {
return coordinates;
}
public void setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getEventClass() {
return eventClass;
}
public void setEventClass(String eventClass) {
this.eventClass = eventClass;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
|
}
public int getSpeedKmPerS() {
return speedKmPerS;
}
public void setSpeedKmPerS(int speedKmPerS) {
this.speedKmPerS = speedKmPerS;
}
}
class Coordinates {
@JsonProperty("latitude")
private double latitude;
@JsonProperty("longitude")
private double longitude;
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
}
|
repos\tutorials-master\json-modules\json-operations\src\main\java\com\baeldung\sorting\SolarEvent.java
| 1
|
请完成以下Java代码
|
public ConditionExpression newInstance(ModelTypeInstanceContext instanceContext) {
return new ConditionExpressionImpl(instanceContext);
}
});
typeAttribute = typeBuilder.stringAttribute(XSI_ATTRIBUTE_TYPE)
.namespace(XSI_NS)
.defaultValue("tFormalExpression")
.build();
camundaResourceAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_RESOURCE)
.namespace(CAMUNDA_NS)
.build();
typeBuilder.build();
}
public ConditionExpressionImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getType() {
|
return typeAttribute.getValue(this);
}
public void setType(String type) {
typeAttribute.setValue(this, type);
}
public String getCamundaResource() {
return camundaResourceAttribute.getValue(this);
}
public void setCamundaResource(String camundaResource) {
camundaResourceAttribute.setValue(this, camundaResource);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ConditionExpressionImpl.java
| 1
|
请完成以下Java代码
|
public org.compiere.model.I_C_ElementValue getUser1()
{
return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser1(org.compiere.model.I_C_ElementValue User1)
{
set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1);
}
/** Set User List 1.
@param User1_ID
User defined list element #1
*/
@Override
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
*/
@Override
public int getUser1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ElementValue getUser2()
{
return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser2(org.compiere.model.I_C_ElementValue User2)
{
set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2);
}
/** Set User List 2.
@param User2_ID
User defined list element #2
*/
@Override
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
*/
@Override
public int getUser2_ID ()
{
|
Integer ii = (Integer)get_Value(COLUMNNAME_User2_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set User Element 1.
@param UserElement1_ID
User defined accounting Element
*/
@Override
public void setUserElement1_ID (int UserElement1_ID)
{
if (UserElement1_ID < 1)
set_Value (COLUMNNAME_UserElement1_ID, null);
else
set_Value (COLUMNNAME_UserElement1_ID, Integer.valueOf(UserElement1_ID));
}
/** Get User Element 1.
@return User defined accounting Element
*/
@Override
public int getUserElement1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UserElement1_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set User Element 2.
@param UserElement2_ID
User defined accounting Element
*/
@Override
public void setUserElement2_ID (int UserElement2_ID)
{
if (UserElement2_ID < 1)
set_Value (COLUMNNAME_UserElement2_ID, null);
else
set_Value (COLUMNNAME_UserElement2_ID, Integer.valueOf(UserElement2_ID));
}
/** Get User Element 2.
@return User defined accounting Element
*/
@Override
public int getUserElement2_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UserElement2_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Fact_Acct_Summary.java
| 1
|
请完成以下Java代码
|
public java.math.BigDecimal getQtyDelivered_TU ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyDelivered_TU);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Bestellte Menge (LU).
@param QtyOrdered_LU
Bestellte Menge (LU)
*/
@Override
public void setQtyOrdered_LU (java.math.BigDecimal QtyOrdered_LU)
{
set_Value (COLUMNNAME_QtyOrdered_LU, QtyOrdered_LU);
}
/** Get Bestellte Menge (LU).
@return Bestellte Menge (LU)
*/
@Override
public java.math.BigDecimal getQtyOrdered_LU ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOrdered_LU);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Bestellte Menge (TU).
@param QtyOrdered_TU
Bestellte Menge (TU)
*/
@Override
public void setQtyOrdered_TU (java.math.BigDecimal QtyOrdered_TU)
{
set_Value (COLUMNNAME_QtyOrdered_TU, QtyOrdered_TU);
}
/** Get Bestellte Menge (TU).
@return Bestellte Menge (TU)
*/
@Override
public java.math.BigDecimal getQtyOrdered_TU ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOrdered_TU);
|
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Ausliefermenge (LU).
@param QtyToDeliver_LU Ausliefermenge (LU) */
@Override
public void setQtyToDeliver_LU (java.math.BigDecimal QtyToDeliver_LU)
{
set_Value (COLUMNNAME_QtyToDeliver_LU, QtyToDeliver_LU);
}
/** Get Ausliefermenge (LU).
@return Ausliefermenge (LU) */
@Override
public java.math.BigDecimal getQtyToDeliver_LU ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyToDeliver_LU);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Ausliefermenge (TU).
@param QtyToDeliver_TU Ausliefermenge (TU) */
@Override
public void setQtyToDeliver_TU (java.math.BigDecimal QtyToDeliver_TU)
{
set_Value (COLUMNNAME_QtyToDeliver_TU, QtyToDeliver_TU);
}
/** Get Ausliefermenge (TU).
@return Ausliefermenge (TU) */
@Override
public java.math.BigDecimal getQtyToDeliver_TU ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyToDeliver_TU);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\tourplanning\model\X_M_Tour_Instance.java
| 1
|
请完成以下Java代码
|
public void benchMurmur3_128(ExecutionPlan plan) {
for (int i = plan.iterations; i > 0; i--) {
plan.murmur3.putString(plan.password, Charset.defaultCharset());
}
plan.murmur3.hash();
}
@Benchmark
@Fork(value = 1, warmups = 1)
@BenchmarkMode(Mode.Throughput)
public void init() {
// Do nothing
}
@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public void doNothing() {
}
@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public void objectCreation() {
new Object();
}
@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public Object pillarsOfCreation() {
return new Object();
}
|
@Benchmark
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public void blackHole(Blackhole blackhole) {
blackhole.consume(new Object());
}
@Benchmark
public double foldedLog() {
int x = 8;
return Math.log(x);
}
@Benchmark
public double log(Log input) {
return Math.log(input.x);
}
}
|
repos\tutorials-master\jmh\src\main\java\com\baeldung\BenchMark.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private Instant getLastUpdate(
@NonNull final List<I_M_Product_AlbertaPackagingUnit> packagingUnitList,
@NonNull final List<I_M_Product_AlbertaTherapy> therapies,
@NonNull final List<I_M_Product_AlbertaBillableTherapy> billableTherapies,
@Nullable final I_M_Product_AlbertaArticle albertaArticle,
@Nullable final I_M_ProductPrice productPrice)
{
final List<Instant> updateTimestamps = new ArrayList<>();
packagingUnitList.stream()
.map(I_M_Product_AlbertaPackagingUnit::getUpdated)
.map(Timestamp::toInstant)
.max(Comparator.comparing(Instant::toEpochMilli))
.ifPresent(updateTimestamps::add);
therapies.stream()
.map(I_M_Product_AlbertaTherapy::getUpdated)
.map(Timestamp::toInstant)
.max(Instant::compareTo)
.ifPresent(updateTimestamps::add);
billableTherapies.stream()
.map(I_M_Product_AlbertaBillableTherapy::getUpdated)
.map(Timestamp::toInstant)
.max(Instant::compareTo)
.ifPresent(updateTimestamps::add);
Optional.ofNullable(albertaArticle)
.map(I_M_Product_AlbertaArticle::getUpdated)
.map(Timestamp::toInstant)
.ifPresent(updateTimestamps::add);
Optional.ofNullable(productPrice)
.map(I_M_ProductPrice::getUpdated)
.map(Timestamp::toInstant)
|
.ifPresent(updateTimestamps::add);
return updateTimestamps
.stream()
.max(Instant::compareTo)
.orElseGet(() -> Instant.ofEpochMilli(0));
}
@NonNull
private AlbertaPackagingUnit recordToPackingUnit(@NonNull final I_M_Product_AlbertaPackagingUnit record)
{
return AlbertaPackagingUnit.builder()
.quantity(record.getQty())
.unit(record.getArticleUnit())
.build();
}
@NonNull
private Set<ProductId> getProductIdSet()
{
final ImmutableSet.Builder<ProductId> productIds = ImmutableSet.builder();
product2Therapies.keySet().forEach(productIds::add);
product2BillableTherapies.keySet().forEach(productIds::add);
product2PackagingUnits.keySet().forEach(productIds::add);
product2AlbertaArticle.keySet().forEach(productIds::add);
return productIds.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java\de\metas\vertical\healthcare\alberta\service\AlbertaCompositeProductProducer.java
| 2
|
请完成以下Java代码
|
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
// public Boolean getEnabled() {
// return enabled;
// }
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Boolean getLocked() {
|
return locked;
}
public void setLocked(Boolean locked) {
this.locked = locked;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
}
|
repos\springboot-demo-master\security\src\main\java\com\et\security\entity\User.java
| 1
|
请完成以下Java代码
|
public void setUserDiscount (java.math.BigDecimal UserDiscount)
{
set_Value (COLUMNNAME_UserDiscount, UserDiscount);
}
/** Get UserDiscount.
@return UserDiscount */
@Override
public java.math.BigDecimal getUserDiscount ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_UserDiscount);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/**
* UserLevel AD_Reference_ID=226
* Reference name: AD_Role User Level
*/
public static final int USERLEVEL_AD_Reference_ID=226;
/** System = S__ */
public static final String USERLEVEL_System = "S__";
/** Client = _C_ */
public static final String USERLEVEL_Client = "_C_";
/** Organization = __O */
public static final String USERLEVEL_Organization = "__O";
/** Client+Organization = _CO */
public static final String USERLEVEL_ClientPlusOrganization = "_CO";
/** Set Nutzer-Ebene.
@param UserLevel
System Client Organization
*/
@Override
public void setUserLevel (java.lang.String UserLevel)
{
set_Value (COLUMNNAME_UserLevel, UserLevel);
}
/** Get Nutzer-Ebene.
@return System Client Organization
*/
@Override
public java.lang.String getUserLevel ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserLevel);
}
|
/** Set Is webui role.
@param WEBUI_Role Is webui role */
@Override
public void setWEBUI_Role (boolean WEBUI_Role)
{
set_Value (COLUMNNAME_WEBUI_Role, Boolean.valueOf(WEBUI_Role));
}
/** Get Is webui role.
@return Is webui role */
@Override
public boolean isWEBUI_Role ()
{
Object oo = get_Value(COLUMNNAME_WEBUI_Role);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public void setIsAllowPasswordChangeForOthers (final boolean IsAllowPasswordChangeForOthers)
{
set_Value (COLUMNNAME_IsAllowPasswordChangeForOthers, IsAllowPasswordChangeForOthers);
}
@Override
public boolean isAllowPasswordChangeForOthers()
{
return get_ValueAsBoolean(COLUMNNAME_IsAllowPasswordChangeForOthers);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role.java
| 1
|
请完成以下Java代码
|
public ActiveOrHistoricCurrencyAndAmount getTtlChrgsAndTaxAmt() {
return ttlChrgsAndTaxAmt;
}
/**
* Sets the value of the ttlChrgsAndTaxAmt property.
*
* @param value
* allowed object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public void setTtlChrgsAndTaxAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.ttlChrgsAndTaxAmt = value;
}
/**
* Gets the value of the rcrd property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the rcrd property.
*
* <p>
|
* For example, to add a new item, do as follows:
* <pre>
* getRcrd().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ChargesRecord2 }
*
*
*/
public List<ChargesRecord2> getRcrd() {
if (rcrd == null) {
rcrd = new ArrayList<ChargesRecord2>();
}
return this.rcrd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\Charges4.java
| 1
|
请完成以下Java代码
|
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@PrePersist
private void prePersist() {
logger.info("@PrePersist callback ...");
}
@PreUpdate
private void preUpdate() {
logger.info("@PreUpdate callback ...");
}
@PreRemove
private void preRemove() {
logger.info("@PreRemove callback ...");
}
@PostLoad
private void postLoad() {
logger.info("@PostLoad callback ...");
}
|
@PostPersist
private void postPersist() {
logger.info("@PostPersist callback ...");
}
@PostUpdate
private void postUpdate() {
logger.info("@PostUpdate callback ...");
}
@PostRemove
private void postRemove() {
logger.info("@PostRemove callback ...");
}
@Override
public String toString() {
return "Author{" + "id=" + id + ", age=" + age
+ ", name=" + name + ", genre=" + genre + '}';
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootJpaCallbacks\src\main\java\com\bookstore\entity\Author.java
| 1
|
请完成以下Java代码
|
LocalDate getFirstDayOfMonth() {
LocalDate firstDayOfMonth = LocalDate.now()
.with(TemporalAdjusters.firstDayOfMonth());
return firstDayOfMonth;
}
boolean isLeapYear(LocalDate localDate) {
return localDate.isLeapYear();
}
LocalDateTime getStartOfDay(LocalDate localDate) {
LocalDateTime startofDay = localDate.atStartOfDay();
return startofDay;
}
LocalDateTime getStartOfDayOfLocalDate(LocalDate localDate) {
LocalDateTime startofDay = LocalDateTime.of(localDate, LocalTime.MIDNIGHT);
return startofDay;
}
LocalDateTime getStartOfDayAtMinTime(LocalDate localDate) {
LocalDateTime startofDay = localDate.atTime(LocalTime.MIN);
return startofDay;
}
|
LocalDateTime getStartOfDayAtMidnightTime(LocalDate localDate) {
LocalDateTime startofDay = localDate.atTime(LocalTime.MIDNIGHT);
return startofDay;
}
LocalDateTime getEndOfDay(LocalDate localDate) {
LocalDateTime endOfDay = localDate.atTime(LocalTime.MAX);
return endOfDay;
}
LocalDateTime getEndOfDayFromLocalTime(LocalDate localDate) {
LocalDateTime endOfDate = LocalTime.MAX.atDate(localDate);
return endOfDate;
}
}
|
repos\tutorials-master\core-java-modules\core-java-8-datetime\src\main\java\com\baeldung\datetime\UseLocalDate.java
| 1
|
请完成以下Java代码
|
public String getAlias() {
return alias;
}
@Override
public String getStorePwd() {
return storePwd;
}
@Override
public String getKeyPwd() {
return keyPwd;
}
/**
|
* <p>项目名称: true-license-demo </p>
* <p>文件名称: CustomKeyStoreParam.java </p>
* <p>方法描述: 用于将公私钥存储文件存放到其他磁盘位置而不是项目中,AbstractKeyStoreParam 里面的 getStream() 方法默认文件是存储的项目中 </p>
* <p>创建时间: 2020/10/10 13:31 </p>
*
* @param
* @return java.io.InputStream
* @author 方瑞冬
* @version 1.0
*/
@Override
public InputStream getStream() throws IOException {
return new FileInputStream(new File(storePath));
}
}
|
repos\springboot-demo-master\SoftwareLicense\src\main\java\com\et\license\license\CustomKeyStoreParam.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isRegisterDefaultServlet() {
return this.registerDefaultServlet;
}
public void setRegisterDefaultServlet(boolean registerDefaultServlet) {
this.registerDefaultServlet = registerDefaultServlet;
}
public Map<String, String> getContextParameters() {
return this.contextParameters;
}
public Encoding getEncoding() {
return this.encoding;
}
public Jsp getJsp() {
return this.jsp;
}
public Session getSession() {
return this.session;
}
}
/**
* Reactive server properties.
*/
public static class Reactive {
private final Session session = new Session();
public Session getSession() {
return this.session;
}
public static class Session {
/**
* Session timeout. If a duration suffix is not specified, seconds will be
* used.
*/
@DurationUnit(ChronoUnit.SECONDS)
private Duration timeout = Duration.ofMinutes(30);
/**
* Maximum number of sessions that can be stored.
*/
private int maxSessions = 10000;
@NestedConfigurationProperty
private final Cookie cookie = new Cookie();
public Duration getTimeout() {
return this.timeout;
}
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
public int getMaxSessions() {
return this.maxSessions;
}
public void setMaxSessions(int maxSessions) {
this.maxSessions = maxSessions;
}
public Cookie getCookie() {
return this.cookie;
}
}
}
/**
|
* Strategies for supporting forward headers.
*/
public enum ForwardHeadersStrategy {
/**
* Use the underlying container's native support for forwarded headers.
*/
NATIVE,
/**
* Use Spring's support for handling forwarded headers.
*/
FRAMEWORK,
/**
* Ignore X-Forwarded-* headers.
*/
NONE
}
public static class Encoding {
/**
* Mapping of locale to charset for response encoding.
*/
private @Nullable Map<Locale, Charset> mapping;
public @Nullable Map<Locale, Charset> getMapping() {
return this.mapping;
}
public void setMapping(@Nullable Map<Locale, Charset> mapping) {
this.mapping = mapping;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\autoconfigure\ServerProperties.java
| 2
|
请完成以下Java代码
|
public void setWEBUI_NameNew (java.lang.String WEBUI_NameNew)
{
set_Value (COLUMNNAME_WEBUI_NameNew, WEBUI_NameNew);
}
/** Get New record name.
@return New record name */
@Override
public java.lang.String getWEBUI_NameNew ()
{
return (java.lang.String)get_Value(COLUMNNAME_WEBUI_NameNew);
}
/** Set New record name (breadcrumb).
@param WEBUI_NameNewBreadcrumb New record name (breadcrumb) */
@Override
public void setWEBUI_NameNewBreadcrumb (java.lang.String WEBUI_NameNewBreadcrumb)
{
set_Value (COLUMNNAME_WEBUI_NameNewBreadcrumb, WEBUI_NameNewBreadcrumb);
}
/** Get New record name (breadcrumb).
@return New record name (breadcrumb) */
@Override
public java.lang.String getWEBUI_NameNewBreadcrumb ()
{
return (java.lang.String)get_Value(COLUMNNAME_WEBUI_NameNewBreadcrumb);
}
/**
* WidgetSize AD_Reference_ID=540724
* Reference name: WidgetSize_WEBUI
*/
public static final int WIDGETSIZE_AD_Reference_ID=540724;
/** Small = S */
public static final String WIDGETSIZE_Small = "S";
/** Medium = M */
public static final String WIDGETSIZE_Medium = "M";
/** Large = L */
|
public static final String WIDGETSIZE_Large = "L";
/** Set Widget size.
@param WidgetSize Widget size */
@Override
public void setWidgetSize (java.lang.String WidgetSize)
{
set_Value (COLUMNNAME_WidgetSize, WidgetSize);
}
/** Get Widget size.
@return Widget size */
@Override
public java.lang.String getWidgetSize ()
{
return (java.lang.String)get_Value(COLUMNNAME_WidgetSize);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Element.java
| 1
|
请完成以下Java代码
|
public final class OAuth2AuthorizationServerMetadata extends AbstractOAuth2AuthorizationServerMetadata {
@Serial
private static final long serialVersionUID = 3993358339217009284L;
private OAuth2AuthorizationServerMetadata(Map<String, Object> claims) {
super(claims);
}
/**
* Constructs a new {@link Builder} with empty claims.
* @return the {@link Builder}
*/
public static Builder builder() {
return new Builder();
}
/**
* Constructs a new {@link Builder} with the provided claims.
* @param claims the claims to initialize the builder
* @return the {@link Builder}
*/
public static Builder withClaims(Map<String, Object> claims) {
Assert.notEmpty(claims, "claims cannot be empty");
return new Builder().claims((c) -> c.putAll(claims));
}
|
/**
* Helps configure an {@link OAuth2AuthorizationServerMetadata}.
*/
public static final class Builder extends AbstractBuilder<OAuth2AuthorizationServerMetadata, Builder> {
private Builder() {
}
/**
* Validate the claims and build the {@link OAuth2AuthorizationServerMetadata}.
* <p>
* The following claims are REQUIRED: {@code issuer},
* {@code authorization_endpoint}, {@code token_endpoint} and
* {@code response_types_supported}.
* @return the {@link OAuth2AuthorizationServerMetadata}
*/
@Override
public OAuth2AuthorizationServerMetadata build() {
validate();
return new OAuth2AuthorizationServerMetadata(getClaims());
}
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\OAuth2AuthorizationServerMetadata.java
| 1
|
请完成以下Java代码
|
public int getAD_Attachment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Attachment_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Table getAD_Table() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Table_ID, org.compiere.model.I_AD_Table.class);
}
@Override
public void setAD_Table(org.compiere.model.I_AD_Table AD_Table)
{
set_ValueFromPO(COLUMNNAME_AD_Table_ID, org.compiere.model.I_AD_Table.class, AD_Table);
}
/** Set DB-Tabelle.
@param AD_Table_ID
Database Table information
*/
@Override
public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get DB-Tabelle.
@return Database Table information
*/
@Override
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Binärwert.
@param BinaryData
Binary Data
*/
@Override
public void setBinaryData (byte[] BinaryData)
{
set_ValueNoCheck (COLUMNNAME_BinaryData, BinaryData);
}
/** Get Binärwert.
@return Binary Data
*/
@Override
public byte[] getBinaryData ()
{
return (byte[])get_Value(COLUMNNAME_BinaryData);
}
/** Set Migriert am.
@param MigrationDate Migriert am */
@Override
public void setMigrationDate (java.sql.Timestamp MigrationDate)
{
set_Value (COLUMNNAME_MigrationDate, MigrationDate);
}
/** Get Migriert am.
@return Migriert am */
@Override
|
public java.sql.Timestamp getMigrationDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_MigrationDate);
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Mitteilung.
@param TextMsg
Text Message
*/
@Override
public void setTextMsg (java.lang.String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Mitteilung.
@return Text Message
*/
@Override
public java.lang.String getTextMsg ()
{
return (java.lang.String)get_Value(COLUMNNAME_TextMsg);
}
/** Set Titel.
@param Title
Name this entity is referred to as
*/
@Override
public void setTitle (java.lang.String Title)
{
set_Value (COLUMNNAME_Title, Title);
}
/** Get Titel.
@return Name this entity is referred to as
*/
@Override
public java.lang.String getTitle ()
{
return (java.lang.String)get_Value(COLUMNNAME_Title);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attachment.java
| 1
|
请完成以下Java代码
|
class InOutCostRowsLoader
{
@NonNull private final MoneyService moneyService;
@NonNull final LookupDataSource bpartnerLookup;
@NonNull final LookupDataSource orderLookup;
@NonNull final LookupDataSource inoutLookup;
@NonNull final LookupDataSource costTypeLookup;
@Builder
private InOutCostRowsLoader(
final @NonNull MoneyService moneyService,
final @NonNull LookupDataSource bpartnerLookup,
final @NonNull LookupDataSource orderLookup,
final @NonNull LookupDataSource inoutLookup,
final @NonNull LookupDataSource costTypeLookup)
{
this.moneyService = moneyService;
this.bpartnerLookup = bpartnerLookup;
this.orderLookup = orderLookup;
this.inoutLookup = inoutLookup;
this.costTypeLookup = costTypeLookup;
}
public ImmutableList<InOutCostRow> loadRows(final List<InOutCost> inoutCostsList)
{
if (inoutCostsList.isEmpty())
{
return ImmutableList.of();
}
return inoutCostsList.stream()
.map(this::toRow)
.collect(ImmutableList.toImmutableList());
}
|
private InOutCostRow toRow(final InOutCost inoutCost)
{
final Money costAmountToInvoice = inoutCost.getCostAmountToInvoice();
return InOutCostRow.builder()
.inoutCostId(inoutCost.getId())
.bpartner(bpartnerLookup.findById(inoutCost.getBpartnerId()))
.purchaseOrder(orderLookup.findById(inoutCost.getOrderId()))
.inout(inoutLookup.findById(inoutCost.getInOutId()))
.costType(costTypeLookup.findById(inoutCost.getCostTypeId()))
.currency(moneyService.getCurrencyCodeByCurrencyId(costAmountToInvoice.getCurrencyId()).toThreeLetterCode())
.costAmountToInvoice(costAmountToInvoice.toBigDecimal())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\invoice\match_inout_costs\InOutCostRowsLoader.java
| 1
|
请完成以下Java代码
|
public void updateCountryId(final I_C_Fiscal_Representation fiscalRep)
{
if (fiscalRep.getC_BPartner_Location_ID() > 0)
{
final BPartnerLocationId bpLocation = BPartnerLocationId.ofRepoId(fiscalRep.getC_BPartner_Representative_ID(), fiscalRep.getC_BPartner_Location_ID());
final CountryId countryId = bpartnerDAO.getCountryId(bpLocation);
fiscalRep.setTo_Country_ID(countryId.getRepoId());
}
}
public boolean isValidFromDate(final I_C_Fiscal_Representation fiscalRep)
{
return fiscalRep.getValidFrom().before(fiscalRep.getValidTo());
}
public boolean isValidToDate(final I_C_Fiscal_Representation fiscalRep)
{
return fiscalRep.getValidTo() == null || fiscalRep.getValidTo().after(fiscalRep.getValidFrom());
}
public void updateValidTo(final I_C_Fiscal_Representation fiscalRep)
{
fiscalRep.setValidTo(fiscalRep.getValidFrom());
}
public void updateValidFrom(final I_C_Fiscal_Representation fiscalRep)
{
fiscalRep.setValidFrom(fiscalRep.getValidTo());
}
@Override
public boolean hasFiscalRepresentation(@NonNull final CountryId countryId, @NonNull final OrgId orgId, @NonNull final Timestamp date)
|
{
final ICompositeQueryFilter<I_C_Fiscal_Representation> validToFilter = queryBL.createCompositeQueryFilter(I_C_Fiscal_Representation.class)
.setJoinOr()
.addCompareFilter(I_C_Fiscal_Representation.COLUMN_ValidTo, CompareQueryFilter.Operator.GREATER_OR_EQUAL, date)
.addEqualsFilter(I_C_Fiscal_Representation.COLUMN_ValidTo, null);
return queryBL.createQueryBuilder(I_C_Fiscal_Representation.class)
.addEqualsFilter(I_C_Fiscal_Representation.COLUMNNAME_To_Country_ID, countryId)
.addEqualsFilter(I_C_Fiscal_Representation.COLUMNNAME_AD_Org_ID, orgId)
.addCompareFilter(I_C_Fiscal_Representation.COLUMN_ValidFrom, CompareQueryFilter.Operator.LESS_OR_EQUAL,date)
.filter(validToFilter)
.addOnlyActiveRecordsFilter()
.create()
.anyMatch();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\impl\FiscalRepresentationBL.java
| 1
|
请完成以下Java代码
|
public static boolean isEmpty(@SuppressWarnings("rawtypes") Collection collection) {
return (collection == null || collection.isEmpty());
}
public static boolean isNotEmpty(@SuppressWarnings("rawtypes") Collection collection) {
return !isEmpty(collection);
}
public static <T> List<List<T>> partition(Collection<T> values, int partitionSize) {
if (values == null) {
return null;
} else if (values.isEmpty()) {
return Collections.emptyList();
}
List<T> valuesList;
if (values instanceof List) {
valuesList = (List<T>) values;
} else {
valuesList = new ArrayList<>(values);
}
int valuesSize = values.size();
if (valuesSize <= partitionSize) {
return Collections.singletonList(valuesList);
}
List<List<T>> safeValuesList = new ArrayList<>();
consumePartitions(values, partitionSize, safeValuesList::add);
return safeValuesList;
}
public static <T> void consumePartitions(Collection<T> values, int partitionSize, Consumer<List<T>> partitionConsumer) {
int valuesSize = values.size();
List<T> valuesList;
if (values instanceof List) {
valuesList = (List<T>) values;
} else {
valuesList = new ArrayList<>(values);
}
|
if (valuesSize <= partitionSize) {
partitionConsumer.accept(valuesList);
} else {
for (int startIndex = 0; startIndex < valuesSize; startIndex += partitionSize) {
int endIndex = startIndex + partitionSize;
if (endIndex > valuesSize) {
endIndex = valuesSize; // endIndex in #subList is exclusive
}
List<T> subList = valuesList.subList(startIndex, endIndex);
partitionConsumer.accept(subList);
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\util\CollectionUtil.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SQLValidationRule implements IValidationRule
{
String name;
@NonNull IStringExpression prefilterWhereClause;
@NonNull ImmutableSet<String> dependsOnTableNames;
@Builder
private SQLValidationRule(
final String name,
@NonNull final IStringExpression prefilterWhereClause,
@Singular final Set<String> dependsOnTableNames)
{
Check.assume(!prefilterWhereClause.isNullExpression(), "prefilterWhereClause is not empty");
this.name = name;
this.prefilterWhereClause = prefilterWhereClause;
this.dependsOnTableNames = dependsOnTableNames != null ? ImmutableSet.copyOf(dependsOnTableNames) : ImmutableSet.of();
}
public static IValidationRule ofNullableSqlWhereClause(@Nullable final String sqlWhereClause)
{
final String sqlWhereClauseNorm = StringUtils.trimBlankToNull(sqlWhereClause);
if (sqlWhereClauseNorm == null)
{
return NullValidationRule.instance;
}
return ofSqlWhereClause(sqlWhereClauseNorm);
}
public static IValidationRule ofSqlWhereClause(@NonNull final String sqlWhereClause)
{
final String sqlWhereClauseNorm = StringUtils.trimBlankToNull(sqlWhereClause);
if (sqlWhereClauseNorm == null)
{
throw new AdempiereException("sqlWhereClause cannot be blank");
}
|
final IStringExpression sqlWhereClauseExpr = IStringExpression.compileOrDefault(sqlWhereClauseNorm, IStringExpression.NULL);
return ofNullableSqlWhereClause(sqlWhereClauseExpr);
}
public static IValidationRule ofNullableSqlWhereClause(@Nullable final IStringExpression sqlWhereClauseExpr)
{
if (sqlWhereClauseExpr == null || sqlWhereClauseExpr.isNullExpression())
{
return NullValidationRule.instance;
}
return builder().prefilterWhereClause(sqlWhereClauseExpr).build();
}
@Override
public Set<String> getAllParameters()
{
return prefilterWhereClause.getParameterNames();
// NOTE: we are not checking post-filter params because that's always empty
}
@Override
public boolean isImmutable()
{
return getAllParameters().isEmpty();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\validationRule\impl\SQLValidationRule.java
| 2
|
请完成以下Java代码
|
public class HazelcastCacheMeterBinderProvider implements CacheMeterBinderProvider<HazelcastCache> {
@Override
public MeterBinder getMeterBinder(HazelcastCache cache, Iterable<Tag> tags) {
try {
return new HazelcastCacheMetrics(cache.getNativeCache(), tags);
}
catch (NoSuchMethodError ex) {
// Hazelcast 4
return createHazelcast4CacheMetrics(cache, tags);
}
}
private MeterBinder createHazelcast4CacheMetrics(HazelcastCache cache, Iterable<Tag> tags) {
try {
Method nativeCacheAccessor = ReflectionUtils.findMethod(HazelcastCache.class, "getNativeCache");
Assert.state(nativeCacheAccessor != null, "'nativeCacheAccessor' must not be null");
Object nativeCache = ReflectionUtils.invokeMethod(nativeCacheAccessor, cache);
return HazelcastCacheMetrics.class.getConstructor(Object.class, Iterable.class)
.newInstance(nativeCache, tags);
}
catch (Exception ex) {
throw new IllegalStateException("Failed to create MeterBinder for Hazelcast", ex);
|
}
}
static class HazelcastCacheMeterBinderProviderRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
try {
Method getNativeCacheMethod = ReflectionUtils.findMethod(HazelcastCache.class, "getNativeCache");
Assert.state(getNativeCacheMethod != null, "Unable to find 'getNativeCache' method");
Constructor<?> constructor = HazelcastCacheMetrics.class.getConstructor(Object.class, Iterable.class);
hints.reflection()
.registerMethod(getNativeCacheMethod, ExecutableMode.INVOKE)
.registerConstructor(constructor, ExecutableMode.INVOKE);
}
catch (NoSuchMethodException ex) {
throw new IllegalStateException(ex);
}
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\metrics\HazelcastCacheMeterBinderProvider.java
| 1
|
请完成以下Java代码
|
public byte[] getBase64() {
return base64;
}
/**
* Sets the value of the base64 property.
*
* @param value
* allowed object is
* byte[]
*/
public void setBase64(byte[] value) {
this.base64 = value;
}
/**
* Gets the value of the url property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUrl() {
return url;
}
/**
* Sets the value of the url property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUrl(String value) {
this.url = value;
}
/**
* Gets the value of the filename property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFilename() {
return filename;
}
/**
* Sets the value of the filename property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFilename(String value) {
this.filename = value;
}
/**
|
* Gets the value of the mimeType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMimeType() {
return mimeType;
}
/**
* Sets the value of the mimeType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMimeType(String value) {
this.mimeType = value;
}
/**
* Gets the value of the viewer property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getViewer() {
return viewer;
}
/**
* Sets the value of the viewer property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setViewer(String value) {
this.viewer = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\DocumentType.java
| 1
|
请完成以下Java代码
|
protected void createAndStartGrpcServer() throws IOException {
if (this.server == null) {
final Server localServer = this.factory.createServer();
this.server = localServer;
localServer.start();
final String address = this.factory.getAddress();
final int port = this.factory.getPort();
log.info("gRPC Server started, listening on address: {}, port: {}", address, port);
this.eventPublisher.publishEvent(new GrpcServerStartedEvent(this, localServer, address, port));
// Prevent the JVM from shutting down while the server is running
final Thread awaitThread = new Thread(() -> {
try {
localServer.awaitTermination();
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
}
});
awaitThread.setName("grpc-server-container-" + (serverCounter.incrementAndGet()));
awaitThread.setDaemon(false);
awaitThread.start();
}
}
/**
* Initiates an orderly shutdown of the grpc server and releases the references to the server. This call waits for
* the server to be completely shut down.
*/
protected void stopAndReleaseGrpcServer() {
final Server localServer = this.server;
if (localServer != null) {
final long millis = this.shutdownGracePeriod.toMillis();
log.debug("Initiating gRPC server shutdown");
this.eventPublisher.publishEvent(new GrpcServerShutdownEvent(this, localServer));
localServer.shutdown();
|
// Wait for the server to shutdown completely before continuing with destroying the spring context
try {
if (millis > 0) {
localServer.awaitTermination(millis, MILLISECONDS);
} else if (millis == 0) {
// Do not wait
} else {
// Wait infinitely
localServer.awaitTermination();
}
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
localServer.shutdownNow();
this.server = null;
}
log.info("Completed gRPC server shutdown");
this.eventPublisher.publishEvent(new GrpcServerTerminatedEvent(this, localServer));
}
}
}
|
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\serverfactory\GrpcServerLifecycle.java
| 1
|
请完成以下Java代码
|
public class XxlJobUser {
private int id;
private String username; // 账号
private String password; // 密码
private int role; // 角色:0-普通用户、1-管理员
private String permission; // 权限:执行器ID列表,多个逗号分割
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getRole() {
return role;
}
public void setRole(int role) {
this.role = role;
}
public String getPermission() {
return permission;
|
}
public void setPermission(String permission) {
this.permission = permission;
}
// plugin
public boolean validPermission(int jobGroup){
if (this.role == 1) {
return true;
} else {
if (StringUtils.hasText(this.permission)) {
for (String permissionItem : this.permission.split(",")) {
if (String.valueOf(jobGroup).equals(permissionItem)) {
return true;
}
}
}
return false;
}
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobUser.java
| 1
|
请完成以下Java代码
|
public int exactMatchSearch(String key)
{
return exactMatchSearch(key.getBytes(utf8));
}
/**
* Returns the corresponding value if the key is found. Otherwise returns -1.
*
* @param key search key
* @return found value
*/
public int exactMatchSearch(byte[] key)
{
int unit = _array[0];
int nodePos = 0;
for (byte b : key)
{
// nodePos ^= unit.offset() ^ b
nodePos ^= ((unit >>> 10) << ((unit & (1 << 9)) >>> 6)) ^ (b & 0xFF);
unit = _array[nodePos];
// if (unit.label() != b)
if ((unit & ((1 << 31) | 0xFF)) != (b & 0xff))
{
return -1;
}
}
// if (!unit.has_leaf()) {
if (((unit >>> 8) & 1) != 1)
{
return -1;
}
// unit = _array[nodePos ^ unit.offset()];
unit = _array[nodePos ^ ((unit >>> 10) << ((unit & (1 << 9)) >>> 6))];
// return unit.value();
return unit & ((1 << 31) - 1);
}
/**
* Returns the keys that begins with the given key and its corresponding values.
* The first of the returned pair represents the length of the found key.
*
* @param key
* @param offset
* @param maxResults
* @return found keys and values
*/
public List<Pair<Integer, Integer>> commonPrefixSearch(byte[] key,
|
int offset,
int maxResults)
{
ArrayList<Pair<Integer, Integer>> result = new ArrayList<Pair<Integer, Integer>>();
int unit = _array[0];
int nodePos = 0;
// nodePos ^= unit.offset();
nodePos ^= ((unit >>> 10) << ((unit & (1 << 9)) >>> 6));
for (int i = offset; i < key.length; ++i)
{
byte b = key[i];
nodePos ^= (b & 0xff);
unit = _array[nodePos];
// if (unit.label() != b) {
if ((unit & ((1 << 31) | 0xFF)) != (b & 0xff))
{
return result;
}
// nodePos ^= unit.offset();
nodePos ^= ((unit >>> 10) << ((unit & (1 << 9)) >>> 6));
// if (unit.has_leaf()) {
if (((unit >>> 8) & 1) == 1)
{
if (result.size() < maxResults)
{
// result.add(new Pair<i, _array[nodePos].value());
result.add(new Pair<Integer, Integer>(i + 1, _array[nodePos] & ((1 << 31) - 1)));
}
}
}
return result;
}
/**
* 大小
*
* @return
*/
public int size()
{
return _array.length;
}
private static final int UNIT_SIZE = 4; // sizeof(int)
private int[] _array;
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\DoubleArray.java
| 1
|
请完成以下Java代码
|
public class XxlJobRegistry {
private int id;
private String registryGroup;
private String registryKey;
private String registryValue;
private Date updateTime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRegistryGroup() {
return registryGroup;
}
public void setRegistryGroup(String registryGroup) {
this.registryGroup = registryGroup;
}
public String getRegistryKey() {
return registryKey;
}
|
public void setRegistryKey(String registryKey) {
this.registryKey = registryKey;
}
public String getRegistryValue() {
return registryValue;
}
public void setRegistryValue(String registryValue) {
this.registryValue = registryValue;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobRegistry.java
| 1
|
请完成以下Java代码
|
private Resource asLoaderHidingResource(Resource resource) {
return (resource instanceof LoaderHidingResource) ? resource : new LoaderHidingResource(this.base, resource);
}
@Override
public @Nullable Resource resolve(String subUriPath) {
if (subUriPath.startsWith(LOADER_RESOURCE_PATH_PREFIX)) {
return null;
}
Resource resolved = this.delegate.resolve(subUriPath);
return (resolved != null) ? new LoaderHidingResource(this.base, resolved) : null;
}
@Override
public boolean isAlias() {
return this.delegate.isAlias();
}
@Override
public URI getRealURI() {
return this.delegate.getRealURI();
}
@Override
|
public void copyTo(Path destination) throws IOException {
this.delegate.copyTo(destination);
}
@Override
public Collection<Resource> getAllResources() {
return asLoaderHidingResources(this.delegate.getAllResources());
}
@Override
public String toString() {
return this.delegate.toString();
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\servlet\LoaderHidingResource.java
| 1
|
请完成以下Java代码
|
public HistoricBatchQuery orderByStartTime() {
return orderBy(HistoricBatchQueryProperty.START_TIME);
}
public HistoricBatchQuery orderByEndTime() {
return orderBy(HistoricBatchQueryProperty.END_TIME);
}
@Override
public HistoricBatchQuery orderByTenantId() {
return orderBy(HistoricBatchQueryProperty.TENANT_ID);
}
@Override
public long executeCount(CommandContext commandContext) {
|
checkQueryOk();
return commandContext
.getHistoricBatchManager()
.findBatchCountByQueryCriteria(this);
}
@Override
public List<HistoricBatch> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getHistoricBatchManager()
.findBatchesByQueryCriteria(this, page);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\history\HistoricBatchQueryImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Quantity computeQtyOfSparePartsAlreadyReturned(
@NonNull final ProductId sparePartId,
@NonNull final I_C_UOM uom,
@NonNull final QuantityUOMConverter uomConverter)
{
Quantity qtyTotal = Quantity.zero(uom);
final UomId uomId = UomId.ofRepoId(uom.getC_UOM_ID());
for (final SparePart sparePart : getSpareParts(sparePartId))
{
final Quantity qty = uomConverter.convertQuantityTo(sparePart.getQty(), sparePartId, uomId);
qtyTotal = qtyTotal.add(qty);
}
return qtyTotal;
}
public List<SparePart> getSpareParts(@NonNull final ProductId sparePartId)
{
return spareParts.stream()
.filter(sparePart -> ProductId.equals(sparePart.getSparePartId(), sparePartId))
.collect(ImmutableList.toImmutableList());
}
//
//
// ------------
//
//
@Value
@Builder
public static class FinishedGoodToRepair
{
@NonNull Quantity qty;
@NonNull QtyCalculationsBOM sparePartsBOM;
@NonNull @Builder.Default AttributeSetInstanceId asiId = AttributeSetInstanceId.NONE;
@NonNull WarrantyCase warrantyCase;
@NonNull HuId repairVhuId;
@NonNull InOutAndLineId customerReturnLineId;
public Stream<ProductId> streamComponentIds()
|
{
return sparePartsBOM.getLines().stream().map(QtyCalculationsBOMLine::getProductId);
}
@Nullable
public Quantity computeQtyOfComponentsRequired(
@NonNull final ProductId componentId,
@NonNull final QuantityUOMConverter uomConverter)
{
final QtyCalculationsBOMLine bomLine = sparePartsBOM.getLineByComponentId(componentId).orElse(null);
if (bomLine == null)
{
return null;
}
final Quantity qtyInBomUOM = uomConverter.convertQuantityTo(qty, bomLine.getBomProductId(), bomLine.getBomProductUOMId());
return bomLine.computeQtyRequired(qtyInBomUOM);
}
public ProductId getProductId()
{
return sparePartsBOM.getBomProductId();
}
}
@Value
@Builder
public static class SparePart
{
@NonNull ProductId sparePartId;
@NonNull Quantity qty;
@NonNull InOutAndLineId customerReturnLineId;
@NonNull HuId sparePartsVhuId;
public Quantity getQty(@NonNull final UomId targetUomId, @NonNull final QuantityUOMConverter uomConverter)
{
return uomConverter.convertQuantityTo(getQty(), getSparePartId(), targetUomId);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\customerreturns\SparePartsReturnCalculation.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
http.getConfigurer(OAuth2AuthorizationServerConfigurer.class)
.oidc(Customizer.withDefaults()); // Enable OpenID Connect 1.0
http
// Redirect to the login page when not authenticated from the
// authorization endpoint
.exceptionHandling((exceptions) -> exceptions
.defaultAuthenticationEntryPointFor(
new LoginUrlAuthenticationEntryPoint("/login"),
new MediaTypeRequestMatcher(MediaType.TEXT_HTML)
)
)
// Accept access tokens for User Info and/or Client Registration
.oauth2ResourceServer((resourceServer) -> resourceServer
.jwt(Customizer.withDefaults()));
return http.build();
}
@Bean
@Order(2)
|
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http)
throws Exception {
http
.authorizeHttpRequests((authorize) -> authorize
.anyRequest().authenticated()
)
// Form login handles the redirect to the login page from the
// authorization server filter chain
.formLogin(Customizer.withDefaults());
return http.build();
}
}
|
repos\tutorials-master\libraries-security-2\src\main\java\com\baeldung\scribejava\oauth\AuthServiceConfig.java
| 2
|
请完成以下Java代码
|
public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get Table.
@return Database Table information
*/
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Landscape.
@param IsLandscape
Landscape orientation
*/
public void setIsLandscape (boolean IsLandscape)
{
set_Value (COLUMNNAME_IsLandscape, Boolean.valueOf(IsLandscape));
}
/** Get Landscape.
@return Landscape orientation
*/
public boolean isLandscape ()
{
Object oo = get_Value(COLUMNNAME_IsLandscape);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Label Height.
@param LabelHeight
Height of the label
*/
public void setLabelHeight (int LabelHeight)
{
set_Value (COLUMNNAME_LabelHeight, Integer.valueOf(LabelHeight));
}
/** Get Label Height.
@return Height of the label
*/
public int getLabelHeight ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_LabelHeight);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Label Width.
@param LabelWidth
Width of the Label
*/
public void setLabelWidth (int LabelWidth)
{
set_Value (COLUMNNAME_LabelWidth, Integer.valueOf(LabelWidth));
}
/** Get Label Width.
@return Width of the Label
*/
public int getLabelWidth ()
{
|
Integer ii = (Integer)get_Value(COLUMNNAME_LabelWidth);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Printer Name.
@param PrinterName
Name of the Printer
*/
public void setPrinterName (String PrinterName)
{
set_Value (COLUMNNAME_PrinterName, PrinterName);
}
/** Get Printer Name.
@return Name of the Printer
*/
public String getPrinterName ()
{
return (String)get_Value(COLUMNNAME_PrinterName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintLabel.java
| 1
|
请完成以下Java代码
|
protected void switchVersionOfIncident(CommandContext commandContext, IncidentEntity incidentEntity, ProcessDefinitionEntity newProcessDefinition) {
incidentEntity.setProcessDefinitionId(newProcessDefinition.getId());
}
protected void validateAndSwitchVersionOfExecution(CommandContext commandContext, ExecutionEntity execution, ProcessDefinitionEntity newProcessDefinition) {
// check that the new process definition version contains the current activity
if (execution.getActivity() != null) {
String activityId = execution.getActivity().getId();
PvmActivity newActivity = newProcessDefinition.findActivity(activityId);
if (newActivity == null) {
throw new ProcessEngineException(
"The new process definition " +
"(key = '" + newProcessDefinition.getKey() + "') " +
"does not contain the current activity " +
"(id = '" + activityId + "') " +
"of the process instance " +
|
"(id = '" + processInstanceId + "').");
}
// clear cached activity so that outgoing transitions are refreshed
execution.setActivity(newActivity);
}
// switch the process instance to the new process definition version
execution.setProcessDefinition(newProcessDefinition);
// and change possible existing tasks (as the process definition id is stored there too)
List<TaskEntity> tasks = commandContext.getTaskManager().findTasksByExecutionId(execution.getId());
for (TaskEntity taskEntity : tasks) {
taskEntity.setProcessDefinitionId(newProcessDefinition.getId());
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SetProcessDefinitionVersionCmd.java
| 1
|
请完成以下Java代码
|
public org.compiere.model.I_S_Resource getS_Resource()
{
return get_ValueAsPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class);
}
@Override
public void setS_Resource(final org.compiere.model.I_S_Resource S_Resource)
{
set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource);
}
@Override
public void setS_Resource_ID (final int S_Resource_ID)
{
if (S_Resource_ID < 1)
set_Value (COLUMNNAME_S_Resource_ID, null);
else
set_Value (COLUMNNAME_S_Resource_ID, S_Resource_ID);
}
@Override
public int getS_Resource_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Resource_ID);
}
@Override
public void setStorageAttributesKey (final @Nullable java.lang.String StorageAttributesKey)
{
set_Value (COLUMNNAME_StorageAttributesKey, StorageAttributesKey);
}
@Override
public java.lang.String getStorageAttributesKey()
{
return get_ValueAsString(COLUMNNAME_StorageAttributesKey);
}
@Override
public void setTransfertTime (final @Nullable BigDecimal TransfertTime)
{
set_Value (COLUMNNAME_TransfertTime, TransfertTime);
}
@Override
public BigDecimal getTransfertTime()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TransfertTime);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setWorkingTime (final @Nullable BigDecimal WorkingTime)
{
set_Value (COLUMNNAME_WorkingTime, WorkingTime);
}
@Override
public BigDecimal getWorkingTime()
{
|
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WorkingTime);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setYield (final int Yield)
{
set_Value (COLUMNNAME_Yield, Yield);
}
@Override
public int getYield()
{
return get_ValueAsInt(COLUMNNAME_Yield);
}
@Override
public void setC_Manufacturing_Aggregation_ID (final int C_Manufacturing_Aggregation_ID)
{
if (C_Manufacturing_Aggregation_ID < 1)
set_Value (COLUMNNAME_C_Manufacturing_Aggregation_ID, null);
else
set_Value (COLUMNNAME_C_Manufacturing_Aggregation_ID, C_Manufacturing_Aggregation_ID);
}
@Override
public int getC_Manufacturing_Aggregation_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Manufacturing_Aggregation_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Product_Planning.java
| 1
|
请完成以下Java代码
|
public void invalidateAll()
{
invalidate(DocumentIdsSelection.ALL);
}
@Override
public void invalidate(@NonNull final DocumentIdsSelection rowIds)
{
final ImmutableSet<InvoiceId> invoiceIds = rowsHolder.getRecordIdsToRefresh(rowIds, InvoiceRow::convertDocumentIdToInvoiceId);
final ImmutableMap<DocumentId, InvoiceRow> oldRowsById = rowsHolder.getDocumentId2TopLevelRows();
final List<InvoiceRow> newRows = repository.getInvoiceRowsListByInvoiceId(invoiceIds, evaluationDate)
.stream()
.map(newRow -> mergeFromOldRow(newRow, oldRowsById))
.collect(ImmutableList.toImmutableList());
rowsHolder.compute(rows -> rows.replacingRows(rowIds, newRows));
}
private static InvoiceRow mergeFromOldRow(
@NonNull final InvoiceRow newRow,
@NonNull final ImmutableMap<DocumentId, InvoiceRow> oldRowsById)
{
final InvoiceRow oldRow = oldRowsById.get(newRow.getId());
if (oldRow == null)
{
return newRow;
}
return newRow.withPreparedForAllocation(oldRow.isPreparedForAllocation());
}
public void addInvoice(@NonNull final InvoiceId invoiceId)
{
final InvoiceRow row = repository.getInvoiceRowByInvoiceId(invoiceId, evaluationDate).orElse(null);
if (row == null)
{
throw new AdempiereException("@InvoiceNotOpen@");
}
rowsHolder.compute(rows -> rows.addingRow(row));
}
@Override
|
public void patchRow(final RowEditingContext ctx, final List<JSONDocumentChangedEvent> fieldChangeRequests)
{
final DocumentId rowIdToChange = ctx.getRowId();
rowsHolder.compute(rows -> rows.changingRow(rowIdToChange, row -> InvoiceRowReducers.reduce(row, fieldChangeRequests)));
}
public ImmutableList<InvoiceRow> getRowsWithPreparedForAllocationFlagSet()
{
return getAllRows()
.stream()
.filter(InvoiceRow::isPreparedForAllocation)
.collect(ImmutableList.toImmutableList());
}
public void markPreparedForAllocation(@NonNull final DocumentIdsSelection rowIds)
{
rowsHolder.compute(rows -> rows.changingRows(rowIds, InvoiceRow::withPreparedForAllocationSet));
}
public void unmarkPreparedForAllocation(@NonNull final DocumentIdsSelection rowIds)
{
rowsHolder.compute(rows -> rows.changingRows(rowIds, InvoiceRow::withPreparedForAllocationUnset));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\InvoiceRows.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class HeadersExchangeParser extends AbstractExchangeParser {
@Override
protected Class<?> getBeanClass(Element element) {
return HeadersExchange.class;
}
@Override
protected BeanDefinitionBuilder parseBinding(String exchangeName, Element binding, ParserContext parserContext) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(BindingFactoryBean.class);
Element argumentsElement = DomUtils.getChildElementByTagName(binding, BINDING_ARGUMENTS);
String key = binding.getAttribute("key");
String value = binding.getAttribute("value");
boolean hasKey = StringUtils.hasText(key);
boolean hasValue = StringUtils.hasText(value);
if (argumentsElement != null && (hasKey || hasValue)) {
parserContext.getReaderContext()
.error("'binding-arguments' sub-element and 'key/value' attributes are mutually exclusive.", binding);
}
parseDestination(binding, parserContext, builder);
|
if (hasKey ^ hasValue) {
parserContext.getReaderContext().error("Both 'key/value' attributes have to be declared.", binding);
}
if (argumentsElement == null) {
if (!hasKey & !hasValue) {
parserContext.getReaderContext()
.error("At least one of 'binding-arguments' sub-element or 'key/value' attributes pair have to be declared.", binding);
}
ManagedMap<TypedStringValue, TypedStringValue> map = new ManagedMap<>();
map.put(new TypedStringValue(key), new TypedStringValue(value));
builder.addPropertyValue("arguments", map);
}
builder.addPropertyValue("exchange", new TypedStringValue(exchangeName));
return builder;
}
}
|
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\config\HeadersExchangeParser.java
| 2
|
请完成以下Java代码
|
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "Passenger{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + '}';
}
|
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Passenger passenger = (Passenger) o;
return Objects.equals(firstName, passenger.firstName) && Objects.equals(lastName, passenger.lastName);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName);
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-2\src\main\java\com\baeldung\jpa\domain\Passenger.java
| 1
|
请完成以下Java代码
|
public String getId() {
return id;
}
@Override
public void setId(String id) {
// Not supported
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
// Not supported
}
@Override
public String getType() {
|
return type;
}
@Override
public void setType(String string) {
// Not supported
}
public static GroupDetails create(Group group) {
return new GroupDetails(group.getId(), group.getName(), group.getType());
}
public static List<GroupDetails> create(List<Group> groups) {
List<GroupDetails> groupDetails = new ArrayList<>(groups.size());
for (Group group : groups) {
groupDetails.add(create(group));
}
return groupDetails;
}
}
|
repos\flowable-engine-main\modules\flowable-spring-security\src\main\java\org\flowable\spring\security\GroupDetails.java
| 1
|
请完成以下Spring Boot application配置
|
# H2
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.profiles.active=h2
# MySQL
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#spring.datasource.username=mysqluser
#spring.datasource.password=mysqlpass
#spring.datasource.url=jdbc:mysql://localhost:33
|
06/myDb?createDatabaseIfNotExist=true
# MultiTenantApplication
defaultTenant=tenant_1
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
|
repos\tutorials-master\persistence-modules\spring-jpa\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
protected boolean afterSave (boolean newRecord)
{
log.info("beforeSave");
//int p_A_Asset_ID = 0;
int p_wkasset_ID = 0;
//p_A_Asset_ID = getA_Asset_ID();
p_wkasset_ID = getA_Depreciation_Workfile_ID();
StringBuffer sqlB = new StringBuffer ("UPDATE A_Depreciation_Workfile "
+ "SET Processing = 'Y'"
+ " WHERE A_Depreciation_Workfile_ID = " + p_wkasset_ID );
int no = DB.executeUpdateAndSaveErrorOnFail(sqlB.toString(), null);
if (no == -1)
log.info("Update to Deprecaition Workfile failed");
return true;
}
/**
* after Save
* @param newRecord new
* @return true
*/
protected boolean beforeSave (boolean newRecord)
{
log.info("beforeSave");
int p_A_Asset_ID = 0;
//int p_wkasset_ID = 0;
p_A_Asset_ID = getA_Asset_ID();
//p_wkasset_ID = getA_Depreciation_Workfile_ID();
log.info("afterSave");
X_A_Asset asset = new X_A_Asset (getCtx(), p_A_Asset_ID, null);
asset.setA_QTY_Current(getA_QTY_Current());
asset.setA_QTY_Original(getA_QTY_Current());
asset.save();
if (getA_Accumulated_Depr().equals(null))
|
setA_Accumulated_Depr(new BigDecimal(0.0));
if (new BigDecimal(getA_Period_Posted()).equals(null))
setA_Period_Posted(0);
MAssetChange change = new MAssetChange (getCtx(), 0,null);
log.info("0");
String sql2 = "SELECT COUNT(*) FROM A_Depreciation_Workfile WHERE A_Asset_ID=? AND PostingType = ?";
if (DB.getSQLValue(null, sql2, p_A_Asset_ID,getPostingType())!= 0)
{
change.setA_Asset_ID(p_A_Asset_ID);
change.setChangeType("BAL");
MRefList RefList = new MRefList (getCtx(), 0, null);
change.setTextDetails(RefList.getListDescription (getCtx(),"A_Update_Type" , "BAL"));
change.setPostingType(getPostingType());
change.setAssetValueAmt(getA_Asset_Cost());
change.setA_QTY_Current(getA_QTY_Current());
change.setA_QTY_Original(getA_QTY_Current());
change.setAssetAccumDepreciationAmt(getA_Accumulated_Depr());
change.save();
}
return true;
} // beforeSave
} // MAssetAddition
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\MDepreciationWorkfile.java
| 1
|
请完成以下Java代码
|
private OrderLineCandidate toOrderLineCandidate(final I_C_OrderLine ol)
{
final ImmutableAttributeSet attributeSet = asiBL.getImmutableAttributeSetById(AttributeSetInstanceId.ofRepoId(ol.getM_AttributeSetInstance_ID()));
return OrderLineCandidate.builder()
.orderId(OrderId.ofRepoId(ol.getC_Order_ID()))
.productId(ProductId.ofRepoId(ol.getM_Product_ID()))
.attributes(attributeSet)
.qty(Quantitys.of(ol.getQtyEntered(), UomId.ofRepoId(ol.getC_UOM_ID())))
.bestBeforePolicy(ShipmentAllocationBestBeforePolicy.ofNullableCode(ol.getShipmentAllocation_BestBefore_Policy()))
.bpartnerId(BPartnerId.ofRepoId(ol.getC_BPartner_ID()))
.soTrx(SOTrx.SALES)
.build();
}
/**
* Returns a "virtual" I_C_OrderLine which represents a single BOM component from:
* <ul>
* <li>the given sales order line containing a Product that has a BOM</li>
* <li>the given BOM component</li>
* </ul>
*
* @param candidate a BOM component
* @param bomSalesOrderLine the original BOM product C_OrderLine
* @return a NOT SAFE FOR PERSISTING instance of I_C_OrderLine which should only be used for creating a PO OrderLine
*/
private @NonNull I_C_OrderLine fromOrderLineCandidate(final @NonNull OrderLineCandidate candidate, @NonNull final I_C_OrderLine bomSalesOrderLine)
{
final I_C_OrderLine newOrderLine = InterfaceWrapperHelper.newInstance(I_C_OrderLine.class, bomSalesOrderLine);
PO.copyValues((X_C_OrderLine)bomSalesOrderLine, (X_C_OrderLine)newOrderLine);
newOrderLine.setM_Product_ID(candidate.getProductId().getRepoId());
newOrderLine.setC_UOM_ID(candidate.getQty().getUomId().getRepoId());
newOrderLine.setQtyOrdered(candidate.getQty().toBigDecimal());
newOrderLine.setQtyReserved(candidate.getQty().toBigDecimal());
if (candidate.getBestBeforePolicy() != null)
{
newOrderLine.setShipmentAllocation_BestBefore_Policy(candidate.getBestBeforePolicy().getCode());
}
newOrderLine.setM_AttributeSetInstance_ID(AttributeSetInstanceId.NONE.getRepoId());
|
newOrderLine.setExplodedFrom_BOMLine_ID(candidate.getExplodedFromBOMLineId().getRepoId());
final GroupId compensationGroupId = candidate.getCompensationGroupId();
if (compensationGroupId != null)
{
final Group group = orderGroupsRepo.retrieveGroupIfExists(compensationGroupId);
final ActivityId groupActivityId = group == null ? null : group.getActivityId();
newOrderLine.setC_Order_CompensationGroup_ID(compensationGroupId.getOrderCompensationGroupId());
newOrderLine.setC_Activity_ID(ActivityId.toRepoId(groupActivityId));
}
//needed to know to what SO line the resulting PO Lines should be allocated to
newOrderLine.setC_OrderLine_ID(bomSalesOrderLine.getC_OrderLine_ID());
return newOrderLine;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\process\C_Order_CreatePOFromSOs.java
| 1
|
请完成以下Java代码
|
private IHUAttributeTransferStrategy getHUAttributeTransferStrategy(final IHUAttributeTransferRequest request, final I_M_Attribute attribute)
{
final IAttributeSet attributesFrom = request.getAttributesFrom();
if (attributesFrom instanceof IAttributeStorage)
{
return ((IAttributeStorage)attributesFrom).retrieveTransferStrategy(attribute);
}
final IAttributeStorage attributesTo = request.getAttributesTo();
return attributesTo.retrieveTransferStrategy(attribute);
}
@Override
public IAllocationResult createAllocationResult()
{
final List<IHUTransactionAttribute> attributeTrxs = getAndClearTransactions();
if (attributeTrxs.isEmpty())
{
// no transactions, nothing to do
return AllocationUtils.nullResult();
}
return AllocationUtils.createQtyAllocationResult(
BigDecimal.ZERO, // qtyToAllocate
BigDecimal.ZERO, // qtyAllocated
|
Collections.emptyList(), // trxs
attributeTrxs // attribute transactions
);
}
@Override
public IAllocationResult createAndProcessAllocationResult()
{
final IAllocationResult result = createAllocationResult();
Services.get(IHUTrxBL.class).createTrx(huContext, result);
return result;
}
@Override
public void dispose()
{
// Unregister the listener/collector
if (attributeStorageFactory != null && trxAttributesCollector != null)
{
trxAttributesCollector.dispose();
attributeStorageFactory.removeAttributeStorageListener(trxAttributesCollector);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\HUTransactionAttributeBuilder.java
| 1
|
请完成以下Java代码
|
public class MainPart
{
/**
* 主语
*/
public TreeGraphNode subject;
/**
* 谓语
*/
public TreeGraphNode predicate;
/**
* 宾语
*/
public TreeGraphNode object;
/**
* 结果
*/
public String result;
public MainPart(TreeGraphNode subject, TreeGraphNode predicate, TreeGraphNode object)
{
this.subject = subject;
this.predicate = predicate;
this.object = object;
}
public MainPart(TreeGraphNode predicate)
{
this(null, predicate, null);
}
public MainPart()
{
result = "";
}
|
/**
* 结果填充完成
*/
public void done()
{
result = predicate.toString("value");
if (subject != null)
{
result = subject.toString("value") + result;
}
if (object != null)
{
result = result + object.toString("value");
}
}
public boolean isDone()
{
return result != null;
}
@Override
public String toString()
{
if (result != null) return result;
return "MainPart{" +
"主语='" + subject + '\'' +
", 谓语='" + predicate + '\'' +
", 宾语='" + object + '\'' +
'}';
}
}
|
repos\springboot-demo-master\neo4j\src\main\java\com\et\neo4j\hanlp\MainPart.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class InvoiceVerificationSetLineId implements RepoIdAware
{
@JsonCreator
public static InvoiceVerificationSetLineId ofRepoId(final int repoId)
{
return new InvoiceVerificationSetLineId(repoId);
}
@Nullable
public static InvoiceVerificationSetLineId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new InvoiceVerificationSetLineId(repoId) : null;
}
int repoId;
private InvoiceVerificationSetLineId(final int repoId)
|
{
this.repoId = Check.assumeGreaterThanZero(repoId, "M_MatchInv_ID");
}
@JsonValue
@Override
public int getRepoId()
{
return repoId;
}
public static int toRepoId(final InvoiceVerificationSetLineId id)
{
return id != null ? id.getRepoId() : -1;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\InvoiceVerificationSetLineId.java
| 2
|
请完成以下Spring Boot application配置
|
spring.datasource.url=jdbc:mysql://localhost:3306/bookstoredb?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.datasource.initialization-mode=always
spring.datasource.platform=mysql
spring.jpa.open-in-view=false
spring.datasource.hikari.auto-commit=false
spring.jpa.propertie
|
s.hibernate.connection.provider_disables_autocommit=true
# Enable logging for HikariCP to verify that it is used
logging.level.com.zaxxer.hikari.HikariConfig=DEBUG
logging.level.com.zaxxer.hikari=TRACE
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootDelayConnection\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public boolean isPickingSourceHURow()
{
return pickingSlotRowId.isPickingSourceHURow();
}
public WarehouseId getPickingSlotWarehouseId()
{
return pickingSlotWarehouse != null ? WarehouseId.ofRepoId(pickingSlotWarehouse.getIdAsInt()) : null;
}
public BigDecimal getHuQtyCU()
{
return huQtyCU;
}
public ProductId getHuProductId()
{
return huProduct != null ? ProductId.ofRepoId(huProduct.getKeyAsInt()) : null;
}
@Override
public ViewId getIncludedViewId()
{
return includedViewId;
}
public LocatorId getPickingSlotLocatorId()
{
return pickingSlotLocatorId;
}
public int getBPartnerId()
{
return pickingSlotBPartner != null ? pickingSlotBPartner.getIdAsInt() : -1;
}
public int getBPartnerLocationId()
{
return pickingSlotBPLocation != null ? pickingSlotBPLocation.getIdAsInt() : -1;
}
@NonNull
public Optional<PickingSlotRow> findRowMatching(@NonNull final Predicate<PickingSlotRow> predicate)
{
return streamThisRowAndIncludedRowsRecursivelly()
.filter(predicate)
.findFirst();
}
public boolean thereIsAnOpenPickingForOrderId(@NonNull final OrderId orderId)
{
final HuId huId = getHuId();
|
if (huId == null)
{
throw new AdempiereException("Not a PickedHURow!")
.appendParametersToMessage()
.setParameter("PickingSlotRow", this);
}
final boolean hasOpenPickingForOrderId = getPickingOrderIdsForHUId(huId).contains(orderId);
if (hasOpenPickingForOrderId)
{
return true;
}
if (isLU())
{
return findRowMatching(row -> !row.isLU() && row.thereIsAnOpenPickingForOrderId(orderId))
.isPresent();
}
return false;
}
@NonNull
private ImmutableSet<OrderId> getPickingOrderIdsForHUId(@NonNull final HuId huId)
{
return Optional.ofNullable(huId2OpenPickingOrderIds.get(huId))
.orElse(ImmutableSet.of());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotRow.java
| 1
|
请完成以下Java代码
|
protected ELResolver createElResolver(VariableScope variableScope) {
CompositeELResolver elResolver = new CompositeELResolver();
elResolver.add(new VariableScopeElResolver(variableScope));
if (customELResolvers != null) {
customELResolvers.forEach(elResolver::add);
}
addBeansResolver(elResolver);
addBaseResolvers(elResolver);
return elResolver;
}
protected void addBeansResolver(CompositeELResolver elResolver) {
if (beans != null) {
// ACT-1102: Also expose all beans in configuration when using
// standalone activiti, not
// in spring-context
elResolver.add(new ReadOnlyMapELResolver(beans));
}
}
private void addBaseResolvers(CompositeELResolver elResolver) {
elResolver.add(new ArrayELResolver());
elResolver.add(new ListELResolver());
elResolver.add(new MapELResolver());
elResolver.add(new CustomMapperJsonNodeELResolver());
elResolver.add(new DynamicBeanPropertyELResolver(ItemInstance.class, "getFieldValue", "setFieldValue")); // TODO: needs verification
elResolver.add(new ELResolverReflectionBlockerDecorator(new BeanELResolver()));
}
public Map<Object, Object> getBeans() {
return beans;
|
}
public void setBeans(Map<Object, Object> beans) {
this.beans = beans;
}
public ELContext getElContext(Map<String, Object> availableVariables) {
CompositeELResolver elResolver = new CompositeELResolver();
addBaseResolvers(elResolver);
return new ELContextBuilder()
.withResolvers(elResolver)
.withVariables(availableVariables)
.buildWithCustomFunctions(customFunctionProviders);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\el\ExpressionManager.java
| 1
|
请完成以下Java代码
|
protected final void assertNotActive(final String errmsg)
{
assertActive(false, errmsg);
}
protected void assertActive(final boolean activeExpected, final String errmsg)
{
final boolean activeActual = isActive();
if (activeActual != activeExpected)
{
final String errmsgToUse = "Inconsistent transaction state: " + errmsg;
throw new TrxException(errmsgToUse
+ "\n Expected active: " + activeExpected
+ "\n Actual active: " + activeActual
+ "\n Trx: " + this);
}
}
private TrxStatus getTrxStatus()
{
return trxStatus;
}
private void setTrxStatus(final TrxStatus trxStatus)
{
final String detailMsg = null;
setTrxStatus(trxStatus, detailMsg);
}
private void setTrxStatus(final TrxStatus trxStatus, @Nullable final String detailMsg)
{
final TrxStatus trxStatusOld = this.trxStatus;
this.trxStatus = trxStatus;
// Log it
if (debugLog != null)
{
|
final StringBuilder msg = new StringBuilder();
msg.append(trxStatusOld).append("->").append(trxStatus);
if (!Check.isEmpty(detailMsg, true))
{
msg.append(" (").append(detailMsg).append(")");
}
logTrxAction(msg.toString());
}
}
private void logTrxAction(final String message)
{
if (debugLog == null)
{
return;
}
debugLog.add(message);
logger.info("{}: trx action: {}", getTrxName(), message);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\PlainTrx.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private Resource getPropertiesResource() {
Resource result = this.resource;
if (result == null && this.resourceLocation != null) {
result = this.resourceLoader.getResource(this.resourceLocation);
}
Assert.notNull(result, "resource cannot be null if resourceLocation is null");
return result;
}
/**
* Create a UserDetailsResourceFactoryBean with the location of a Resource that is a
* Properties file in the format defined in {@link UserDetailsResourceFactoryBean}.
* @param resourceLocation the location of the properties file that contains the users
* (i.e. "classpath:users.properties")
* @return the UserDetailsResourceFactoryBean
*/
public static UserDetailsResourceFactoryBean fromResourceLocation(String resourceLocation) {
UserDetailsResourceFactoryBean result = new UserDetailsResourceFactoryBean();
result.setResourceLocation(resourceLocation);
return result;
}
/**
* Create a UserDetailsResourceFactoryBean with a Resource that is a Properties file
* in the format defined in {@link UserDetailsResourceFactoryBean}.
* @param propertiesResource the Resource that is a properties file that contains the
* users
* @return the UserDetailsResourceFactoryBean
|
*/
public static UserDetailsResourceFactoryBean fromResource(Resource propertiesResource) {
UserDetailsResourceFactoryBean result = new UserDetailsResourceFactoryBean();
result.setResource(propertiesResource);
return result;
}
/**
* Creates a UserDetailsResourceFactoryBean with a resource from the provided String
* @param users the string representing the users
* @return the UserDetailsResourceFactoryBean
*/
public static UserDetailsResourceFactoryBean fromString(String users) {
InMemoryResource resource = new InMemoryResource(users);
return fromResource(resource);
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\core\userdetails\UserDetailsResourceFactoryBean.java
| 2
|
请完成以下Java代码
|
private static String parseHost(String value) {
int index = String.valueOf(value).trim().indexOf("[");
return index > 0 ? value.trim().substring(0, index).trim()
: index != 0 && StringUtils.hasText(value) ? value.trim()
: DEFAULT_LOCATOR_HOST;
}
private static int parsePort(String value) {
StringBuilder digits = new StringBuilder();
for (char chr : String.valueOf(value).toCharArray()) {
if (Character.isDigit(chr)) {
digits.append(chr);
}
}
return digits.length() > 0 ? Integer.parseInt(digits.toString()) : DEFAULT_LOCATOR_PORT;
}
/**
* Construct a new {@link Locator} initialized with the {@link String host} and {@link Integer port}
* on which this {@link Locator} is running and listening for connections.
*
* @param host {@link String} containing the name of the host on which this {@link Locator} is running.
* @param port {@link Integer} specifying the port number on which this {@link Locator} is listening.
*/
private Locator(String host, Integer port) {
this.host = host;
this.port = port;
}
/**
* Return the {@link String name} of the host on which this {@link Locator} is running.
*
* Defaults to {@literal localhost}.
*
* @return the {@link String name} of the host on which this {@link Locator} is running.
*/
public String getHost() {
return StringUtils.hasText(this.host) ? this.host : DEFAULT_LOCATOR_HOST;
}
/**
* Returns the {@link Integer port} on which this {@link Locator} is listening.
*
* Defaults to {@literal 10334}.
*
* @return the {@link Integer port} on which this {@link Locator} is listening.
*/
public int getPort() {
return this.port != null ? this.port : DEFAULT_LOCATOR_PORT;
}
@Override
public int compareTo(Locator other) {
int result = this.getHost().compareTo(other.getHost());
|
return result != 0 ? result : (this.getPort() - other.getPort());
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Locator)) {
return false;
}
Locator that = (Locator) obj;
return this.getHost().equals(that.getHost())
&& this.getPort() == that.getPort();
}
@Override
public int hashCode() {
int hashValue = 17;
hashValue = 37 * hashValue + ObjectUtils.nullSafeHashCode(getHost());
hashValue = 37 * hashValue + ObjectUtils.nullSafeHashCode(getPort());
return hashValue;
}
@Override
public String toString() {
return String.format("%s[%d]", getHost(), getPort());
}
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\env\support\CloudCacheService.java
| 1
|
请完成以下Java代码
|
public Resource loadSecretKeyResource() {
return loadResource(secretKeyResource, secretKey, secretKeyLocation);
}
/**
* <p>getSecretKeyPasswordChars.</p>
*
* @return an array of {@link char} objects
*/
public char[] getSecretKeyPasswordChars() {
return secretKeyPassword.toCharArray();
}
/**
* <p>getSecretKeySaltGenerator.</p>
*
* @return a {@link org.jasypt.salt.SaltGenerator} object
*/
public SaltGenerator getSecretKeySaltGenerator() {
return saltGenerator != null ?
saltGenerator :
(secretKeySalt == null ?
new ZeroSaltGenerator() :
|
new FixedBase64ByteArraySaltGenerator(secretKeySalt));
}
@SneakyThrows
private IvGenerator instantiateIvGenerator() {
return (IvGenerator)Class.forName(this.ivGeneratorClassName).newInstance();
}
/**
* <p>getActualIvGenerator.</p>
*
* @return a {@link org.jasypt.iv.IvGenerator} object
*/
public IvGenerator getActualIvGenerator() {
return Optional.ofNullable(ivGenerator).orElseGet(this::instantiateIvGenerator);
}
}
|
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\encryptor\SimpleGCMConfig.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.