instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public class SpringJobExecutor extends JobExecutor {
private TaskExecutor taskExecutor;
public TaskExecutor getTaskExecutor() {
return taskExecutor;
}
/**
* Required spring injected {@link TaskExecutor}} implementation that will be used to execute runnable jobs.
*
* @param taskExecutor
*/
public void setTaskExecutor(TaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
public void executeJobs(List<String> jobIds, ProcessEngineImpl processEngine) {
try {
taskExecutor.execute(getExecuteJobsRunnable(jobIds, processEngine));
} catch (RejectedExecutionException e) {
logRejectedExecution(processEngine, jobIds.size());
rejectedJobsHandler.jobsRejected(jobIds, processEngine, this);
} finally {
if (taskExecutor instanceof ThreadPoolTaskExecutor) { | logJobExecutionInfo(processEngine, ((ThreadPoolTaskExecutor) taskExecutor).getQueueSize(),
((ThreadPoolTaskExecutor) taskExecutor).getQueueCapacity(),
((ThreadPoolTaskExecutor) taskExecutor).getMaxPoolSize(),
((ThreadPoolTaskExecutor) taskExecutor).getActiveCount());
}
}
}
@Override
protected void startExecutingJobs() {
startJobAcquisitionThread();
}
@Override
protected void stopExecutingJobs() {
stopJobAcquisitionThread();
}
} | repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\components\jobexecutor\SpringJobExecutor.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the branchId
*/
public Long getBranchId() {
return branchId;
}
/**
* @param branchId the branchId to set
*/
public void setBranchId(Long branchId) {
this.branchId = branchId;
}
/**
* @return the customerId
*/
public Long getCustomerId() {
return customerId;
}
/**
* @param customerId the customerId to set
*/
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((branchId == null) ? 0 : branchId.hashCode());
result = prime * result + ((customerId == null) ? 0 : customerId.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override | public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Account other = (Account) obj;
if (branchId == null) {
if (other.branchId != null)
return false;
} else if (!branchId.equals(other.branchId))
return false;
if (customerId == null) {
if (other.customerId != null)
return false;
} else if (!customerId.equals(other.customerId))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-vault\src\main\java\com\baeldung\spring\cloud\vaultsample\domain\Account.java | 1 |
请完成以下Java代码 | public Expression getExpression() {
return expressionChild.getChild(this);
}
public void setExpression(Expression expression) {
expressionChild.setChild(this, expression);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Binding.class, DMN_ELEMENT_BINDING)
.namespaceUri(LATEST_DMN_NS)
.instanceProvider(new ModelTypeInstanceProvider<Binding>() {
public Binding newInstance(ModelTypeInstanceContext instanceContext) {
return new BindingImpl(instanceContext);
} | });
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
parameterChild = sequenceBuilder.element(Parameter.class)
.required()
.build();
expressionChild = sequenceBuilder.element(Expression.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\BindingImpl.java | 1 |
请完成以下Java代码 | public void setValue(Object model)
{
final int adTableId;
final int recordId;
if (model == null)
{
adTableId = -1;
recordId = -1;
}
else
{
adTableId = InterfaceWrapperHelper.getModelTableId(model);
recordId = InterfaceWrapperHelper.getId(model);
}
setTableAndRecordId(adTableId, recordId);
setModel(model, adTableId, recordId);
}
private Properties getModelCtx()
{
return InterfaceWrapperHelper.getCtx(model);
}
private String getModelTrxName()
{
return InterfaceWrapperHelper.getTrxName(model);
}
private int getModelTableId()
{
return modelTableId;
}
private int getModelRecordId()
{
return modelRecordId;
}
private final <RT> RT loadModel(final Properties ctx, final int adTableId, final int recordId, final Class<RT> modelClass, final String trxName)
{
final String tableName = Services.get(IADTableDAO.class).retrieveTableName(adTableId); | final RT modelCasted = InterfaceWrapperHelper.create(ctx, tableName, recordId, modelClass, trxName);
setModel(modelCasted, modelTableId, modelRecordId);
return modelCasted;
}
private final void setModel(final Object model, int adTableId, int recordId)
{
this.model = model;
this.modelTableId = adTableId;
this.modelRecordId = recordId;
}
private final void resetModel()
{
this.model = null;
this.modelTableId = -1;
this.modelRecordId = -1;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\impl\TableRecordCacheLocal.java | 1 |
请完成以下Java代码 | public class PrintQRCode extends JavaProcess
{
private final GlobalQRCodeService globalQRCodeService = SpringContextHolder.instance.getBean(GlobalQRCodeService.class);
@Override
protected String doIt()
{
final ExternalSystemConfigQRCode qrCode = ExternalSystemConfigQRCode.builder()
.childConfigId(getChildConfigId())
.build();
final PrintableQRCode printableQRCode = qrCode.toPrintableQRCode();
final QRCodePDFResource pdf = globalQRCodeService.createPDF(ImmutableList.of(printableQRCode));
getResult().setReportData(pdf, pdf.getFilename(), pdf.getContentType());
return MSG_OK;
} | @NonNull
private IExternalSystemChildConfigId getChildConfigId()
{
final String tableName = getTableName();
if (I_ExternalSystem_Config_LeichMehl.Table_Name.equals(tableName))
{
return ExternalSystemLeichMehlConfigId.ofRepoId(getRecord_ID());
}
else
{
throw new AdempiereException("Unsupported child config table: " + tableName);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\PrintQRCode.java | 1 |
请完成以下Java代码 | public final boolean isDateWithTime()
{
return this == ZonedDateTime
|| this == Timestamp;
}
public final boolean isNumeric()
{
return TYPES_ALL_NUMERIC.contains(this);
}
public final boolean isBigDecimal()
{
return isNumeric() && BigDecimal.class.equals(getValueClassOrNull());
}
public final boolean isStrictText()
{
return this == Text || this == LongText;
}
public final boolean isText()
{
return isStrictText() || this == URL || this == Password;
}
public final boolean isButton()
{
return this == Button || this == ActionButton || this == ProcessButton || this == ZoomIntoButton;
}
public final boolean isLookup()
{
return this == Lookup || this == List;
}
public final boolean isSupportZoomInto()
{
return isLookup() || this == DocumentFieldWidgetType.ZoomIntoButton
// || this == DocumentFieldWidgetType.Labels // not implemented yet
;
} | public final boolean isBoolean()
{
return this == YesNo || this == Switch;
}
/**
* Same as {@link #getValueClassOrNull()} but it will throw exception in case there is no valueClass.
*
* @return value class
*/
public Class<?> getValueClass()
{
if (valueClass == null)
{
throw new IllegalStateException("valueClass is unknown for " + this);
}
return valueClass;
}
/**
* Gets the standard value class to be used for this widget.
* In case there are multiple value classes which can be used for this widget, the method will return null.
*
* @return value class or <code>null</code>
*/
public Class<?> getValueClassOrNull()
{
return valueClass;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentFieldWidgetType.java | 1 |
请完成以下Java代码 | protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (!getSelectedRowIds().isSingleDocumentId())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
final IView husToPickView = createHUsToPickView();
getResult().setWebuiViewToOpen(WebuiViewToOpen.builder()
.viewId(husToPickView.getViewId().getViewId())
.profileId("husToPick")
.target(ViewOpenTarget.IncludedView)
.build()); | return MSG_OK;
}
private IView createHUsToPickView()
{
final PickingSlotView pickingSlotsView = getPickingSlotView();
final PickingSlotRowId pickingSlotRowId = getSingleSelectedPickingSlotRow().getPickingSlotRowId();
return viewsRepo.createView(husToPickViewFactory.createViewRequest(
pickingSlotsView.getViewId(),
pickingSlotRowId,
pickingSlotsView.getCurrentShipmentScheduleId(),
getBarcodeFilterData().orElse(null)));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\process\WEBUI_Picking_HUEditor_Launcher.java | 1 |
请完成以下Java代码 | public Long getBranchId() {
return branchId;
}
/**
* @param branchId the branchId to set
*/
public void setBranchId(Long branchId) {
this.branchId = branchId;
}
/**
* @return the customerId
*/
public Long getCustomerId() {
return customerId;
}
/**
* @param customerId the customerId to set
*/
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((branchId == null) ? 0 : branchId.hashCode());
result = prime * result + ((customerId == null) ? 0 : customerId.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass()) | return false;
Account other = (Account) obj;
if (branchId == null) {
if (other.branchId != null)
return false;
} else if (!branchId.equals(other.branchId))
return false;
if (customerId == null) {
if (other.customerId != null)
return false;
} else if (!customerId.equals(other.customerId))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-vault\src\main\java\com\baeldung\spring\cloud\vaultsample\domain\Account.java | 1 |
请完成以下Java代码 | public List<String> findHistoricCaseInstanceIdsByParentIds(Collection<String> caseInstanceIds) {
return getDbSqlSession().selectList("selectHistoricCaseInstanceIdsByParentIds", createSafeInValuesList(caseInstanceIds));
}
@Override
@SuppressWarnings("unchecked")
public List<HistoricCaseInstance> findByCriteria(HistoricCaseInstanceQueryImpl query) {
setSafeInValueLists(query);
return getDbSqlSession().selectList("selectHistoricCaseInstancesByQueryCriteria", query, getManagedEntityClass());
}
@Override
public long countByCriteria(HistoricCaseInstanceQueryImpl query) {
setSafeInValueLists(query);
return (Long) getDbSqlSession().selectOne("selectHistoricCaseInstanceCountByQueryCriteria", query);
}
@Override
@SuppressWarnings("unchecked")
public List<HistoricCaseInstance> findWithVariablesByQueryCriteria(HistoricCaseInstanceQueryImpl historicCaseInstanceQuery) {
setSafeInValueLists(historicCaseInstanceQuery);
return getDbSqlSession().selectList("selectHistoricCaseInstancesWithVariablesByQueryCriteria", historicCaseInstanceQuery, getManagedEntityClass());
}
@Override
@SuppressWarnings("unchecked")
public List<HistoricCaseInstance> findIdsByCriteria(HistoricCaseInstanceQueryImpl query) {
setSafeInValueLists(query);
return getDbSqlSession().selectList("selectHistoricCaseInstanceIdsByQueryCriteria", query, getManagedEntityClass());
}
@Override
public void deleteByCaseDefinitionId(String caseDefinitionId) { | getDbSqlSession().delete("deleteHistoricCaseInstanceByCaseDefinitionId", caseDefinitionId, getManagedEntityClass());
}
@Override
public void deleteHistoricCaseInstances(HistoricCaseInstanceQueryImpl historicCaseInstanceQuery) {
getDbSqlSession().delete("bulkDeleteHistoricCaseInstances", historicCaseInstanceQuery, getManagedEntityClass());
}
@Override
public void bulkDeleteHistoricCaseInstances(Collection<String> caseInstanceIds) {
getDbSqlSession().delete("bulkDeleteHistoricCaseInstancesByIds", createSafeInValuesList(caseInstanceIds), getManagedEntityClass());
}
protected void setSafeInValueLists(HistoricCaseInstanceQueryImpl caseInstanceQuery) {
if (caseInstanceQuery.getCaseInstanceIds() != null) {
caseInstanceQuery.setSafeCaseInstanceIds(createSafeInValuesList(caseInstanceQuery.getCaseInstanceIds()));
}
if (caseInstanceQuery.getInvolvedGroups() != null) {
caseInstanceQuery.setSafeInvolvedGroups(createSafeInValuesList(caseInstanceQuery.getInvolvedGroups()));
}
if (caseInstanceQuery.getOrQueryObjects() != null && !caseInstanceQuery.getOrQueryObjects().isEmpty()) {
for (HistoricCaseInstanceQueryImpl orCaseInstanceQuery : caseInstanceQuery.getOrQueryObjects()) {
setSafeInValueLists(orCaseInstanceQuery);
}
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\data\impl\MybatisHistoricCaseInstanceDataManagerImpl.java | 1 |
请完成以下Java代码 | public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getConfiguration() {
return configuration;
}
public void setConfiguration(String configuration) {
this.configuration = configuration;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getProcessDefinitionId() {
return processDefinitionId;
} | public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
EventSubscriptionEntityImpl other = (EventSubscriptionEntityImpl) obj;
if (id == null) {
if (other.id != null) return false;
} else if (!id.equals(other.id)) return false;
return true;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\EventSubscriptionEntityImpl.java | 1 |
请完成以下Java代码 | public static boolean isConnectionError(final Exception e)
{
if (e instanceof EMailSendException)
{
return ((EMailSendException)e).isConnectionError();
}
else
return e instanceof java.net.ConnectException;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("sentMsg", sentMsg)
.add("sentConnectionError", sentConnectionError)
.add("messageId", messageId)
.toString();
}
@JsonIgnore
public boolean isSentOK() | {
return Util.same(sentMsg, SENT_OK);
}
public void throwIfNotOK()
{
throwIfNotOK(null);
}
public void throwIfNotOK(@Nullable final Consumer<EMailSendException> exceptionDecorator)
{
if (!isSentOK())
{
final EMailSendException exception = new EMailSendException(this);
if (exceptionDecorator != null)
{
exceptionDecorator.accept(exception);
}
throw exception;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\EMailSentStatus.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Host {
/**
* IP address to listen to.
*/
private String ip = "127.0.0.1";
/**
* Port to listener to.
*/
private int port = 9797;
// @fold:on // getters/setters ...
public String getIp() {
return this.ip; | }
public void setIp(String ip) {
this.ip = ip;
}
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
// @fold:off
} | repos\spring-boot-4.0.1\documentation\spring-boot-docs\src\main\java\org\springframework\boot\docs\appendix\configurationmetadata\annotationprocessor\automaticmetadatageneration\source\Host.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void addH110(final H110 h110)
{
h110Lines.add(h110);
}
public void addH120(final H120 h120)
{
h120Lines.add(h120);
}
public void addH130(final H130 h130)
{
h130Lines.add(h130);
}
public void addOrderLine(final OrderLine orderLine)
{
orderLines.add(orderLine);
}
public void addT100(final T100 t100)
{
t100Lines.add(t100);
}
public H100 getH100()
{
return h100;
}
public List<H110> getH110Lines()
{
return h110Lines;
}
public List<H120> getH120Lines()
{ | return h120Lines;
}
public List<H130> getH130Lines()
{
return h130Lines;
}
public List<OrderLine> getOrderLines()
{
return orderLines;
}
public List<T100> getT100Lines()
{
return t100Lines;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\ordersimport\OrderHeader.java | 2 |
请完成以下Java代码 | public HuId getTopLevelHUId(final HuId huId)
{
return topLevelHUIds.computeIfAbsent(huId, this::retrieveTopLevelHUId);
}
private HuId retrieveTopLevelHUId(final HuId huId)
{
final I_M_HU hu = getHUById(huId);
final I_M_HU topLevelHU = handlingUnitsBL.getTopLevelParentAsLUTUCUPair(hu).getTopLevelHU();
addToCache(topLevelHU);
return extractHUId(topLevelHU);
}
public ImmutableSet<HuId> getVHUIds(final HuId huId) {return vhuIds.computeIfAbsent(huId, this::retrieveVHUIds);}
private ImmutableSet<HuId> retrieveVHUIds(final HuId huId)
{
final I_M_HU hu = getHUById(huId);
final List<I_M_HU> vhus = handlingUnitsBL.getVHUs(hu);
addToCache(vhus);
return extractHUIds(vhus);
}
private static ImmutableSet<HuId> extractHUIds(final List<I_M_HU> hus) {return hus.stream().map(HUsLoadingCache::extractHUId).collect(ImmutableSet.toImmutableSet());}
private static HuId extractHUId(final I_M_HU hu) {return HuId.ofRepoId(hu.getM_HU_ID());}
public ImmutableAttributeSet getHUAttributes(final HuId huId)
{ | return huAttributesCache.computeIfAbsent(huId, this::retrieveHUAttributes);
}
private ImmutableAttributeSet retrieveHUAttributes(final HuId huId)
{
final I_M_HU hu = getHUById(huId);
final IAttributeStorage attributes = attributesFactory.getAttributeStorage(hu);
return ImmutableAttributeSet.createSubSet(attributes, a -> attributesToConsider.contains(AttributeCode.ofString(a.getValue())));
}
public LocatorId getLocatorIdByHuId(final HuId huId)
{
final I_M_HU hu = getHUById(huId);
return IHandlingUnitsBL.extractLocatorId(hu);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\plan\generator\pickFromHUs\HUsLoadingCache.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getConsignmentReference() {
return consignmentReference;
}
/**
* Sets the value of the consignmentReference property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConsignmentReference(String value) {
this.consignmentReference = value;
}
/**
* Free text information.Gets the value of the freeText 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 freeText property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre> | * getFreeText().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link FreeTextType }
*
*
*/
public List<FreeTextType> getFreeText() {
if (freeText == null) {
freeText = new ArrayList<FreeTextType>();
}
return this.freeText;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ORDRSPExtensionType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private static class LoadLabelsValues implements DocumentFieldValueLoader
{
@NonNull String sqlValuesColumn;
@Override
public LookupValuesList retrieveFieldValue(
@NonNull final ResultSet rs,
final boolean isDisplayColumnAvailable_NOTUSED,
final String adLanguage_NOTUSED,
@Nullable final LookupDescriptor lookupDescriptor) throws SQLException
{
// FIXME: atm we are avoiding NPE by returning EMPTY.
if (lookupDescriptor == null)
{
return LookupValuesList.EMPTY;
}
final LabelsLookup lookup = LabelsLookup.cast(lookupDescriptor);
final List<Object> ids = retrieveIds(rs);
return lookup.retrieveExistingValuesByIds(ids);
}
private List<Object> retrieveIds(final ResultSet rs) throws SQLException
{
final Array sqlArray = rs.getArray(sqlValuesColumn);
if (sqlArray != null)
{
return Stream.of((Object[])sqlArray.getArray())
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList());
}
else
{
return ImmutableList.of();
}
}
} | @Builder
@Value
private static class ColorDocumentFieldValueLoader implements DocumentFieldValueLoader
{
@NonNull String sqlColumnName;
@Override
@Nullable
public Object retrieveFieldValue(
@NonNull final ResultSet rs,
final boolean isDisplayColumnAvailable_NOTUSED,
final String adLanguage_NOTUSED,
final LookupDescriptor lookupDescriptor_NOTUSED) throws SQLException
{
final ColorId adColorId = ColorId.ofRepoIdOrNull(rs.getInt(sqlColumnName));
if (adColorId == null)
{
return null;
}
final IColorRepository colorRepository = Services.get(IColorRepository.class);
final MFColor color = colorRepository.getColorById(adColorId);
if (color == null)
{
return null;
}
final Color awtColor = color.toFlatColor().getFlatColor();
return ColorValue.ofRGB(awtColor.getRed(), awtColor.getGreen(), awtColor.getBlue());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\DocumentFieldValueLoaders.java | 2 |
请完成以下Java代码 | private void commit(final ASIDocument asiDoc)
{
final DocumentId asiDocId = asiDoc.getDocumentId();
if (asiDoc.isCompleted())
{
final ASIDocument asiDocRemoved = id2asiDoc.remove(asiDocId);
logger.trace("Removed from repository by ID={}: {}", asiDocId, asiDocRemoved);
}
else
{
final ASIDocument asiDocReadonly = asiDoc.copy(CopyMode.CheckInReadonly, NullDocumentChangesCollector.instance);
id2asiDoc.put(asiDocId, asiDocReadonly);
logger.trace("Added to repository: {}", asiDocReadonly);
}
}
public <R> R forASIDocumentReadonly(
@NonNull final DocumentId asiDocId,
@NonNull final DocumentCollection documentsCollection,
@NonNull final Function<ASIDocument, R> processor)
{
try (final IAutoCloseable ignored = getASIDocumentNoLock(asiDocId).lockForReading())
{
final ASIDocument asiDoc = getASIDocumentNoLock(asiDocId)
.copy(CopyMode.CheckInReadonly, NullDocumentChangesCollector.instance) | .bindContextDocumentIfPossible(documentsCollection);
return processor.apply(asiDoc);
}
}
public <R> R forASIDocumentWritable(
@NonNull final DocumentId asiDocId,
@NonNull final IDocumentChangesCollector changesCollector,
@NonNull final DocumentCollection documentsCollection,
@NonNull final Function<ASIDocument, R> processor)
{
try (final IAutoCloseable ignored = getASIDocumentNoLock(asiDocId).lockForWriting())
{
final ASIDocument asiDoc = getASIDocumentNoLock(asiDocId)
.copy(CopyMode.CheckOutWritable, changesCollector)
.bindContextDocumentIfPossible(documentsCollection);
final R result = processor.apply(asiDoc);
trxManager.runAfterCommit(() -> commit(asiDoc));
return result;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pattribute\ASIRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WebConfig implements WebMvcConfigurer {
private final ApplicationContext applicationContext;
public WebConfig(ApplicationContext applicationContext) {
super();
this.applicationContext = applicationContext;
}
@Override
public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {
converters.add(new MappingJackson2HttpMessageConverter());
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
final PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
ppc.setIgnoreUnresolvablePlaceholders(true);
return ppc;
}
@Bean
public ViewResolver viewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setCharacterEncoding("UTF-8");
return resolver;
}
@Bean
public ISpringTemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine(); | engine.setEnableSpringELCompiler(true);
engine.setTemplateResolver(templateResolver());
engine.addDialect(new SpringSecurityDialect());
return engine;
}
private ITemplateResolver templateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("/WEB-INF/templates/");
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
return resolver;
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-rest-custom\src\main\java\com\baeldung\config\child\WebConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ExternalWorkerJobFailureBuilderImpl implements ExternalWorkerJobFailureBuilder {
protected final String externalJobId;
protected final String workerId;
protected final CommandExecutor commandExecutor;
protected final JobServiceConfiguration jobServiceConfiguration;
protected String errorMessage;
protected String errorDetails;
protected int retries = -1;
protected Duration retryTimeout;
public ExternalWorkerJobFailureBuilderImpl(String externalJobId, String workerId, CommandExecutor commandExecutor,
JobServiceConfiguration jobServiceConfiguration) {
this.externalJobId = externalJobId;
this.workerId = workerId;
this.commandExecutor = commandExecutor;
this.jobServiceConfiguration = jobServiceConfiguration;
}
@Override
public ExternalWorkerJobFailureBuilder errorMessage(String errorMessage) {
this.errorMessage = errorMessage;
return this; | }
@Override
public ExternalWorkerJobFailureBuilder errorDetails(String errorDetails) {
this.errorDetails = errorDetails;
return this;
}
@Override
public ExternalWorkerJobFailureBuilder retries(int retries) {
this.retries = retries;
return this;
}
@Override
public ExternalWorkerJobFailureBuilder retryTimeout(Duration retryTimeout) {
this.retryTimeout = retryTimeout;
return this;
}
@Override
public void fail() {
commandExecutor.execute(new ExternalWorkerJobFailCmd(externalJobId, workerId, retries, retryTimeout,
errorMessage, errorDetails, jobServiceConfiguration));
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\ExternalWorkerJobFailureBuilderImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String xxlJobTrigger() {
Map<String, Object> jobInfo = Maps.newHashMap();
jobInfo.put("id", 4);
jobInfo.put("executorParam", JSONUtil.toJsonStr(jobInfo));
HttpResponse execute = HttpUtil.createGet(baseUri + JOB_INFO_URI + "/trigger").form(jobInfo).execute();
log.info("【execute】= {}", execute);
return execute.body();
}
/**
* 测试手动删除任务
*/
@GetMapping("/remove")
public String xxlJobRemove() {
Map<String, Object> jobInfo = Maps.newHashMap();
jobInfo.put("id", 4);
HttpResponse execute = HttpUtil.createGet(baseUri + JOB_INFO_URI + "/remove").form(jobInfo).execute();
log.info("【execute】= {}", execute);
return execute.body();
}
/**
* 测试手动停止任务
*/ | @GetMapping("/stop")
public String xxlJobStop() {
Map<String, Object> jobInfo = Maps.newHashMap();
jobInfo.put("id", 4);
HttpResponse execute = HttpUtil.createGet(baseUri + JOB_INFO_URI + "/stop").form(jobInfo).execute();
log.info("【execute】= {}", execute);
return execute.body();
}
/**
* 测试手动启动任务
*/
@GetMapping("/start")
public String xxlJobStart() {
Map<String, Object> jobInfo = Maps.newHashMap();
jobInfo.put("id", 4);
HttpResponse execute = HttpUtil.createGet(baseUri + JOB_INFO_URI + "/start").form(jobInfo).execute();
log.info("【execute】= {}", execute);
return execute.body();
}
} | repos\spring-boot-demo-master\demo-task-xxl-job\src\main\java\com\xkcoding\task\xxl\job\controller\ManualOperateController.java | 2 |
请完成以下Java代码 | public List<Product> parseCsvFileIntoBeans(String relativePath) {
try (Reader inputReader = new InputStreamReader(new FileInputStream(new File(relativePath)), "UTF-8")) {
BeanListProcessor<Product> rowProcessor = new BeanListProcessor<Product>(Product.class);
CsvParserSettings settings = new CsvParserSettings();
settings.setHeaderExtractionEnabled(true);
settings.setProcessor(rowProcessor);
CsvParser parser = new CsvParser(settings);
parser.parse(inputReader);
return rowProcessor.getBeans();
} catch (IOException e) {
logger.error("IOException opening file: " + relativePath + " " + e.getMessage());
return new ArrayList<Product>();
}
}
public List<String[]> parseCsvFileInBatches(String relativePath) { | try (Reader inputReader = new InputStreamReader(new FileInputStream(new File(relativePath)), "UTF-8")) {
CsvParserSettings settings = new CsvParserSettings();
settings.setProcessor(new BatchedColumnProcessor(5) {
@Override
public void batchProcessed(int rowsInThisBatch) {
}
});
CsvParser parser = new CsvParser(settings);
List<String[]> parsedRows = parser.parseAll(inputReader);
return parsedRows;
} catch (IOException e) {
logger.error("IOException opening file: " + relativePath + " " + e.getMessage());
return new ArrayList<String[]>();
}
}
} | repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\univocity\ParsingService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CreateProjectCostCollectorRequest
{
@NonNull ServiceRepairProjectTaskId taskId;
@NonNull ServiceRepairProjectCostCollectorType type;
@NonNull ProductId productId;
@NonNull AttributeSetInstanceId asiId;
@NonNull WarrantyCase warrantyCase;
@NonNull Quantity qtyReserved;
@NonNull Quantity qtyConsumed;
@Nullable HuId reservedVhuId;
@Nullable PPOrderAndCostCollectorId repairOrderCostCollectorId;
@Builder
private CreateProjectCostCollectorRequest(
@NonNull final ServiceRepairProjectTaskId taskId,
@NonNull final ServiceRepairProjectCostCollectorType type,
@NonNull final ProductId productId,
@Nullable final AttributeSetInstanceId asiId,
@Nullable final WarrantyCase warrantyCase,
@Nullable final Quantity qtyReserved,
@Nullable final Quantity qtyConsumed,
@Nullable final HuId reservedVhuId,
@Nullable final PPOrderAndCostCollectorId repairOrderCostCollectorId)
{
final Quantity qtyFirstNotNull = CoalesceUtil.coalesce(qtyReserved, qtyConsumed);
if (qtyFirstNotNull == null)
{
throw new AdempiereException("At least one qty shall be set");
}
this.taskId = taskId; | this.type = type;
this.productId = productId;
this.asiId = asiId != null ? asiId : AttributeSetInstanceId.NONE;
this.warrantyCase = warrantyCase != null ? warrantyCase : WarrantyCase.NO;
this.qtyReserved = qtyReserved != null ? qtyReserved : qtyFirstNotNull.toZero();
this.qtyConsumed = qtyConsumed != null ? qtyConsumed : qtyFirstNotNull.toZero();
this.reservedVhuId = reservedVhuId;
this.repairOrderCostCollectorId = repairOrderCostCollectorId;
}
public UomId getUomId()
{
return Quantity.getCommonUomIdOfAll(qtyReserved, qtyConsumed);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\repository\requests\CreateProjectCostCollectorRequest.java | 2 |
请完成以下Java代码 | public ClientAndOrgId getClientAndOrgId()
{
assertNotEmpty();
return list.get(0).getClientAndOrgId();
}
public MaterialDispoGroupId getEffectiveGroupId()
{
assertNotEmpty();
return list.get(0).getEffectiveGroupId();
}
public CandidateBusinessCase getBusinessCase()
{
assertNotEmpty();
return CollectionUtils.extractSingleElement(list, Candidate::getBusinessCase);
} | public Candidate getSingleCandidate()
{
return CollectionUtils.singleElement(list);
}
public Candidate getSingleSupplyCandidate()
{
return CollectionUtils.singleElement(list, candidate -> CandidateType.equals(candidate.getType(), CandidateType.SUPPLY));
}
public Candidate getSingleDemandCandidate()
{
return CollectionUtils.singleElement(list, candidate -> CandidateType.equals(candidate.getType(), CandidateType.DEMAND));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\CandidatesGroup.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WebUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
WebUser(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false; | WebUser webUser = (WebUser) o;
return Objects.equals(id, webUser.id);
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
protected WebUser() {
}
} | repos\tutorials-master\persistence-modules\java-jpa-3\src\main\java\com\baeldung\jpa\hibernateunproxy\WebUser.java | 2 |
请完成以下Java代码 | private ChartOfAccountsMap getMap()
{
return cache.getOrLoad(0, this::retrieveMap);
}
private ChartOfAccountsMap retrieveMap()
{
return new ChartOfAccountsMap(
queryBL.createQueryBuilder(I_C_Element.class)
.addOnlyActiveRecordsFilter()
.create()
.stream()
.map(ChartOfAccountsRepository::fromRecord)
.collect(ImmutableList.toImmutableList()));
}
private static ChartOfAccounts fromRecord(@NonNull final I_C_Element record)
{
return ChartOfAccounts.builder()
.id(ChartOfAccountsId.ofRepoId(record.getC_Element_ID()))
.name(record.getName())
.clientId(ClientId.ofRepoId(record.getAD_Client_ID()))
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.treeId(AdTreeId.ofRepoId(record.getAD_Tree_ID()))
.build();
}
public ChartOfAccounts getById(final ChartOfAccountsId chartOfAccountsId)
{
return getMap().getById(chartOfAccountsId);
}
public List<ChartOfAccounts> getByIds(final Set<ChartOfAccountsId> chartOfAccountsIds)
{ | return getMap().getByIds(chartOfAccountsIds);
}
public Optional<ChartOfAccounts> getByName(@NonNull final String chartOfAccountsName, @NonNull final ClientId clientId, @NonNull final OrgId orgId)
{
return getMap().getByName(chartOfAccountsName, clientId, orgId);
}
public Optional<ChartOfAccounts> getByTreeId(@NonNull final AdTreeId treeId)
{
return getMap().getByTreeId(treeId);
}
ChartOfAccounts createChartOfAccounts(
@NonNull final String name,
@NonNull final ClientId clientId,
@NonNull final OrgId orgId,
@NonNull final AdTreeId chartOfAccountsTreeId)
{
final I_C_Element record = InterfaceWrapperHelper.newInstance(I_C_Element.class);
InterfaceWrapperHelper.setValue(record, I_C_Element.COLUMNNAME_AD_Client_ID, clientId.getRepoId());
record.setAD_Org_ID(orgId.getRepoId());
record.setName(name);
record.setAD_Tree_ID(chartOfAccountsTreeId.getRepoId());
record.setElementType(X_C_Element.ELEMENTTYPE_Account);
record.setIsNaturalAccount(true);
InterfaceWrapperHelper.save(record);
return fromRecord(record);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\elementvalue\ChartOfAccountsRepository.java | 1 |
请完成以下Java代码 | public class SysDepartPositionVo {
/**
* 部门id
*/
private String id;
/**
* 是否为叶子节点(数据返回)
*/
private Integer izLeaf;
/**
* 部门名称
*/
private String departName;
/**
* 职务名称
*/
private String positionName;
/**
* 父级id
*/ | private String parentId;
/**
* 部门编码
*/
private String orgCode;
/**
* 机构类型
*/
private String orgCategory;
/**
* 上级岗位id
*/
private String depPostParentId;
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\vo\SysDepartPositionVo.java | 1 |
请完成以下Java代码 | public Long getProductCategoryId() {
return productCategoryId;
}
public void setProductCategoryId(Long productCategoryId) {
this.productCategoryId = productCategoryId;
}
public String getProductBrand() {
return productBrand;
}
public void setProductBrand(String productBrand) {
this.productBrand = productBrand;
}
public String getProductSn() {
return productSn;
}
public void setProductSn(String productSn) {
this.productSn = productSn;
}
public String getProductAttr() {
return productAttr;
}
public void setProductAttr(String productAttr) {
this.productAttr = productAttr;
}
@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(", productSkuId=").append(productSkuId);
sb.append(", memberId=").append(memberId);
sb.append(", quantity=").append(quantity);
sb.append(", price=").append(price);
sb.append(", productPic=").append(productPic);
sb.append(", productName=").append(productName);
sb.append(", productSubTitle=").append(productSubTitle);
sb.append(", productSkuCode=").append(productSkuCode);
sb.append(", memberNickname=").append(memberNickname);
sb.append(", createDate=").append(createDate);
sb.append(", modifyDate=").append(modifyDate);
sb.append(", deleteStatus=").append(deleteStatus);
sb.append(", productCategoryId=").append(productCategoryId);
sb.append(", productBrand=").append(productBrand);
sb.append(", productSn=").append(productSn);
sb.append(", productAttr=").append(productAttr);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsCartItem.java | 1 |
请完成以下Java代码 | public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
@Override
public void setEntityType (final java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
@Override
public java.lang.String getEntityType()
{
return get_ValueAsString(COLUMNNAME_EntityType);
}
@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);
}
/**
* ResponsibleType AD_Reference_ID=304
* Reference name: WF_Participant Type
*/
public static final int RESPONSIBLETYPE_AD_Reference_ID=304;
/** Organisation = O */
public static final String RESPONSIBLETYPE_Organisation = "O";
/** Human = H */
public static final String RESPONSIBLETYPE_Human = "H";
/** Rolle = R */
public static final String RESPONSIBLETYPE_Rolle = "R";
/** Systemressource = S */
public static final String RESPONSIBLETYPE_Systemressource = "S";
/** Other = X */
public static final String RESPONSIBLETYPE_Other = "X";
@Override
public void setResponsibleType (final java.lang.String ResponsibleType)
{
set_Value (COLUMNNAME_ResponsibleType, ResponsibleType);
}
@Override
public java.lang.String getResponsibleType()
{
return get_ValueAsString(COLUMNNAME_ResponsibleType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Responsible.java | 1 |
请完成以下Java代码 | private ImmutableMap<SecurPharmLogId, I_M_Securpharm_Log> retrieveLogRecordsByIds(final Collection<SecurPharmLogId> ids)
{
if (ids.isEmpty())
{
return ImmutableMap.of();
}
return Services.get(IQueryBL.class)
.createQueryBuilder(I_M_Securpharm_Log.class)
.addInArrayFilter(I_M_Securpharm_Log.COLUMN_M_Securpharm_Log_ID, ids)
.create()
.stream()
.collect(GuavaCollectors.toImmutableMapByKey(record -> SecurPharmLogId.ofRepoId(record.getM_Securpharm_Log_ID())));
}
private void saveLog(
@NonNull final SecurPharmLog log,
@Nullable final I_M_Securpharm_Log existingLogRecord,
@Nullable final SecurPharmProductId productId,
@Nullable final SecurPharmActionResultId actionId)
{
final I_M_Securpharm_Log record;
if (existingLogRecord != null)
{
record = existingLogRecord;
}
else
{
record = newInstance(I_M_Securpharm_Log.class);
}
record.setIsActive(true);
record.setIsError(log.isError());
//
// Request
record.setRequestUrl(log.getRequestUrl());
record.setRequestMethod(log.getRequestMethod() != null ? log.getRequestMethod().name() : null);
record.setRequestStartTime(TimeUtil.asTimestamp(log.getRequestTime()));
//
// Response
record.setRequestEndTime(TimeUtil.asTimestamp(log.getResponseTime()));
record.setResponseCode(log.getResponseCode() != null ? log.getResponseCode().value() : 0);
record.setResponseText(log.getResponseData()); | //
record.setTransactionIDClient(log.getClientTransactionId());
record.setTransactionIDServer(log.getServerTransactionId());
//
// Links
if (productId != null)
{
record.setM_Securpharm_Productdata_Result_ID(productId.getRepoId());
}
if (actionId != null)
{
record.setM_Securpharm_Action_Result_ID(actionId.getRepoId());
}
saveRecord(record);
log.setId(SecurPharmLogId.ofRepoId(record.getM_Securpharm_Log_ID()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\log\SecurPharmLogRepository.java | 1 |
请完成以下Java代码 | private ImmutableList<GeographicalCoordinates> queryAllCoordinates(final @NonNull GeoCoordinatesRequest request)
{
final Map<String, String> parameterList = prepareParameterList(request);
//@formatter:off
final ParameterizedTypeReference<List<NominatimOSMGeographicalCoordinatesJSON>> returnType = new ParameterizedTypeReference<List<NominatimOSMGeographicalCoordinatesJSON>>(){};
//@formatter:on
final HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.USER_AGENT, "openstreetmapbot@metasfresh.com");
final HttpEntity<String> entity = new HttpEntity<>(headers);
final ResponseEntity<List<NominatimOSMGeographicalCoordinatesJSON>> exchange = restTemplate.exchange(
baseUrl + QUERY_STRING,
HttpMethod.GET,
entity,
returnType,
parameterList);
final List<NominatimOSMGeographicalCoordinatesJSON> coords = exchange.getBody();
lastRequestTime = Instant.now();
final ImmutableList<GeographicalCoordinates> result = coords.stream()
.map(NominatimOSMGeocodingProviderImpl::toGeographicalCoordinates)
.collect(GuavaCollectors.toImmutableList());
logger.debug("Got result for {}: {}", request, result);
return result;
}
@SuppressWarnings("SpellCheckingInspection")
@NonNull
private Map<String, String> prepareParameterList(final @NonNull GeoCoordinatesRequest request)
{
final String defaultEmptyValue = "";
final Map<String, String> m = new HashMap<>();
m.put("numberAndStreet", CoalesceUtil.coalesce(request.getAddress(), defaultEmptyValue));
m.put("postalcode", CoalesceUtil.coalesce(request.getPostal(), defaultEmptyValue)); | m.put("city", CoalesceUtil.coalesce(request.getCity(), defaultEmptyValue));
m.put("countrycodes", request.getCountryCode2());
m.put("format", "json");
m.put("dedupe", "1");
m.put("email", "openstreetmapbot@metasfresh.com");
m.put("polygon_geojson", "0");
m.put("polygon_kml", "0");
m.put("polygon_svg", "0");
m.put("polygon_text", "0");
return m;
}
private static GeographicalCoordinates toGeographicalCoordinates(final NominatimOSMGeographicalCoordinatesJSON json)
{
return GeographicalCoordinates.builder()
.latitude(new BigDecimal(json.getLat()))
.longitude(new BigDecimal(json.getLon()))
.build();
}
private void sleepMillis(final long timeToSleep)
{
if (timeToSleep <= 0)
{
return;
}
try
{
logger.trace("Sleeping {}ms (rate limit)", timeToSleep);
TimeUnit.MILLISECONDS.sleep(timeToSleep);
}
catch (final InterruptedException e)
{
// nothing to do here
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\geocoding\provider\openstreetmap\NominatimOSMGeocodingProviderImpl.java | 1 |
请完成以下Java代码 | public DmnDecisionLogicEvaluationEvent evaluate(DmnDecision decision, VariableContext variableContext) {
DmnDecisionLiteralExpressionEvaluationEventImpl evaluationResult = new DmnDecisionLiteralExpressionEvaluationEventImpl();
evaluationResult.setDecision(decision);
evaluationResult.setExecutedDecisionElements(1);
DmnDecisionLiteralExpressionImpl dmnDecisionLiteralExpression = (DmnDecisionLiteralExpressionImpl) decision.getDecisionLogic();
DmnVariableImpl variable = dmnDecisionLiteralExpression.getVariable();
DmnExpressionImpl expression = dmnDecisionLiteralExpression.getExpression();
Object evaluateExpression = evaluateLiteralExpression(expression, variableContext);
TypedValue typedValue = variable.getTypeDefinition().transform(evaluateExpression);
evaluationResult.setOutputValue(typedValue);
evaluationResult.setOutputName(variable.getName());
return evaluationResult;
}
protected Object evaluateLiteralExpression(DmnExpressionImpl expression, VariableContext variableContext) {
String expressionLanguage = expression.getExpressionLanguage(); | if (expressionLanguage == null) {
expressionLanguage = literalExpressionLanguage;
}
return expressionEvaluationHandler.evaluateExpression(expressionLanguage, expression, variableContext);
}
@Override
public DmnDecisionResult generateDecisionResult(DmnDecisionLogicEvaluationEvent event) {
DmnDecisionLiteralExpressionEvaluationEvent evaluationEvent = (DmnDecisionLiteralExpressionEvaluationEvent) event;
DmnDecisionResultEntriesImpl result = new DmnDecisionResultEntriesImpl();
result.putValue(evaluationEvent.getOutputName(), evaluationEvent.getOutputValue());
return new DmnDecisionResultImpl(Collections.<DmnDecisionResultEntries> singletonList(result));
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\evaluation\DecisionLiteralExpressionEvaluationHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Map<String, Integer> maxBucketsPerMeter() {
return obtain(perMeter(Meter::getMaxBucketCount), OtlpConfig.super::maxBucketsPerMeter);
}
@Override
public int maxScale() {
return obtain(OtlpMetricsProperties::getMaxScale, OtlpConfig.super::maxScale);
}
@Override
public int maxBucketCount() {
return obtain(OtlpMetricsProperties::getMaxBucketCount, OtlpConfig.super::maxBucketCount);
}
@Override
public TimeUnit baseTimeUnit() {
return obtain(OtlpMetricsProperties::getBaseTimeUnit, OtlpConfig.super::baseTimeUnit);
}
private <V> Getter<OtlpMetricsProperties, Map<String, V>> perMeter(Getter<Meter, V> getter) {
return (properties) -> { | if (CollectionUtils.isEmpty(properties.getMeter())) {
return null;
}
Map<String, V> perMeter = new LinkedHashMap<>();
properties.getMeter().forEach((key, meterProperties) -> {
V value = getter.get(meterProperties);
if (value != null) {
perMeter.put(key, value);
}
});
return (!perMeter.isEmpty()) ? perMeter : null;
};
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\otlp\OtlpMetricsPropertiesConfigAdapter.java | 2 |
请完成以下Java代码 | public void setIsSold (final boolean IsSold)
{
set_Value (COLUMNNAME_IsSold, IsSold);
}
@Override
public boolean isSold()
{
return get_ValueAsBoolean(COLUMNNAME_IsSold);
}
@Override
public void setM_Product_Category_ID (final int M_Product_Category_ID)
{
if (M_Product_Category_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_ID, null);
else
set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID);
}
@Override
public int getM_Product_Category_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setName (final @Nullable java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setQtyAvailable (final @Nullable BigDecimal QtyAvailable)
{
set_Value (COLUMNNAME_QtyAvailable, QtyAvailable);
}
@Override
public BigDecimal getQtyAvailable()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyAvailable);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyOnHand (final @Nullable BigDecimal QtyOnHand)
{
set_Value (COLUMNNAME_QtyOnHand, QtyOnHand);
}
@Override
public BigDecimal getQtyOnHand()
{ | final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHand);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyOrdered (final @Nullable BigDecimal QtyOrdered)
{
set_Value (COLUMNNAME_QtyOrdered, QtyOrdered);
}
@Override
public BigDecimal getQtyOrdered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyReserved (final @Nullable BigDecimal QtyReserved)
{
set_Value (COLUMNNAME_QtyReserved, QtyReserved);
}
@Override
public BigDecimal getQtyReserved()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValue (final @Nullable java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_RV_HU_Quantities_Summary.java | 1 |
请完成以下Java代码 | public String getReminderLevel() {
if (reminderLevel == null) {
return "1";
} else {
return reminderLevel;
}
}
/**
* Sets the value of the reminderLevel property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReminderLevel(String value) {
this.reminderLevel = value;
}
/**
* Gets the value of the reminderText property.
* | * @return
* possible object is
* {@link String }
*
*/
public String getReminderText() {
return reminderText;
}
/**
* Sets the value of the reminderText property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReminderText(String value) {
this.reminderText = 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\ReminderType.java | 1 |
请完成以下Java代码 | public int getES_FTS_Index_Queue_ID()
{
return get_ValueAsInt(COLUMNNAME_ES_FTS_Index_Queue_ID);
}
/**
* EventType AD_Reference_ID=541373
* Reference name: ES_FTS_Index_Queue_EventType
*/
public static final int EVENTTYPE_AD_Reference_ID=541373;
/** Update = U */
public static final String EVENTTYPE_Update = "U";
/** Delete = D */
public static final String EVENTTYPE_Delete = "D";
@Override
public void setEventType (final java.lang.String EventType)
{
set_ValueNoCheck (COLUMNNAME_EventType, EventType);
}
@Override
public java.lang.String getEventType()
{
return get_ValueAsString(COLUMNNAME_EventType);
}
@Override
public void setIsError (final boolean IsError)
{
set_Value (COLUMNNAME_IsError, IsError);
}
@Override
public boolean isError()
{
return get_ValueAsBoolean(COLUMNNAME_IsError);
}
@Override
public void setProcessed (final boolean Processed)
{ | set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessingTag (final @Nullable java.lang.String ProcessingTag)
{
set_Value (COLUMNNAME_ProcessingTag, ProcessingTag);
}
@Override
public java.lang.String getProcessingTag()
{
return get_ValueAsString(COLUMNNAME_ProcessingTag);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java-gen\de\metas\elasticsearch\model\X_ES_FTS_Index_Queue.java | 1 |
请完成以下Java代码 | protected Class<DeviceCredentialsEntity> getEntityClass() {
return DeviceCredentialsEntity.class;
}
@Override
protected JpaRepository<DeviceCredentialsEntity, UUID> getRepository() {
return deviceCredentialsRepository;
}
@Override
public DeviceCredentials findByDeviceId(TenantId tenantId, UUID deviceId) {
return DaoUtil.getData(deviceCredentialsRepository.findByDeviceId(deviceId));
}
@Override
public DeviceCredentials findByCredentialsId(TenantId tenantId, String credentialsId) { | log.trace("[{}] findByCredentialsId [{}]", tenantId, credentialsId);
return DaoUtil.getData(deviceCredentialsRepository.findByCredentialsId(credentialsId));
}
@Override
public DeviceCredentials removeByDeviceId(TenantId tenantId, DeviceId deviceId) {
return DaoUtil.getData(deviceCredentialsRepository.deleteByDeviceId(deviceId.getId()));
}
@Override
public PageData<DeviceCredentials> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return DaoUtil.toPageData(deviceCredentialsRepository.findByTenantId(tenantId.getId(), DaoUtil.toPageable(pageLink)));
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\device\JpaDeviceCredentialsDao.java | 1 |
请完成以下Java代码 | public class ProductPriceAware implements IProductPriceAware
{
/**
* Introspects given model and returns {@link IProductPriceAware} is possible.
* <p>
* Basically a model to be {@link IProductPriceAware}
* <ul>
* <li>it has to implement that interface and in this case it will be returned right away.
* <li>or it needs to have the {@link IProductPriceAware#COLUMNNAME_M_ProductPrice_ID} column.
* </ul>
*
* @return {@link IProductPriceAware}.
*/
public static Optional<IProductPriceAware> ofModel(final Object model)
{
if (model == null)
{
return Optional.empty();
}
if (model instanceof IProductPriceAware)
{
final IProductPriceAware productPriceAware = (IProductPriceAware)model;
return Optional.of(productPriceAware);
}
// If model does not have product price column we consider that it's not product price aware
if (!InterfaceWrapperHelper.hasModelColumnName(model, COLUMNNAME_M_ProductPrice_ID))
{
return Optional.empty();
}
final Integer productPriceId = InterfaceWrapperHelper.getValueOrNull(model, COLUMNNAME_M_ProductPrice_ID);
final boolean productPriceIdSet = productPriceId != null && productPriceId > 0;
final boolean isExplicitProductPrice;
if (InterfaceWrapperHelper.hasModelColumnName(model, COLUMNNAME_IsExplicitProductPriceAttribute))
{
final Object isExplicitObj = InterfaceWrapperHelper.getValueOrNull(model, COLUMNNAME_IsExplicitProductPriceAttribute);
isExplicitProductPrice = DisplayType.toBooleanNonNull(isExplicitObj, false);
}
else
{
// In case the "IsExplicit" column is missing, | // we are considering it as Explicit if the actual M_ProductPrice_ID is set.
isExplicitProductPrice = productPriceIdSet;
}
final IProductPriceAware productPriceAware = new ProductPriceAware(
isExplicitProductPrice,
productPriceIdSet ? productPriceId : -1);
return Optional.of(productPriceAware);
}
private final boolean isExplicitProductPrice;
private final int productPriceId;
private ProductPriceAware(final boolean isExplicitProductPrice, final int productPriceId)
{
this.isExplicitProductPrice = isExplicitProductPrice;
this.productPriceId = productPriceId;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("productPriceId", productPriceId)
.add("isExplicit", isExplicitProductPrice)
.toString();
}
@Override
public boolean isExplicitProductPriceAttribute()
{
return isExplicitProductPrice;
}
@Override
public int getM_ProductPrice_ID()
{
return productPriceId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\attributebased\ProductPriceAware.java | 1 |
请完成以下Java代码 | private Step childJobTwoStep() {
return new JobStepBuilder(new StepBuilder("childJobTwoStep"))
.job(childJobTwo())
.launcher(jobLauncher)
.repository(jobRepository)
.transactionManager(platformTransactionManager)
.build();
}
// 子任务一
private Job childJobOne() {
return jobBuilderFactory.get("childJobOne")
.start(
stepBuilderFactory.get("childJobOneStep")
.tasklet((stepContribution, chunkContext) -> {
System.out.println("子任务一执行步骤。。。");
return RepeatStatus.FINISHED; | }).build()
).build();
}
// 子任务二
private Job childJobTwo() {
return jobBuilderFactory.get("childJobTwo")
.start(
stepBuilderFactory.get("childJobTwoStep")
.tasklet((stepContribution, chunkContext) -> {
System.out.println("子任务二执行步骤。。。");
return RepeatStatus.FINISHED;
}).build()
).build();
}
} | repos\SpringAll-master\67.spring-batch-start\src\main\java\cc\mrbird\batch\job\NestedJobDemo.java | 1 |
请完成以下Java代码 | public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password; | }
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
} | repos\SpringAll-master\08.Spring-Boot-Thymeleaf\src\main\java\com\springboot\bean\Account.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Price getPrice(Long productId){
LOGGER.info("Getting Price from Price Repo With Product Id {}", productId);
if(!priceMap.containsKey(productId)){
LOGGER.error("Price Not Found for Product Id {}", productId);
throw new PriceNotFoundException("Product Not Found");
}
return priceMap.get(productId);
}
@PostConstruct
private void setupRepo(){
Price price1 = getPrice(100001L, 12.5, 2.5);
priceMap.put(100001L, price1);
Price price2 = getPrice(100002L, 10.5, 2.1); | priceMap.put(100002L, price2);
Price price3 = getPrice(100003L, 18.5, 2.0);
priceMap.put(100003L, price3);
Price price4 = getPrice(100004L, 18.5, 2.0);
priceMap.put(100004L, price4);
}
private static Price getPrice(long productId, double priceAmount, double discount) {
Price price = new Price();
price.setProductId(productId);
price.setPriceAmount(priceAmount);
price.setDiscount(discount);
return price;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-open-telemetry\spring-boot-open-telemetry2\src\main\java\com\baeldung\opentelemetry\repository\PriceRepository.java | 2 |
请完成以下Java代码 | public List<CleanableHistoricBatchReportResult> executeList(CommandContext commandContext, Page page) {
provideHistoryCleanupStrategy(commandContext);
checkQueryOk();
checkPermissions(commandContext);
Map<String, Integer> batchOperationsForHistoryCleanup = commandContext.getProcessEngineConfiguration().getParsedBatchOperationsForHistoryCleanup();
if (isHistoryCleanupStrategyRemovalTimeBased()) {
addBatchOperationsWithoutTTL(batchOperationsForHistoryCleanup);
}
return commandContext.getHistoricBatchManager().findCleanableHistoricBatchesReportByCriteria(this, page, batchOperationsForHistoryCleanup);
}
protected void addBatchOperationsWithoutTTL(Map<String, Integer> batchOperations) {
Map<String, BatchJobHandler<?>> batchJobHandlers = Context.getProcessEngineConfiguration().getBatchHandlers();
Set<String> batchOperationKeys = null;
if (batchJobHandlers != null) {
batchOperationKeys = batchJobHandlers.keySet();
}
if (batchOperationKeys != null) {
for (String batchOperation : batchOperationKeys) {
Integer ttl = batchOperations.get(batchOperation);
batchOperations.put(batchOperation, ttl);
}
} | }
public Date getCurrentTimestamp() {
return currentTimestamp;
}
public void setCurrentTimestamp(Date currentTimestamp) {
this.currentTimestamp = currentTimestamp;
}
private void checkPermissions(CommandContext commandContext) {
for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkReadHistoricBatch();
}
}
protected void provideHistoryCleanupStrategy(CommandContext commandContext) {
String historyCleanupStrategy = commandContext.getProcessEngineConfiguration()
.getHistoryCleanupStrategy();
isHistoryCleanupStrategyRemovalTimeBased = HISTORY_CLEANUP_STRATEGY_REMOVAL_TIME_BASED.equals(historyCleanupStrategy);
}
public boolean isHistoryCleanupStrategyRemovalTimeBased() {
return isHistoryCleanupStrategyRemovalTimeBased;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\CleanableHistoricBatchReportImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ResponseBo login(String username, String password) {
password = MD5Utils.encrypt(username, password);
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token);
return ResponseBo.ok();
} catch (UnknownAccountException e) {
return ResponseBo.error(e.getMessage());
} catch (IncorrectCredentialsException e) {
return ResponseBo.error(e.getMessage());
} catch (LockedAccountException e) {
return ResponseBo.error(e.getMessage());
} catch (AuthenticationException e) {
return ResponseBo.error("认证失败!"); | }
}
@RequestMapping("/")
public String redirectIndex() {
return "redirect:/index";
}
@RequestMapping("/index")
public String index(Model model) {
User user = (User) SecurityUtils.getSubject().getPrincipal();
model.addAttribute("user", user);
return "index";
}
} | repos\SpringAll-master\11.Spring-Boot-Shiro-Authentication\src\main\java\com\springboot\controller\LoginController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class C_Request_CreateFromDDOrder_Async extends WorkpackageProcessorAdapter
{
@Override
public Result processWorkPackage(final I_C_Queue_WorkPackage workPackage, final String localTrxName)
{// Services
final IQueueDAO queueDAO = Services.get(IQueueDAO.class);
final IRequestBL requestBL = Services.get(IRequestBL.class);
// retrieve the items (DDOrder lines) that were enqueued and put them in a list
final List<I_DD_OrderLine> lines = queueDAO.retrieveAllItems(workPackage, I_DD_OrderLine.class);
// for each line that was enqueued, create a R_Request containing the information from the DDOrder line and DDOrder
for (final I_DD_OrderLine line : lines)
{
requestBL.createRequestFromDDOrderLine(line);
}
return Result.SUCCESS;
}
public static void createWorkpackage(final List<DDOrderLineId> ddOrderLineIds)
{
SCHEDULER.scheduleAll(ddOrderLineIds);
}
private static final WorkpackagesOnCommitSchedulerTemplate<DDOrderLineId> SCHEDULER = new WorkpackagesOnCommitSchedulerTemplate<DDOrderLineId>(C_Request_CreateFromDDOrder_Async.class)
{
@Override
protected boolean isEligibleForScheduling(final DDOrderLineId ddOrderLineId)
{
return ddOrderLineId != null;
}
@Override
protected Properties extractCtxFromItem(final DDOrderLineId ddOrderLineId) | {
return Env.getCtx();
}
@Override
protected String extractTrxNameFromItem(final DDOrderLineId ddOrderLineId)
{
return ITrx.TRXNAME_ThreadInherited;
}
@Override
protected TableRecordReference extractModelToEnqueueFromItem(final Collector collector, final DDOrderLineId ddOrderLineId)
{
return TableRecordReference.of(I_DD_OrderLine.Table_Name, ddOrderLineId);
}
};
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\request\service\async\spi\impl\C_Request_CreateFromDDOrder_Async.java | 2 |
请完成以下Java代码 | public class Tree {
private final int value;
private final Tree left;
private final Tree right;
public Tree(int value, Tree left, Tree right) {
this.value = value;
this.left = left;
this.right = right;
}
public int value() {
return value;
}
public Tree left() { | return left;
}
public Tree right() {
return right;
}
@Override
public String toString() {
return String.format("[%s, %s, %s]",
value,
left == null ? "null" : left.toString(),
right == null ? "null" : right.toString()
);
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-5\src\main\java\com\baeldung\algorithms\balancedbinarytree\Tree.java | 1 |
请完成以下Java代码 | public ModelQuery createModelQuery() {
return new ModelQueryImpl(commandExecutor);
}
@Override
public NativeModelQuery createNativeModelQuery() {
return new NativeModelQueryImpl(commandExecutor);
}
public Model getModel(String modelId) {
return commandExecutor.execute(new GetModelCmd(modelId));
}
public byte[] getModelEditorSource(String modelId) {
return commandExecutor.execute(new GetModelEditorSourceCmd(modelId));
}
public byte[] getModelEditorSourceExtra(String modelId) {
return commandExecutor.execute(new GetModelEditorSourceExtraCmd(modelId));
}
public void addCandidateStarterUser(String processDefinitionId, String userId) {
commandExecutor.execute(new AddIdentityLinkForProcessDefinitionCmd(processDefinitionId, userId, null));
} | public void addCandidateStarterGroup(String processDefinitionId, String groupId) {
commandExecutor.execute(new AddIdentityLinkForProcessDefinitionCmd(processDefinitionId, null, groupId));
}
public void deleteCandidateStarterGroup(String processDefinitionId, String groupId) {
commandExecutor.execute(new DeleteIdentityLinkForProcessDefinitionCmd(processDefinitionId, null, groupId));
}
public void deleteCandidateStarterUser(String processDefinitionId, String userId) {
commandExecutor.execute(new DeleteIdentityLinkForProcessDefinitionCmd(processDefinitionId, userId, null));
}
public List<IdentityLink> getIdentityLinksForProcessDefinition(String processDefinitionId) {
return commandExecutor.execute(new GetIdentityLinksForProcessDefinitionCmd(processDefinitionId));
}
public List<ValidationError> validateProcess(BpmnModel bpmnModel) {
return commandExecutor.execute(new ValidateBpmnModelCmd(bpmnModel));
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\RepositoryServiceImpl.java | 1 |
请完成以下Java代码 | public synchronized T compute(@NonNull final UnaryOperator<T> remappingFunction)
{
this.value = remappingFunction.apply(this.value);
return this.value;
}
@SuppressWarnings("unused")
public synchronized OldAndNewValues<T> computeReturningOldAndNew(@NonNull final UnaryOperator<T> remappingFunction)
{
final T oldValue = this.value;
final T newValue = this.value = remappingFunction.apply(oldValue);
return OldAndNewValues.<T>builder()
.oldValue(oldValue)
.newValue(newValue)
.build();
}
@Override
public synchronized T computeIfNull(@NonNull final Supplier<T> supplier)
{
if (value == null)
{
this.value = supplier.get();
}
return this.value;
}
@Nullable
public synchronized T computeIfNotNull(@NonNull final UnaryOperator<T> remappingFunction)
{
if (value != null)
{
this.value = remappingFunction.apply(this.value);
} | return this.value;
}
public synchronized OldAndNewValues<T> computeIfNotNullReturningOldAndNew(@NonNull final UnaryOperator<T> remappingFunction)
{
if (value != null)
{
final T oldValue = this.value;
this.value = remappingFunction.apply(oldValue);
return OldAndNewValues.<T>builder()
.oldValue(oldValue)
.newValue(this.value)
.build();
}
else
{
return OldAndNewValues.nullValues();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\lang\SynchronizedMutable.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setLOCATIONCODE(String value) {
this.locationcode = value;
}
/**
* Gets the value of the locationname property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLOCATIONNAME() {
return locationname;
}
/**
* Sets the value of the locationname property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLOCATIONNAME(String value) {
this.locationname = value;
}
/**
* Gets the value of the hfini1 property.
*
* @return
* possible object is
* {@link HFINI1 }
*
*/
public HFINI1 getHFINI1() {
return hfini1;
}
/**
* Sets the value of the hfini1 property.
*
* @param value
* allowed object is
* {@link HFINI1 }
*
*/
public void setHFINI1(HFINI1 value) {
this.hfini1 = value;
}
/** | * Gets the value of the hrfad1 property.
*
* @return
* possible object is
* {@link HRFAD1 }
*
*/
public HRFAD1 getHRFAD1() {
return hrfad1;
}
/**
* Sets the value of the hrfad1 property.
*
* @param value
* allowed object is
* {@link HRFAD1 }
*
*/
public void setHRFAD1(HRFAD1 value) {
this.hrfad1 = value;
}
/**
* Gets the value of the hctad1 property.
*
* @return
* possible object is
* {@link HCTAD1 }
*
*/
public HCTAD1 getHCTAD1() {
return hctad1;
}
/**
* Sets the value of the hctad1 property.
*
* @param value
* allowed object is
* {@link HCTAD1 }
*
*/
public void setHCTAD1(HCTAD1 value) {
this.hctad1 = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\HADRE1.java | 2 |
请完成以下Java代码 | public boolean existsByTenantIdAndTargetId(TenantId tenantId, NotificationTargetId targetId) {
return notificationRuleRepository.existsByTenantIdAndRecipientsConfigContaining(tenantId.getId(), targetId.getId().toString());
}
@Override
public List<NotificationRule> findByTenantIdAndTriggerTypeAndEnabled(TenantId tenantId, NotificationRuleTriggerType triggerType, boolean enabled) {
return DaoUtil.convertDataList(notificationRuleRepository.findAllByTenantIdAndTriggerTypeAndEnabled(tenantId.getId(), triggerType, enabled));
}
@Override
public NotificationRuleInfo findInfoById(TenantId tenantId, NotificationRuleId id) {
NotificationRuleInfoEntity infoEntity = notificationRuleRepository.findInfoById(id.getId());
return infoEntity != null ? infoEntity.toData() : null;
}
@Override
public void removeByTenantId(TenantId tenantId) {
notificationRuleRepository.deleteByTenantId(tenantId.getId());
}
@Override
public NotificationRule findByTenantIdAndExternalId(UUID tenantId, UUID externalId) {
return DaoUtil.getData(notificationRuleRepository.findByTenantIdAndExternalId(tenantId, externalId));
}
@Override
public NotificationRule findByTenantIdAndName(UUID tenantId, String name) {
return DaoUtil.getData(notificationRuleRepository.findByTenantIdAndName(tenantId, name));
}
@Override
public PageData<NotificationRule> findByTenantId(UUID tenantId, PageLink pageLink) { | return DaoUtil.toPageData(notificationRuleRepository.findByTenantId(tenantId, DaoUtil.toPageable(pageLink)));
}
@Override
public NotificationRuleId getExternalIdByInternal(NotificationRuleId internalId) {
return DaoUtil.toEntityId(notificationRuleRepository.getExternalIdByInternal(internalId.getId()), NotificationRuleId::new);
}
@Override
public PageData<NotificationRule> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findByTenantId(tenantId.getId(), pageLink);
}
@Override
protected Class<NotificationRuleEntity> getEntityClass() {
return NotificationRuleEntity.class;
}
@Override
protected JpaRepository<NotificationRuleEntity, UUID> getRepository() {
return notificationRuleRepository;
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION_RULE;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\notification\JpaNotificationRuleDao.java | 1 |
请完成以下Java代码 | public class HibernateUtil {
private static SessionFactory sessionFactory;
private static String PROPERTY_FILE_NAME;
public static SessionFactory getSessionFactory() throws IOException {
return getSessionFactory(null);
}
public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
PROPERTY_FILE_NAME = propertyFileName;
if (sessionFactory == null) {
ServiceRegistry serviceRegistry = configureServiceRegistry();
sessionFactory = getSessionFactoryBuilder(serviceRegistry).build();
}
return sessionFactory;
}
public static SessionFactory getSessionFactoryWithInterceptor(String propertyFileName, Interceptor interceptor) throws IOException {
PROPERTY_FILE_NAME = propertyFileName;
if (sessionFactory == null) {
ServiceRegistry serviceRegistry = configureServiceRegistry();
sessionFactory = getSessionFactoryBuilder(serviceRegistry).applyInterceptor(interceptor)
.build();
}
return sessionFactory;
}
public static Session getSessionWithInterceptor(Interceptor interceptor) throws IOException {
return getSessionFactory().withOptions()
.interceptor(interceptor)
.openSession();
}
private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) { | MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addPackage("com.baeldung.hibernate.interceptors");
metadataSources.addAnnotatedClass(User.class);
Metadata metadata = metadataSources.buildMetadata();
return metadata.getSessionFactoryBuilder();
}
private static ServiceRegistry configureServiceRegistry() throws IOException {
Properties properties = getProperties();
return new StandardServiceRegistryBuilder().applySettings(properties)
.build();
}
private static Properties getProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate-interceptors.properties"));
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
} | repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\interceptors\HibernateUtil.java | 1 |
请完成以下Java代码 | public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} | public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
} | repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\SpringSecurity\src\main\java\spring\security\entities\User.java | 1 |
请完成以下Java代码 | public Void execute(CommandContext commandContext) {
ensureNotNull("userId", userId);
IdentityInfoEntity pictureInfo = commandContext.getIdentityInfoManager()
.findUserInfoByUserIdAndKey(userId, "picture");
if (pictureInfo != null) {
String byteArrayId = pictureInfo.getValue();
if (byteArrayId != null) {
commandContext.getByteArrayManager()
.deleteByteArrayById(byteArrayId);
}
} else {
pictureInfo = new IdentityInfoEntity(); | pictureInfo.setUserId(userId);
pictureInfo.setKey("picture");
commandContext.getDbEntityManager().insert(pictureInfo);
}
ByteArrayEntity byteArrayEntity = new ByteArrayEntity(picture.getMimeType(), picture.getBytes(), ResourceTypes.REPOSITORY);
commandContext.getByteArrayManager()
.insertByteArray(byteArrayEntity);
pictureInfo.setValue(byteArrayEntity.getId());
return null;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SetUserPictureCmd.java | 1 |
请完成以下Java代码 | public String toString()
{
return "ModelClassInfo ["
+ "modelClass=" + modelClass
+ ", tableName=" + tableName
+ "]";
}
@Override
public Class<?> getModelClass()
{
return modelClass;
}
@Override
public String getTableName()
{
return tableName;
}
@Override
public final IModelMethodInfo getMethodInfo(final Method method)
{
modelMethodInfosLock.lock();
try
{
final Map<Method, IModelMethodInfo> methodInfos = getMethodInfos0();
IModelMethodInfo methodInfo = methodInfos.get(method);
//
// If methodInfo was not found, try to create it now
if (methodInfo == null)
{
methodInfo = introspector.createModelMethodInfo(method);
if (methodInfo == null)
{
throw new IllegalStateException("No method info was found for " + method + " in " + this);
}
methodInfos.put(method, methodInfo);
}
return methodInfo;
}
finally
{
modelMethodInfosLock.unlock();
}
}
/**
* Gets the inner map of {@link Method} to {@link IModelMethodInfo}.
*
* NOTE: this method is not thread safe
*
* @return | */
private final Map<Method, IModelMethodInfo> getMethodInfos0()
{
if (_modelMethodInfos == null)
{
_modelMethodInfos = introspector.createModelMethodInfos(getModelClass());
}
return _modelMethodInfos;
}
@Override
public synchronized final Set<String> getDefinedColumnNames()
{
if (_definedColumnNames == null)
{
_definedColumnNames = findDefinedColumnNames();
}
return _definedColumnNames;
}
@SuppressWarnings("unchecked")
private final Set<String> findDefinedColumnNames()
{
//
// Collect all columnnames
final ImmutableSet.Builder<String> columnNamesBuilder = ImmutableSet.builder();
ReflectionUtils.getAllFields(modelClass, new Predicate<Field>()
{
@Override
public boolean apply(final Field field)
{
final String fieldName = field.getName();
if (fieldName.startsWith("COLUMNNAME_"))
{
final String columnName = fieldName.substring("COLUMNNAME_".length());
columnNamesBuilder.add(columnName);
}
return false;
}
});
return columnNamesBuilder.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\ModelClassInfo.java | 1 |
请完成以下Java代码 | public boolean isContractedProduct()
{
final I_C_Flatrate_DataEntry flatrateDataEntry = getC_Flatrate_DataEntry();
if (flatrateDataEntry == null)
{
return false;
}
// Consider that we have a contracted product only if the data entry has the Price or the QtyPlanned set (FRESH-568)
return Services.get(IPMMContractsBL.class).hasPriceOrQty(flatrateDataEntry);
}
@Override
public I_M_Product getM_Product()
{
return candidate.getM_Product();
}
@Override
public int getProductId()
{
return candidate.getM_Product_ID();
}
@Override
public I_C_UOM getC_UOM()
{
return candidate.getC_UOM();
}
@Override
public I_C_Flatrate_Term getC_Flatrate_Term()
{
final I_C_Flatrate_DataEntry flatrateDataEntry = getC_Flatrate_DataEntry();
if(flatrateDataEntry == null)
{
return null;
}
return flatrateDataEntry.getC_Flatrate_Term();
}
@Override
public I_C_Flatrate_DataEntry getC_Flatrate_DataEntry()
{
return InterfaceWrapperHelper.create(candidate.getC_Flatrate_DataEntry(), I_C_Flatrate_DataEntry.class);
}
@Override
public Object getWrappedModel() | {
return candidate;
}
@Override
public Timestamp getDate()
{
return candidate.getDatePromised();
}
@Override
public BigDecimal getQty()
{
// TODO: shall we use QtyToOrder instead... but that could affect our price (if we have some prices defined on breaks)
return candidate.getQtyPromised();
}
@Override
public void setM_PricingSystem_ID(int M_PricingSystem_ID)
{
candidate.setM_PricingSystem_ID(M_PricingSystem_ID);
}
@Override
public void setM_PriceList_ID(int M_PriceList_ID)
{
candidate.setM_PriceList_ID(M_PriceList_ID);
}
@Override
public void setCurrencyId(final CurrencyId currencyId)
{
candidate.setC_Currency_ID(CurrencyId.toRepoId(currencyId));
}
@Override
public void setPrice(BigDecimal priceStd)
{
candidate.setPrice(priceStd);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\PMMPricingAware_PurchaseCandidate.java | 1 |
请完成以下Java代码 | public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
@Override
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
@Override
public String getJobType() {
return jobType;
}
public void setJobType(String jobType) {
this.jobType = jobType;
}
@Override
public String getElementId() {
return elementId;
}
public void setElementId(String elementId) {
this.elementId = elementId;
}
@Override
public String getElementName() {
return elementName;
}
public void setElementName(String elementName) {
this.elementName = elementName;
}
@Override
public String getScopeId() {
return scopeId;
}
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
@Override
public String getSubScopeId() {
return subScopeId;
}
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
@Override
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
@Override
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
} | @Override
public String getJobHandlerType() {
return jobHandlerType;
}
public void setJobHandlerType(String jobHandlerType) {
this.jobHandlerType = jobHandlerType;
}
@Override
public String getJobHandlerConfiguration() {
return jobHandlerConfiguration;
}
public void setJobHandlerConfiguration(String jobHandlerConfiguration) {
this.jobHandlerConfiguration = jobHandlerConfiguration;
}
public String getRepeat() {
return repeat;
}
public void setRepeat(String repeat) {
this.repeat = repeat;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
@Override
public String getExceptionMessage() {
return exceptionMessage;
}
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = StringUtils.abbreviate(exceptionMessage, MAX_EXCEPTION_MESSAGE_LENGTH);
}
@Override
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String getCorrelationId() {
// v5 Jobs have no correlationId
return null;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AbstractJobEntity.java | 1 |
请完成以下Java代码 | protected void updateBulk(DbBulkOperation operation) {
String statement = operation.getStatement();
Object parameter = operation.getParameter();
LOG.executeDatabaseBulkOperation("UPDATE", statement, parameter);
executeUpdate(statement, parameter);
}
@Override
protected void deleteBulk(DbBulkOperation operation) {
String statement = operation.getStatement();
Object parameter = operation.getParameter();
LOG.executeDatabaseBulkOperation("DELETE", statement, parameter);
executeDelete(statement, parameter);
}
@Override
protected void deleteEntity(DbEntityOperation operation) {
final DbEntity dbEntity = operation.getEntity(); | // get statement
String deleteStatement = dbSqlSessionFactory.getDeleteStatement(dbEntity.getClass());
ensureNotNull("no delete statement for " + dbEntity.getClass() + " in the ibatis mapping files", "deleteStatement", deleteStatement);
LOG.executeDatabaseOperation("DELETE", dbEntity);
// execute the delete
executeDelete(deleteStatement, dbEntity);
}
@Override
protected void executeSelectForUpdate(String statement, Object parameter) {
executeSelectList(statement, parameter);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\sql\BatchDbSqlSession.java | 1 |
请完成以下Java代码 | public @Nullable BankAccountId getBPartnerBankAccountId()
{
return bpBankAccountId;
}
public Builder setBPartnerBankAccountId(final @Nullable BankAccountId bpBankAccountId)
{
this.bpBankAccountId = bpBankAccountId;
return this;
}
public BigDecimal getOpenAmt()
{
return CoalesceUtil.coalesceNotNull(_openAmt, BigDecimal.ZERO);
}
public Builder setOpenAmt(final BigDecimal openAmt)
{
this._openAmt = openAmt;
return this;
}
public BigDecimal getPayAmt()
{
final BigDecimal openAmt = getOpenAmt();
final BigDecimal discountAmt = getDiscountAmt();
return openAmt.subtract(discountAmt);
} | public BigDecimal getDiscountAmt()
{
return CoalesceUtil.coalesceNotNull(_discountAmt, BigDecimal.ZERO);
}
public Builder setDiscountAmt(final BigDecimal discountAmt)
{
this._discountAmt = discountAmt;
return this;
}
public BigDecimal getDifferenceAmt()
{
final BigDecimal openAmt = getOpenAmt();
final BigDecimal payAmt = getPayAmt();
final BigDecimal discountAmt = getDiscountAmt();
return openAmt.subtract(payAmt).subtract(discountAmt);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\impl\PaySelectionLineCandidate.java | 1 |
请完成以下Java代码 | private void addQuantitiesRowsToResult(
@NonNull final DimensionSpec dimensionSpec,
@NonNull final Map<MainRowBucketId, MainRowWithSubRows> result)
{
for (final ProductWithDemandSupply qtyRecord : request.getQuantitiesRecords())
{
final MainRowBucketId mainRowBucketId = MainRowBucketId.createInstanceForQuantitiesRecord(qtyRecord, request.getDate());
final MainRowWithSubRows mainRowBucket = result.computeIfAbsent(mainRowBucketId, this::newMainRowWithSubRows);
mainRowBucket.addQuantitiesRecord(qtyRecord, dimensionSpec, request.getDetailsRowAggregation());
}
}
private MainRowWithSubRows newMainRowWithSubRows(@NonNull final MainRowBucketId mainRowBucketId)
{
final Money maxPurchasePrice = purchaseLastMaxPriceProvider.getPrice(
PurchaseLastMaxPriceRequest.builder()
.productId(mainRowBucketId.getProductId())
.evalDate(mainRowBucketId.getDate())
.build())
.getMaxPurchasePrice();
final MFColor procurementStatusColor = getProcurementStatusColor(mainRowBucketId.getProductId()).orElse(null);
return MainRowWithSubRows.builder()
.cache(cache) | .rowLookups(rowLookups)
.productIdAndDate(mainRowBucketId)
.procurementStatusColor(procurementStatusColor)
.maxPurchasePrice(maxPurchasePrice)
.build();
}
private Optional<MFColor> getProcurementStatusColor(@NonNull final ProductId productId)
{
return adReferenceService.getRefListById(PROCUREMENTSTATUS_Reference_ID)
.getItemByValue(cache.getProductById(productId).getProcurementStatus())
.map(ADRefListItem::getColorId)
.map(colorRepository::getColorById);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\rowfactory\MaterialCockpitRowFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected String getBeanClassName(Element element) {
return "org.springframework.amqp.rabbit.core.RabbitAdmin";
}
@Override
protected boolean shouldGenerateId() {
return false;
}
@Override
protected boolean shouldGenerateIdAsFallback() {
return true;
}
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
String connectionFactoryRef = element.getAttribute(CONNECTION_FACTORY_ATTRIBUTE);
// At least one of 'templateRef' or 'connectionFactoryRef' attribute must be set.
if (!StringUtils.hasText(connectionFactoryRef)) {
parserContext.getReaderContext().error("A '" + CONNECTION_FACTORY_ATTRIBUTE + "' attribute must be set.",
element); | }
if (StringUtils.hasText(connectionFactoryRef)) {
// Use constructor with connectionFactory parameter
builder.addConstructorArgReference(connectionFactoryRef);
}
String attributeValue;
attributeValue = element.getAttribute(AUTO_STARTUP_ATTRIBUTE);
if (StringUtils.hasText(attributeValue)) {
builder.addPropertyValue("autoStartup", attributeValue);
}
NamespaceUtils.setValueIfAttributeDefined(builder, element, IGNORE_DECLARATION_EXCEPTIONS);
NamespaceUtils.setValueIfAttributeDefined(builder, element, "explicit-declarations-only");
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\config\AdminParser.java | 2 |
请完成以下Java代码 | public static String jsonComposer() throws IOException {
return JSON.std.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
.composeString()
.startObject()
.startArrayField("objectArray")
.startObject()
.put("name", "name1")
.put("age", 11)
.end()
.startObject()
.put("name", "name2")
.put("age", 12)
.end()
.end()
.startArrayField("array")
.add(1)
.add(2)
.add(3)
.end()
.startObjectField("object")
.put("name", "name3")
.put("age", 13)
.end()
.put("last", true)
.end()
.finish();
}
public static String objectSerialization(Person person) throws IOException {
return JSON.std.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
.asString(person);
}
public static String objectAnnotationSerialization(Person person) throws IOException {
return JSON.builder()
.register(JacksonAnnotationExtension.std)
.build()
.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
.asString(person);
}
public static String customObjectSerialization(Person person) throws IOException {
return JSON.builder()
.register(new JacksonJrExtension() {
@Override
protected void register(ExtensionContext extensionContext) { | extensionContext.insertProvider(new MyHandlerProvider());
}
})
.build()
.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
.asString(person);
}
public static Person objectDeserialization(String json) throws IOException {
return JSON.std.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
.beanFrom(Person.class, json);
}
public static Person customObjectDeserialization(String json) throws IOException {
return JSON.builder()
.register(new JacksonJrExtension() {
@Override
protected void register(ExtensionContext extensionContext) {
extensionContext.insertProvider(new MyHandlerProvider());
}
})
.build()
.with(JSON.Feature.PRETTY_PRINT_OUTPUT)
.beanFrom(Person.class, json);
}
} | repos\tutorials-master\jackson-modules\jackson-jr\src\main\java\com\baeldung\jacksonjr\JacksonJrFeatures.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable Set<String> getCiphers() {
return this.ciphers;
}
public void setCiphers(@Nullable Set<String> ciphers) {
this.ciphers = ciphers;
}
public @Nullable Set<String> getEnabledProtocols() {
return this.enabledProtocols;
}
public void setEnabledProtocols(@Nullable Set<String> enabledProtocols) {
this.enabledProtocols = enabledProtocols;
}
}
public static class Key {
/**
* The password used to access the key in the key store.
*/
private @Nullable String password; | /**
* The alias that identifies the key in the key store.
*/
private @Nullable String alias;
public @Nullable String getPassword() {
return this.password;
}
public void setPassword(@Nullable String password) {
this.password = password;
}
public @Nullable String getAlias() {
return this.alias;
}
public void setAlias(@Nullable String alias) {
this.alias = alias;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\ssl\SslBundleProperties.java | 2 |
请完成以下Java代码 | public Long getSuccessQps() {
return successQps;
}
public void setSuccessQps(Long successQps) {
this.successQps = successQps;
}
public Long getExceptionQps() {
return exceptionQps;
}
public void setExceptionQps(Long exceptionQps) {
this.exceptionQps = exceptionQps;
}
public Double getRt() {
return rt;
}
public void setRt(Double rt) { | this.rt = rt;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
@Override
public int compareTo(MetricVo o) {
return Long.compare(this.timestamp, o.timestamp);
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\vo\MetricVo.java | 1 |
请完成以下Java代码 | private EntityManager getEntityManager() {
return emf.createEntityManager();
}
public UserEntity getUserByIdWithPlainQuery(Long id) {
Query jpqlQuery = getEntityManager().createQuery("SELECT u FROM UserEntity u WHERE u.id=:id");
jpqlQuery.setParameter("id", id);
return (UserEntity) jpqlQuery.getSingleResult();
}
public UserEntity getUserByIdWithTypedQuery(Long id) {
TypedQuery<UserEntity> typedQuery = getEntityManager().createQuery("SELECT u FROM UserEntity u WHERE u.id=:id", UserEntity.class);
typedQuery.setParameter("id", id);
return typedQuery.getSingleResult();
}
public UserEntity getUserByIdWithNamedQuery(Long id) {
Query namedQuery = getEntityManager().createNamedQuery("UserEntity.findByUserId");
namedQuery.setParameter("userId", id);
return (UserEntity) namedQuery.getSingleResult();
}
public UserEntity getUserByIdWithNativeQuery(Long id) {
Query nativeQuery = getEntityManager().createNativeQuery("SELECT * FROM users WHERE id=:userId", UserEntity.class); | nativeQuery.setParameter("userId", id);
return (UserEntity) nativeQuery.getSingleResult();
}
public UserEntity getUserByIdWithCriteriaQuery(Long id) {
CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<UserEntity> criteriaQuery = criteriaBuilder.createQuery(UserEntity.class);
Root<UserEntity> userRoot = criteriaQuery.from(UserEntity.class);
UserEntity queryResult = getEntityManager().createQuery(criteriaQuery.select(userRoot)
.where(criteriaBuilder.equal(userRoot.get("id"), id)))
.getSingleResult();
return queryResult;
}
} | repos\tutorials-master\persistence-modules\java-jpa-2\src\main\java\com\baeldung\jpa\querytypes\QueryTypesExamples.java | 1 |
请完成以下Spring Boot application配置 | spring:
security:
oauth2:
client:
registration:
github-client-1:
client-id: ${APP-CLIENT-ID}
client-secret: ${APP-CLIENT-SECRET}
client-name: Github user
provider: github
scope: user
redirect-uri: http://localhost:8080/login/oauth2/code/github
github-client-2:
client-id: ${APP-CLIENT-ID}
client-secret: ${APP-CLIENT-SECRET}
client-name: Github email
provider: github
scope: user:email
redirect-uri: http://localhost:8080/login/oauth2/code/github
yahoo-oidc:
client-id: ${YAHOO-CLIENT-ID}
client-secret: ${YAHOO-CLIENT-SECRET}
github-repos:
| client-id: ${APP-CLIENT-ID}
client-secret: ${APP-CLIENT-SECRET}
scope: public_repo
redirect-uri: "{baseUrl}/github-repos"
provider: github
client-name: GitHub Repositories
provider:
yahoo-oidc:
issuer-uri: https://api.login.yahoo.com | repos\spring-boot-4.0.1\smoke-test\spring-boot-smoke-test-oauth2-client\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
@Override
public String toString() {
return "ByteArrayEntity[id=" + id + ", name=" + name + ", size=" + (bytes != null ? bytes.length : 0) + "]";
}
// Wrapper for a byte array, needed to do byte array comparisons
// See https://activiti.atlassian.net/browse/ACT-1524
private static class PersistentState {
private final String name;
private final byte[] bytes;
public PersistentState(String name, byte[] bytes) { | this.name = name;
this.bytes = bytes;
}
public boolean equals(Object obj) {
if (obj instanceof PersistentState) {
PersistentState other = (PersistentState) obj;
return StringUtils.equals(this.name, other.name) && Arrays.equals(this.bytes, other.bytes);
}
return false;
}
@Override
public int hashCode() {
throw new UnsupportedOperationException();
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ByteArrayEntityImpl.java | 1 |
请完成以下Java代码 | public void setDocBaseType (java.lang.String DocBaseType)
{
set_Value (COLUMNNAME_DocBaseType, DocBaseType);
}
/** Get Document BaseType.
@return Logical type of document
*/
@Override
public java.lang.String getDocBaseType ()
{
return (java.lang.String)get_Value(COLUMNNAME_DocBaseType);
}
@Override
public org.compiere.model.I_R_RequestType getR_RequestType() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class);
}
@Override
public void setR_RequestType(org.compiere.model.I_R_RequestType R_RequestType)
{
set_ValueFromPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class, R_RequestType);
}
/** Set Anfrageart.
@param R_RequestType_ID
Type of request (e.g. Inquiry, Complaint, ..) | */
@Override
public void setR_RequestType_ID (int R_RequestType_ID)
{
if (R_RequestType_ID < 1)
set_Value (COLUMNNAME_R_RequestType_ID, null);
else
set_Value (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID));
}
/** Get Anfrageart.
@return Type of request (e.g. Inquiry, Complaint, ..)
*/
@Override
public int getR_RequestType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserBPAccess.java | 1 |
请完成以下Java代码 | public class ShipmentService {
private static final ShipmentDAO shipmentDAO = new ShipmentDAO("jdbc:sqlite:food_delivery.db");
public static int createShipment(ShippingRequest shippingRequest) {
String orderId = shippingRequest.getOrderId();
Shipment shipment = new Shipment();
shipment.setOrderId(orderId);
shipment.setDeliveryAddress(shippingRequest.getDeliveryAddress());
shipment.setDeliveryInstructions(shippingRequest.getDeliveryInstructions());
int driverId = findDriver();
shipment.setDriverId(driverId);
if (!shipmentDAO.insertShipment(shipment)) {
log.error("Shipment creation for order {} failed.", orderId);
return 0;
}
Driver driver = new Driver();
driver.setName("");
shipmentDAO.readDriver(driverId, driver);
if (driver.getName().isBlank()) {
log.error("Shipment creation for order {} failed as driver in the area is not available.", orderId);
shipmentDAO.cancelShipment(orderId);
return 0;
}
else {
log.info("Assigned driver {} to order with id: {}", driverId, orderId);
shipmentDAO.confirmShipment(orderId);
}
return driverId;
} | public static void cancelDelivery(String orderId) {
shipmentDAO.cancelShipment(orderId);
}
private static int findDriver() {
Random random = new Random();
int driverId = 0;
int counter = 0;
while (counter < 10) {
driverId = random.nextInt(4);
if(driverId !=0) break;
counter += 1;
}
return driverId;
}
} | repos\tutorials-master\microservices-modules\saga-pattern\src\main\java\io\orkes\example\saga\service\ShipmentService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WebConfigurer implements WebFluxConfigurer {
private final Logger log = LoggerFactory.getLogger(WebConfigurer.class);
private final JHipsterProperties jHipsterProperties;
public WebConfigurer(Environment env, JHipsterProperties jHipsterProperties) {
this.jHipsterProperties = jHipsterProperties;
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
try {
H2ConfigurationHelper.initH2Console();
} catch (Exception e) {
// Console may already be running on another app or after a refresh.
e.printStackTrace();
}
}
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = jHipsterProperties.getCors();
if (!CollectionUtils.isEmpty(config.getAllowedOrigins()) || !CollectionUtils.isEmpty(config.getAllowedOriginPatterns())) {
log.debug("Registering CORS filter");
source.registerCorsConfiguration("/api/**", config);
source.registerCorsConfiguration("/management/**", config);
source.registerCorsConfiguration("/v3/api-docs", config);
source.registerCorsConfiguration("/swagger-ui/**", config);
source.registerCorsConfiguration("/*/api/**", config);
source.registerCorsConfiguration("/services/*/api/**", config);
source.registerCorsConfiguration("/*/management/**", config);
}
return source;
} | // TODO: remove when this is supported in spring-boot
@Bean
HandlerMethodArgumentResolver reactivePageableHandlerMethodArgumentResolver() {
return new ReactivePageableHandlerMethodArgumentResolver();
}
// TODO: remove when this is supported in spring-boot
@Bean
HandlerMethodArgumentResolver reactiveSortHandlerMethodArgumentResolver() {
return new ReactiveSortHandlerMethodArgumentResolver();
}
@Bean
@Order(-2) // The handler must have precedence over WebFluxResponseStatusExceptionHandler and Spring Boot's ErrorWebExceptionHandler
public WebExceptionHandler problemExceptionHandler(ObjectMapper mapper, ExceptionTranslator problemHandling) {
return new ReactiveWebExceptionHandler(problemHandling, mapper);
}
@Bean
ResourceHandlerRegistrationCustomizer registrationCustomizer() {
// Disable built-in cache control to use our custom filter instead
return registration -> registration.setCacheControl(null);
}
@Bean
@Profile(JHipsterConstants.SPRING_PROFILE_PRODUCTION)
public CachingHttpHeadersFilter cachingHttpHeadersFilter() {
// Use a cache filter that only match selected paths
return new CachingHttpHeadersFilter(TimeUnit.DAYS.toMillis(jHipsterProperties.getHttp().getCache().getTimeToLiveInDays()));
}
} | repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\config\WebConfigurer.java | 2 |
请完成以下Spring Boot application配置 | spring:
mail:
host: smtp.mxhichina.com
port: 465
username: spring-boot-demo@xkcoding.com
# 使用 jasypt 加密密码,使用com.xkcoding.email.PasswordTest.testGeneratePassword 生成加密密码,替换 ENC(加密密码)
password: ENC(OT0qGOpXrr1Iog1W+fjOiIDCJdBjHyhy)
protocol: smtp
test-connection: true
default-encoding: UTF-8
properties:
mail.smtp.auth: true
mail.smtp.starttls.enable: true
mai | l.smtp.starttls.required: true
mail.smtp.ssl.enable: true
mail.display.sendmail: spring-boot-demo
# 为 jasypt 配置解密秘钥
jasypt:
encryptor:
password: spring-boot-demo | repos\spring-boot-demo-master\demo-email\src\main\resources\application.yml | 2 |
请完成以下Java代码 | private static void configureLUTUConfigTU(
@NonNull final I_M_HU_LUTU_Configuration lutuConfigNew,
final HUPIItemProductId M_HU_PI_Item_Product_ID,
@NonNull final BigDecimal qtyTU)
{
final I_M_HU_PI_Item_Product tuPIItemProduct = Services.get(IHUPIItemProductDAO.class).getRecordById(M_HU_PI_Item_Product_ID);
final I_M_HU_PI tuPI = tuPIItemProduct.getM_HU_PI_Item().getM_HU_PI_Version().getM_HU_PI();
lutuConfigNew.setM_HU_PI_Item_Product_ID(tuPIItemProduct.getM_HU_PI_Item_Product_ID());
lutuConfigNew.setM_TU_HU_PI(tuPI);
lutuConfigNew.setQtyTU(qtyTU);
lutuConfigNew.setIsInfiniteQtyTU(false);
}
private static void configureLUTUConfigLU(
@NonNull final I_M_HU_LUTU_Configuration lutuConfigNew,
final int lu_PI_Item_ID,
final BigDecimal qtyLU)
{
if (lu_PI_Item_ID > 0)
{
if (qtyLU == null || qtyLU.signum() <= 0)
{
throw new FillMandatoryException(PARAM_QtyLU);
}
final I_M_HU_PI_Item luPI_Item = loadOutOfTrx(lu_PI_Item_ID, I_M_HU_PI_Item.class);
lutuConfigNew.setM_LU_HU_PI_Item(luPI_Item);
lutuConfigNew.setM_LU_HU_PI(luPI_Item.getM_HU_PI_Version().getM_HU_PI());
lutuConfigNew.setQtyLU(qtyLU);
lutuConfigNew.setIsInfiniteQtyLU(false);
}
else
{
lutuConfigNew.setM_LU_HU_PI(null);
lutuConfigNew.setM_LU_HU_PI_Item(null);
lutuConfigNew.setQtyLU(BigDecimal.ZERO);
}
}
public int getLuPiItemId()
{
return lu_PI_Item_ID;
}
public void setLuPiItemId(final int lu_PI_Item_ID)
{
this.lu_PI_Item_ID = lu_PI_Item_ID;
}
private HUPIItemProductId getTU_HU_PI_Item_Product_ID()
{
if (tu_HU_PI_Item_Product_ID <= 0)
{
throw new FillMandatoryException(PARAM_M_HU_PI_Item_Product_ID);
}
return HUPIItemProductId.ofRepoId(tu_HU_PI_Item_Product_ID);
}
public void setTU_HU_PI_Item_Product_ID(final int tu_HU_PI_Item_Product_ID)
{
this.tu_HU_PI_Item_Product_ID = tu_HU_PI_Item_Product_ID;
}
public BigDecimal getQtyCUsPerTU()
{
return qtyCUsPerTU;
}
public void setQtyCUsPerTU(final BigDecimal qtyCU) | {
this.qtyCUsPerTU = qtyCU;
}
/**
* Called from the process class to set the TU qty from the process parameter.
*/
public void setQtyTU(final BigDecimal qtyTU)
{
this.qtyTU = qtyTU;
}
public void setQtyLU(final BigDecimal qtyLU)
{
this.qtyLU = qtyLU;
}
private boolean getIsReceiveIndividualCUs()
{
if (isReceiveIndividualCUs == null)
{
isReceiveIndividualCUs = computeIsReceiveIndividualCUs();
}
return isReceiveIndividualCUs;
}
private boolean computeIsReceiveIndividualCUs()
{
if (selectedRow.getType() != PPOrderLineType.MainProduct
|| selectedRow.getUomId() == null
|| !selectedRow.getUomId().isEach())
{
return false;
}
return Optional.ofNullable(selectedRow.getOrderId())
.flatMap(ppOrderBOMBL::getSerialNoSequenceId)
.isPresent();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\PackingInfoProcessParams.java | 1 |
请完成以下Java代码 | public ModelAndView welcome(){
ModelAndView model = new ModelAndView();
model.setViewName("welcome");
return model;
}
private List getUsers() {
User user = new User();
user.setEmail("johndoe123@gmail.com");
user.setName("John Doe");
user.setAddress("Bangalore, Karnataka");
User user1 = new User();
user1.setEmail("amitsingh@yahoo.com"); | user1.setName("Amit Singh");
user1.setAddress("Chennai, Tamilnadu");
User user2 = new User();
user2.setEmail("bipulkumar@gmail.com");
user2.setName("Bipul Kumar");
user2.setAddress("Bangalore, Karnataka");
User user3 = new User();
user3.setEmail("prakashranjan@gmail.com");
user3.setName("Prakash Ranjan");
user3.setAddress("Chennai, Tamilnadu");
return Arrays.asList(user, user1, user2, user3);
}
} | repos\Spring-Boot-Advanced-Projects-main\Springboot integrated with JSP\SpringJSPUpdate\src\main\java\spring\jsp\DashboardController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PPOrderAllocator
{
@NonNull
String headerAggKey;
@NonNull
PPOrderCreateRequestBuilder ppOrderCreateRequestBuilder;
@NonNull
Map<PPOrderCandidateId, Quantity> ppOrderCand2AllocatedQty = new HashMap<>();
@NonNull
Quantity capacityPerProductionCycle;
@NonNull
@NonFinal
Quantity allocatedQty;
@Builder
public PPOrderAllocator(
@NonNull final String headerAggKey,
@NonNull final Quantity capacityPerProductionCycle)
{
Check.assume(capacityPerProductionCycle.signum() >= 0, "capacityPerProductionCycle must be a positive number!");
this.headerAggKey = headerAggKey;
this.capacityPerProductionCycle = capacityPerProductionCycle;
this.allocatedQty = capacityPerProductionCycle.toZero();
this.ppOrderCreateRequestBuilder = new PPOrderCreateRequestBuilder();
}
/**
* @return the successfully allocated qty (if nothing was allocated it will return zero)
*/
public Quantity allocate(@NonNull final PPOrderCandidateToAllocate ppOrderCandidateToAllocate)
{
if (!headerAggKey.equals(ppOrderCandidateToAllocate.getHeaderAggregationKey()))
{
return capacityPerProductionCycle.toZero();
}
if (isFullCapacityReached())
{
return capacityPerProductionCycle.toZero();
} | ppOrderCreateRequestBuilder.addRecord(ppOrderCandidateToAllocate.getPpOrderCandidate());
final Quantity qtyToAllocate = getQtyToAllocate(ppOrderCandidateToAllocate);
allocateQuantity(ppOrderCandidateToAllocate, qtyToAllocate);
return qtyToAllocate;
}
@NonNull
public PPOrderCreateRequest getPPOrderCreateRequest()
{
return ppOrderCreateRequestBuilder.build(allocatedQty);
}
private boolean isFullCapacityReached()
{
return !isInfiniteCapacity() && capacityPerProductionCycle.compareTo(allocatedQty) <= 0;
}
private void allocateQuantity(@NonNull final PPOrderCandidateToAllocate ppOrderCandidateToAllocate, @NonNull final Quantity quantityToAllocate)
{
allocatedQty = allocatedQty.add(quantityToAllocate);
final PPOrderCandidateId ppOrderCandidateId = PPOrderCandidateId.ofRepoId(ppOrderCandidateToAllocate.getPpOrderCandidate().getPP_Order_Candidate_ID());
ppOrderCand2AllocatedQty.put(ppOrderCandidateId, quantityToAllocate);
}
@NonNull
private Quantity getQtyToAllocate(@NonNull final PPOrderCandidateToAllocate ppOrderCandidateToAllocate)
{
if (isInfiniteCapacity())
{
return ppOrderCandidateToAllocate.getOpenQty();
}
final Quantity remainingCapacity = capacityPerProductionCycle.subtract(allocatedQty);
return ppOrderCandidateToAllocate.getOpenQty().min(remainingCapacity);
}
private boolean isInfiniteCapacity()
{
return capacityPerProductionCycle.signum() == 0;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\service\produce\PPOrderAllocator.java | 2 |
请完成以下Java代码 | public String getParameterName()
{
return documentField.getFieldName();
}
@Override
public DocumentFieldWidgetType getWidgetType()
{
return documentField.getWidgetType();
}
@Override
public OptionalInt getMinPrecision()
{
return documentField.getMinPrecision();
}
@Override
public Object getValueAsJsonObject(final JSONOptions jsonOpts)
{
return documentField.getValueAsJsonObject(jsonOpts);
}
@Override
public LogicExpressionResult getReadonly()
{
return documentField.getReadonly();
} | @Override
public LogicExpressionResult getMandatory()
{
return documentField.getMandatory();
}
@Override
public LogicExpressionResult getDisplayed()
{
return documentField.getDisplayed();
}
@Override
public DocumentValidStatus getValidStatus()
{
return documentField.getValidStatus();
}
@Override
public DeviceDescriptorsList getDevices()
{
return documentField.getDescriptor()
.getDeviceDescriptorsProvider()
.getDeviceDescriptors();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\adprocess\DocumentFieldAsProcessInstanceParameter.java | 1 |
请完成以下Java代码 | public CamundaIn newInstance(ModelTypeInstanceContext instanceContext) {
return new CamundaInImpl(instanceContext);
}
});
camundaSourceAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_SOURCE)
.namespace(CAMUNDA_NS)
.build();
camundaSourceExpressionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_SOURCE_EXPRESSION)
.namespace(CAMUNDA_NS)
.build();
camundaVariablesAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_VARIABLES)
.namespace(CAMUNDA_NS)
.build();
camundaTargetAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_TARGET)
.namespace(CAMUNDA_NS)
.build();
camundaBusinessKeyAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_BUSINESS_KEY)
.namespace(CAMUNDA_NS)
.build();
camundaLocalAttribute = typeBuilder.booleanAttribute(CAMUNDA_ATTRIBUTE_LOCAL)
.namespace(CAMUNDA_NS)
.build();
typeBuilder.build();
}
public CamundaInImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getCamundaSource() {
return camundaSourceAttribute.getValue(this);
}
public void setCamundaSource(String camundaSource) {
camundaSourceAttribute.setValue(this, camundaSource);
} | public String getCamundaSourceExpression() {
return camundaSourceExpressionAttribute.getValue(this);
}
public void setCamundaSourceExpression(String camundaSourceExpression) {
camundaSourceExpressionAttribute.setValue(this, camundaSourceExpression);
}
public String getCamundaVariables() {
return camundaVariablesAttribute.getValue(this);
}
public void setCamundaVariables(String camundaVariables) {
camundaVariablesAttribute.setValue(this, camundaVariables);
}
public String getCamundaTarget() {
return camundaTargetAttribute.getValue(this);
}
public void setCamundaTarget(String camundaTarget) {
camundaTargetAttribute.setValue(this, camundaTarget);
}
public String getCamundaBusinessKey() {
return camundaBusinessKeyAttribute.getValue(this);
}
public void setCamundaBusinessKey(String camundaBusinessKey) {
camundaBusinessKeyAttribute.setValue(this, camundaBusinessKey);
}
public boolean getCamundaLocal() {
return camundaLocalAttribute.getValue(this);
}
public void setCamundaLocal(boolean camundaLocal) {
camundaLocalAttribute.setValue(this, camundaLocal);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaInImpl.java | 1 |
请完成以下Java代码 | private static boolean hasSecurityContext(Context context) {
return context.hasKey(SECURITY_CONTEXT_KEY);
}
private static Mono<SecurityContext> getSecurityContext(Context context) {
return context.<Mono<SecurityContext>>get(SECURITY_CONTEXT_KEY);
}
/**
* Clears the {@code Mono<SecurityContext>} from Reactor {@link Context}
* @return Return a {@code Mono<Void>} which only replays complete and error signals
* from clearing the context.
*/
public static Function<Context, Context> clearContext() {
return (context) -> context.delete(SECURITY_CONTEXT_KEY);
}
/**
* Creates a Reactor {@link Context} that contains the {@code Mono<SecurityContext>}
* that can be merged into another {@link Context} | * @param securityContext the {@code Mono<SecurityContext>} to set in the returned
* Reactor {@link Context}
* @return a Reactor {@link Context} that contains the {@code Mono<SecurityContext>}
*/
public static Context withSecurityContext(Mono<? extends SecurityContext> securityContext) {
return Context.of(SECURITY_CONTEXT_KEY, securityContext);
}
/**
* A shortcut for {@link #withSecurityContext(Mono)}
* @param authentication the {@link Authentication} to be used
* @return a Reactor {@link Context} that contains the {@code Mono<SecurityContext>}
*/
public static Context withAuthentication(Authentication authentication) {
return withSecurityContext(Mono.just(new SecurityContextImpl(authentication)));
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\core\context\ReactiveSecurityContextHolder.java | 1 |
请完成以下Java代码 | public void setRandomClass(String randomClass) {
this.randomClass = randomClass;
}
@Override
public void destroy() {
}
/**
* Determine if the request a non-modifying request. A non-modifying
* request is one that is either a 'HTTP GET/OPTIONS/HEAD' request, or
* is allowed explicitly through the 'entryPoints' parameter in the web.xml
*
* @return true if the request is a non-modifying request
* */
protected boolean isNonModifyingRequest(HttpServletRequest request) {
return CsrfConstants.CSRF_NON_MODIFYING_METHODS_PATTERN.matcher(request.getMethod()).matches()
|| entryPoints.contains(getRequestedPath(request));
}
/**
* Generate a one-time token for authenticating subsequent
* requests.
*
* @return the generated token
*/
protected String generateCSRFToken() {
byte random[] = new byte[16];
// Render the result as a String of hexadecimal digits
StringBuilder buffer = new StringBuilder();
randomSource.nextBytes(random);
for (int j = 0; j < random.length; j++) {
byte b1 = (byte) ((random[j] & 0xf0) >> 4);
byte b2 = (byte) (random[j] & 0x0f);
if (b1 < 10) {
buffer.append((char) ('0' + b1));
} else {
buffer.append((char) ('A' + (b1 - 10)));
}
if (b2 < 10) {
buffer.append((char) ('0' + b2));
} else {
buffer.append((char) ('A' + (b2 - 10)));
}
}
return buffer.toString();
}
private Object getCSRFTokenSession(HttpSession session) {
return session.getAttribute(CsrfConstants.CSRF_TOKEN_SESSION_ATTR_NAME);
}
private String getCSRFTokenHeader(HttpServletRequest request) {
return request.getHeader(CsrfConstants.CSRF_TOKEN_HEADER_NAME);
}
private Object getSessionMutex(HttpSession session) {
if (session == null) {
throw new InvalidRequestException(Response.Status.BAD_REQUEST, "HttpSession is missing");
}
Object mutex = session.getAttribute(CsrfConstants.CSRF_SESSION_MUTEX);
if (mutex == null) {
mutex = session;
} | return mutex;
}
private boolean isBlank(String s) {
return s == null || s.trim().isEmpty();
}
private String getRequestedPath(HttpServletRequest request) {
String path = request.getServletPath();
if (request.getPathInfo() != null) {
path = path + request.getPathInfo();
}
return path;
}
private Set<String> parseURLs(String urlString) {
Set<String> urlSet = new HashSet<>();
if (urlString != null && !urlString.isEmpty()) {
String values[] = urlString.split(",");
for (String value : values) {
urlSet.add(value.trim());
}
}
return urlSet;
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\CsrfPreventionFilter.java | 1 |
请完成以下Java代码 | public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getTaskAssignee() {
return taskAssignee;
}
public void setTaskAssignee(String taskAssignee) {
this.taskAssignee = taskAssignee;
}
public void setActivityInstanceState(int activityInstanceState) {
this.activityInstanceState = activityInstanceState;
}
public int getActivityInstanceState() {
return activityInstanceState;
}
public boolean isCompleteScope() {
return ActivityInstanceState.SCOPE_COMPLETE.getStateCode() == activityInstanceState;
}
public boolean isCanceled() {
return ActivityInstanceState.CANCELED.getStateCode() == activityInstanceState;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
} | public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[activityId=" + activityId
+ ", activityName=" + activityName
+ ", activityType=" + activityType
+ ", activityInstanceId=" + activityInstanceId
+ ", activityInstanceState=" + activityInstanceState
+ ", parentActivityInstanceId=" + parentActivityInstanceId
+ ", calledProcessInstanceId=" + calledProcessInstanceId
+ ", calledCaseInstanceId=" + calledCaseInstanceId
+ ", taskId=" + taskId
+ ", taskAssignee=" + taskAssignee
+ ", durationInMillis=" + durationInMillis
+ ", startTime=" + startTime
+ ", endTime=" + endTime
+ ", eventType=" + eventType
+ ", executionId=" + executionId
+ ", processDefinitionId=" + processDefinitionId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", processInstanceId=" + processInstanceId
+ ", tenantId=" + tenantId
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricActivityInstanceEventEntity.java | 1 |
请完成以下Java代码 | public class BooleanRestVariableConverter implements RestVariableConverter {
@Override
public String getRestTypeName() {
return "boolean";
}
@Override
public Class<?> getVariableType() {
return Boolean.class;
}
@Override
public Object getVariableValue(EngineRestVariable result) {
if (result.getValue() != null) {
if (!(result.getValue() instanceof Boolean)) {
throw new FlowableIllegalArgumentException("Converter can only convert booleans");
}
return result.getValue();
}
return null; | }
@Override
public void convertVariableValue(Object variableValue, EngineRestVariable result) {
if (variableValue != null) {
if (!(variableValue instanceof Boolean)) {
throw new FlowableIllegalArgumentException("Converter can only convert booleans");
}
result.setValue(variableValue);
} else {
result.setValue(null);
}
}
} | repos\flowable-engine-main\modules\flowable-common-rest\src\main\java\org\flowable\common\rest\variable\BooleanRestVariableConverter.java | 1 |
请完成以下Java代码 | public String toCamelCaseFormat() {
String[] tokens = this.property.split("[-.]");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < tokens.length; i++) {
String part = tokens[i];
if (i > 0) {
part = StringUtils.capitalize(part);
}
sb.append(part);
}
return sb.toString();
}
public String toStandardFormat() {
return this.property;
}
private static String validateFormat(String property) {
for (char c : property.toCharArray()) {
if (Character.isUpperCase(c)) {
throw new IllegalArgumentException("Invalid property '" + property + "', must not contain upper case");
}
if (!Character.isLetterOrDigit(c) && !SUPPORTED_CHARS.contains(c)) {
throw new IllegalArgumentException("Unsupported character '" + c + "' for '" + property + "'");
}
}
return property;
}
@Override
public int compareTo(VersionProperty o) {
return this.property.compareTo(o.property);
}
@Override
public boolean equals(Object o) { | if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
VersionProperty that = (VersionProperty) o;
return this.internal == that.internal && this.property.equals(that.property);
}
@Override
public int hashCode() {
return Objects.hash(this.property, this.internal);
}
@Override
public String toString() {
return this.property;
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\version\VersionProperty.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setDateFunctionCodeQualifier(String value) {
this.dateFunctionCodeQualifier = value;
}
/**
* Gets the value of the dateFormatCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDateFormatCode() {
return dateFormatCode;
}
/**
* Sets the value of the dateFormatCode property.
*
* @param value
* allowed object is
* {@link String } | *
*/
public void setDateFormatCode(String value) {
this.dateFormatCode = value;
}
}
}
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ListLineItemExtensionType.java | 2 |
请完成以下Java代码 | public void setC_Print_Package_ID (int C_Print_Package_ID)
{
if (C_Print_Package_ID < 1)
set_Value (COLUMNNAME_C_Print_Package_ID, null);
else
set_Value (COLUMNNAME_C_Print_Package_ID, Integer.valueOf(C_Print_Package_ID));
}
@Override
public int getC_Print_Package_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Print_Package_ID);
}
@Override
public void setM_Warehouse_ID (int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_Value (COLUMNNAME_M_Warehouse_ID, null);
else
set_Value (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID));
}
@Override
public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
@Override
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(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 (int S_Resource_ID)
{
if (S_Resource_ID < 1)
set_Value (COLUMNNAME_S_Resource_ID, null);
else
set_Value (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID));
}
@Override
public int getS_Resource_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Resource_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_Job_Instructions_v.java | 1 |
请完成以下Java代码 | public void setQtyPromised_TU (java.math.BigDecimal QtyPromised_TU)
{
set_ValueNoCheck (COLUMNNAME_QtyPromised_TU, QtyPromised_TU);
}
/** Get Zusagbar (TU).
@return Zusagbar (TU) */
@Override
public java.math.BigDecimal getQtyPromised_TU ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised_TU);
if (bd == null)
return Env.ZERO;
return bd;
} | /** Set Wochenerster.
@param WeekDate Wochenerster */
@Override
public void setWeekDate (java.sql.Timestamp WeekDate)
{
set_ValueNoCheck (COLUMNNAME_WeekDate, WeekDate);
}
/** Get Wochenerster.
@return Wochenerster */
@Override
public java.sql.Timestamp getWeekDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_WeekDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_Balance.java | 1 |
请完成以下Java代码 | public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Possession other = (Possession) obj;
if (id != other.id) {
return false;
}
if (name == null) { | if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
@Override
public String toString() {
return "Possession [id=" + id + ", name=" + name + "]";
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-simple\src\main\java\com\baeldung\jpa\modifying\model\Possession.java | 1 |
请完成以下Java代码 | public static PaymentToReconcileRow cast(final IViewRow row)
{
return (PaymentToReconcileRow)row;
}
@Override
public DocumentId getId()
{
return rowId;
}
@Override
public boolean isProcessed()
{
return isReconciled();
}
@Override
public DocumentPath getDocumentPath()
{
return null;
}
@Override
public Set<String> getFieldNames()
{
return values.getFieldNames();
}
@Override
public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues()
{
return values.get(this);
} | static DocumentId convertPaymentIdToDocumentId(@NonNull final PaymentId paymentId)
{
return DocumentId.of(paymentId);
}
static PaymentId convertDocumentIdToPaymentId(@NonNull final DocumentId rowId)
{
return rowId.toId(PaymentId::ofRepoId);
}
public Amount getPayAmtNegateIfOutbound()
{
return getPayAmt().negateIf(!inboundPayment);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\PaymentToReconcileRow.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void save(@NonNull final PostgRESTConfig postgRESTConfig)
{
final I_S_PostgREST_Config configRecord = InterfaceWrapperHelper.loadOrNew(postgRESTConfig.getId(), I_S_PostgREST_Config.class);
configRecord.setAD_Org_ID(postgRESTConfig.getOrgId().getRepoId());
configRecord.setBase_url(postgRESTConfig.getBaseURL());
if (postgRESTConfig.getConnectionTimeout() == null)
{
configRecord.setConnection_timeout(0);
}
else
{
final long millis = postgRESTConfig.getConnectionTimeout().toMillis();
configRecord.setConnection_timeout((int)millis); | }
if (postgRESTConfig.getReadTimeout() == null)
{
configRecord.setRead_timeout(0);
}
else
{
final long millis = postgRESTConfig.getReadTimeout().toMillis();
configRecord.setRead_timeout((int)millis);
}
configRecord.setPostgREST_ResultDirectory(postgRESTConfig.getResultDirectory());
InterfaceWrapperHelper.saveRecord(configRecord);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\postgrest\config\PostgRESTConfigRepository.java | 2 |
请完成以下Java代码 | public String getRecurringType ()
{
return (String)get_Value(COLUMNNAME_RecurringType);
}
/** Set Maximum Runs.
@param RunsMax
Number of recurring runs
*/
public void setRunsMax (int RunsMax)
{
set_Value (COLUMNNAME_RunsMax, Integer.valueOf(RunsMax));
}
/** Get Maximum Runs.
@return Number of recurring runs
*/
public int getRunsMax ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_RunsMax);
if (ii == null)
return 0;
return ii.intValue();
} | /** Set Remaining Runs.
@param RunsRemaining
Number of recurring runs remaining
*/
public void setRunsRemaining (int RunsRemaining)
{
set_ValueNoCheck (COLUMNNAME_RunsRemaining, Integer.valueOf(RunsRemaining));
}
/** Get Remaining Runs.
@return Number of recurring runs remaining
*/
public int getRunsRemaining ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_RunsRemaining);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Recurring.java | 1 |
请完成以下Java代码 | public class ManualActivationRuleImpl extends CmmnElementImpl implements ManualActivationRule {
protected static Attribute<String> nameAttribute;
protected static AttributeReference<CaseFileItem> contextRefAttribute;
protected static ChildElement<ConditionExpression> conditionChild;
public ManualActivationRuleImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getName() {
return nameAttribute.getValue(this);
}
public void setName(String name) {
nameAttribute.setValue(this, name);
}
public CaseFileItem getContext() {
return contextRefAttribute.getReferenceTargetElement(this);
}
public void setContext(CaseFileItem caseFileItem) {
contextRefAttribute.setReferenceTargetElement(this, caseFileItem);
}
public ConditionExpression getCondition() {
return conditionChild.getChild(this);
}
public void setCondition(ConditionExpression condition) {
conditionChild.setChild(this, condition);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ManualActivationRule.class, CMMN_ELEMENT_MANUAL_ACTIVATION_RULE)
.namespaceUri(CMMN11_NS)
.extendsType(CmmnElement.class)
.instanceProvider(new ModelTypeInstanceProvider<ManualActivationRule>() { | public ManualActivationRule newInstance(ModelTypeInstanceContext instanceContext) {
return new ManualActivationRuleImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME)
.build();
contextRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_CONTEXT_REF)
.idAttributeReference(CaseFileItem.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
conditionChild = sequenceBuilder.element(ConditionExpression.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\ManualActivationRuleImpl.java | 1 |
请完成以下Java代码 | public String getTo() {
return to;
}
/**
* Sets the value of the to property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTo(String value) {
this.to = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="via" use="required" type="{http://www.forum-datenaustausch.ch/invoice}eanPartyType" />
* <attribute name="sequence_id" use="required" type="{http://www.w3.org/2001/XMLSchema}unsignedShort" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
public static class Via {
@XmlAttribute(name = "via", required = true)
protected String via;
@XmlAttribute(name = "sequence_id", required = true)
@XmlSchemaType(name = "unsignedShort")
protected int sequenceId; | /**
* Gets the value of the via property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVia() {
return via;
}
/**
* Sets the value of the via property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVia(String value) {
this.via = value;
}
/**
* Gets the value of the sequenceId property.
*
*/
public int getSequenceId() {
return sequenceId;
}
/**
* Sets the value of the sequenceId property.
*
*/
public void setSequenceId(int value) {
this.sequenceId = 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\TransportType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ADInfoWindowBL implements IADInfoWindowBL
{
@Override
public String getSqlFrom(final I_AD_InfoWindow infoWindow)
{
Check.assumeNotNull(infoWindow, "infoWindow not null");
final StringBuilder sqlFrom = new StringBuilder();
if (!Check.isEmpty(infoWindow.getFromClause(), true))
{
sqlFrom.append(infoWindow.getFromClause());
}
//
// Add addtional SQL FROM clauses
final List<I_AD_InfoWindow_From> fromDefs = Services.get(IADInfoWindowDAO.class).retrieveFroms(infoWindow);
for (final I_AD_InfoWindow_From fromDef : fromDefs)
{
if (!fromDef.isActive())
{
continue;
}
if (Check.isEmpty(fromDef.getFromClause(), true))
{
continue;
}
if (sqlFrom.length() > 0)
{
sqlFrom.append("\n");
}
sqlFrom.append(fromDef.getFromClause());
}
return sqlFrom.toString();
}
@Override
public String getTableName(final I_AD_InfoWindow infoWindow)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(infoWindow);
return Services.get(IADTableDAO.class).retrieveTableName(infoWindow.getAD_Table_ID());
}
@Override
public String getTreeColumnName(final I_AD_InfoWindow infoWindow)
{
final I_AD_InfoColumn treeColumn = Services.get(IADInfoWindowDAO.class).retrieveTreeInfoColumn(infoWindow);
if (treeColumn == null)
{
return null;
} | final String treeColumnName = treeColumn.getSelectClause();
return treeColumnName;
}
@Override
// @Cached
public int getAD_Tree_ID(final I_AD_InfoWindow infoWindow)
{
String keyName = getTreeColumnName(infoWindow);
// the keyName is wrong typed in Mtree class
// TODO: HARDCODED
if ("M_Product_Category_ID".equals(keyName))
{
keyName = "M_ProductCategory_ID";
}
final Properties ctx = InterfaceWrapperHelper.getCtx(infoWindow);
final int adTreeId = MTree.getDefaultAD_Tree_ID(Env.getAD_Client_ID(ctx), keyName);
return adTreeId;
}
@Override
public boolean isShowTotals(final I_AD_InfoWindow infoWindow)
{
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\service\impl\ADInfoWindowBL.java | 2 |
请完成以下Java代码 | public String getCustomer() {
return customer;
}
public void setCustomer(String customer) {
this.customer = customer;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getValidUntil() {
return validUntil;
}
public void setValidUntil(String validUntil) {
this.validUntil = validUntil;
}
public Boolean isUnlimited() {
return isUnlimited;
}
public void setUnlimited(Boolean isUnlimited) {
this.isUnlimited = isUnlimited;
} | public Map<String, String> getFeatures() {
return features;
}
public void setFeatures(Map<String, String> features) {
this.features = features;
}
public String getRaw() {
return raw;
}
public void setRaw(String raw) {
this.raw = raw;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\telemetry\dto\LicenseKeyDataImpl.java | 1 |
请完成以下Java代码 | public void setPDFCount (final int PDFCount)
{
throw new IllegalArgumentException ("PDFCount is virtual column"); }
@Override
public int getPDFCount()
{
return get_ValueAsInt(COLUMNNAME_PDFCount);
}
@Override
public void setPOReference (final @Nullable String POReference)
{
set_ValueNoCheck (COLUMNNAME_POReference, POReference);
}
@Override
public String getPOReference()
{
return get_ValueAsString(COLUMNNAME_POReference);
}
@Override
public void setPrintCount (final int PrintCount)
{
throw new IllegalArgumentException ("PrintCount is virtual column"); }
@Override
public int getPrintCount()
{
return get_ValueAsInt(COLUMNNAME_PrintCount);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID); | }
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setStoreCount (final int StoreCount)
{
throw new IllegalArgumentException ("StoreCount is virtual column"); }
@Override
public int getStoreCount()
{
return get_ValueAsInt(COLUMNNAME_StoreCount);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java-gen\de\metas\document\archive\model\X_C_Doc_Outbound_Log.java | 1 |
请完成以下Java代码 | private String supplementWildCards(@NonNull final String stringVal)
{
final StringBuilder result = new StringBuilder();
if (!stringVal.startsWith("%"))
{
result.append("%");
}
result.append(stringVal.replace("'", "''")); // escape quotes within the string
if (!stringVal.endsWith("%"))
{
result.append("%");
}
return result.toString();
}
/**
* Just prepends a space to the given <code>columnSql</code>.
*/
@Override
public @NonNull String getColumnSql(final @NonNull String columnName)
{
return columnName + " "; // nothing more to do
}
/**
* Uppercases the given {@code value} if {@code ignoreCase} was specified.
*/
@Nullable
@Override
public Object convertValue(@Nullable final String columnName, @Nullable final Object value, final @Nullable Object model)
{
if (value == null)
{
return ""; // shall not happen, see constructor
}
final String str;
if (ignoreCase)
{
// will return the uppercase version of both operands
str = ((String)value).toUpperCase();
}
else | {
str = (String)value;
}
return supplementWildCards(str);
}
@Override
public String toString()
{
return "Modifier[ignoreCase=" + ignoreCase + "]";
}
}
public StringLikeFilter(
@NonNull final String columnName,
@NonNull final String substring,
final boolean ignoreCase)
{
super(columnName,
ignoreCase ? Operator.STRING_LIKE_IGNORECASE : Operator.STRING_LIKE,
substring,
new StringLikeQueryFilterModifier(ignoreCase));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\StringLikeFilter.java | 1 |
请完成以下Java代码 | private void dispatchExecutionCancelled(ActivityExecution execution, ActivityImpl causeActivity) {
// subprocesses
for (ActivityExecution subExecution : execution.getExecutions()) {
dispatchExecutionCancelled(subExecution, causeActivity);
}
// call activities
ExecutionEntity subProcessInstance = Context.getCommandContext().getExecutionEntityManager().findSubProcessInstanceBySuperExecutionId(execution.getId());
if (subProcessInstance != null) {
dispatchExecutionCancelled(subProcessInstance, causeActivity);
}
// activity with message/signal boundary events
ActivityImpl activity = (ActivityImpl) execution.getActivity();
if (activity != null && activity.getActivityBehavior() != null && activity != causeActivity) {
dispatchActivityCancelled(execution, activity, causeActivity);
}
} | protected void dispatchActivityCancelled(ActivityExecution execution, ActivityImpl activity, ActivityImpl causeActivity) {
Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createActivityCancelledEvent(activity.getId(),
(String) activity.getProperties().get("name"),
execution.getId(),
execution.getProcessInstanceId(), execution.getProcessDefinitionId(),
(String) activity.getProperties().get("type"),
activity.getActivityBehavior().getClass().getCanonicalName(),
causeActivity),
EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG);
}
public EndEvent getEndEvent() {
return this.endEvent;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\TerminateEndEventActivityBehavior.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class InstanceProperties {
/**
* Management-url to register with. Inferred at runtime, can be overridden in case the
* reachable URL is different (e.g. Docker).
*/
@Nullable
private String managementUrl;
/**
* Base url for computing the management-url to register with. The path is inferred at
* runtime, and appended to the base url.
*/
@Nullable
private String managementBaseUrl;
/**
* Client-service-URL register with. Inferred at runtime, can be overridden in case
* the reachable URL is different (e.g. Docker).
*/
@Nullable
private String serviceUrl;
/**
* Base url for computing the service-url to register with. The path is inferred at
* runtime, and appended to the base url.
*/
@Nullable
private String serviceBaseUrl;
/**
* Path for computing the service-url to register with. If not specified, defaults to
* "/"
*/
@Nullable
private String servicePath;
/**
* Client-health-URL to register with. Inferred at runtime, can be overridden in case
* the reachable URL is different (e.g. Docker). Must be unique all services registry.
*/
@Nullable
private String healthUrl;
/** | * Name to register with. Defaults to ${spring.application.name}
*/
@Value("${spring.application.name:spring-boot-application}")
private String name = "spring-boot-application";
/**
* Should the registered urls be built with server.address or with hostname.
* @deprecated Use serviceHostType instead.
*/
@Deprecated
private boolean preferIp = false;
/**
* Should the registered urls be built with server.address or with hostname.
*/
private ServiceHostType serviceHostType = ServiceHostType.CANONICAL_HOST_NAME;
/**
* Metadata that should be associated with this application
*/
private Map<String, String> metadata = new LinkedHashMap<>();
} | repos\spring-boot-admin-master\spring-boot-admin-client\src\main\java\de\codecentric\boot\admin\client\config\InstanceProperties.java | 2 |
请完成以下Java代码 | public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public List<String> getImageUrls() {
return imageUrls;
}
public void setImageUrls(List<String> imageUrls) {
this.imageUrls = imageUrls;
}
public List<String> getVideoUrls() {
return videoUrls;
}
public void setVideoUrls(List<String> videoUrls) {
this.videoUrls = videoUrls;
}
public Integer getStock() {
return stock;
} | public void setStock(Integer stock) {
this.stock = stock;
}
@Override
public String toString() {
return "ProductModel{" +
"name='" + name + '\'' +
", description='" + description + '\'' +
", status='" + status + '\'' +
", currency='" + currency + '\'' +
", price=" + price +
", imageUrls=" + imageUrls +
", videoUrls=" + videoUrls +
", stock=" + stock +
'}';
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-graphql-2\src\main\java\com\baeldung\graphqlvsrest\model\ProductModel.java | 1 |
请完成以下Java代码 | public void setProperty(final String propertyName, final Object value)
{
Check.assumeNotNull(propertyName, "propertyName not null");
if (properties == null)
{
properties = new HashMap<String, Object>();
}
properties.put(propertyName, value);
}
@Override
public <T> T getProperty(final String propertyName)
{
final T defaultValue = null;
return getProperty(propertyName, defaultValue);
}
@Override
public <T> T getProperty(final String propertyName, final T defaultValue)
{
Check.assumeNotNull(propertyName, "propertyName not null");
if (properties == null)
{
return defaultValue;
}
final Object valueObj = properties.get(propertyName);
if (valueObj == null)
{
return defaultValue; | }
@SuppressWarnings("unchecked")
final T value = (T)valueObj;
return value;
}
@Override
public boolean isProperty(final String propertyName)
{
final boolean defaultValue = false;
return isProperty(propertyName, defaultValue);
}
@Override
public boolean isProperty(final String propertyName, final boolean defaultValue)
{
final Boolean value = getProperty(propertyName);
if (value == null)
{
return defaultValue;
}
return value.booleanValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\AbstractDunningContext.java | 1 |
请完成以下Java代码 | public class Person {
@Id
private String id;
@Field
@NotNull
private String firstName;
@Field
@NotNull
private String lastName;
@Field
@NotNull
private DateTime created;
@Field
private DateTime updated;
public Person(String id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) { | this.lastName = lastName;
}
public DateTime getCreated() {
return created;
}
public void setCreated(DateTime created) {
this.created = created;
}
public DateTime getUpdated() {
return updated;
}
public void setUpdated(DateTime updated) {
this.updated = updated;
}
@Override
public int hashCode() {
int hash = 1;
if (id != null) {
hash = hash * 31 + id.hashCode();
}
if (firstName != null) {
hash = hash * 31 + firstName.hashCode();
}
if (lastName != null) {
hash = hash * 31 + lastName.hashCode();
}
return hash;
}
@Override
public boolean equals(Object obj) {
if ((obj == null) || (obj.getClass() != this.getClass()))
return false;
if (obj == this)
return true;
Person other = (Person) obj;
return this.hashCode() == other.hashCode();
}
} | repos\tutorials-master\persistence-modules\spring-data-couchbase-2\src\main\java\com\baeldung\spring\data\couchbase\model\Person.java | 1 |
请完成以下Java代码 | public int getM_HU_Attribute_Snapshot_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_Attribute_Snapshot_ID);
}
@Override
public de.metas.handlingunits.model.I_M_HU getM_HU()
{
return get_ValueAsPO(COLUMNNAME_M_HU_ID, de.metas.handlingunits.model.I_M_HU.class);
}
@Override
public void setM_HU(final de.metas.handlingunits.model.I_M_HU M_HU)
{
set_ValueFromPO(COLUMNNAME_M_HU_ID, de.metas.handlingunits.model.I_M_HU.class, M_HU);
}
@Override
public void setM_HU_ID (final int M_HU_ID)
{
if (M_HU_ID < 1)
set_Value (COLUMNNAME_M_HU_ID, null);
else
set_Value (COLUMNNAME_M_HU_ID, M_HU_ID);
}
@Override
public int getM_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_ID);
}
@Override
public void setM_HU_PI_Attribute_ID (final int M_HU_PI_Attribute_ID)
{
if (M_HU_PI_Attribute_ID < 1)
set_Value (COLUMNNAME_M_HU_PI_Attribute_ID, null);
else
set_Value (COLUMNNAME_M_HU_PI_Attribute_ID, M_HU_PI_Attribute_ID);
}
@Override
public int getM_HU_PI_Attribute_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PI_Attribute_ID);
}
@Override
public void setSnapshot_UUID (final java.lang.String Snapshot_UUID)
{
set_Value (COLUMNNAME_Snapshot_UUID, Snapshot_UUID);
}
@Override
public java.lang.String getSnapshot_UUID()
{
return get_ValueAsString(COLUMNNAME_Snapshot_UUID);
}
@Override
public void setValue (final @Nullable java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
} | @Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setValueInitial (final @Nullable java.lang.String ValueInitial)
{
set_ValueNoCheck (COLUMNNAME_ValueInitial, ValueInitial);
}
@Override
public java.lang.String getValueInitial()
{
return get_ValueAsString(COLUMNNAME_ValueInitial);
}
@Override
public void setValueNumber (final @Nullable BigDecimal ValueNumber)
{
set_Value (COLUMNNAME_ValueNumber, ValueNumber);
}
@Override
public BigDecimal getValueNumber()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumber);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValueNumberInitial (final @Nullable BigDecimal ValueNumberInitial)
{
set_ValueNoCheck (COLUMNNAME_ValueNumberInitial, ValueNumberInitial);
}
@Override
public BigDecimal getValueNumberInitial()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumberInitial);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Attribute_Snapshot.java | 1 |
请完成以下Java代码 | public boolean isValidNewState(final WFState newState)
{
final WFState[] options = getNewStateOptions();
for (final WFState option : options)
{
if (option.equals(newState))
return true;
}
return false;
}
/**
* @return true if the action is valid based on current state
*/
public boolean isValidAction(final WFAction action)
{
final WFAction[] options = getActionOptions();
for (final WFAction option : options)
{
if (option.equals(action))
{
return true;
}
}
return false;
} | /**
* @return valid actions based on current State
*/
private WFAction[] getActionOptions()
{
if (isNotStarted())
return new WFAction[] { WFAction.Start, WFAction.Abort, WFAction.Terminate };
if (isRunning())
return new WFAction[] { WFAction.Suspend, WFAction.Complete, WFAction.Abort, WFAction.Terminate };
if (isSuspended())
return new WFAction[] { WFAction.Resume, WFAction.Abort, WFAction.Terminate };
else
return new WFAction[] {};
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\WFState.java | 1 |
请完成以下Java代码 | private OLCandOrderFactory newOrderFactory()
{
return OLCandOrderFactory.builder()
.orderDefaults(orderDefaults)
.userInChargeId(userInChargeId)
.loggable(loggable)
.olCandProcessorId(olCandProcessorId)
.olCandListeners(olCandListeners)
.propagateAsyncBatchIdToOrderRecord(propagateAsyncBatchIdToOrderRecord)
.build();
}
/**
* Computes an order-line-related grouping key for the given candidate. The key is made such that two different candidates that should be grouped (i.e. qtys aggregated) end up with the same grouping key.
*/
private ArrayKey mkGroupingKey(@NonNull final OLCand candidate)
{
if (aggregationInfo.getGroupByColumns().isEmpty())
{
// each candidate results in its own order line
return Util.mkKey(candidate.getId());
}
final ArrayKeyBuilder groupingValues = ArrayKey.builder()
.appendAll(groupingValuesProviders.provideLineGroupingValues(candidate));
for (final OLCandAggregationColumn column : aggregationInfo.getColumns())
{
if (!column.isGroupByColumn())
{
// we don't group by the current column, so all different values result in their own order lines
groupingValues.append(candidate.getValueByColumn(column));
}
else if (column.getGranularity() != null)
{
// create a grouping key based on the granularity level
final Granularity granularity = column.getGranularity();
final Timestamp timestamp = (Timestamp)candidate.getValueByColumn(column);
final long groupingValue = truncateDateByGranularity(timestamp, granularity).getTime();
groupingValues.append(groupingValue); | }
}
return groupingValues.build();
}
private static Timestamp truncateDateByGranularity(final Timestamp date, final Granularity granularity)
{
if (granularity == Granularity.Day)
{
return TimeUtil.trunc(date, TimeUtil.TRUNC_DAY);
}
else if (granularity == Granularity.Week)
{
return TimeUtil.trunc(date, TimeUtil.TRUNC_WEEK);
}
else if (granularity == Granularity.Month)
{
return TimeUtil.trunc(date, TimeUtil.TRUNC_MONTH);
}
else
{
throw new AdempiereException("Unknown granularity: " + granularity);
}
}
@NonNull
private List<OLCand> getEligibleOLCand()
{
final GetEligibleOLCandRequest request = GetEligibleOLCandRequest.builder()
.aggregationInfo(aggregationInfo)
.orderDefaults(orderDefaults)
.selection(selectionId)
.asyncBatchId(asyncBatchId)
.build();
return olCandProcessingHelper.getOLCandsForProcessing(request);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\OLCandsProcessorExecutor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void run() {
ExecutorService executorService = Executors.newSingleThreadExecutor();
try {
this.session.sendMessage(new TextMessage("sh -c ls -la\r\n"));
ProcessBuilder builder = new ProcessBuilder();
builder.command("sh", "-c", "ls -la");
builder.directory(new File(System.getProperty("user.home")));
Process process = builder.start();
StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), this::accept);
executorService.submit(streamGobbler);
int exitCode = process.waitFor();
assert exitCode == 0;
} catch (IOException e) {
LOG.error("IOException: ", e);
} catch (InterruptedException e) {
LOG.error("InterruptedException: ", e);
} finally {
executorService.shutdownNow();
}
}
@Override
public void accept(String message) {
Executors.newSingleThreadExecutor().submit(new WSSender(session, message));
//this.session.sendMessage(new TextMessage(message));
} | private class WSSender implements Runnable {
private final WebSocketSession session;
private final String message;
public WSSender(WebSocketSession session, String message) {
this.session = session;
this.message = message;
}
@Override
public void run() {
try {
this.session.sendMessage(new TextMessage(message + "\r\n"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
} | repos\spring-examples-java-17\spring-websockets\src\main\java\itx\examples\springboot\websockets\config\WSTerminalSession.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.