instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public String getLanguage()
{
return language;
}
public LanguageKey getLanguageKeyOrDefault()
{
final LanguageKey languageKey = LanguageKey.ofNullableString(getLanguage());
return languageKey != null ? languageKey : LanguageKey.getDefault();
}
public String getPassword()
{
return password;
}
public void setPassword(final String password)
{
this.password = password;
}
@Nullable
public String getPasswordResetKey()
{
return passwordResetKey;
}
public void setPasswordResetKey(@Nullable final String passwordResetKey)
{
this.passwordResetKey = passwordResetKey; | }
public void markDeleted()
{
setDeleted(true);
deleted_id = getId(); // FRESH-176: set the delete_id to current ID just to avoid the unique constraint
}
public void markNotDeleted()
{
setDeleted(false);
deleted_id = null; // FRESH-176: set the delete_id to NULL just to make sure the the unique index is enforced
}
@Nullable
@VisibleForTesting
public Long getDeleted_id()
{
return deleted_id;
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\User.java | 2 |
请完成以下Java代码 | public class EncryptableSystemEnvironmentPropertySourceWrapper extends SystemEnvironmentPropertySource implements EncryptablePropertySource<Map<String, Object>> {
private final CachingDelegateEncryptablePropertySource<Map<String, Object>> encryptableDelegate;
/**
* <p>Constructor for EncryptableSystemEnvironmentPropertySourceWrapper.</p>
*
* @param delegate a {@link SystemEnvironmentPropertySource} object
* @param resolver a {@link EncryptablePropertyResolver} object
* @param filter a {@link EncryptablePropertyFilter} object
*/
public EncryptableSystemEnvironmentPropertySourceWrapper(SystemEnvironmentPropertySource delegate, EncryptablePropertyResolver resolver, EncryptablePropertyFilter filter) {
super(delegate.getName(), delegate.getSource());
encryptableDelegate = new CachingDelegateEncryptablePropertySource<>(delegate, resolver, filter);
}
/**
* {@inheritDoc}
*/
@Override
public Object getProperty(@NonNull String name) {
return encryptableDelegate.getProperty(name);
}
/**
* {@inheritDoc}
*/
@Override
public PropertySource<Map<String, Object>> getDelegate() {
return encryptableDelegate;
}
/**
* {@inheritDoc}
*/
@Override
public Origin getOrigin(String key) {
Origin fromSuper = EncryptablePropertySource.super.getOrigin(key);
if (fromSuper != null) {
return fromSuper;
}
String property = resolvePropertyName(key); | if (super.containsProperty(property)) {
return new SystemEnvironmentOrigin(property);
}
return null;
}
/**
* <p>Set whether getSource() should wrap the source Map in an EncryptableMapWrapper.</p>
*
* @param wrapGetSource true to wrap the source Map
*/
public void setWrapGetSource(boolean wrapGetSource) {
encryptableDelegate.setWrapGetSource(wrapGetSource);
}
@Override
@NonNull
public Map<String, Object> getSource() {
return encryptableDelegate.getSource();
}
} | repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\wrapper\EncryptableSystemEnvironmentPropertySourceWrapper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @NonNull DocumentReportInfo getDocumentReportInfo(
@NonNull final TableRecordReference recordRef,
@Nullable final PrintFormatId adPrintFormatToUseId, final AdProcessId reportProcessIdToUse)
{
final InvoiceId invoiceId = recordRef.getIdAssumingTableName(I_C_Invoice.Table_Name, InvoiceId::ofRepoId);
final I_C_Invoice invoice = invoiceBL.getById(invoiceId);
final BPartnerId bpartnerId = BPartnerId.ofRepoId(invoice.getC_BPartner_ID());
final I_C_BPartner bpartner = util.getBPartnerById(bpartnerId);
final DocTypeId docTypeId = extractDocTypeId(invoice);
final I_C_DocType docType = util.getDocTypeById(docTypeId);
final ClientId clientId = ClientId.ofRepoId(invoice.getAD_Client_ID());
final PrintFormatId printFormatId = CoalesceUtil.coalesceSuppliers(
() -> adPrintFormatToUseId,
() -> util.getBPartnerPrintFormats(bpartnerId).getPrintFormatIdByDocTypeId(docTypeId).orElse(null),
() -> PrintFormatId.ofRepoIdOrNull(bpartner.getInvoice_PrintFormat_ID()),
() -> PrintFormatId.ofRepoIdOrNull(docType.getAD_PrintFormat_ID()),
() -> util.getDefaultPrintFormats(clientId).getInvoicePrintFormatId());
if (printFormatId == null)
{
throw new AdempiereException("@NotFound@ @AD_PrintFormat_ID@");
}
final Language language = util.getBPartnerLanguage(bpartner).orElse(null);
final BPPrintFormatQuery bpPrintFormatQuery = BPPrintFormatQuery.builder()
.adTableId(recordRef.getAdTableId())
.bpartnerId(bpartnerId)
.bPartnerLocationId(BPartnerLocationId.ofRepoId(bpartnerId, invoice.getC_BPartner_Location_ID()))
.docTypeId(docTypeId)
.onlyCopiesGreaterZero(true)
.build();
return DocumentReportInfo.builder() | .recordRef(TableRecordReference.of(I_C_Invoice.Table_Name, invoiceId))
.reportProcessId(util.getReportProcessIdByPrintFormatId(printFormatId))
.copies(util.getDocumentCopies(docType, bpPrintFormatQuery))
.documentNo(invoice.getDocumentNo())
.bpartnerId(bpartnerId)
.docTypeId(docTypeId)
.language(language)
.poReference(invoice.getPOReference())
.build();
}
private DocTypeId extractDocTypeId(@NonNull final I_C_Invoice invoice)
{
final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(invoice.getC_DocType_ID());
if (docTypeId != null)
{
return docTypeId;
}
final DocTypeId docTypeTargetId = DocTypeId.ofRepoIdOrNull(invoice.getC_DocTypeTarget_ID());
if (docTypeTargetId != null)
{
return docTypeTargetId;
}
throw new AdempiereException("No document type set");
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\service\InvoiceDocumentReportAdvisor.java | 2 |
请完成以下Java代码 | public String getTextValue() {
return textValue;
}
@Override
public void setTextValue(String textValue) {
this.textValue = textValue;
}
@Override
public String getTextValue2() {
return textValue2;
}
@Override
public void setTextValue2(String textValue2) {
this.textValue2 = textValue2;
}
@Override
public Long getLongValue() {
return longValue;
}
@Override
public void setLongValue(Long longValue) {
this.longValue = longValue;
}
@Override
public Double getDoubleValue() {
return doubleValue;
}
@Override
public void setDoubleValue(Double doubleValue) {
this.doubleValue = doubleValue;
}
public String getByteArrayValueId() {
return byteArrayField.getByteArrayId();
}
public void setByteArrayValueId(String byteArrayId) {
byteArrayField.setByteArrayId(byteArrayId);
}
@Override
public byte[] getByteArrayValue() {
return byteArrayField.getByteArrayValue();
}
@Override
public void setByteArrayValue(byte[] bytes) {
byteArrayField.setByteArrayValue(bytes);
} | public void setValue(TypedValue typedValue) {
typedValueField.setValue(typedValue);
}
public String getSerializerName() {
return typedValueField.getSerializerName();
}
public void setSerializerName(String serializerName) {
typedValueField.setSerializerName(serializerName);
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public void delete() {
byteArrayField.deleteByteArrayValue();
Context
.getCommandContext()
.getDbEntityManager()
.delete(this);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricDecisionInputInstanceEntity.java | 1 |
请完成以下Java代码 | public MTax getDefaultTax()
{
MTax m_tax = new MTax(getCtx(), 0, get_TrxName());
String whereClause = I_C_Tax.COLUMNNAME_C_TaxCategory_ID+"=? AND "+ I_C_Tax.COLUMNNAME_IsDefault+"='Y'";
List<MTax> list = new Query(getCtx(), MTax.Table_Name, whereClause, get_TrxName())
.setParameters(new Object[]{getC_TaxCategory_ID()})
.list(MTax.class);
if (list.size() == 1)
{
m_tax = list.get(0);
}
else {
// Error - should only be one default
throw new AdempiereException("TooManyDefaults");
} | return m_tax;
} // getDefaultTax
@Override
public String toString()
{
return getClass().getSimpleName()+"["+get_ID()
+", Name="+getName()
+", IsActive="+isActive()
+"]";
}
} // MTaxCategory | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTaxCategory.java | 1 |
请完成以下Java代码 | public int getDLM_Partition_Config_ID()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Partition_Config_ID);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
/**
* Set Partition.
*
* @param DLM_Partition_ID Partition
*/
@Override
public void setDLM_Partition_ID(final int DLM_Partition_ID)
{
if (DLM_Partition_ID < 1)
{
set_ValueNoCheck(COLUMNNAME_DLM_Partition_ID, null);
}
else
{
set_ValueNoCheck(COLUMNNAME_DLM_Partition_ID, Integer.valueOf(DLM_Partition_ID));
}
}
/**
* Get Partition.
*
* @return Partition
*/
@Override
public int getDLM_Partition_ID()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Partition_ID);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
/**
* Set Partition is vollständig.
*
* @param IsPartitionComplete
* Sagt aus, ob das System dieser Partition noch weitere Datensätze hinzufügen muss bevor sie als Ganzes verschoben werden kann.
*/
@Override
public void setIsPartitionComplete(final boolean IsPartitionComplete)
{
set_Value(COLUMNNAME_IsPartitionComplete, Boolean.valueOf(IsPartitionComplete));
}
/**
* Get Partition is vollständig.
*
* @return Sagt aus, ob das System dieser Partition noch weitere Datensätze hinzufügen muss bevor sie als Ganzes verschoben werden kann.
*/
@Override
public boolean isPartitionComplete()
{
final Object oo = get_Value(COLUMNNAME_IsPartitionComplete);
if (oo != null)
{
if (oo instanceof Boolean)
{
return ((Boolean)oo).booleanValue();
}
return "Y".equals(oo);
}
return false;
} | /**
* Set Anz. zugeordneter Datensätze.
*
* @param PartitionSize Anz. zugeordneter Datensätze
*/
@Override
public void setPartitionSize(final int PartitionSize)
{
set_Value(COLUMNNAME_PartitionSize, Integer.valueOf(PartitionSize));
}
/**
* Get Anz. zugeordneter Datensätze.
*
* @return Anz. zugeordneter Datensätze
*/
@Override
public int getPartitionSize()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_PartitionSize);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
/**
* Set Ziel-DLM-Level.
*
* @param Target_DLM_Level Ziel-DLM-Level
*/
@Override
public void setTarget_DLM_Level(final int Target_DLM_Level)
{
set_Value(COLUMNNAME_Target_DLM_Level, Integer.valueOf(Target_DLM_Level));
}
/**
* Get Ziel-DLM-Level.
*
* @return Ziel-DLM-Level
*/
@Override
public int getTarget_DLM_Level()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_Target_DLM_Level);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition.java | 1 |
请完成以下Java代码 | public CamundaScript newInstance(ModelTypeInstanceContext instanceContext) {
return new CamundaScriptImpl(instanceContext);
}
});
camundaScriptFormatAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_SCRIPT_FORMAT)
.required()
.build();
camundaResourceAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_RESOURCE)
.build();
typeBuilder.build();
}
public CamundaScriptImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
} | public String getCamundaScriptFormat() {
return camundaScriptFormatAttribute.getValue(this);
}
public void setCamundaScriptFormat(String camundaScriptFormat) {
camundaScriptFormatAttribute.setValue(this, camundaScriptFormat);
}
public String getCamundaResource() {
return camundaResourceAttribute.getValue(this);
}
public void setCamundaResource(String camundaResource) {
camundaResourceAttribute.setValue(this, camundaResource);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaScriptImpl.java | 1 |
请完成以下Java代码 | public class DeserializationUtils {
private DeserializationUtils() {
}
public static Object deserialize(InputStream inStream) {
return deserialize(inStream, null);
}
public static Object deserialize(InputStream inStream, ObjectInputFilter filter) {
try (ObjectInputStream in = new ObjectInputStream(inStream)) {
if (filter != null) {
in.setObjectInputFilter(filter);
}
return in.readObject();
} catch (InvalidClassException e) {
return null;
} catch (Throwable e) {
e.printStackTrace();
return null;
} | }
public static Set<ContextSpecific> deserializeIntoSet(InputStream... inputStreams) {
return deserializeIntoSet(null, inputStreams);
}
public static Set<ContextSpecific> deserializeIntoSet(ObjectInputFilter filter, InputStream... inputStreams) {
Set<ContextSpecific> set = new TreeSet<>();
for (InputStream inputStream : inputStreams) {
Object object = deserialize(inputStream, filter);
if (object != null) {
set.add((ContextSpecific) object);
}
}
return set;
}
} | repos\tutorials-master\core-java-modules\core-java-17\src\main\java\com\baeldung\deserializationfilters\utils\DeserializationUtils.java | 1 |
请完成以下Java代码 | public java.sql.Timestamp getSupportExpDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_SupportExpDate);
}
/** Set Internal Users.
@param SupportUnits
Number of Internal Users for Adempiere Support
*/
@Override
public void setSupportUnits (int SupportUnits)
{
set_ValueNoCheck (COLUMNNAME_SupportUnits, Integer.valueOf(SupportUnits));
}
/** Get Internal Users.
@return Number of Internal Users for Adempiere Support
*/
@Override
public int getSupportUnits ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SupportUnits);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* SystemStatus AD_Reference_ID=374
* Reference name: AD_System Status
*/
public static final int SYSTEMSTATUS_AD_Reference_ID=374;
/** Evaluation = E */
public static final String SYSTEMSTATUS_Evaluation = "E";
/** Implementation = I */
public static final String SYSTEMSTATUS_Implementation = "I";
/** Production = P */
public static final String SYSTEMSTATUS_Production = "P";
/** Set System Status.
@param SystemStatus
Status of the system - Support priority depends on system status
*/
@Override
public void setSystemStatus (java.lang.String SystemStatus)
{
set_Value (COLUMNNAME_SystemStatus, SystemStatus);
}
/** Get System Status.
@return Status of the system - Support priority depends on system status
*/
@Override
public java.lang.String getSystemStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_SystemStatus);
} | /** Set Registered EMail.
@param UserName
Email of the responsible for the System
*/
@Override
public void setUserName (java.lang.String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
/** Get Registered EMail.
@return Email of the responsible for the System
*/
@Override
public java.lang.String getUserName ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserName);
}
/** Set Version.
@param Version
Version of the table definition
*/
@Override
public void setVersion (java.lang.String Version)
{
set_ValueNoCheck (COLUMNNAME_Version, Version);
}
/** Get Version.
@return Version of the table definition
*/
@Override
public java.lang.String getVersion ()
{
return (java.lang.String)get_Value(COLUMNNAME_Version);
}
/** Set ZK WebUI URL.
@param WebUI_URL
ZK WebUI root URL
*/
@Override
public void setWebUI_URL (java.lang.String WebUI_URL)
{
set_Value (COLUMNNAME_WebUI_URL, WebUI_URL);
}
/** Get ZK WebUI URL.
@return ZK WebUI root URL
*/
@Override
public java.lang.String getWebUI_URL ()
{
return (java.lang.String)get_Value(COLUMNNAME_WebUI_URL);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_System.java | 1 |
请完成以下Java代码 | public class C_OLCand_ClearGroupingError extends JavaProcess
{
protected final IQueryBL queryBL = Services.get(IQueryBL.class);
@Override
protected void prepare()
{
// Display process logs only if the process failed.
// NOTE: we do that because this process is called from window Gear and the user shall not see a popoup, only the status line.
setShowProcessLogs(ProcessExecutionResult.ShowProcessLogs.OnError);
}
@Override
protected String doIt() throws Exception
{
final ICompositeQueryUpdater<I_C_OLCand> updater = queryBL.createCompositeQueryUpdater(I_C_OLCand.class) | .addSetColumnValue(I_C_OLCand.COLUMNNAME_IsGroupingError, false)
.addSetColumnValue(I_C_OLCand.COLUMNNAME_GroupingErrorMessage, null);
return "@Updated@ #" + createOLCandQueryBuilder().create().update(updater);
}
protected IQueryBuilder<I_C_OLCand> createOLCandQueryBuilder()
{
return queryBL.createQueryBuilder(I_C_OLCand.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_OLCand.COLUMNNAME_Processed, false)
.addEqualsFilter(I_C_OLCand.COLUMNNAME_IsGroupingError, true)
.filter(getProcessInfo().getQueryFilterOrElseFalse());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\server\rpl\trx\process\C_OLCand_ClearGroupingError.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CustomerService {
public CustomerService(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
private final CustomerRepository customerRepository;
public Page<Customer> getCustomers(int page, int size) {
Pageable pageRequest = createPageRequestUsing(page, size);
List<Customer> allCustomers = customerRepository.findAll();
int start = (int) pageRequest.getOffset();
int end = Math.min((start + pageRequest.getPageSize()), allCustomers.size()); | List<Customer> pageContent = allCustomers.subList(start, end);
return new PageImpl<>(pageContent, pageRequest, allCustomers.size());
}
public List<Customer> getCustomerListFromPage(int page, int size) {
Pageable pageRequest = createPageRequestUsing(page, size);
Page<Customer> allCustomers = customerRepository.findAll(pageRequest);
return allCustomers.hasContent() ? allCustomers.getContent() : Collections.emptyList();
}
private Pageable createPageRequestUsing(int page, int size) {
return PageRequest.of(page, size);
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-query-4\src\main\java\com\baeldung\spring\data\jpa\paging\CustomerService.java | 2 |
请完成以下Java代码 | public int compare(Object o1, Object o2) {
CompareToBuilder compareToBuilder = new CompareToBuilder();
for (Map.Entry<String, List<Object>> entry : executionContext.getOutputValues().entrySet()) {
List<Object> outputValues = entry.getValue();
if (outputValues != null && !outputValues.isEmpty()) {
noOutputValuesPresent = false;
compareToBuilder.append(((Map<String, Object>) o1).get(entry.getKey()),
((Map<String, Object>) o2).get(entry.getKey()),
new OutputOrderComparator<>(outputValues.toArray(new Comparable[outputValues.size()])));
}
}
if (!noOutputValuesPresent) {
return compareToBuilder.toComparison();
} else {
if (CommandContextUtil.getDmnEngineConfiguration().isStrictMode()) {
throw new FlowableException(String.format("HitPolicy %s violated; no output values present.", getHitPolicyName())); | } else {
executionContext.getAuditContainer().setValidationMessage(
String.format("HitPolicy %s violated; no output values present. Setting first valid result as final result.",
getHitPolicyName()));
}
return 0;
}
}
});
if (!ruleResults.isEmpty()) {
executionContext.getAuditContainer().addDecisionResultObject(ruleResults.get(0));
}
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\hitpolicy\HitPolicyPriority.java | 1 |
请完成以下Java代码 | private void notifyViewOfChanges(final List<DocumentId> changedRowIds)
{
final IView view = viewSupplier.get();
if (view != null)
{
ViewChangesCollector
.getCurrentOrAutoflush()
.collectRowsChanged(view, DocumentIdsSelection.of(changedRowIds));
}
}
@VisibleForTesting
static class PurchaseRowsList
{
@Getter
private final ImmutableList<PurchaseRow> topLevelRows;
private final ImmutableMap<TrackingId, PurchaseRowId> trackingIdsByTopLevelRowIds;
@Getter
private final ImmutableMap<TrackingId, PurchaseCandidatesGroup> purchaseCandidatesGroups;
private final ImmutableMap<TrackingId, PurchaseRow> purchaseCandidateRows;
@lombok.Builder
public PurchaseRowsList(
@NonNull @lombok.Singular final ImmutableList<PurchaseRow> topLevelRows,
@NonNull @lombok.Singular final ImmutableMap<TrackingId, PurchaseRowId> trackingIdsByTopLevelRowIds,
@NonNull @lombok.Singular final ImmutableMap<TrackingId, PurchaseCandidatesGroup> purchaseCandidatesGroups, | @NonNull @lombok.Singular final ImmutableMap<TrackingId, PurchaseRow> purchaseCandidateRows)
{
this.topLevelRows = topLevelRows;
this.trackingIdsByTopLevelRowIds = trackingIdsByTopLevelRowIds;
this.purchaseCandidatesGroups = purchaseCandidatesGroups;
this.purchaseCandidateRows = purchaseCandidateRows;
}
public PurchaseRow getPurchaseRowByTrackingId(TrackingId trackingId)
{
return purchaseCandidateRows.get(trackingId);
}
public DocumentId getTopLevelDocumentIdByTrackingId(final TrackingId trackingId, final DocumentId defaultValue)
{
final PurchaseRowId purchaseRowId = trackingIdsByTopLevelRowIds.get(trackingId);
return purchaseRowId != null ? purchaseRowId.toDocumentId() : defaultValue;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseRowsLoader.java | 1 |
请完成以下Java代码 | public class CriteriaExport implements CmmnXmlConstants {
public static void writeCriteriaElements(PlanItem planItem, XMLStreamWriter xtw) throws Exception {
if (!(planItem.getPlanItemDefinition() instanceof TimerEventListener)) {
// Timer event listeners are not allowed to have criteria.
// However the planItemStartTrigger is implemented as a fake criterion.
// Therefore we ignore writing the entry criteria elements for Timer Event listeners
writeEntryCriteriaElements(planItem.getEntryCriteria(), xtw);
}
writeExitCriteriaElements(planItem.getExitCriteria(), xtw);
}
public static void writeEntryCriteriaElements(List<Criterion> criterionList, XMLStreamWriter xtw) throws Exception {
writeCriteriaElements(ELEMENT_ENTRY_CRITERION, criterionList, xtw);
}
public static void writeExitCriteriaElements(List<Criterion> criterionList, XMLStreamWriter xtw) throws Exception {
writeCriteriaElements(ELEMENT_EXIT_CRITERION, criterionList, xtw);
}
public static void writeCriteriaElements(String criteriaElementLabel, List<Criterion> criterionList, XMLStreamWriter xtw) throws Exception {
for (Criterion criterion : criterionList) {
// start entry criterion element | xtw.writeStartElement(criteriaElementLabel);
xtw.writeAttribute(ATTRIBUTE_ID, criterion.getId());
if (StringUtils.isNotEmpty(criterion.getName())) {
xtw.writeAttribute(ATTRIBUTE_NAME, criterion.getName());
}
if (StringUtils.isNotEmpty(criterion.getSentryRef())) {
xtw.writeAttribute(ATTRIBUTE_SENTRY_REF, criterion.getSentryRef());
}
if (StringUtils.isNotEmpty(criterion.getExitType())) {
xtw.writeAttribute(FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_EXIT_TYPE, criterion.getExitType());
}
if (StringUtils.isNotEmpty(criterion.getExitEventType())) {
xtw.writeAttribute(FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_EXIT_EVENT_TYPE, criterion.getExitEventType());
}
// end entry criterion element
xtw.writeEndElement();
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\export\CriteriaExport.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BusinessRule
{
@NonNull BusinessRuleId id;
@NonNull String name;
@NonNull AdTableId adTableId;
@NonNull ImmutableList<BusinessRulePrecondition> preconditions;
@NonNull Validation validation;
@NonNull ImmutableList<BusinessRuleTrigger> triggers;
@NonNull @Getter(AccessLevel.NONE) ImmutableMap<BusinessRuleTriggerId, BusinessRuleTrigger> triggersById;
@NonNull ImmutableSet<BusinessRuleWarningTarget> warningTargets;
@NonNull AdMessageId warningMessageId;
@NonNull Severity severity;
@Nullable BusinessRuleLogLevel logLevel;
@Builder
private BusinessRule(
@NonNull final BusinessRuleId id,
@NonNull final String name,
@NonNull final AdTableId adTableId,
@NonNull final ImmutableList<BusinessRulePrecondition> preconditions,
@NonNull final Validation validation,
@NonNull final ImmutableList<BusinessRuleTrigger> triggers,
@NonNull final ImmutableSet<BusinessRuleWarningTarget> warningTargets,
@NonNull final AdMessageId warningMessageId,
@NonNull final Severity severity,
@Nullable final BusinessRuleLogLevel logLevel)
{ | this.id = id;
this.name = name;
this.adTableId = adTableId;
this.preconditions = preconditions;
this.validation = validation;
this.triggers = triggers;
this.triggersById = Maps.uniqueIndex(triggers, BusinessRuleTrigger::getId);
this.warningTargets = warningTargets;
this.warningMessageId = warningMessageId;
this.severity = severity;
this.logLevel = logLevel;
}
@NonNull
public BusinessRuleTrigger getTriggerById(final BusinessRuleTriggerId triggerId)
{
final BusinessRuleTrigger trigger = triggersById.get(triggerId);
if (trigger == null)
{
throw new AdempiereException("No trigger found for " + triggerId + " in " + this);
}
return trigger;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\descriptor\model\BusinessRule.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Optional<CreateCommissionSharesRequest> createRequestFor(@NonNull final CommissionTriggerDocument commissionTriggerDocument)
{
final BPartnerId customerBPartnerId = commissionTriggerDocument.getCustomerBPartnerId();
final BPartnerId salesRepBPartnerId = commissionTriggerDocument.getSalesRepBPartnerId();
// note: we include the end-customer in the hierarchy because they might be a salesrep
// and their contract might indicate that metasfresh shall create a 0% commission share for them
final Hierarchy hierarchy = commissionHierarchyFactory.createForCustomer(customerBPartnerId, salesRepBPartnerId);
final CommissionConfigProvider.ConfigRequestForNewInstance contractRequest = CommissionConfigProvider.ConfigRequestForNewInstance.builder()
.orgId(commissionTriggerDocument.getOrgId())
.commissionHierarchy(hierarchy)
.customerBPartnerId(customerBPartnerId)
.salesRepBPartnerId(salesRepBPartnerId)
.commissionDate(commissionTriggerDocument.getCommissionDate())
.salesProductId(commissionTriggerDocument.getProductId())
.commissionTriggerType(commissionTriggerDocument.getTriggerType())
.build();
final ImmutableList<CommissionConfig> configs = configProvider.createForNewCommissionInstances(contractRequest);
if (configs.isEmpty())
{ | logger.debug("Found no CommissionConfigs for contractRequest; -> return empty; contractRequest={}", contractRequest);
return Optional.empty();
}
final CommissionTrigger commissionTrigger = commissionTriggerFactory.createForDocument(commissionTriggerDocument, false /* candidateDeleted */);
return Optional.of(createRequest(hierarchy, configs, commissionTrigger));
}
private CreateCommissionSharesRequest createRequest(
@NonNull final Hierarchy hierarchy,
@NonNull final ImmutableList<CommissionConfig> configs,
@NonNull final CommissionTrigger trigger)
{
return CreateCommissionSharesRequest.builder()
.configs(configs)
.hierarchy(hierarchy)
.trigger(trigger)
.startingHierarchyLevel(HierarchyLevel.ZERO)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\services\CommissionInstanceRequestFactory.java | 2 |
请完成以下Java代码 | public int getAD_Tab_Callout_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Tab_Callout_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_AD_Tab getAD_Tab() throws RuntimeException
{
return (org.compiere.model.I_AD_Tab)MTable.get(getCtx(), org.compiere.model.I_AD_Tab.Table_Name)
.getPO(getAD_Tab_ID(), get_TrxName()); }
/** Set Register.
@param AD_Tab_ID
Register auf einem Fenster
*/
public void setAD_Tab_ID (int AD_Tab_ID)
{
if (AD_Tab_ID < 1)
set_Value (COLUMNNAME_AD_Tab_ID, null);
else
set_Value (COLUMNNAME_AD_Tab_ID, Integer.valueOf(AD_Tab_ID));
}
/** Get Register.
@return Register auf einem Fenster
*/
public int getAD_Tab_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Tab_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Classname.
@param Classname
Java Classname
*/
public void setClassname (String Classname)
{
set_Value (COLUMNNAME_Classname, Classname);
}
/** Get Classname.
@return Java Classname
*/
public String getClassname ()
{
return (String)get_Value(COLUMNNAME_Classname);
}
/** EntityType AD_Reference_ID=389 */
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entitäts-Art.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
public void setEntityType (String EntityType)
{ | set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitäts-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
public void setSeqNo (String SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
public String getSeqNo ()
{
return (String)get_Value(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\model\X_AD_Tab_Callout.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BankId implements RepoIdAware
{
@JsonCreator
public static BankId ofRepoId(final int repoId)
{
return new BankId(repoId);
}
@Nullable
public static BankId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new BankId(repoId) : null;
}
public static Optional<BankId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
int repoId;
private BankId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_Bank_ID"); | }
@JsonValue
@Override
public int getRepoId()
{
return repoId;
}
public static int toRepoId(@Nullable final BankId id)
{
return id != null ? id.getRepoId() : -1;
}
public static int optionalToRepoId(@NonNull final Optional<BankId> idOpt)
{
return idOpt.map(BankId::getRepoId).orElse(-1);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\banking\BankId.java | 2 |
请完成以下Java代码 | public static WorkflowLaunchersFacetId fromJson(@Nullable final String json)
{
final String jsonNorm = StringUtils.trimBlankToNull(json);
if (jsonNorm == null)
{
return null;
}
final int idx = jsonNorm.indexOf(SEPARATOR);
if (idx <= 0)
{
throw new AdempiereException("Canont convert JSON `" + jsonNorm + "` to " + WorkflowLaunchersFacetId.class);
}
final String groupIdPart = json.substring(0, idx);
final String facetIdPart = json.substring(idx + SEPARATOR.length());
if (facetIdPart.isEmpty())
{
throw new AdempiereException("Canont convert JSON `" + jsonNorm + "` to " + WorkflowLaunchersFacetId.class);
}
final WorkflowLaunchersFacetGroupId groupId = WorkflowLaunchersFacetGroupId.ofString(groupIdPart);
return new WorkflowLaunchersFacetId(groupId, facetIdPart);
}
public static WorkflowLaunchersFacetId ofString(@NonNull final WorkflowLaunchersFacetGroupId groupId, @NonNull final String string)
{
return new WorkflowLaunchersFacetId(groupId, string);
}
public static WorkflowLaunchersFacetId ofId(@NonNull final WorkflowLaunchersFacetGroupId groupId, @NonNull final RepoIdAware id)
{
return ofString(groupId, String.valueOf(id.getRepoId()));
}
public static WorkflowLaunchersFacetId ofLocalDate(@NonNull final WorkflowLaunchersFacetGroupId groupId, @NonNull final LocalDate localDate)
{
return ofString(groupId, localDate.toString());
}
// NOTE: Quantity class is not accessible from this project :(
public static WorkflowLaunchersFacetId ofQuantity(@NonNull final WorkflowLaunchersFacetGroupId groupId, @NonNull final BigDecimal value, @NonNull final RepoIdAware uomId)
{
return ofString(groupId, value + QTY_SEPARATOR + uomId.getRepoId());
}
@Override
@Deprecated
public String toString() {return toJsonString();}
@JsonValue
@NonNull
public String toJsonString() {return groupId.getAsString() + SEPARATOR + value;}
@NonNull
public <T extends RepoIdAware> T getAsId(@NonNull final Class<T> type) {return RepoIdAwares.ofObject(value, type);}
@NonNull
public LocalDate getAsLocalDate() {return LocalDate.parse(value);} | // NOTE: Quantity class is not accessible from this project :(
@NonNull
public ImmutablePair<BigDecimal, Integer> getAsQuantity()
{
try
{
final List<String> parts = Splitter.on(QTY_SEPARATOR).splitToList(value);
if (parts.size() != 2)
{
throw new AdempiereException("Cannot get Quantity from " + this);
}
return ImmutablePair.of(new BigDecimal(parts.get(0)), Integer.parseInt(parts.get(1)));
}
catch (AdempiereException ex)
{
throw ex;
}
catch (final Exception ex)
{
throw new AdempiereException("Cannot get Quantity from " + this, ex);
}
}
@NonNull
public String getAsString() {return value;}
@NonNull
public <T> T deserializeTo(@NonNull final Class<T> targetClass)
{
return JSONObjectMapper.forClass(targetClass).readValue(value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\rest_workflows\facets\WorkflowLaunchersFacetId.java | 1 |
请完成以下Java代码 | public void onTermination(CmmnActivityExecution execution) {
ensureTransitionAllowed(execution, AVAILABLE, TERMINATED, "terminate");
performTerminate(execution);
}
public void onParentTermination(CmmnActivityExecution execution) {
if (execution.isCompleted()) {
String id = execution.getId();
throw LOG.executionAlreadyCompletedException("parentTerminate", id);
}
performParentTerminate(execution);
}
public void onExit(CmmnActivityExecution execution) {
throw createIllegalStateTransitionException("exit", execution);
}
// occur /////////////////////////////////////////////////////////////////
public void onOccur(CmmnActivityExecution execution) {
ensureTransitionAllowed(execution, AVAILABLE, COMPLETED, "occur");
}
// suspension ////////////////////////////////////////////////////////////
public void onSuspension(CmmnActivityExecution execution) {
ensureTransitionAllowed(execution, AVAILABLE, SUSPENDED, "suspend");
performSuspension(execution);
}
public void onParentSuspension(CmmnActivityExecution execution) {
throw createIllegalStateTransitionException("parentSuspend", execution);
}
// resume ////////////////////////////////////////////////////////////////
public void onResume(CmmnActivityExecution execution) {
ensureTransitionAllowed(execution, SUSPENDED, AVAILABLE, "resume");
CmmnActivityExecution parent = execution.getParent();
if (parent != null) {
if (!parent.isActive()) {
String id = execution.getId();
throw LOG.resumeInactiveCaseException("resume", id);
}
}
resuming(execution);
} | public void onParentResume(CmmnActivityExecution execution) {
throw createIllegalStateTransitionException("parentResume", execution);
}
// re-activation ////////////////////////////////////////////////////////
public void onReactivation(CmmnActivityExecution execution) {
throw createIllegalStateTransitionException("reactivate", execution);
}
// sentry ///////////////////////////////////////////////////////////////
protected boolean isAtLeastOneExitCriterionSatisfied(CmmnActivityExecution execution) {
return false;
}
public void fireExitCriteria(CmmnActivityExecution execution) {
throw LOG.criteriaNotAllowedForEventListenerOrMilestonesException("exit", execution.getId());
}
// helper ////////////////////////////////////////////////////////////////
protected CaseIllegalStateTransitionException createIllegalStateTransitionException(String transition, CmmnActivityExecution execution) {
String id = execution.getId();
return LOG.illegalStateTransitionException(transition, id, getTypeName());
}
protected abstract String getTypeName();
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\EventListenerOrMilestoneActivityBehavior.java | 1 |
请完成以下Java代码 | public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Bewegungs-Menge.
@param MovementQty
Menge eines bewegten Produktes.
*/
@Override
public void setMovementQty (java.math.BigDecimal MovementQty)
{
set_Value (COLUMNNAME_MovementQty, MovementQty);
}
/** Get Bewegungs-Menge.
@return Menge eines bewegten Produktes.
*/
@Override
public java.math.BigDecimal getMovementQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MovementQty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Einzelpreis.
@param PriceActual
Effektiver Preis
*/ | @Override
public void setPriceActual (java.math.BigDecimal PriceActual)
{
set_Value (COLUMNNAME_PriceActual, PriceActual);
}
/** Get Einzelpreis.
@return Effektiver Preis
*/
@Override
public java.math.BigDecimal getPriceActual ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceActual);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InOutLine_To_C_Customs_Invoice_Line.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void deleteHistoricIdentityLinksByScopeIdAndScopeType(String scopeId, String scopeType) {
dataManager.deleteHistoricIdentityLinksByScopeIdAndType(scopeId, scopeType);
}
@Override
public void deleteHistoricIdentityLinksByScopeDefinitionIdAndScopeType(String scopeDefinitionId, String scopeType) {
dataManager.deleteHistoricIdentityLinksByScopeDefinitionIdAndType(scopeDefinitionId, scopeType);
}
@Override
public void bulkDeleteHistoricIdentityLinksForProcessInstanceIds(Collection<String> processInstanceIds) {
dataManager.bulkDeleteHistoricIdentityLinksForProcessInstanceIds(processInstanceIds);
}
@Override
public void bulkDeleteHistoricIdentityLinksForTaskIds(Collection<String> taskIds) {
dataManager.bulkDeleteHistoricIdentityLinksForTaskIds(taskIds);
}
@Override | public void bulkDeleteHistoricIdentityLinksForScopeIdsAndScopeType(Collection<String> scopeIds, String scopeType) {
dataManager.bulkDeleteHistoricIdentityLinksForScopeIdsAndScopeType(scopeIds, scopeType);
}
@Override
public void deleteHistoricProcessIdentityLinksForNonExistingInstances() {
dataManager.deleteHistoricProcessIdentityLinksForNonExistingInstances();
}
@Override
public void deleteHistoricCaseIdentityLinksForNonExistingInstances() {
dataManager.deleteHistoricCaseIdentityLinksForNonExistingInstances();
}
@Override
public void deleteHistoricTaskIdentityLinksForNonExistingInstances() {
dataManager.deleteHistoricTaskIdentityLinksForNonExistingInstances();
}
} | repos\flowable-engine-main\modules\flowable-identitylink-service\src\main\java\org\flowable\identitylink\service\impl\persistence\entity\HistoricIdentityLinkEntityManagerImpl.java | 2 |
请完成以下Java代码 | public void setValue(Object value, ValueFields valueFields) {
try {
valueFields.setTextValue(objectMapper.writeValueAsString(value));
if (value != null) {
valueFields.setTextValue2(value.getClass().getName());
}
} catch (JsonProcessingException e) {
logger.error("Error writing json variable " + valueFields.getName(), e);
}
}
public boolean isAbleToStore(Object value) {
if (value == null) {
return true;
} | if (
JsonNode.class.isAssignableFrom(value.getClass()) ||
(objectMapper.canSerialize(value.getClass()) && serializePOJOsInVariablesToJson)
) {
try {
return objectMapper.writeValueAsString(value).length() <= maxLength;
} catch (JsonProcessingException e) {
logger.error("Error writing json variable of type " + value.getClass(), e);
}
}
return false;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\variable\JsonType.java | 1 |
请完成以下Java代码 | public TransactionSendResult sendMessageInTransaction(Integer id) {
// 创建 Demo07Message 消息
Message<Demo07Message> message = MessageBuilder.withPayload(new Demo07Message().setId(id))
.build();
// 发送事务消息
return rocketMQTemplate.sendMessageInTransaction(TX_PRODUCER_GROUP, Demo07Message.TOPIC, message,
id);
}
@RocketMQTransactionListener(txProducerGroup = TX_PRODUCER_GROUP)
public class TransactionListenerImpl implements RocketMQLocalTransactionListener {
private Logger logger = LoggerFactory.getLogger(getClass());
@Override | public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
// ... local transaction process, return rollback, commit or unknown
logger.info("[executeLocalTransaction][执行本地事务,消息:{} arg:{}]", msg, arg);
return RocketMQLocalTransactionState.UNKNOWN;
}
@Override
public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
// ... check transaction status and return rollback, commit or unknown
logger.info("[checkLocalTransaction][回查消息:{}]", msg);
return RocketMQLocalTransactionState.COMMIT;
}
}
} | repos\SpringBoot-Labs-master\lab-31\lab-31-rocketmq-demo\src\main\java\cn\iocoder\springboot\lab31\rocketmqdemo\producer\Demo07Producer.java | 1 |
请完成以下Java代码 | public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String name;
private Integer age;
public Person() {
super();
}
public Person(String id,String name, Integer age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
} | public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
} | repos\spring-boot-student-master\spring-boot-student-data-redis\src\main\java\com\xiaolyuh\entity\Person.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setPort(@Nullable Integer port) {
this.port = port;
}
public @Nullable InetAddress getAddress() {
return this.address;
}
public void setAddress(@Nullable InetAddress address) {
this.address = address;
}
public String getBasePath() {
return this.basePath;
}
public void setBasePath(String basePath) {
this.basePath = cleanBasePath(basePath);
}
public @Nullable Ssl getSsl() {
return this.ssl;
}
public void setSsl(@Nullable Ssl ssl) {
this.ssl = ssl;
}
@Contract("!null -> !null")
private @Nullable String cleanBasePath(@Nullable String basePath) { | String candidate = null;
if (StringUtils.hasLength(basePath)) {
candidate = basePath.strip();
}
if (StringUtils.hasText(candidate)) {
if (!candidate.startsWith("/")) {
candidate = "/" + candidate;
}
if (candidate.endsWith("/")) {
candidate = candidate.substring(0, candidate.length() - 1);
}
}
return candidate;
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\web\server\ManagementServerProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class BatchExecutor<T> {
private static final Logger logger = Logger.getLogger(BatchExecutor.class.getName());
@Value("${spring.jpa.properties.hibernate.jdbc.batch_size}")
private int batchSize;
private final EntityManagerFactory entityManagerFactory;
public BatchExecutor(EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
}
public <S extends T> void saveInBatch(Iterable<S> entities) {
if (entities == null) {
throw new IllegalArgumentException("The given Iterable of entities not be null!");
}
EntityManager entityManager = entityManagerFactory.createEntityManager();
EntityTransaction entityTransaction = entityManager.getTransaction();
try {
entityTransaction.begin();
int i = 0;
for (S entity : entities) {
if (i % batchSize == 0 && i > 0) {
logger.log(Level.INFO, | "Flushing the EntityManager containing {0} entities ...", batchSize);
entityTransaction.commit();
entityTransaction.begin();
entityManager.clear();
}
entityManager.persist(entity);
i++;
}
logger.log(Level.INFO,
"Flushing the remaining entities ...");
entityTransaction.commit();
} catch (RuntimeException e) {
if (entityTransaction.isActive()) {
entityTransaction.rollback();
}
throw e;
} finally {
entityManager.close();
}
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchInsertOrderBatchPerTransaction\src\main\java\com\bookstore\impl\BatchExecutor.java | 2 |
请完成以下Java代码 | public int getM_HU_PI_Attribute_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PI_Attribute_ID);
}
@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 setValueDate (final @Nullable java.sql.Timestamp ValueDate)
{
set_Value (COLUMNNAME_ValueDate, ValueDate);
}
@Override
public java.sql.Timestamp getValueDate()
{
return get_ValueAsTimestamp(COLUMNNAME_ValueDate);
}
@Override
public void setValueDateInitial (final @Nullable java.sql.Timestamp ValueDateInitial)
{
set_Value (COLUMNNAME_ValueDateInitial, ValueDateInitial);
}
@Override
public java.sql.Timestamp getValueDateInitial()
{
return get_ValueAsTimestamp(COLUMNNAME_ValueDateInitial);
}
@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.java | 1 |
请完成以下Java代码 | public static <T> CurrencyId getCommonCurrencyIdOfAll(
@NonNull final Function<T, CurrencyId> getCurrencyId,
@NonNull final String name,
@Nullable final T... objects)
{
if (objects == null || objects.length == 0)
{
throw new AdempiereException("No " + name + " provided");
}
else if (objects.length == 1 && objects[0] != null)
{
return getCurrencyId.apply(objects[0]);
}
else
{
CurrencyId commonCurrencyId = null;
for (final T object : objects)
{
if (object == null)
{
continue;
}
final CurrencyId currencyId = getCurrencyId.apply(object);
if (commonCurrencyId == null)
{
commonCurrencyId = currencyId;
}
else if (!CurrencyId.equals(commonCurrencyId, currencyId))
{
throw new AdempiereException("All given " + name + "(s) shall have the same currency: " + Arrays.asList(objects));
}
}
if (commonCurrencyId == null)
{
throw new AdempiereException("At least one non null " + name + " instance was expected: " + Arrays.asList(objects));
}
return commonCurrencyId;
} | }
@SafeVarargs
public static <T> void assertCurrencyMatching(
@NonNull final Function<T, CurrencyId> getCurrencyId,
@NonNull final String name,
@Nullable final T... objects)
{
if (objects == null || objects.length <= 1)
{
return;
}
CurrencyId expectedCurrencyId = null;
for (final T object : objects)
{
if (object == null)
{
continue;
}
final CurrencyId currencyId = getCurrencyId.apply(object);
if (expectedCurrencyId == null)
{
expectedCurrencyId = currencyId;
}
else if (!CurrencyId.equals(currencyId, expectedCurrencyId))
{
throw new AdempiereException("" + name + " has invalid currency: " + object + ". Expected: " + expectedCurrencyId);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\money\CurrencyId.java | 1 |
请完成以下Java代码 | public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public static class User {
private String username;
private String password;
private List<String> roles;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username; | }
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<String> getRoles() {
return roles;
}
public void setRoles(List<String> roles) {
this.roles = roles;
}
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-properties\src\main\java\com\baeldung\yamllist\pojo\ApplicationProps.java | 1 |
请完成以下Java代码 | private static Optional<AccountId> extractAccountId(@NonNull final I_M_Product_Category_Acct record, @NonNull final String acctColumnName)
{
final Integer validCombinationId = InterfaceWrapperHelper.getValueOrNull(record, acctColumnName);
return validCombinationId != null
? AccountId.optionalOfRepoId(validCombinationId)
: Optional.empty();
}
public Optional<ProductCategoryAccounts> getProductCategoryAccounts(
@NonNull final AcctSchemaId acctSchemaId,
@NonNull final ProductCategoryId productCategoryId)
{
return getProductCategoryAccountsCollection()
.getBy(productCategoryId, acctSchemaId);
}
@Override
public Optional<AccountId> getProductCategoryAccount(
@NonNull final AcctSchemaId acctSchemaId,
@NonNull final ProductCategoryId productCategoryId,
@NonNull final ProductAcctType acctType)
{
return getProductCategoryAccounts(acctSchemaId, productCategoryId)
.flatMap(productCategoryAcct -> productCategoryAcct.getAccountId(acctType));
}
@Value(staticConstructor = "of")
private static class ProductIdAndAcctSchemaId
{
@NonNull
ProductId productId;
@NonNull
AcctSchemaId acctSchemaId;
}
@Value(staticConstructor = "of")
private static class ProductCategoryIdAndAcctSchemaId
{
@NonNull
ProductCategoryId productCategoryId;
@NonNull
AcctSchemaId acctSchemaId; | }
@EqualsAndHashCode
@ToString
private static class ProductCategoryAccountsCollection
{
private final ImmutableMap<ProductCategoryIdAndAcctSchemaId, ProductCategoryAccounts> productCategoryAccts;
public ProductCategoryAccountsCollection(final List<ProductCategoryAccounts> productCategoryAccts)
{
this.productCategoryAccts = Maps.uniqueIndex(
productCategoryAccts,
productCategoryAcct -> ProductCategoryIdAndAcctSchemaId.of(productCategoryAcct.getProductCategoryId(), productCategoryAcct.getAcctSchemaId()));
}
public Optional<ProductCategoryAccounts> getBy(
@NonNull final ProductCategoryId productCategoryId,
@NonNull final AcctSchemaId acctSchemaId)
{
final ProductCategoryIdAndAcctSchemaId key = ProductCategoryIdAndAcctSchemaId.of(productCategoryId, acctSchemaId);
return Optional.ofNullable(productCategoryAccts.get(key));
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\api\impl\ProductAcctDAO.java | 1 |
请完成以下Java代码 | public String getDiagramResourceName() {
return diagramResourceName;
}
@Override
public boolean hasStartFormKey() {
return hasStartFormKey;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setDescription(String description) {
this.description = description;
}
@Override
public void setCategory(String category) {
this.category = category;
}
@Override
public void setVersion(int version) {
this.version = version;
}
@Override
public void setKey(String key) {
this.key = key;
}
@Override
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
@Override
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@Override
public void setHasGraphicalNotation(boolean hasGraphicalNotation) {
this.isGraphicalNotationDefined = hasGraphicalNotation;
}
@Override
public void setDiagramResourceName(String diagramResourceName) {
this.diagramResourceName = diagramResourceName;
}
@Override
public void setHasStartFormKey(boolean hasStartFormKey) {
this.hasStartFormKey = hasStartFormKey; | }
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public List<IdentityLinkEntity> getIdentityLinks() {
if (!isIdentityLinksInitialized) {
definitionIdentityLinkEntities = CommandContextUtil.getCmmnEngineConfiguration().getIdentityLinkServiceConfiguration()
.getIdentityLinkService().findIdentityLinksByScopeDefinitionIdAndType(id, ScopeTypes.CMMN);
isIdentityLinksInitialized = true;
}
return definitionIdentityLinkEntities;
}
public String getLocalizedName() {
return localizedName;
}
@Override
public void setLocalizedName(String localizedName) {
this.localizedName = localizedName;
}
public String getLocalizedDescription() {
return localizedDescription;
}
@Override
public void setLocalizedDescription(String localizedDescription) {
this.localizedDescription = localizedDescription;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\CaseDefinitionEntityImpl.java | 1 |
请完成以下Java代码 | public class SpringBootProcessEngineLogger extends BaseLogger {
public static final String PROJECT_CODE = "STARTER";
public static final String PROJECT_ID = "SB";
public static final String PACKAGE = "org.camunda.bpm.spring.boot";
public static final SpringBootProcessEngineLogger LOG = createLogger(SpringBootProcessEngineLogger.class, PROJECT_CODE, PACKAGE, PROJECT_ID);
public void creatingInitialAdminUser(User adminUser) {
logDebug("010", "Creating initial Admin User: {}", adminUser);
}
public void skipAdminUserCreation(User existingUser) {
logDebug("011", "Skip creating initial Admin User, user does exist: {}", existingUser);
}
public void createInitialFilter(Filter filter) {
logInfo("015", "Create initial filter: id={} name={}", filter.getId(), filter.getName());
}
public void skipCreateInitialFilter(String filterName) {
logInfo("016",
"Skip initial filter creation, the filter with this name already exists: {}",
filterName);
}
public void skipAutoDeployment() {
logInfo("020", "ProcessApplication enabled: autoDeployment via springConfiguration#deploymentResourcePattern is disabled");
}
public void autoDeployResources(Set<Resource> resources) {
// Only log the description of `Resource` objects since log libraries that serialize them and
// therefore consume the input stream make the deployment fail since the input stream has
// already been consumed.
Set<String> resourceDescriptions = resources.stream()
.filter(Objects::nonNull)
.map(Resource::getDescription)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
logInfo("021", "Auto-Deploying resources: {}", resourceDescriptions); | }
public void enterLicenseKey(String licenseKeySource) {
logInfo("030", "Setting up license key: {}", licenseKeySource);
}
public void enterLicenseKeyFailed(URL licenseKeyFile, Exception e) {
logWarn("031", "Failed setting up license key: {}", licenseKeyFile, e);
}
public void configureJobExecutorPool(Integer corePoolSize, Integer maxPoolSize) {
logInfo("040", "Setting up jobExecutor with corePoolSize={}, maxPoolSize:{}", corePoolSize, maxPoolSize);
}
public SpringBootStarterException exceptionDuringBinding(String message) {
return new SpringBootStarterException(exceptionMessage(
"050", message));
}
public void propertiesApplied(GenericProperties genericProperties) {
logDebug("051", "Properties bound to configuration: {}", genericProperties);
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\util\SpringBootProcessEngineLogger.java | 1 |
请完成以下Java代码 | public MigrationInstructionBuilder mapActivities(String sourceActivityId, String targetActivityId) {
this.explicitMigrationInstructions.add(
new MigrationInstructionImpl(sourceActivityId, targetActivityId)
);
return this;
}
public MigrationInstructionBuilder updateEventTrigger() {
explicitMigrationInstructions
.get(explicitMigrationInstructions.size() - 1)
.setUpdateEventTrigger(true);
return this;
}
public MigrationInstructionsBuilder updateEventTriggers() {
this.updateEventTriggersForGeneratedInstructions = true;
return this;
}
public String getSourceProcessDefinitionId() {
return sourceProcessDefinitionId;
}
public String getTargetProcessDefinitionId() {
return targetProcessDefinitionId;
}
public boolean isMapEqualActivities() {
return mapEqualActivities;
}
public VariableMap getVariables() { | return variables;
}
public boolean isUpdateEventTriggersForGeneratedInstructions() {
return updateEventTriggersForGeneratedInstructions;
}
public List<MigrationInstructionImpl> getExplicitMigrationInstructions() {
return explicitMigrationInstructions;
}
public MigrationPlan build() {
return commandExecutor.execute(new CreateMigrationPlanCmd(this));
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\MigrationPlanBuilderImpl.java | 1 |
请完成以下Java代码 | public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getNickname() { | return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getRegTime() {
return regTime;
}
public void setRegTime(String regTime) {
this.regTime = regTime;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
", nickname='" + nickname + '\'' +
", regTime='" + regTime + '\'' +
'}';
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 4-2 课:Spring Boot 和 Redis 常用操作\spring-boot-redis\src\main\java\com\neo\model\User.java | 1 |
请完成以下Java代码 | public boolean open(String arg)
{
return open(arg.split(" ", -1));
}
private static class Option
{
@Argument(description = "set FILE for model file", alias = "m", required = true)
String model;
@Argument(description = "output n-best results", alias = "n")
Integer nbest = 0;
@Argument(description = "set INT for verbose level", alias = "v")
Integer verbose = 0;
@Argument(description = "set cost factor", alias = "c")
Double cost_factor = 1.0;
}
public boolean open(String[] args)
{
Option cmd = new Option();
try
{
Args.parse(cmd, args);
}
catch (IllegalArgumentException e)
{
System.err.println("invalid arguments");
return false;
}
String model = cmd.model;
int nbest = cmd.nbest;
int vlevel = cmd.verbose;
double costFactor = cmd.cost_factor;
return open(model, nbest, vlevel, costFactor);
}
public boolean open(InputStream stream, int nbest, int vlevel, double costFactor)
{
featureIndex_ = new DecoderFeatureIndex();
nbest_ = nbest;
vlevel_ = vlevel;
if (costFactor > 0)
{
featureIndex_.setCostFactor_(costFactor);
}
return featureIndex_.open(stream);
}
public boolean open(String model, int nbest, int vlevel, double costFactor)
{
try
{
InputStream stream = IOUtil.newInputStream(model);
return open(stream, nbest, vlevel, costFactor);
}
catch (Exception e) | {
return false;
}
}
public String getTemplate()
{
if (featureIndex_ != null)
{
return featureIndex_.getTemplate();
}
else
{
return null;
}
}
public int getNbest_()
{
return nbest_;
}
public void setNbest_(int nbest_)
{
this.nbest_ = nbest_;
}
public int getVlevel_()
{
return vlevel_;
}
public void setVlevel_(int vlevel_)
{
this.vlevel_ = vlevel_;
}
public DecoderFeatureIndex getFeatureIndex_()
{
return featureIndex_;
}
public void setFeatureIndex_(DecoderFeatureIndex featureIndex_)
{
this.featureIndex_ = featureIndex_;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\ModelImpl.java | 1 |
请完成以下Java代码 | protected List<RelatedProcessDescriptor> getAdditionalProcessDescriptors()
{
return ImmutableList.of();
}
private final PurchaseRowsSupplier createRowsSupplier(
final ViewId viewId,
final List<PurchaseDemandWithCandidates> purchaseDemandWithCandidatesList)
{
final PurchaseRowsSupplier rowsSupplier = PurchaseRowsLoader.builder()
.purchaseDemandWithCandidatesList(purchaseDemandWithCandidatesList)
.viewSupplier(() -> getByIdOrNull(viewId)) // needed for async stuff
.purchaseRowFactory(purchaseRowFactory)
.availabilityCheckService(availabilityCheckService)
.build() | .createPurchaseRowsSupplier();
return rowsSupplier;
}
protected final RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass)
{
final AdProcessId processId = adProcessRepo.retrieveProcessIdByClassIfUnique(processClass);
Preconditions.checkArgument(processId != null, "No AD_Process_ID found for %s", processClass);
return RelatedProcessDescriptor.builder()
.processId(processId)
.displayPlace(DisplayPlace.ViewQuickActions)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseViewFactoryTemplate.java | 1 |
请完成以下Java代码 | public MFColor toFlatColor()
{
switch (getType())
{
case FLAT:
return this;
case GRADIENT:
return ofFlatColor(getGradientUpperColor());
case LINES:
return ofFlatColor(getLineBackColor());
case TEXTURE:
return ofFlatColor(getTextureTaintColor());
default:
throw new IllegalStateException("Type not supported: " + getType());
}
} | public String toHexString()
{
final Color awtColor = toFlatColor().getFlatColor();
return toHexString(awtColor.getRed(), awtColor.getGreen(), awtColor.getBlue());
}
public static String toHexString(final int red, final int green, final int blue)
{
Check.assume(red >= 0 && red <= 255, "Invalid red value: {}", red);
Check.assume(green >= 0 && green <= 255, "Invalid green value: {}", green);
Check.assume(blue >= 0 && blue <= 255, "Invalid blue value: {}", blue);
return String.format("#%02x%02x%02x", red, green, blue);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\util\MFColor.java | 1 |
请完成以下Java代码 | public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Note.
@param Note
Optional additional user defined information
*/
public void setNote (String Note)
{
set_Value (COLUMNNAME_Note, Note);
}
/** Get Note.
@return Optional additional user defined information
*/
public String getNote ()
{
return (String)get_Value(COLUMNNAME_Note);
}
/** Set Achievement.
@param PA_Achievement_ID
Performance Achievement
*/
public void setPA_Achievement_ID (int PA_Achievement_ID)
{
if (PA_Achievement_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_Achievement_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_Achievement_ID, Integer.valueOf(PA_Achievement_ID));
}
/** Get Achievement.
@return Performance Achievement
*/
public int getPA_Achievement_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Achievement_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_PA_Measure getPA_Measure() throws RuntimeException
{
return (I_PA_Measure)MTable.get(getCtx(), I_PA_Measure.Table_Name)
.getPO(getPA_Measure_ID(), get_TrxName()); } | /** Set Measure.
@param PA_Measure_ID
Concrete Performance Measurement
*/
public void setPA_Measure_ID (int PA_Measure_ID)
{
if (PA_Measure_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_Measure_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_Measure_ID, Integer.valueOf(PA_Measure_ID));
}
/** Get Measure.
@return Concrete Performance Measurement
*/
public int getPA_Measure_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Measure_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_Achievement.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
bean.setOrder(0);
return bean;
}
@Bean
@Description("Thymeleaf template resolver serving HTML 5")
public ITemplateResolver templateResolver() {
final SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML");
return templateResolver;
}
@Bean
@Description("Thymeleaf template engine with Spring integration")
public SpringTemplateEngine templateEngine() {
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}
@Bean
@Description("Spring message resolver")
public MessageSource messageSource() {
final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
@Override
public void extendMessageConverters(final List<HttpMessageConverter<?>> converters) {
converters.add(byteArrayHttpMessageConverter());
}
@Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() { | final ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
arrayHttpMessageConverter.setSupportedMediaTypes(getSupportedMediaTypes());
return arrayHttpMessageConverter;
}
private List<MediaType> getSupportedMediaTypes() {
final List<MediaType> list = new ArrayList<MediaType>();
list.add(MediaType.IMAGE_JPEG);
list.add(MediaType.IMAGE_PNG);
list.add(MediaType.APPLICATION_OCTET_STREAM);
return list;
}
@Override
public void configurePathMatch(final PathMatchConfigurer configurer) {
final UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
@Bean(name = "multipartResolver")
public StandardServletMultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-java\src\main\java\com\baeldung\spring\web\config\WebConfig.java | 2 |
请完成以下Java代码 | public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public boolean isActive() {
return state == ACTIVE.getStateCode();
}
public boolean isCompleted() {
return state == COMPLETED.getStateCode();
}
public boolean isTerminated() {
return state == TERMINATED.getStateCode();
}
public boolean isFailed() {
return state == FAILED.getStateCode();
}
public boolean isSuspended() {
return state == SUSPENDED.getStateCode();
}
public boolean isClosed() {
return state == CLOSED.getStateCode(); | }
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[businessKey=" + businessKey
+ ", startUserId=" + createUserId
+ ", superCaseInstanceId=" + superCaseInstanceId
+ ", superProcessInstanceId=" + superProcessInstanceId
+ ", durationInMillis=" + durationInMillis
+ ", createTime=" + startTime
+ ", closeTime=" + endTime
+ ", id=" + id
+ ", eventType=" + eventType
+ ", caseExecutionId=" + caseExecutionId
+ ", caseDefinitionId=" + caseDefinitionId
+ ", caseInstanceId=" + caseInstanceId
+ ", tenantId=" + tenantId
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricCaseInstanceEventEntity.java | 1 |
请完成以下Java代码 | public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public String getEmail() {
return email;
} | public void setEmail(String email) {
this.email = email;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getRegTime() {
return regTime;
}
public void setRegTime(String regTime) {
this.regTime = regTime;
}
} | repos\spring-boot-leaning-master\1.x\第04课:Spring Data Jpa 的使用\spring-boot-Jpa\src\main\java\com\neo\domain\User.java | 1 |
请完成以下Java代码 | public class FastDFSFile {
private String name;
private byte[] content;
private String ext;
private String md5;
private String author;
public FastDFSFile(String name, byte[] content, String ext, String height,
String width, String author) {
super();
this.name = name;
this.content = content;
this.ext = ext;
this.author = author;
}
public FastDFSFile(String name, byte[] content, String ext) {
super();
this.name = name;
this.content = content;
this.ext = ext;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} | public byte[] getContent() {
return content;
}
public void setContent(byte[] content) {
this.content = content;
}
public String getExt() {
return ext;
}
public void setExt(String ext) {
this.ext = ext;
}
public String getMd5() {
return md5;
}
public void setMd5(String md5) {
this.md5 = md5;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 2-7 课:使用 Spring Boot 上传文件到 FastDFS\spring-boot-fastDFS\src\main\java\com\neo\fastdfs\FastDFSFile.java | 1 |
请完成以下Java代码 | class StatementLine
{
protected String routingNo = null;
protected String bankAccountNo = null;
protected String statementReference = null;
protected Timestamp statementLineDate = null;
protected String reference = null;
protected Timestamp valutaDate;
protected String trxType = null;
protected boolean isReversal = false;
protected String currency = null;
protected BigDecimal stmtAmt = null;
protected String memo = null;
protected String chargeName = null;
protected BigDecimal chargeAmt = null;
protected String payeeAccountNo = null;
protected String payeeName = null; | protected String trxID = null;
protected String checkNo = null;
/**
* Constructor for StatementLine
* @param RoutingNo String
* @param BankAccountNo String
* @param Currency String
*/
public StatementLine(String RoutingNo, String BankAccountNo, String Currency)
{
bankAccountNo = BankAccountNo;
routingNo = RoutingNo;
currency = Currency;
}
}
} //OFXBankStatementHandler | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-legacy\org\compiere\impexp\OFXBankStatementHandler.java | 1 |
请完成以下Java代码 | default boolean isAccountNonExpired() {
return true;
}
/**
* Indicates whether the user is locked or unlocked. A locked user cannot be
* authenticated.
* @return <code>true</code> if the user is not locked, <code>false</code> otherwise
*/
default boolean isAccountNonLocked() {
return true;
}
/**
* Indicates whether the user's credentials (password) has expired. Expired
* credentials prevent authentication. | * @return <code>true</code> if the user's credentials are valid (ie non-expired),
* <code>false</code> if no longer valid (ie expired)
*/
default boolean isCredentialsNonExpired() {
return true;
}
/**
* Indicates whether the user is enabled or disabled. A disabled user cannot be
* authenticated.
* @return <code>true</code> if the user is enabled, <code>false</code> otherwise
*/
default boolean isEnabled() {
return true;
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\core\userdetails\UserDetails.java | 1 |
请完成以下Java代码 | public StartTrigger getTimerStart() {
return timerStartChild.getChild(this);
}
public void setTimerStart(StartTrigger timerStart) {
timerStartChild.setChild(this, timerStart);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(TimerEventListener.class, CMMN_ELEMENT_TIMER_EVENT_LISTENER)
.namespaceUri(CMMN11_NS)
.extendsType(EventListener.class)
.instanceProvider(new ModelTypeInstanceProvider<TimerEventListener>() {
public TimerEventListener newInstance(ModelTypeInstanceContext instanceContext) {
return new TimerEventListenerImpl(instanceContext); | }
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
timerExpressionChild = sequenceBuilder.element(TimerExpression.class)
.build();
timerStartChild = sequenceBuilder.element(StartTrigger.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\TimerEventListenerImpl.java | 1 |
请完成以下Java代码 | public TokenQuery tokenData(String tokenData) {
if (tokenData == null) {
throw new FlowableIllegalArgumentException("Provided token data is null");
}
this.tokenData = tokenData;
return this;
}
@Override
public TokenQuery tokenDataLike(String tokenDataLike) {
if (tokenDataLike == null) {
throw new FlowableIllegalArgumentException("Provided tokenDataLike is null");
}
this.tokenDataLike = tokenDataLike;
return this;
}
// sorting //////////////////////////////////////////////////////////
@Override
public TokenQuery orderByTokenId() {
return orderBy(TokenQueryProperty.TOKEN_ID);
}
@Override
public TokenQuery orderByTokenDate() {
return orderBy(TokenQueryProperty.TOKEN_DATE);
}
// results //////////////////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
return CommandContextUtil.getTokenEntityManager(commandContext).findTokenCountByQueryCriteria(this);
}
@Override
public List<Token> executeList(CommandContext commandContext) {
return CommandContextUtil.getTokenEntityManager(commandContext).findTokenByQueryCriteria(this);
}
// getters //////////////////////////////////////////////////////////
@Override
public String getId() {
return id;
}
public List<String> getIds() {
return ids;
} | public String getTokenValue() {
return tokenValue;
}
public Date getTokenDate() {
return tokenDate;
}
public Date getTokenDateBefore() {
return tokenDateBefore;
}
public Date getTokenDateAfter() {
return tokenDateAfter;
}
public String getIpAddress() {
return ipAddress;
}
public String getIpAddressLike() {
return ipAddressLike;
}
public String getUserAgent() {
return userAgent;
}
public String getUserAgentLike() {
return userAgentLike;
}
public String getUserId() {
return userId;
}
public String getUserIdLike() {
return userIdLike;
}
public String getTokenData() {
return tokenData;
}
public String getTokenDataLike() {
return tokenDataLike;
}
} | repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\TokenQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserService {
private static final String DUPLICATE_ACCOUNT_ERROR = "EMAIL_EXISTS";
private final FirebaseAuth firebaseAuth;
private final AuthenticatedUserIdProvider authenticatedUserIdProvider;
public UserService(FirebaseAuth firebaseAuth, AuthenticatedUserIdProvider authenticatedUserIdProvider) {
this.firebaseAuth = firebaseAuth;
this.authenticatedUserIdProvider = authenticatedUserIdProvider;
}
public void create(String emailId, String password) throws FirebaseAuthException {
CreateRequest request = new CreateRequest();
request.setEmail(emailId);
request.setPassword(password);
request.setEmailVerified(Boolean.TRUE);
try {
firebaseAuth.createUser(request);
} catch (FirebaseAuthException exception) {
if (exception.getMessage().contains(DUPLICATE_ACCOUNT_ERROR)) {
throw new AccountAlreadyExistsException("Account with given email-id already exists"); | }
throw exception;
}
}
public void logout() throws FirebaseAuthException {
String userId = authenticatedUserIdProvider.getUserId();
firebaseAuth.revokeRefreshTokens(userId);
}
public UserRecord retrieve() throws FirebaseAuthException {
String userId = authenticatedUserIdProvider.getUserId();
return firebaseAuth.getUser(userId);
}
} | repos\tutorials-master\gcp-firebase\src\main\java\com\baeldung\gcp\firebase\auth\UserService.java | 2 |
请完成以下Java代码 | public int countUnreadByDeliveryMethodAndRecipientId(TenantId tenantId, NotificationDeliveryMethod deliveryMethod, UserId recipientId) {
return notificationRepository.countByDeliveryMethodAndRecipientIdAndStatusNot(deliveryMethod, recipientId.getId(), NotificationStatus.READ);
}
@Override
public boolean deleteByIdAndRecipientId(TenantId tenantId, UserId recipientId, NotificationId notificationId) {
return notificationRepository.deleteByIdAndRecipientId(notificationId.getId(), recipientId.getId()) != 0;
}
@Override
public int updateStatusByDeliveryMethodAndRecipientId(TenantId tenantId, NotificationDeliveryMethod deliveryMethod, UserId recipientId, NotificationStatus status) {
return notificationRepository.updateStatusByDeliveryMethodAndRecipientIdAndStatusNot(deliveryMethod, recipientId.getId(), status);
}
@Override
public void deleteByRequestId(TenantId tenantId, NotificationRequestId requestId) {
notificationRepository.deleteByRequestId(requestId.getId());
}
@Override
public void deleteByRecipientId(TenantId tenantId, UserId recipientId) {
notificationRepository.deleteByRecipientId(recipientId.getId());
}
@Override
public void createPartition(NotificationEntity entity) {
partitioningRepository.createPartitionIfNotExists(ModelConstants.NOTIFICATION_TABLE_NAME, | entity.getCreatedTime(), TimeUnit.HOURS.toMillis(partitionSizeInHours));
}
@Override
protected Class<NotificationEntity> getEntityClass() {
return NotificationEntity.class;
}
@Override
protected JpaRepository<NotificationEntity, UUID> getRepository() {
return notificationRepository;
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\notification\JpaNotificationDao.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SerialLetterService
{
private final static transient Logger logger = LogManager.getLogger(SerialLetterService.class);
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final IPrintingQueueBL printingQueueBL = Services.get(IPrintingQueueBL.class);
private final ISessionBL sessionBL = Services.get(ISessionBL.class);
private final PrintOutputFacade printOutputFacade;
public SerialLetterService(@NonNull final PrintOutputFacade printOutputFacade)
{
this.printOutputFacade = printOutputFacade;
}
public void printAutomaticallyLetters(@NonNull final I_C_Async_Batch asyncBatch)
{
final List<IPrintingQueueSource> sources = createPrintingQueueSource(asyncBatch);
if (sources.isEmpty())
{
throw new AdempiereException("Nothing selected");
}
for (final IPrintingQueueSource source : sources)
{
source.setName("Print letter for C_Async_Batch_ID = " + asyncBatch.getC_Async_Batch_ID());
print(source, asyncBatch);
}
}
/**
* Create Printing queue source.
*
* Contains printing queues for the letters that belong to a specific <code>C_Async_Batch_ID</code>
*/
private List<IPrintingQueueSource> createPrintingQueueSource(@NonNull final I_C_Async_Batch asyncBatch)
{
final IQuery<I_C_Printing_Queue> query = queryBL.createQueryBuilder(I_C_Printing_Queue.class, Env.getCtx(), ITrx.TRXNAME_None) | .addOnlyActiveRecordsFilter()
.addOnlyContextClient()
.addEqualsFilter(I_C_Printing_Queue.COLUMN_C_Async_Batch_ID, asyncBatch.getC_Async_Batch_ID())
.addEqualsFilter(I_C_Printing_Queue.COLUMNNAME_Processed, false)
.create();
final PInstanceId pinstanceId = PInstanceId.ofRepoId(asyncBatch.getAD_PInstance_ID());
final int selectionLength = query.createSelection(pinstanceId);
if (selectionLength <= 0)
{
logger.info("Nothing to print!");
return Collections.emptyList();
}
final IPrintingQueueQuery printingQuery = printingQueueBL.createPrintingQueueQuery();
printingQuery.setFilterByProcessedQueueItems(false);
printingQuery.setOnlyAD_PInstance_ID(pinstanceId);
final Properties ctx = Env.getCtx();
// we need to make sure exists AD_Session_ID in context; if not, a new session will be created
sessionBL.getCurrentOrCreateNewSession(ctx);
return printingQueueBL.createPrintingQueueSources(ctx, printingQuery);
}
private void print(@NonNull final IPrintingQueueSource source, @NonNull final I_C_Async_Batch asyncBatch)
{
final ContextForAsyncProcessing printJobContext = ContextForAsyncProcessing.builder()
.adPInstanceId(PInstanceId.ofRepoIdOrNull(asyncBatch.getAD_PInstance_ID()))
.parentAsyncBatchId(asyncBatch.getC_Async_Batch_ID())
.build();
printOutputFacade.print(source, printJobContext);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\serialletter\src\main\java\de\metas\letter\service\SerialLetterService.java | 2 |
请完成以下Java代码 | public static Splash getSplash(final String text)
{
if (s_splash == null)
{
s_splash = new Splash(text);
}
else
{
s_splash.setText(text);
}
return s_splash;
} // getSplash
private static Splash s_splash = null;
/**************************************************************************
* Standard constructor
*
* @param text clear text
*/
public Splash(final String text)
{
super(Adempiere.getName());
message.setText(text);
try
{
jbInit();
}
catch (final Exception e)
{
System.out.println("Splash");
e.printStackTrace();
}
display();
} // Splash
private final Label message = new Label();
/**
* Static Init
*
* @throws Exception
*/
private void jbInit() throws Exception
{
final Color background = UIManager.getColor(MetasFreshTheme.KEY_Logo_BackgroundColor);
setBackground(background);
setName("splash");
setUndecorated(true);
final JPanel contentPanel = new JPanel();
contentPanel.setLayout(new BorderLayout());
contentPanel.setBackground(background);
// NOTE: set some border to not have the logo near the margin
contentPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
this.add(contentPanel);
//
message.setFont(UIManager.getFont(MetasFreshTheme.KEY_Logo_TextFont));
message.setForeground(UIManager.getColor(MetasFreshTheme.KEY_Logo_TextColor));
message.setAlignment(Label.CENTER);
//
// North: Product logo (if any)
final JLabel productLogo = new JLabel();
final Image productLogoImage = Adempiere.getProductLogoLarge();
if (productLogoImage != null)
{
productLogo.setIcon(new ImageIcon(productLogoImage));
contentPanel.add(productLogo, BorderLayout.NORTH);
}
//
// South: message
contentPanel.add(message, BorderLayout.SOUTH);
} // jbInit
/**
* Set Text (20 pt) and display the splash screen.
*
* @param text translated text to display
*/
public void setText(final String text)
{
message.setText(text);
display();
} // setText | /**
* Show Window
*
* @param visible true if visible
*/
@Override
public void setVisible(final boolean visible)
{
super.setVisible(visible);
if (visible)
{
toFront();
}
} // setVisible
/**
* Calculate size and display
*/
private void display()
{
pack();
final Dimension ss = Toolkit.getDefaultToolkit().getScreenSize();
final Rectangle bounds = getBounds();
setBounds((ss.width - bounds.width) / 2, (ss.height - bounds.height) / 2,
bounds.width, bounds.height);
setVisible(true);
} // display
/**
* Dispose Splash
*/
@Override
public void dispose()
{
super.dispose();
s_splash = null;
} // dispose
} // Splash | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Splash.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public abstract class User {
// ==============
// PRIVATE FIELDS
// ==============
// An autogenerated id (unique for each user in the db)
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
// The user email
@NotNull
private String email;
// ==============
// PUBLIC METHODS
// ==============
/**
* @return the id
*/
public long getId() {
return id;
} | /**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
} // class User | repos\spring-boot-samples-master\spring-boot-springdatajpa-inheritance\src\main\java\netgloo\models\User.java | 2 |
请完成以下Java代码 | public Integer getDelFlag() {
return delFlag;
}
public void setDelFlag(Integer delFlag) {
this.delFlag = delFlag;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getPerms() {
return perms;
}
public void setPerms(String perms) {
this.perms = perms;
}
public boolean getIsLeaf() {
return isLeaf;
} | public void setIsLeaf(boolean isLeaf) {
this.isLeaf = isLeaf;
}
public String getPermsType() {
return permsType;
}
public void setPermsType(String permsType) {
this.permsType = permsType;
}
public java.lang.String getStatus() {
return status;
}
public void setStatus(java.lang.String status) {
this.status = status;
}
/*update_begin author:wuxianquan date:20190908 for:get set方法 */
public boolean isInternalOrExternal() {
return internalOrExternal;
}
public void setInternalOrExternal(boolean internalOrExternal) {
this.internalOrExternal = internalOrExternal;
}
/*update_end author:wuxianquan date:20190908 for:get set 方法 */
public boolean isHideTab() {
return hideTab;
}
public void setHideTab(boolean hideTab) {
this.hideTab = hideTab;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\SysPermissionTree.java | 1 |
请完成以下Java代码 | public List<CacheInvalidateRequest> createRequestsFromModel(@NonNull final ICacheSourceModel sourceModel, final ModelCacheInvalidationTiming timing_NOTUSED)
{
final int linkId = sourceModel.getValueAsInt(sourceLinkColumnName, -1);
return getTargetRecordIdsByLinkId(linkId)
.stream()
.map(targetRecordId -> CacheInvalidateRequest.rootRecord(targetTableName, targetRecordId))
.collect(ImmutableList.toImmutableList());
}
private ImmutableSet<Integer> getTargetRecordIdsByLinkId(final int linkId)
{
if (linkId < 0)
{
return ImmutableSet.of();
}
if (isTargetLinkColumnSameAsKeyColumn)
{
return ImmutableSet.of(linkId);
}
final ImmutableSet.Builder<Integer> targetRecordIds = ImmutableSet.builder();
DB.forEachRow( | Check.assumeNotNull(this.sqlGetTargetRecordIdByLinkId, "sqlGetTargetRecordIdByLinkId shall not be null"),
ImmutableList.of(linkId),
rs -> {
final int targetRecordId = rs.getInt(1);
if (targetRecordId > 0)
{
targetRecordIds.add(targetRecordId);
}
});
return targetRecordIds.build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\ColumnSqlCacheInvalidateRequestFactories.java | 1 |
请完成以下Java代码 | public String toString() {
StringBuffer sb = new StringBuffer ("X_EXP_FormatLine[ID=").append(get_ID()).append("; Value="+getValue()+"; Type="+getType()+"]");
return sb.toString();
}
public static MEXPFormatLine getFormatLineByValue(Properties ctx, String value, int EXP_Format_ID, String trxName)
throws SQLException
{
MEXPFormatLine result = null;
StringBuffer sql = new StringBuffer("SELECT * ")
.append(" FROM ").append(X_EXP_FormatLine.Table_Name)
.append(" WHERE ").append(X_EXP_Format.COLUMNNAME_Value).append("=?")
//.append(" AND IsActive = ?")
//.append(" AND AD_Client_ID = ?")
.append(" AND ").append(X_EXP_Format.COLUMNNAME_EXP_Format_ID).append(" = ?")
;
PreparedStatement pstmt = null;
try {
pstmt = DB.prepareStatement (sql.toString(), trxName);
pstmt.setString(1, value);
pstmt.setInt(2, EXP_Format_ID);
ResultSet rs = pstmt.executeQuery ();
if ( rs.next() ) {
result = new MEXPFormatLine (ctx, rs, trxName);
}
rs.close ();
pstmt.close ();
pstmt = null;
} catch (SQLException e) {
s_log.error(sql.toString(), e);
throw e;
} finally {
try {
if (pstmt != null) pstmt.close ();
pstmt = null;
} catch (Exception e) { pstmt = null; }
} | return result;
}
@Override
protected boolean afterSave (boolean newRecord, boolean success)
{
if(!success)
{
return false;
}
CacheMgt.get().reset(I_EXP_Format.Table_Name);
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MEXPFormatLine.java | 1 |
请完成以下Java代码 | public static void increment() {
count++;
}
public static int getCount() {
return count;
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for(int index=0; index<MAX_LIMIT; index++) {
increment();
}
}
}); | Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for(int index=0; index<MAX_LIMIT; index++) {
increment();
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
LOG.info("value of counter variable: "+count);
}
} | repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-4\src\main\java\com\baeldung\volatilekeywordthreadsafety\VolatileVarNotThreadSafe.java | 1 |
请完成以下Java代码 | public class CamundaBpmRunAuthenticationProperties {
public static final String PREFIX = CamundaBpmRunProperties.PREFIX + ".auth";
public static final String DEFAULT_AUTH = "basic";
public static final List<String> AUTH_METHODS = Arrays.asList(DEFAULT_AUTH);
boolean enabled;
String authentication = DEFAULT_AUTH;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
} | public String getAuthentication() {
return authentication;
}
public void setAuthentication(String authentication) {
if (authentication != null && !AUTH_METHODS.contains(authentication)) {
throw new RuntimeException("Please provide a valid authentication method. The available ones are: " + AUTH_METHODS.toString());
}
this.authentication = authentication;
}
@Override
public String toString() {
return "CamundaBpmRunAuthenticationProperties [enabled=" + enabled + ", authentication=" + authentication + "]";
}
} | repos\camunda-bpm-platform-master\distro\run\core\src\main\java\org\camunda\bpm\run\property\CamundaBpmRunAuthenticationProperties.java | 1 |
请完成以下Java代码 | public String getContentId() {
return contentId;
}
@Override
public void setContentId(String contentId) {
this.contentId = contentId;
}
@Override
public ByteArrayEntity getContent() {
return content;
}
@Override
public void setContent(ByteArrayEntity content) {
this.content = content;
}
@Override
public void setUserId(String userId) {
this.userId = userId; | }
@Override
public String getUserId() {
return userId;
}
@Override
public Date getTime() {
return time;
}
@Override
public void setTime(Date time) {
this.time = time;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\AttachmentEntityImpl.java | 1 |
请完成以下Java代码 | public static LocatorQRCode ofGlobalQRCodeJsonString(final String json) {return LocatorQRCodeJsonConverter.fromGlobalQRCodeJsonString(json);}
public static LocatorQRCode ofGlobalQRCode(final GlobalQRCode globalQRCode) {return LocatorQRCodeJsonConverter.fromGlobalQRCode(globalQRCode);}
@JsonCreator
public static LocatorQRCode ofScannedCode(final ScannedCode scannedCode) {return LocatorQRCodeJsonConverter.fromGlobalQRCodeJsonString(scannedCode.getAsString());}
public static LocatorQRCode ofLocator(@NonNull final I_M_Locator locator)
{
return builder()
.locatorId(LocatorId.ofRepoId(locator.getM_Warehouse_ID(), locator.getM_Locator_ID()))
.caption(locator.getValue())
.build();
}
public PrintableQRCode toPrintableQRCode()
{
return PrintableQRCode.builder()
.qrCode(toGlobalQRCodeJsonString()) | .bottomText(caption)
.build();
}
public GlobalQRCode toGlobalQRCode()
{
return LocatorQRCodeJsonConverter.toGlobalQRCode(this);
}
public ScannedCode toScannedCode()
{
return ScannedCode.ofString(toGlobalQRCodeJsonString());
}
public static boolean isTypeMatching(@NonNull final GlobalQRCode globalQRCode)
{
return LocatorQRCodeJsonConverter.isTypeMatching(globalQRCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\qrcode\LocatorQRCode.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class ConfigurationMetadataHint {
private static final String KEY_SUFFIX = ".keys";
private static final String VALUE_SUFFIX = ".values";
private String id;
private final List<ValueHint> valueHints = new ArrayList<>();
private final List<ValueProvider> valueProviders = new ArrayList<>();
boolean isMapKeyHints() {
return (this.id != null && this.id.endsWith(KEY_SUFFIX));
}
boolean isMapValueHints() {
return (this.id != null && this.id.endsWith(VALUE_SUFFIX));
}
String resolveId() {
if (isMapKeyHints()) {
return this.id.substring(0, this.id.length() - KEY_SUFFIX.length());
}
if (isMapValueHints()) { | return this.id.substring(0, this.id.length() - VALUE_SUFFIX.length());
}
return this.id;
}
String getId() {
return this.id;
}
void setId(String id) {
this.id = id;
}
List<ValueHint> getValueHints() {
return this.valueHints;
}
List<ValueProvider> getValueProviders() {
return this.valueProviders;
}
} | repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-metadata\src\main\java\org\springframework\boot\configurationmetadata\ConfigurationMetadataHint.java | 2 |
请完成以下Java代码 | private void pollAndPublish()
{
if (onPollingEventsSupplier == null)
{
return;
}
try
{
final List<?> events = onPollingEventsSupplier.produceEvents();
if (events != null && !events.isEmpty())
{
for (final Object event : events)
{
websocketSender.convertAndSend(topicName, event); | logger.trace("Event sent to {}: {}", topicName, event);
}
}
else
{
logger.trace("Got no events from {}", onPollingEventsSupplier);
}
}
catch (final Exception ex)
{
logger.warn("Failed producing event for {}. Ignored.", this, ex);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\websocket\producers\WebSocketProducersRegistry.java | 1 |
请完成以下Java代码 | private void deleteAll() {
this.authorRepository.deleteAll();
long count = this.authorRepository.count();
System.out.printf("deleteAll(): count = %d%n", count);
}
private void queryFindByName() {
Author author1 = this.authorRepository.queryFindByName("Josh Long").orElse(null);
Author author2 = this.authorRepository.queryFindByName("Martin Kleppmann").orElse(null);
System.out.printf("queryFindByName(): author1 = %s%n", author1);
System.out.printf("queryFindByName(): author2 = %s%n", author2);
}
private void findByPartialName() {
Author author1 = this.authorRepository.findByNameContainingIgnoreCase("sh lo").orElse(null);
Author author2 = this.authorRepository.findByNameContainingIgnoreCase("in kl").orElse(null);
System.out.printf("findByPartialName(): author1 = %s%n", author1);
System.out.printf("findByPartialName(): author2 = %s%n", author2);
}
private void findById() {
Author author1 = this.authorRepository.findById(1L).orElse(null);
Author author2 = this.authorRepository.findById(2L).orElse(null);
System.out.printf("findById(): author1 = %s%n", author1); | System.out.printf("findById(): author2 = %s%n", author2);
}
private void listAllAuthors() {
List<Author> authors = this.authorRepository.findAll();
for (Author author : authors) {
System.out.printf("listAllAuthors(): author = %s%n", author);
for (Book book : author.getBooks()) {
System.out.printf("\t%s%n", book);
}
}
}
private void insertAuthors() {
Author author1 = this.authorRepository.save(new Author(null, "Josh Long",
Set.of(new Book(null, "Reactive Spring"), new Book(null, "Cloud Native Java"))));
Author author2 = this.authorRepository.save(
new Author(null, "Martin Kleppmann", Set.of(new Book(null, "Designing Data Intensive Applications"))));
System.out.printf("insertAuthors(): author1 = %s%n", author1);
System.out.printf("insertAuthors(): author2 = %s%n", author2);
}
} | repos\spring-data-examples-main\jdbc\graalvm-native\src\main\java\example\springdata\jdbc\graalvmnative\CLR.java | 1 |
请完成以下Java代码 | public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx)
{
final int countryId = evalCtx.get_ValueAsInt(I_C_Location.COLUMNNAME_C_Country_ID, -1);
if (countryId <= 0)
{
return LookupValuesPage.EMPTY;
}
//
// Determine what we will filter
final String filter = evalCtx.getFilter();
final boolean matchAll;
final String filterUC;
final int limit;
final int offset = evalCtx.getOffset(0);
if (filter == LookupDataSourceContext.FILTER_Any)
{
matchAll = true;
filterUC = null; // N/A
limit = evalCtx.getLimit(Integer.MAX_VALUE);
}
else if (Check.isEmpty(filter, true))
{
return LookupValuesPage.EMPTY;
}
else
{
matchAll = false;
filterUC = filter.trim().toUpperCase();
limit = evalCtx.getLimit(100);
}
//
// Get, filter, return
return getRegionLookupValues(countryId)
.getValues()
.stream()
.filter(region -> matchAll || matchesFilter(region, filterUC))
.collect(LookupValuesList.collect())
.pageByOffsetAndLimit(offset, limit);
}
private boolean matchesFilter(final LookupValue region, final String filterUC)
{
final String displayName = region.getDisplayName();
if (Check.isEmpty(displayName))
{
return false;
} | final String displayNameUC = displayName.trim().toUpperCase();
return displayNameUC.contains(filterUC);
}
private LookupValuesList getRegionLookupValues(final int countryId)
{
return regionsByCountryId.getOrLoad(countryId, () -> retrieveRegionLookupValues(countryId));
}
private LookupValuesList retrieveRegionLookupValues(final int countryId)
{
return Services.get(ICountryDAO.class)
.retrieveRegions(Env.getCtx(), countryId)
.stream()
.map(this::createLookupValue)
.collect(LookupValuesList.collect());
}
private IntegerLookupValue createLookupValue(final I_C_Region regionRecord)
{
return IntegerLookupValue.of(regionRecord.getC_Region_ID(), regionRecord.getName());
}
@Override
public Optional<WindowId> getZoomIntoWindowId()
{
return Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\address\AddressRegionLookupDescriptor.java | 1 |
请完成以下Java代码 | public void addChild(MigratingCompensationEventSubscriptionInstance migratingEventSubscription) {
this.childCompensationSubscriptionInstances.add(migratingEventSubscription);
}
@Override
public void removeChild(MigratingCompensationEventSubscriptionInstance migratingEventSubscription) {
this.childCompensationSubscriptionInstances.remove(migratingEventSubscription);
}
@Override
public boolean migrates() {
return targetScope != null;
}
@Override
public void detachChildren() {
Set<MigratingProcessElementInstance> childrenCopy = new HashSet<MigratingProcessElementInstance>(getChildren());
for (MigratingProcessElementInstance child : childrenCopy) {
child.detachState();
}
}
@Override
public void remove(boolean skipCustomListeners, boolean skipIoMappings) {
// never invokes listeners and io mappings because this does not remove an active
// activity instance
eventScopeExecution.remove(); | migratingEventSubscription.remove();
setParent(null);
}
@Override
public Collection<MigratingProcessElementInstance> getChildren() {
Set<MigratingProcessElementInstance> children = new HashSet<MigratingProcessElementInstance>(childInstances);
children.addAll(childCompensationSubscriptionInstances);
return children;
}
@Override
public Collection<MigratingScopeInstance> getChildScopeInstances() {
return new HashSet<MigratingScopeInstance>(childInstances);
}
@Override
public void removeUnmappedDependentInstances() {
}
public MigratingCompensationEventSubscriptionInstance getEventSubscription() {
return migratingEventSubscription;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingEventScopeInstance.java | 1 |
请完成以下Java代码 | public DocumentLocation withRenderedAddress(@NonNull final RenderedAddressAndCapturedLocation renderedAddress)
{
return toBuilder()
.locationId(renderedAddress.getCapturedLocationId())
.bpartnerAddress(renderedAddress.getRenderedAddress())
.build();
}
private DocumentLocation withoutRenderedAddress()
{
return bpartnerAddress != null
? toBuilder().bpartnerAddress(null).build()
: this;
}
public boolean equalsIgnoringRenderedAddress(@NonNull final DocumentLocation other)
{
return Objects.equals(this.withoutRenderedAddress(), other.withoutRenderedAddress());
}
public BPartnerLocationAndCaptureId toBPartnerLocationAndCaptureId() | {
if (bpartnerLocationId == null)
{
throw new AdempiereException("Cannot convert " + this + " to " + BPartnerLocationAndCaptureId.class.getSimpleName() + " because bpartnerLocationId is null");
}
return BPartnerLocationAndCaptureId.of(bpartnerLocationId, locationId);
}
public DocumentLocation withContactId(@Nullable final BPartnerContactId contactId)
{
return !Objects.equals(this.contactId, contactId)
? toBuilder().contactId(contactId).build()
: this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\location\DocumentLocation.java | 1 |
请完成以下Java代码 | public void setTemplateDefaults(AnnotationTemplateExpressionDefaults defaults) {
this.registry.setTemplateDefaults(defaults);
}
/**
* {@inheritDoc}
*/
@Override
public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
/**
* {@inheritDoc}
*/
@Override
public Pointcut getPointcut() {
return this.pointcut;
}
@Override
public Advice getAdvice() {
return this;
}
@Override
public boolean isPerInstance() {
return true;
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. | *
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy strategy) {
this.securityContextHolderStrategy = () -> strategy;
}
/**
* Filter a {@code returnedObject} using the {@link PostFilter} annotation that the
* {@link MethodInvocation} specifies.
* @param mi the {@link MethodInvocation} to check check
* @return filtered {@code returnedObject}
*/
@Override
public @Nullable Object invoke(MethodInvocation mi) throws Throwable {
Object returnedObject = mi.proceed();
ExpressionAttribute attribute = this.registry.getAttribute(mi);
if (attribute == null) {
return returnedObject;
}
MethodSecurityExpressionHandler expressionHandler = this.registry.getExpressionHandler();
EvaluationContext ctx = expressionHandler.createEvaluationContext(this::getAuthentication, mi);
return expressionHandler.filter(returnedObject, attribute.getExpression(), ctx);
}
private Authentication getAuthentication() {
Authentication authentication = this.securityContextHolderStrategy.get().getContext().getAuthentication();
if (authentication == null) {
throw new AuthenticationCredentialsNotFoundException(
"An Authentication object was not found in the SecurityContext");
}
return authentication;
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\PostFilterAuthorizationMethodInterceptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected String getJobByteArrayRefAsString(ByteArrayRef jobByteArrayRef) {
if (jobByteArrayRef == null) {
return null;
}
return jobByteArrayRef.asString(getEngineType());
}
protected String getEngineType() {
if (StringUtils.isNotEmpty(scopeType)) {
return scopeType;
} else {
return ScopeTypes.BPMN;
}
}
@Override | public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("HistoryJobEntity[").append("id=").append(id)
.append(", jobHandlerType=").append(jobHandlerType);
if (scopeType != null) {
sb.append(", scopeType=").append(scopeType);
}
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
sb.append("]");
return sb.toString();
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\HistoryJobEntityImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public PMESU1 getPMESU1() {
return pmesu1;
}
/**
* Sets the value of the pmesu1 property.
*
* @param value
* allowed object is
* {@link PMESU1 }
*
*/
public void setPMESU1(PMESU1 value) {
this.pmesu1 = value;
}
/**
* Gets the value of the phand1 property.
*
* @return
* possible object is
* {@link PHAND1 }
*
*/
public PHAND1 getPHAND1() {
return phand1;
}
/**
* Sets the value of the phand1 property.
*
* @param value
* allowed object is
* {@link PHAND1 }
*
*/
public void setPHAND1(PHAND1 value) {
this.phand1 = value;
}
/**
* Gets the value of the detail property.
*
* @return | * possible object is
* {@link DETAILXbest }
*
*/
public DETAILXbest getDETAIL() {
return detail;
}
/**
* Sets the value of the detail property.
*
* @param value
* allowed object is
* {@link DETAILXbest }
*
*/
public void setDETAIL(DETAILXbest value) {
this.detail = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_orders\de\metas\edi\esb\jaxb\stepcom\orders\PPACK1.java | 2 |
请完成以下Java代码 | public RetryTopicConfiguration findRetryConfigurationFor(String[] topics, Method method, Object bean) {
return findRetryConfigurationFor(topics, method, null, bean);
}
/**
* Find retry topic configuration.
* @param topics the retryable topic list.
* @param method the method that gets @RetryableTopic annotation.
* @param clazz the class that gets @RetryableTopic annotation.
* @param bean the bean.
* @return the retry topic configuration.
*/
@Nullable
public RetryTopicConfiguration findRetryConfigurationFor(String[] topics, @Nullable Method method,
@Nullable Class<?> clazz, Object bean) {
RetryableTopic annotation = getRetryableTopicAnnotationFromAnnotatedElement(
Objects.requireNonNullElse(method, clazz));
Class<?> declaringClass = method != null ? method.getDeclaringClass() : clazz;
Assert.state(declaringClass != null, "No declaring class found for " + method);
return annotation != null
? new RetryableTopicAnnotationProcessor(this.beanFactory, this.resolver, this.expressionContext)
.processAnnotation(topics, declaringClass, annotation, bean)
: maybeGetFromContext(topics);
} | @Nullable
private RetryableTopic getRetryableTopicAnnotationFromAnnotatedElement(AnnotatedElement element) {
return MergedAnnotations.from(element, SearchStrategy.TYPE_HIERARCHY,
RepeatableContainers.none())
.get(RetryableTopic.class)
.synthesize(MergedAnnotation::isPresent)
.orElse(null);
}
@Nullable
private RetryTopicConfiguration maybeGetFromContext(String[] topics) {
if (this.beanFactory == null || !ListableBeanFactory.class.isAssignableFrom(this.beanFactory.getClass())) {
LOGGER.warn("No ListableBeanFactory found, skipping RetryTopic configuration.");
return null;
}
Map<String, RetryTopicConfiguration> retryTopicProcessors = ((ListableBeanFactory) this.beanFactory)
.getBeansOfType(RetryTopicConfiguration.class);
return retryTopicProcessors
.values()
.stream()
.filter(topicConfiguration -> topicConfiguration.hasConfigurationForTopics(topics))
.findFirst()
.orElse(null);
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\annotation\RetryTopicConfigurationProvider.java | 1 |
请完成以下Java代码 | public class FailTrxItemExceptionHandler implements ITrxItemExceptionHandler
{
public static final FailTrxItemExceptionHandler instance = new FailTrxItemExceptionHandler();
protected FailTrxItemExceptionHandler()
{
super();
}
protected void fail(final Throwable e, final Object item)
{
throw AdempiereException.wrapIfNeeded(e);
}
@Override
public void onNewChunkError(final Throwable e, final Object item)
{
fail(e, item);
}
@Override
public void onItemError(final Throwable e, final Object item)
{
fail(e, item);
}
@Override
public void onCompleteChunkError(final Throwable e) | {
final Object item = null;
fail(e, item);
}
@Override
public void afterCompleteChunkError(final Throwable e)
{
// Nothing to do.
// This method will never be called because "onCompleteChunkError" method already threw exception.
}
@Override
public void onCommitChunkError(final Throwable e)
{
final Object item = null;
fail(e, item);
}
@Override
public void onCancelChunkError(final Throwable e)
{
final Object item = null;
fail(e, item);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\FailTrxItemExceptionHandler.java | 1 |
请完成以下Java代码 | public void collectRowsChanged(@NonNull final IView view, @NonNull final Collection<DocumentId> rowIds)
{
if (rowIds.isEmpty())
{
return;
}
viewChanges(view).addChangedRowIds(rowIds);
autoflushIfEnabled();
}
public void collectRowChanged(@NonNull final IView view, final DocumentId rowId)
{
collectRowChanged(view.getViewId(), rowId);
}
public void collectRowChanged(@NonNull final ViewId viewId, final DocumentId rowId)
{
viewChanges(viewId).addChangedRowId(rowId);
autoflushIfEnabled();
}
public void collectHeaderPropertiesChanged(@NonNull final IView view)
{
viewChanges(view).setHeaderPropertiesChanged();
autoflushIfEnabled();
}
public void collectHeaderPropertiesChanged(@NonNull final ViewId viewId)
{
viewChanges(viewId).setHeaderPropertiesChanged();
autoflushIfEnabled();
}
private void collectFromChanges(@NonNull final ViewChanges changes)
{
viewChanges(changes.getViewId()).collectFrom(changes);
autoflushIfEnabled();
}
@Nullable
private ViewChangesCollector getParentOrNull()
{
final ViewChangesCollector threadLocalCollector = getCurrentOrNull();
if (threadLocalCollector != null && threadLocalCollector != this)
{
return threadLocalCollector;
}
return null;
}
void flush()
{
final ImmutableList<ViewChanges> changesList = getAndClean();
if (changesList.isEmpty())
{
return;
}
//
// Try flushing to parent collector if any
final ViewChangesCollector parentCollector = getParentOrNull();
if (parentCollector != null)
{
logger.trace("Flushing {} to parent collector: {}", this, parentCollector);
changesList.forEach(parentCollector::collectFromChanges);
}
//
// Fallback: flush to websocket
else
{
logger.trace("Flushing {} to websocket", this);
final ImmutableList<JSONViewChanges> jsonChangeEvents = changesList.stream()
.filter(ViewChanges::hasChanges)
.map(JSONViewChanges::of)
.collect(ImmutableList.toImmutableList()); | sendToWebsocket(jsonChangeEvents);
}
}
private void autoflushIfEnabled()
{
if (!autoflush)
{
return;
}
flush();
}
private ImmutableList<ViewChanges> getAndClean()
{
if (viewChangesMap.isEmpty())
{
return ImmutableList.of();
}
final ImmutableList<ViewChanges> changesList = ImmutableList.copyOf(viewChangesMap.values());
viewChangesMap.clear();
return changesList;
}
private void sendToWebsocket(@NonNull final List<JSONViewChanges> jsonChangeEvents)
{
if (jsonChangeEvents.isEmpty())
{
return;
}
WebsocketSender websocketSender = _websocketSender;
if (websocketSender == null)
{
websocketSender = this._websocketSender = SpringContextHolder.instance.getBean(WebsocketSender.class);
}
try
{
websocketSender.convertAndSend(jsonChangeEvents);
logger.debug("Sent to websocket: {}", jsonChangeEvents);
}
catch (final Exception ex)
{
logger.warn("Failed sending to websocket {}: {}", jsonChangeEvents, ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\event\ViewChangesCollector.java | 1 |
请完成以下Java代码 | public void save(final Properties ctx, final int windowNo, final IInfoWindowGridRowBuilders builders)
{
for (final IHUPackingAware record : packingInfos.values())
{
// We need to create a key that depends on both the product and the PIIP.
// Note that we assume that both columns are read-only and therefore won't change!
// Keep in sync with the other controllers in this package!
// It's 1:17am, it has to be rolled out tomorrow and i *won't* make it any nicer tonight.
// Future generations will have to live with this shit or rewrite it.
final int recordId = new HashCodeBuilder()
.append(record.getM_Product_ID())
.append(record.getM_HU_PI_Item_Product_ID())
.toHashCode();
final OrderLineHUPackingGridRowBuilder builder = new OrderLineHUPackingGridRowBuilder();
builder.setSource(record);
builders.addGridTabRowBuilder(recordId, builder);
}
}
/**
* Gets existing {@link IHUPackingAware} record for given row (wrapped as IHUPackingAware) or null.
*
* @param rowIndexModel
* @return {@link IHUPackingAware} or null
*/
private IHUPackingAware getSavedHUPackingAware(final IHUPackingAware rowRecord)
{
final ArrayKey key = mkKey(rowRecord);
return packingInfos.get(key);
}
@Override
public void prepareEditor(final CEditor editor, final Object value, final int rowIndexModel, final int columnIndexModel)
{
// nothing
} | @Override
public String getProductCombinations()
{
final List<Integer> piItemProductIds = new ArrayList<Integer>();
for (final IHUPackingAware record : packingInfos.values())
{
piItemProductIds.add(record.getM_HU_PI_Item_Product_ID());
}
if (!piItemProductIds.isEmpty() && piItemProductIds != null)
{
final StringBuilder sb = new StringBuilder(piItemProductIds.get(0).toString());
for (int i = 1; i < piItemProductIds.size(); i++)
{
sb.append(", " + piItemProductIds.get(i).toString());
}
return " AND (" + M_HU_PI_Item_Product_table_alias + "." + I_M_HU_PI_Item_Product.COLUMNNAME_M_HU_PI_Item_Product_ID + " IN " + " ( " + sb + " ) "
+ " OR " + M_HU_PI_Item_Product_table_alias + "." + I_M_HU_PI_Item_Product.COLUMNNAME_M_HU_PI_Item_Product_ID + " IS NULL" + ") ";
}
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\InfoProductQtyPacksController.java | 1 |
请完成以下Java代码 | public void setSelectedRegionId(final int regionId)
{
if(regionId <= 0)
{
setSelectedItem(null);
return;
}
for (int i = 0, size = getSize(); i < size; i++)
{
final MRegion region = getElementAt(i);
if(region != null && region.getC_Region_ID() == regionId)
{
setSelectedItem(region);
}
}
}
}
/**
* Small class used to handle the components of a location part (e.g. the label and field of Address1)
*
* @author metas-dev <dev@metasfresh.com>
*
*/
private final class LocationPart
{
private final JLabel label;
private final JComponent field;
private final String partName;
private boolean enabledCustom = true;
private boolean enabledByCaptureSequence = false;
public LocationPart(final String partName, final String label, final JComponent field)
{
super();
this.partName = partName;
this.field = field;
this.field.setName(label);
this.label = new CLabel(Check.isEmpty(label) ? "" : msgBL.translate(Env.getCtx(), label));
this.label.setHorizontalAlignment(SwingConstants.RIGHT);
this.label.setLabelFor(field);
update();
}
public void setEnabledCustom(final boolean enabledCustom)
{
if (this.enabledCustom == enabledCustom)
{
return;
}
this.enabledCustom = enabledCustom;
update();
}
public void setEnabledByCaptureSequence(final LocationCaptureSequence captureSequence)
{
final boolean enabled = captureSequence.hasPart(partName);
setEnabledByCaptureSequence(enabled);
}
private void setEnabledByCaptureSequence(final boolean enabledByCaptureSequence)
{
if (this.enabledByCaptureSequence == enabledByCaptureSequence) | {
return;
}
this.enabledByCaptureSequence = enabledByCaptureSequence;
update();
}
private final void update()
{
final boolean enabled = enabledCustom && enabledByCaptureSequence;
label.setEnabled(enabled);
label.setVisible(enabled);
field.setEnabled(enabled);
field.setVisible(enabled);
}
public void setLabelText(final String labelText)
{
label.setText(labelText);
}
public JLabel getLabel()
{
return label;
}
public JComponent getField()
{
return field;
}
}
} // VLocationDialog | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLocationDialog.java | 1 |
请完成以下Java代码 | public class TaskCandidateUserAddedListenerDelegate implements ActivitiEventListener {
private final List<TaskRuntimeEventListener<TaskCandidateUserAddedEvent>> listeners;
private final ToAPITaskCandidateUserAddedEventConverter converter;
public TaskCandidateUserAddedListenerDelegate(
List<TaskRuntimeEventListener<TaskCandidateUserAddedEvent>> listeners,
ToAPITaskCandidateUserAddedEventConverter converter
) {
this.listeners = listeners;
this.converter = converter;
}
@Override
public void onEvent(ActivitiEvent event) {
if (event instanceof ActivitiEntityEvent) { | converter
.from((ActivitiEntityEvent) event)
.ifPresent(convertedEvent -> {
for (TaskRuntimeEventListener<TaskCandidateUserAddedEvent> listener : listeners) {
listener.onEvent(convertedEvent);
}
});
}
}
@Override
public boolean isFailOnException() {
return false;
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-runtime-impl\src\main\java\org\activiti\runtime\api\event\internal\TaskCandidateUserAddedListenerDelegate.java | 1 |
请完成以下Java代码 | public void setName(String name) {
this.name = name;
}
@XmlTransient
public void setAuthor(String author) {
this.author = author;
}
public String getName() {
return name;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Long getId() {
return id;
}
public String getAuthor() {
return author;
}
@Override | public String toString() {
return ToStringBuilder.reflectionToString(this);
}
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
} | repos\tutorials-master\xml-modules\jaxb\src\main\java\com\baeldung\jaxb\Book.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HUReservationDocumentFilterService
{
private final OrderLineRepository orderLineRepository;
private final HUReservationService huReservationService;
public HUReservationDocumentFilterService(
@NonNull final OrderLineRepository orderLineRepository,
@NonNull final HUReservationService huReservationService)
{
this.orderLineRepository = orderLineRepository;
this.huReservationService = huReservationService;
}
public DocumentFilter createOrderLineDocumentFilter(@NonNull final OrderLineId orderLineId)
{
final OrderLine salesOrderLine = orderLineRepository.getById(orderLineId);
return createOrderLineDocumentFilter(salesOrderLine);
}
private DocumentFilter createOrderLineDocumentFilter(@NonNull final OrderLine salesOrderLine)
{
final IHUQueryBuilder huQuery = createHUQuery(salesOrderLine);
return HUIdsFilterHelper.createFilter(huQuery);
}
private IHUQueryBuilder createHUQuery(@NonNull final OrderLine salesOrderLine)
{
final OrderLineId salesOrderLineId = salesOrderLine.getId();
final HUReservationDocRef reservationDocRef = salesOrderLineId != null ? HUReservationDocRef.ofSalesOrderLineId(salesOrderLineId) : null;
return huReservationService.prepareHUQuery()
.warehouseId(salesOrderLine.getWarehouseId())
.productId(salesOrderLine.getProductId())
.bpartnerId(salesOrderLine.getBPartnerId())
.asiId(salesOrderLine.getAsiId())
.reservedToDocumentOrNotReservedAtAll(reservationDocRef)
.build(); | }
public DocumentFilter createDocumentFilterIgnoreAttributes(@NonNull final Packageable packageable)
{
final IHUQueryBuilder huQuery = createHUQueryIgnoreAttributes(packageable);
return HUIdsFilterHelper.createFilter(huQuery);
}
private IHUQueryBuilder createHUQueryIgnoreAttributes(final Packageable packageable)
{
final OrderLineId salesOrderLineId = packageable.getSalesOrderLineIdOrNull();
final HUReservationDocRef reservationDocRef = salesOrderLineId != null ? HUReservationDocRef.ofSalesOrderLineId(salesOrderLineId) : null;
return huReservationService.prepareHUQuery()
.warehouseId(packageable.getWarehouseId())
.productId(packageable.getProductId())
.bpartnerId(packageable.getCustomerId())
.asiId(null) // ignore attributes
.reservedToDocumentOrNotReservedAtAll(reservationDocRef)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\hu\reservation\HUReservationDocumentFilterService.java | 2 |
请完成以下Java代码 | public Integer getId(String category)
{
return categoryId.get(category);
}
public String getCategory(int id)
{
assert 0 <= id;
assert id < idCategory.size();
return idCategory.get(id);
}
public List<String> getCategories()
{
return idCategory;
}
public int size() | {
return idCategory.size();
}
public String[] toArray()
{
String[] catalog = new String[idCategory.size()];
idCategory.toArray(catalog);
return catalog;
}
@Override
public String toString()
{
return idCategory.toString();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\corpus\Catalog.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void abortAll(@NonNull final UserId callerId)
{
inventoryService.updateByQuery(
InventoryQuery.builder().onlyDraftOrInProgress().onlyResponsibleId(callerId).build(),
Inventory::unassign
);
}
public Inventory complete(Inventory inventory)
{
final InventoryId inventoryId = inventory.getId();
inventoryService.completeDocument(inventoryId);
return inventoryService.getById(inventory.getId());
}
public LocatorScannedCodeResolverResult resolveLocator(
@NonNull ScannedCode scannedCode,
@NonNull WFProcessId wfProcessId,
@Nullable InventoryLineId lineId,
@NonNull UserId callerId)
{
final Inventory inventory = getById(wfProcessId, callerId);
final Set<LocatorId> eligibleLocatorIds = inventory.getLocatorIdsEligibleForCounting(lineId);
if (eligibleLocatorIds.isEmpty())
{
return LocatorScannedCodeResolverResult.notFound(LocatorGlobalQRCodeResolverKey.ofString("InventoryJobService"), "no such locator in current inventory");
}
return warehouseService.resolveLocator(
LocatorScannedCodeResolverRequest.builder()
.scannedCode(scannedCode)
.context(LocatorScannedCodeResolveContext.builder()
.eligibleLocatorIds(eligibleLocatorIds)
.build())
.build()
);
}
public ResolveHUResponse resolveHU(@NonNull final ResolveHURequest request)
{
return newHUScannedCodeResolveCommand()
.scannedCode(request.getScannedCode())
.inventory(getById(request.getWfProcessId(), request.getCallerId()))
.lineId(request.getLineId()) | .locatorId(request.getLocatorId())
.build()
.execute();
}
private ResolveHUCommandBuilder newHUScannedCodeResolveCommand()
{
return ResolveHUCommand.builder()
.productService(productService)
.huService(huService);
}
public Inventory reportCounting(@NonNull final JsonCountRequest request, final UserId callerId)
{
final InventoryId inventoryId = toInventoryId(request.getWfProcessId());
return inventoryService.updateById(inventoryId, inventory -> {
inventory.assertHasAccess(callerId);
return inventory.updatingLineById(request.getLineId(), line -> {
// TODO handle the case when huId is null
final Quantity qtyBook = huService.getQty(request.getHuId(), line.getProductId());
final Quantity qtyCount = Quantity.of(request.getQtyCount(), qtyBook.getUOM());
return line.withCounting(InventoryLineCountRequest.builder()
.huId(request.getHuId())
.scannedCode(request.getScannedCode())
.qtyBook(qtyBook)
.qtyCount(qtyCount)
.asiId(productService.createASI(line.getProductId(), request.getAttributesAsMap()))
.build());
});
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\job\service\InventoryJobService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public final class JdbcSessionAutoConfiguration {
@Bean
@ConditionalOnMissingBean
@Conditional(OnJdbcSessionDatasourceInitializationCondition.class)
JdbcSessionDataSourceScriptDatabaseInitializer jdbcSessionDataSourceScriptDatabaseInitializer(
@SpringSessionDataSource ObjectProvider<DataSource> sessionDataSource,
ObjectProvider<DataSource> dataSource, JdbcSessionProperties properties) {
DataSource dataSourceToInitialize = sessionDataSource.getIfAvailable(dataSource::getObject);
return new JdbcSessionDataSourceScriptDatabaseInitializer(dataSourceToInitialize, properties);
}
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
SessionRepositoryCustomizer<JdbcIndexedSessionRepository> springBootSessionRepositoryCustomizer(
JdbcSessionProperties jdbcSessionProperties, SessionTimeout sessionTimeout) {
return (sessionRepository) -> {
PropertyMapper map = PropertyMapper.get();
map.from(sessionTimeout::getTimeout).to(sessionRepository::setDefaultMaxInactiveInterval);
map.from(jdbcSessionProperties::getTableName).to(sessionRepository::setTableName); | map.from(jdbcSessionProperties::getFlushMode).to(sessionRepository::setFlushMode);
map.from(jdbcSessionProperties::getSaveMode).to(sessionRepository::setSaveMode);
map.from(jdbcSessionProperties::getCleanupCron).to(sessionRepository::setCleanupCron);
};
}
static class OnJdbcSessionDatasourceInitializationCondition extends OnDatabaseInitializationCondition {
OnJdbcSessionDatasourceInitializationCondition() {
super("Jdbc Session", "spring.session.jdbc.initialize-schema");
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-session-jdbc\src\main\java\org\springframework\boot\session\jdbc\autoconfigure\JdbcSessionAutoConfiguration.java | 2 |
请完成以下Java代码 | public class StopProcessEnginesStep extends DeploymentOperationStep {
private final static ContainerIntegrationLogger LOG = ProcessEngineLogger.CONTAINER_INTEGRATION_LOGGER;
public String getName() {
return "Stopping process engines";
}
public void performOperationStep(DeploymentOperation operationContext) {
final PlatformServiceContainer serviceContainer = operationContext.getServiceContainer();
Set<String> serviceNames = serviceContainer.getServiceNames(ServiceTypes.PROCESS_ENGINE);
for (String serviceName : serviceNames) {
stopProcessEngine(serviceName, serviceContainer);
}
} | /**
* Stops a process engine, failures are logged but no exceptions are thrown.
*
*/
private void stopProcessEngine(String serviceName, PlatformServiceContainer serviceContainer) {
try {
serviceContainer.stopService(serviceName);
}
catch(Exception e) {
LOG.exceptionWhileStopping("Process Engine", serviceName, e);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\StopProcessEnginesStep.java | 1 |
请完成以下Java代码 | private static StringLookupValue fromZoneIdToLookupValue(final String zoneIdStr)
{
final ZoneId zoneId = ZoneId.of(zoneIdStr);
final ITranslatableString displayName = TranslatableStrings.builder()
.appendTimeZone(zoneId, TextStyle.FULL_STANDALONE)
.append(" - ")
.append(zoneId.getId())
.build();
final ITranslatableString helpText = TranslatableStrings.empty();
return StringLookupValue.of(zoneIdStr, displayName, helpText);
}
@Override
public Optional<String> getLookupTableName()
{
return Optional.empty();
}
@Override
public boolean isNumericKey()
{
return false;
}
@Override
public Set<String> getDependsOnFieldNames() | {
return ImmutableSet.of();
}
@Override
@Nullable
public LookupValue retrieveLookupValueById(final @NonNull LookupDataSourceContext evalCtx)
{
return StringUtils.trimBlankToOptional(evalCtx.getIdToFilterAsString())
.map(zoneId -> getAll().getById(zoneId))
.orElse(null);
}
@Override
public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx)
{
final LookupValueFilterPredicate filter = evalCtx.getFilterPredicate();
final int offset = evalCtx.getOffset(0);
final int limit = evalCtx.getLimit(50);
return getAll()
.filter(filter)
.pageByOffsetAndLimit(offset, limit);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\TimeZoneLookupDescriptor.java | 1 |
请完成以下Java代码 | public void stop() {
thread = null;
}
@Override
public void run() {
duration = 0;
try (final ByteArrayOutputStream out = new ByteArrayOutputStream(); final TargetDataLine line = getTargetDataLineForRecord();) {
int frameSizeInBytes = format.getFrameSize();
int bufferLengthInFrames = line.getBufferSize() / 8;
final int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes;
buildByteOutputStream(out, line, frameSizeInBytes, bufferLengthInBytes);
this.audioInputStream = new AudioInputStream(line);
setAudioInputStream(convertToAudioIStream(out, frameSizeInBytes));
audioInputStream.reset();
} catch (IOException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
return;
}
}
public void buildByteOutputStream(final ByteArrayOutputStream out, final TargetDataLine line, int frameSizeInBytes, final int bufferLengthInBytes) throws IOException {
final byte[] data = new byte[bufferLengthInBytes];
int numBytesRead;
line.start();
while (thread != null) {
if ((numBytesRead = line.read(data, 0, bufferLengthInBytes)) == -1) {
break;
}
out.write(data, 0, numBytesRead);
}
}
private void setAudioInputStream(AudioInputStream aStream) {
this.audioInputStream = aStream;
}
public AudioInputStream convertToAudioIStream(final ByteArrayOutputStream out, int frameSizeInBytes) {
byte audioBytes[] = out.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(audioBytes);
AudioInputStream audioStream = new AudioInputStream(bais, format, audioBytes.length / frameSizeInBytes);
long milliseconds = (long) ((audioInputStream.getFrameLength() * 1000) / format.getFrameRate());
duration = milliseconds / 1000.0;
System.out.println("Recorded duration in seconds:" + duration);
return audioStream;
} | public TargetDataLine getTargetDataLineForRecord() {
TargetDataLine line;
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
if (!AudioSystem.isLineSupported(info)) {
return null;
}
try {
line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format, line.getBufferSize());
} catch (final Exception ex) {
return null;
}
return line;
}
public AudioInputStream getAudioInputStream() {
return audioInputStream;
}
public AudioFormat getFormat() {
return format;
}
public void setFormat(AudioFormat format) {
this.format = format;
}
public Thread getThread() {
return thread;
}
public double getDuration() {
return duration;
}
} | repos\tutorials-master\core-java-modules\core-java-os-2\src\main\java\com\baeldung\example\soundapi\SoundRecorder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void evict(TenantId tenantId, AssetId assetId) {
AssetProfileId old = assetsMap.remove(assetId);
if (old != null) {
AssetProfile newProfile = get(tenantId, assetId);
if (newProfile == null || !old.equals(newProfile.getId())) {
notifyAssetListeners(tenantId, assetId, newProfile);
}
}
}
@Override
public void addListener(TenantId tenantId, EntityId listenerId,
Consumer<AssetProfile> profileListener,
BiConsumer<AssetId, AssetProfile> assetListener) {
if (profileListener != null) {
profileListeners.computeIfAbsent(tenantId, id -> new ConcurrentHashMap<>()).put(listenerId, profileListener);
}
if (assetListener != null) {
assetProfileListeners.computeIfAbsent(tenantId, id -> new ConcurrentHashMap<>()).put(listenerId, assetListener);
}
}
@Override
public AssetProfile find(AssetProfileId assetProfileId) {
return assetProfileService.findAssetProfileById(TenantId.SYS_TENANT_ID, assetProfileId);
}
@Override
public AssetProfile findOrCreateAssetProfile(TenantId tenantId, String profileName) {
return assetProfileService.findOrCreateAssetProfile(tenantId, profileName);
}
@Override
public void removeListener(TenantId tenantId, EntityId listenerId) {
ConcurrentMap<EntityId, Consumer<AssetProfile>> tenantListeners = profileListeners.get(tenantId); | if (tenantListeners != null) {
tenantListeners.remove(listenerId);
}
ConcurrentMap<EntityId, BiConsumer<AssetId, AssetProfile>> assetListeners = assetProfileListeners.get(tenantId);
if (assetListeners != null) {
assetListeners.remove(listenerId);
}
}
private void notifyProfileListeners(AssetProfile profile) {
ConcurrentMap<EntityId, Consumer<AssetProfile>> tenantListeners = profileListeners.get(profile.getTenantId());
if (tenantListeners != null) {
tenantListeners.forEach((id, listener) -> listener.accept(profile));
}
}
private void notifyAssetListeners(TenantId tenantId, AssetId assetId, AssetProfile profile) {
if (profile != null) {
ConcurrentMap<EntityId, BiConsumer<AssetId, AssetProfile>> tenantListeners = assetProfileListeners.get(tenantId);
if (tenantListeners != null) {
tenantListeners.forEach((id, listener) -> listener.accept(assetId, profile));
}
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\profile\DefaultTbAssetProfileCache.java | 2 |
请完成以下Java代码 | public void initialize(ModelValidationEngine engine, MClient client)
{
if (client != null)
m_AD_Client_ID = client.getAD_Client_ID();
engine.addModelChange(I_M_ProductGroup.Table_Name, this);
}
@Override
public String login(int AD_Org_ID, int AD_Role_ID, int AD_User_ID)
{
return null;
}
@Override
public String modelChange(final PO po, final int type) throws Exception
{ | if (type == TYPE_BEFORE_NEW || type == TYPE_BEFORE_CHANGE)
{
final I_M_ProductGroup pg = InterfaceWrapperHelper.create(po, I_M_ProductGroup.class);
Services.get(IInvoiceCandDAO.class).invalidateCandsForProductGroup(pg);
}
return null;
}
@Override
public String docValidate(final PO po, final int timing)
{
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\modelvalidator\M_ProductGroup.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Executor taskExecutor1() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(2);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("executor-1-");
/**配置拒绝策略**/
// AbortPolicy策略:默认策略,如果线程池队列满了丢掉这个任务并且抛出RejectedExecutionException异常。
// executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
// DiscardPolicy策略:如果线程池队列满了,会直接丢掉这个任务并且不会有任何异常。
// executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
// DiscardOldestPolicy策略:如果队列满了,会将最早进入队列的任务删掉腾出空间,再尝试加入队列。
// executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
// CallerRunsPolicy策略:如果添加到线程池失败,那么主线程会自己去执行该任务,不会等待线程池中的线程去执行。
// executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); | // 自定义策略
// executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
// @Override
// public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
//
// }
// });
return executor;
}
}
} | repos\SpringBoot-Learning-master\2.x\chapter7-8\src\main\java\com\didispace\chapter78\Chapter78Application.java | 2 |
请完成以下Java代码 | private static class RangeAwareParamsAsEvaluatee implements Evaluatee2
{
private final IRangeAwareParams params;
private RangeAwareParamsAsEvaluatee(@NonNull final IRangeAwareParams params)
{
this.params = params;
}
@Override
public boolean has_Variable(final String variableName)
{
return params.hasParameter(variableName);
}
@SuppressWarnings("unchecked")
@Override
public <T> T get_ValueAsObject(final String variableName)
{
return (T)params.getParameterAsObject(variableName);
}
@Override
public BigDecimal get_ValueAsBigDecimal(final String variableName, final BigDecimal defaultValue)
{
final BigDecimal value = params.getParameterAsBigDecimal(variableName);
return value != null ? value : defaultValue;
}
@Override
public Boolean get_ValueAsBoolean(final String variableName, final Boolean defaultValue_IGNORED)
{ | return params.getParameterAsBool(variableName);
}
@Override
public Date get_ValueAsDate(final String variableName, final Date defaultValue)
{
final Timestamp value = params.getParameterAsTimestamp(variableName);
return value != null ? value : defaultValue;
}
@Override
public Integer get_ValueAsInt(final String variableName, final Integer defaultValue)
{
final int defaultValueInt = defaultValue != null ? defaultValue : 0;
return params.getParameterAsInt(variableName, defaultValueInt);
}
@Override
public String get_ValueAsString(final String variableName)
{
return params.getParameterAsString(variableName);
}
@Override
public String get_ValueOldAsString(final String variableName)
{
return get_ValueAsString(variableName);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\util\Evaluatees.java | 1 |
请完成以下Spring Boot application配置 | spring:
security:
saml2:
relyingparty:
registration:
simplesamlphp:
signing:
credentials:
- private-key-location: "classpath:saml/privatekey.txt"
certificate-location: "classpath:saml/certificate.txt"
assertingparty:
verification:
credentials:
- certificate-location: "classpath:saml/certificate.txt"
entity-id: simplesaml
singlesignon:
url: https://simplesaml-for-spring-saml/SSOService.php
relying-party-entity-id: "{baseUrl}/saml2/simple-relying-party"
okta:
signing:
credentials:
- private-key-location: "classpath:saml/privatekey.txt"
certificate-loc | ation: "classpath:saml/certificate.txt"
assertingparty:
verification:
credentials:
- certificate-location: "classpath:saml/certificate.txt"
entity-id: okta-id-1234
singlesignon:
url:
https://okta-for-spring/saml2/idp/SSOService.php | repos\spring-boot-4.0.1\smoke-test\spring-boot-smoke-test-saml2-service-provider\src\main\resources\application.yml | 2 |
请在Spring Boot框架中完成以下Java代码 | public class OrderServiceImpl implements OrderService {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private OrderDao orderDao;
@Override
@GlobalTransactional
public Integer createOrder(Long userId, Long productId, Integer price) throws Exception {
Integer amount = 1; // 购买数量,暂时设置为 1。
logger.info("[createOrder] 当前 XID: {}", RootContext.getXID());
// 扣减库存
this.reduceStock(productId, amount);
// 扣减余额
this.reduceBalance(userId, price);
// 保存订单
OrderDO order = new OrderDO().setUserId(userId).setProductId(productId).setPayAmount(amount * price);
orderDao.saveOrder(order);
logger.info("[createOrder] 保存订单: {}", order.getId());
// 返回订单编号
return order.getId();
}
private void reduceStock(Long productId, Integer amount) throws IOException {
// 参数拼接
JSONObject params = new JSONObject().fluentPut("productId", String.valueOf(productId))
.fluentPut("amount", String.valueOf(amount));
// 执行调用
HttpResponse response = DefaultHttpExecutor.getInstance().executePost("http://127.0.0.1:8082", "/product/reduce-stock",
params, HttpResponse.class);
// 解析结果
Boolean success = Boolean.valueOf(EntityUtils.toString(response.getEntity()));
if (!success) { | throw new RuntimeException("扣除库存失败");
}
}
private void reduceBalance(Long userId, Integer price) throws IOException {
// 参数拼接
JSONObject params = new JSONObject().fluentPut("userId", String.valueOf(userId))
.fluentPut("price", String.valueOf(price));
// 执行调用
HttpResponse response = DefaultHttpExecutor.getInstance().executePost("http://127.0.0.1:8083", "/account/reduce-balance",
params, HttpResponse.class);
// 解析结果
Boolean success = Boolean.valueOf(EntityUtils.toString(response.getEntity()));
if (!success) {
throw new RuntimeException("扣除余额失败");
}
}
} | repos\SpringBoot-Labs-master\lab-52\lab-52-seata-at-httpclient-demo\lab-52-seata-at-httpclient-demo-order-service\src\main\java\cn\iocoder\springboot\lab52\orderservice\service\OrderServiceImpl.java | 2 |
请完成以下Java代码 | public String getJobId() {
return jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public String getJobDefinitionId() {
return jobDefinitionId;
}
public void setJobDefinitionId(String jobDefinitionId) {
this.jobDefinitionId = jobDefinitionId;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getBatchId() {
return batchId;
}
public void setBatchId(String batchId) {
this.batchId = batchId;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public String getExternalTaskId() {
return externalTaskId;
}
public void setExternalTaskId(String externalTaskId) {
this.externalTaskId = externalTaskId;
}
public String getAnnotation() {
return annotation;
} | public void setAnnotation(String annotation) {
this.annotation = annotation;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[taskId=" + taskId
+ ", deploymentId=" + deploymentId
+ ", processDefinitionKey=" + processDefinitionKey
+ ", jobId=" + jobId
+ ", jobDefinitionId=" + jobDefinitionId
+ ", batchId=" + batchId
+ ", operationId=" + operationId
+ ", operationType=" + operationType
+ ", userId=" + userId
+ ", timestamp=" + timestamp
+ ", property=" + property
+ ", orgValue=" + orgValue
+ ", newValue=" + newValue
+ ", id=" + id
+ ", eventType=" + eventType
+ ", executionId=" + executionId
+ ", processDefinitionId=" + processDefinitionId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", processInstanceId=" + processInstanceId
+ ", externalTaskId=" + externalTaskId
+ ", tenantId=" + tenantId
+ ", entityType=" + entityType
+ ", category=" + category
+ ", annotation=" + annotation
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\UserOperationLogEntryEventEntity.java | 1 |
请完成以下Java代码 | public I_M_HU_Assignment getM_HU_Assignment()
{
return assignment;
}
@Override
public boolean isNewAssignment()
{
return InterfaceWrapperHelper.isNew(assignment);
}
@Override
public IHUAssignmentBuilder initializeAssignment(final Properties ctx, final String trxName)
{
final I_M_HU_Assignment assignment = InterfaceWrapperHelper.create(ctx, I_M_HU_Assignment.class, trxName);
setAssignmentRecordToUpdate(assignment);
return this;
}
@Override
public IHUAssignmentBuilder setTemplateForNewRecord(final I_M_HU_Assignment assignmentRecord)
{
this.assignment = newInstance(I_M_HU_Assignment.class);
return updateFromRecord(assignmentRecord);
}
@Override
public IHUAssignmentBuilder setAssignmentRecordToUpdate(@NonNull final I_M_HU_Assignment assignmentRecord)
{
this.assignment = assignmentRecord;
return updateFromRecord(assignmentRecord);
}
private IHUAssignmentBuilder updateFromRecord(final I_M_HU_Assignment assignmentRecord)
{
setTopLevelHU(assignmentRecord.getM_HU());
setM_LU_HU(assignmentRecord.getM_LU_HU());
setM_TU_HU(assignmentRecord.getM_TU_HU());
setVHU(assignmentRecord.getVHU());
setQty(assignmentRecord.getQty());
setIsTransferPackingMaterials(assignmentRecord.isTransferPackingMaterials());
setIsActive(assignmentRecord.isActive()); | return this;
}
@Override
public I_M_HU_Assignment build()
{
Check.assumeNotNull(model, "model not null");
Check.assumeNotNull(topLevelHU, "topLevelHU not null");
Check.assumeNotNull(assignment, "assignment not null");
TableRecordCacheLocal.setReferencedValue(assignment, model);
assignment.setM_HU(topLevelHU);
assignment.setM_LU_HU(luHU);
assignment.setM_TU_HU(tuHU);
assignment.setVHU(vhu);
assignment.setQty(qty);
assignment.setIsTransferPackingMaterials(isTransferPackingMaterials);
assignment.setIsActive(isActive);
InterfaceWrapperHelper.save(assignment);
return assignment;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUAssignmentBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public StatsdProtocol protocol() {
return obtain(StatsdProperties::getProtocol, StatsdConfig.super::protocol);
}
@Override
public int maxPacketLength() {
return obtain(StatsdProperties::getMaxPacketLength, StatsdConfig.super::maxPacketLength);
}
@Override
public Duration pollingFrequency() {
return obtain(StatsdProperties::getPollingFrequency, StatsdConfig.super::pollingFrequency);
}
@Override | public Duration step() {
return obtain(StatsdProperties::getStep, StatsdConfig.super::step);
}
@Override
public boolean publishUnchangedMeters() {
return obtain(StatsdProperties::isPublishUnchangedMeters, StatsdConfig.super::publishUnchangedMeters);
}
@Override
public boolean buffered() {
return obtain(StatsdProperties::isBuffered, StatsdConfig.super::buffered);
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\statsd\StatsdPropertiesConfigAdapter.java | 2 |
请完成以下Java代码 | public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Integer getShowStatus() {
return showStatus;
}
public void setShowStatus(Integer showStatus) {
this.showStatus = showStatus;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getReadCount() {
return readCount;
}
public void setReadCount(Integer readCount) {
this.readCount = readCount;
} | public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@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(", categoryId=").append(categoryId);
sb.append(", icon=").append(icon);
sb.append(", title=").append(title);
sb.append(", showStatus=").append(showStatus);
sb.append(", createTime=").append(createTime);
sb.append(", readCount=").append(readCount);
sb.append(", content=").append(content);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsHelp.java | 1 |
请完成以下Java代码 | public int hashCode()
{
return Objects.hash(idInt);
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (!(obj instanceof IntDocumentId))
{
return false;
}
final IntDocumentId other = (IntDocumentId)obj;
return idInt == other.idInt;
}
@Override
public boolean isInt()
{
return true;
}
@Override
public int toInt()
{
return idInt;
}
@Override
public boolean isNew()
{
return idInt == NEW_ID;
}
@Override
public boolean isComposedKey()
{
return false;
}
@Override
public List<Object> toComposedKeyParts()
{
return ImmutableList.of(idInt);
}
}
private static final class StringDocumentId extends DocumentId
{
private final String idStr;
private StringDocumentId(final String idStr)
{
Check.assumeNotEmpty(idStr, "idStr is not empty");
this.idStr = idStr;
}
@Override
public String toJson()
{
return idStr;
}
@Override
public int hashCode()
{
return Objects.hash(idStr);
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{ | return true;
}
if (!(obj instanceof StringDocumentId))
{
return false;
}
final StringDocumentId other = (StringDocumentId)obj;
return Objects.equals(idStr, other.idStr);
}
@Override
public boolean isInt()
{
return false;
}
@Override
public int toInt()
{
if (isComposedKey())
{
throw new AdempiereException("Composed keys cannot be converted to int: " + this);
}
else
{
throw new AdempiereException("String document IDs cannot be converted to int: " + this);
}
}
@Override
public boolean isNew()
{
return false;
}
@Override
public boolean isComposedKey()
{
return idStr.contains(COMPOSED_KEY_SEPARATOR);
}
@Override
public List<Object> toComposedKeyParts()
{
final ImmutableList.Builder<Object> composedKeyParts = ImmutableList.builder();
COMPOSED_KEY_SPLITTER.split(idStr).forEach(composedKeyParts::add);
return composedKeyParts.build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DocumentId.java | 1 |
请完成以下Java代码 | public class GLJournalDAO implements IGLJournalDAO
{
@Override
public List<I_GL_Journal> retrieveJournalsForBatch(final I_GL_JournalBatch batch)
{
final List<I_GL_Journal> journals = Services.get(IQueryBL.class).createQueryBuilder(I_GL_Journal.class, batch)
.filter(new EqualsQueryFilter<I_GL_Journal>(I_GL_Journal.COLUMNNAME_GL_JournalBatch_ID, batch.getGL_JournalBatch_ID()))
.addOnlyActiveRecordsFilter()
.create()
.list(I_GL_Journal.class);
return journals;
}
@Override
public List<I_GL_Journal> retrievePostedWithoutFactAcct(final Properties ctx, final Date startTime)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final String trxName = ITrx.TRXNAME_ThreadInherited;
final IQueryBuilder<I_GL_Journal> queryBuilder = queryBL.createQueryBuilder(I_GL_Journal.class, ctx, trxName)
.addOnlyActiveRecordsFilter();
queryBuilder
.addEqualsFilter(I_GL_Journal.COLUMNNAME_Posted, true) // Posted
.addEqualsFilter(I_GL_Journal.COLUMNNAME_Processed, true) // Processed
.addInArrayOrAllFilter(I_GL_Journal.COLUMNNAME_DocStatus, IDocument.STATUS_Closed, IDocument.STATUS_Completed); // DocStatus in ('CO', 'CL')
// Exclude the entries that don't have either Credit or Debit amounts. These entries will produce 0 in posting
final ICompositeQueryFilter<I_GL_Journal> nonZeroFilter = queryBL.createCompositeQueryFilter(I_GL_Journal.class).setJoinOr()
.addNotEqualsFilter(I_GL_Journal.COLUMNNAME_TotalCr, BigDecimal.ZERO)
.addNotEqualsFilter(I_GL_Journal.COLUMNNAME_TotalDr, BigDecimal.ZERO); | queryBuilder.filter(nonZeroFilter);
// Only the documents created after the given start time
if (startTime != null)
{
queryBuilder.addCompareFilter(I_GL_Journal.COLUMNNAME_Created, Operator.GREATER_OR_EQUAL, startTime);
}
// Check if there are fact accounts created for each document
final IQueryBuilder<I_Fact_Acct> factAcctQuery = queryBL.createQueryBuilder(I_Fact_Acct.class, ctx, trxName)
.addEqualsFilter(I_Fact_Acct.COLUMNNAME_AD_Table_ID, InterfaceWrapperHelper.getTableId(I_GL_Journal.class));
queryBuilder
.addNotInSubQueryFilter(I_GL_Journal.COLUMNNAME_GL_Journal_ID, I_Fact_Acct.COLUMNNAME_Record_ID, factAcctQuery.create()) // has no accounting
;
return queryBuilder
.create()
.list();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal\impl\GLJournalDAO.java | 1 |
请完成以下Java代码 | final void save()
{
// Make sure the storage was not disposed
assertNotDisposed();
// Make sure HU Attribute contains the right/fresh data
huAttribute.setValue(valueString);
huAttribute.setValueNumber(valueNumber);
huAttribute.setValueDate(TimeUtil.asTimestamp(valueDate));
getHUAttributesDAO().save(huAttribute);
}
@Override
public boolean isNew()
{
return huAttribute.getM_HU_Attribute_ID() <= 0;
}
@Override
protected void setInternalValueDate(Date value)
{
huAttribute.setValueDate(TimeUtil.asTimestamp(value));
this.valueDate = value; | }
@Override
protected Date getInternalValueDate()
{
return valueDate;
}
@Override
protected void setInternalValueDateInitial(Date value)
{
huAttribute.setValueDateInitial(TimeUtil.asTimestamp(value));
}
@Override
protected Date getInternalValueDateInitial()
{
return huAttribute.getValueDateInitial();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\HUAttributeValue.java | 1 |
请完成以下Java代码 | private @NonNull ShipperGatewayId getShipperGatewayId()
{
return ShipperGatewayId.ofString(Check.assumeNotNull(
getParameters().getParameterAsString(PARAM_ShipperGatewayId),
"Parameter {} is set", PARAM_ShipperGatewayId
));
}
private DeliveryOrder retrieveDeliveryOrder()
{
@NonNull final ShipperGatewayId shipperGatewayId = getShipperGatewayId();
final DeliveryOrderService deliveryOrderRepo = shipperRegistry.getDeliveryOrderService(shipperGatewayId);
final DeliveryOrderId deliveryOrderRepoId = getDeliveryOrderRepoId();
return deliveryOrderRepo.getByRepoId(deliveryOrderRepoId);
}
public DeliveryOrderId getDeliveryOrderRepoId()
{
final int repoId = getParameters().getParameterAsInt(PARAM_DeliveryOrderRepoId, -1);
return DeliveryOrderId.ofRepoId(repoId);
}
public void printLabels(
@NonNull final DeliveryOrder deliveryOrder,
@NonNull final List<PackageLabels> packageLabels,
@NonNull final DeliveryOrderService deliveryOrderRepo,
@Nullable final AsyncBatchId asyncBatchId)
{
for (final PackageLabels packageLabel : packageLabels)
{
final PackageLabel defaultPackageLabel = packageLabel.getDefaultPackageLabel();
printLabel(deliveryOrder, defaultPackageLabel, deliveryOrderRepo, asyncBatchId);
} | }
private void printLabel(
final DeliveryOrder deliveryOrder,
final PackageLabel packageLabel,
@NonNull final DeliveryOrderService deliveryOrderRepo,
@Nullable final AsyncBatchId asyncBatchId)
{
final IArchiveStorageFactory archiveStorageFactory = Services.get(IArchiveStorageFactory.class);
final String fileExtWithDot = MimeType.getExtensionByType(packageLabel.getContentType());
final String fileName = CoalesceUtil.firstNotEmptyTrimmed(packageLabel.getFileName(), packageLabel.getType().toString()) + fileExtWithDot;
final byte[] labelData = packageLabel.getLabelData();
final Properties ctx = Env.getCtx();
final IArchiveStorage archiveStorage = archiveStorageFactory.getArchiveStorage(ctx);
final I_AD_Archive archive = InterfaceWrapperHelper.create(archiveStorage.newArchive(ctx, ITrx.TRXNAME_ThreadInherited), I_AD_Archive.class);
final ITableRecordReference deliveryOrderRef = deliveryOrderRepo.toTableRecordReference(deliveryOrder);
archive.setAD_Table_ID(deliveryOrderRef.getAD_Table_ID());
archive.setRecord_ID(deliveryOrderRef.getRecord_ID());
archive.setC_BPartner_ID(deliveryOrder.getDeliveryAddress().getBpartnerId());
// archive.setAD_Org_ID(); // TODO: do we need to orgId too?
archive.setName(fileName);
archiveStorage.setBinaryData(archive, labelData);
archive.setIsReport(false);
archive.setIsDirectEnqueue(true);
archive.setIsDirectProcessQueueItem(true);
archive.setC_Async_Batch_ID(AsyncBatchId.toRepoId(asyncBatchId));
InterfaceWrapperHelper.save(archive);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\async\DeliveryOrderWorkpackageProcessor.java | 1 |
请完成以下Java代码 | public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getAD_Replication_Run_ID()));
}
public I_AD_ReplicationTable getAD_ReplicationTable() throws RuntimeException
{
return (I_AD_ReplicationTable)MTable.get(getCtx(), I_AD_ReplicationTable.Table_Name)
.getPO(getAD_ReplicationTable_ID(), get_TrxName()); }
/** Set Replication Table.
@param AD_ReplicationTable_ID
Data Replication Strategy Table Info
*/
public void setAD_ReplicationTable_ID (int AD_ReplicationTable_ID)
{
if (AD_ReplicationTable_ID < 1)
set_Value (COLUMNNAME_AD_ReplicationTable_ID, null);
else
set_Value (COLUMNNAME_AD_ReplicationTable_ID, Integer.valueOf(AD_ReplicationTable_ID));
}
/** Get Replication Table.
@return Data Replication Strategy Table Info
*/
public int getAD_ReplicationTable_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_ReplicationTable_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Replicated.
@param IsReplicated
The data is successfully replicated
*/
public void setIsReplicated (boolean IsReplicated)
{
set_Value (COLUMNNAME_IsReplicated, Boolean.valueOf(IsReplicated));
}
/** Get Replicated.
@return The data is successfully replicated
*/
public boolean isReplicated ()
{
Object oo = get_Value(COLUMNNAME_IsReplicated);
if (oo != null) | {
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Message.
@param P_Msg Process Message */
public void setP_Msg (String P_Msg)
{
set_Value (COLUMNNAME_P_Msg, P_Msg);
}
/** Get Process Message.
@return Process Message */
public String getP_Msg ()
{
return (String)get_Value(COLUMNNAME_P_Msg);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Replication_Log.java | 1 |
请完成以下Java代码 | public void setC_Country_Sequence_ID (int C_Country_Sequence_ID)
{
if (C_Country_Sequence_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Country_Sequence_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Country_Sequence_ID, Integer.valueOf(C_Country_Sequence_ID));
}
/** Get Country Sequence.
@return Country Sequence */
@Override
public int getC_Country_Sequence_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Country_Sequence_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Adress-Druckformat.
@param DisplaySequence
Format for printing this Address
*/
@Override
public void setDisplaySequence (java.lang.String DisplaySequence)
{
set_Value (COLUMNNAME_DisplaySequence, DisplaySequence);
}
/** Get Adress-Druckformat.
@return Format for printing this Address
*/
@Override
public java.lang.String getDisplaySequence () | {
return (java.lang.String)get_Value(COLUMNNAME_DisplaySequence);
}
/** Set Local Address Format.
@param DisplaySequenceLocal
Format for printing this Address locally
*/
@Override
public void setDisplaySequenceLocal (java.lang.String DisplaySequenceLocal)
{
set_Value (COLUMNNAME_DisplaySequenceLocal, DisplaySequenceLocal);
}
/** Get Local Address Format.
@return Format for printing this Address locally
*/
@Override
public java.lang.String getDisplaySequenceLocal ()
{
return (java.lang.String)get_Value(COLUMNNAME_DisplaySequenceLocal);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Country_Sequence.java | 1 |
请完成以下Java代码 | public int getAD_UI_Section_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_UI_Section_ID);
}
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
@Override
public void setHelp (java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
@Override
public java.lang.String getHelp()
{
return (java.lang.String)get_Value(COLUMNNAME_Help);
}
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{ | return (java.lang.String)get_Value(COLUMNNAME_Name);
}
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setUIStyle (java.lang.String UIStyle)
{
set_Value (COLUMNNAME_UIStyle, UIStyle);
}
@Override
public java.lang.String getUIStyle()
{
return (java.lang.String)get_Value(COLUMNNAME_UIStyle);
}
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UI_Section.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class MSV3PurchaseCandidateId
{
public static MSV3PurchaseCandidateId ofRepoId(final int repoId)
{
return new MSV3PurchaseCandidateId(repoId);
}
@JsonCreator
public static MSV3PurchaseCandidateId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new MSV3PurchaseCandidateId(repoId) : null;
}
public static int toRepoId(final MSV3PurchaseCandidateId id)
{
return id != null ? id.getRepoId() : -1;
}
int repoId; | private MSV3PurchaseCandidateId(final int repoId)
{
if (repoId <= 0)
{
throw new IllegalArgumentException("Invalid repoId: " + repoId);
}
this.repoId = repoId;
}
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\order\MSV3PurchaseCandidateId.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.