instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public class PricingConditionsResult
{
public static final PricingConditionsResult ZERO = builder().build();
Percent discount;
PaymentTermId paymentTermId;
CurrencyId currencyId;
BigDecimal priceListOverride;
BigDecimal priceStdOverride;
BigDecimal priceLimitOverride;
PricingConditionsId pricingConditionsId;
PricingConditionsBreak pricingConditionsBreak;
PricingSystemId basePricingSystemId;
@Builder
public PricingConditionsResult(
@Nullable final Percent discount,
final PaymentTermId paymentTermId,
final CurrencyId currencyId,
final BigDecimal priceListOverride,
final BigDecimal priceStdOverride,
final BigDecimal priceLimitOverride,
final PricingConditionsId pricingConditionsId,
final PricingConditionsBreak pricingConditionsBreak,
final PricingSystemId basePricingSystemId)
{
this.discount = discount != null ? discount : Percent.ZERO;
this.paymentTermId = paymentTermId; | this.currencyId = currencyId;
this.priceListOverride = priceListOverride;
this.priceStdOverride = priceStdOverride;
this.priceLimitOverride = priceLimitOverride;
this.pricingConditionsBreak = pricingConditionsBreak;
this.pricingConditionsId = extractPricingConditionsId(pricingConditionsId, pricingConditionsBreak);
this.basePricingSystemId = basePricingSystemId;
}
private static PricingConditionsId extractPricingConditionsId(PricingConditionsId pricingConditionsId, PricingConditionsBreak pricingConditionsBreak)
{
if (pricingConditionsBreak == null)
{
return pricingConditionsId;
}
else if (pricingConditionsId == null)
{
return pricingConditionsBreak.getPricingConditionsIdOrNull();
}
else if (pricingConditionsBreak.getId() == null)
{
return pricingConditionsId;
}
else
{
PricingConditionsBreakId.assertMatching(pricingConditionsId, pricingConditionsBreak.getId());
return pricingConditionsId;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\conditions\service\PricingConditionsResult.java | 2 |
请完成以下Java代码 | public class X509AuthenticationFilter extends AbstractPreAuthenticatedProcessingFilter {
private X509PrincipalExtractor principalExtractor = new SubjectX500PrincipalExtractor();
@Override
protected @Nullable Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
X509Certificate cert = extractClientCertificate(request);
return (cert != null) ? this.principalExtractor.extractPrincipal(cert) : null;
}
@Override
protected @Nullable Object getPreAuthenticatedCredentials(HttpServletRequest request) {
return extractClientCertificate(request);
} | private @Nullable X509Certificate extractClientCertificate(HttpServletRequest request) {
X509Certificate[] certs = (X509Certificate[]) request.getAttribute("jakarta.servlet.request.X509Certificate");
if (certs != null && certs.length > 0) {
this.logger.debug(LogMessage.format("X.509 client authentication certificate:%s", certs[0]));
return certs[0];
}
this.logger.debug("No client certificate found in request.");
return null;
}
public void setPrincipalExtractor(X509PrincipalExtractor principalExtractor) {
this.principalExtractor = principalExtractor;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\preauth\x509\X509AuthenticationFilter.java | 1 |
请完成以下Java代码 | public String getRel() {
return this.rel;
}
public void setRel(String rel) {
this.rel = rel;
}
public boolean isTemplated() {
return this.templated;
}
public void setTemplated(boolean templated) {
this.templated = templated;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getHref() {
return this.href;
}
public Set<String> getTemplateVariables() {
return Collections.unmodifiableSet(this.templateVariables);
}
public void setHref(String href) {
this.href = href;
}
public void resolve() {
if (this.rel == null) {
throw new InvalidInitializrMetadataException("Invalid link " + this + ": rel attribute is mandatory");
}
if (this.href == null) {
throw new InvalidInitializrMetadataException("Invalid link " + this + ": href attribute is mandatory");
}
Matcher matcher = VARIABLE_REGEX.matcher(this.href); | while (matcher.find()) {
String variable = matcher.group(1);
this.templateVariables.add(variable);
}
this.templated = !this.templateVariables.isEmpty();
}
/**
* Expand the link using the specified parameters.
* @param parameters the parameters value
* @return an URI where all variables have been expanded
*/
public URI expand(Map<String, String> parameters) {
AtomicReference<String> result = new AtomicReference<>(this.href);
this.templateVariables.forEach((var) -> {
Object value = parameters.get(var);
if (value == null) {
throw new IllegalArgumentException(
"Could not expand " + this.href + ", missing value for '" + var + "'");
}
result.set(result.get().replace("{" + var + "}", value.toString()));
});
try {
return new URI(result.get());
}
catch (URISyntaxException ex) {
throw new IllegalStateException("Invalid URL", ex);
}
}
public static Link create(String rel, String href) {
return new Link(rel, href);
}
public static Link create(String rel, String href, String description) {
return new Link(rel, href, description);
}
public static Link create(String rel, String href, boolean templated) {
return new Link(rel, href, templated);
}
} | repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\Link.java | 1 |
请完成以下Java代码 | public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Budget.
@param GL_Budget_ID
General Ledger Budget
*/
public void setGL_Budget_ID (int GL_Budget_ID)
{
if (GL_Budget_ID < 1)
set_ValueNoCheck (COLUMNNAME_GL_Budget_ID, null);
else
set_ValueNoCheck (COLUMNNAME_GL_Budget_ID, Integer.valueOf(GL_Budget_ID));
}
/** Get Budget.
@return General Ledger Budget
*/
public int getGL_Budget_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GL_Budget_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Primary.
@param IsPrimary
Indicates if this is the primary budget
*/
public void setIsPrimary (boolean IsPrimary)
{
set_Value (COLUMNNAME_IsPrimary, Boolean.valueOf(IsPrimary)); | }
/** Get Primary.
@return Indicates if this is the primary budget
*/
public boolean isPrimary ()
{
Object oo = get_Value(COLUMNNAME_IsPrimary);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_Budget.java | 1 |
请完成以下Java代码 | public void setDefaultFlow(String defaultFlow) {
this.defaultFlow = defaultFlow;
}
public MultiInstanceLoopCharacteristics getLoopCharacteristics() {
return loopCharacteristics;
}
public void setLoopCharacteristics(MultiInstanceLoopCharacteristics loopCharacteristics) {
this.loopCharacteristics = loopCharacteristics;
}
public boolean hasMultiInstanceLoopCharacteristics() {
return getLoopCharacteristics() != null;
}
public IOSpecification getIoSpecification() {
return ioSpecification;
}
public void setIoSpecification(IOSpecification ioSpecification) {
this.ioSpecification = ioSpecification;
}
public List<DataAssociation> getDataInputAssociations() {
return dataInputAssociations;
}
public void setDataInputAssociations(List<DataAssociation> dataInputAssociations) {
this.dataInputAssociations = dataInputAssociations;
}
public List<DataAssociation> getDataOutputAssociations() {
return dataOutputAssociations;
}
public void setDataOutputAssociations(List<DataAssociation> dataOutputAssociations) {
this.dataOutputAssociations = dataOutputAssociations;
}
public List<MapExceptionEntry> getMapExceptions() {
return mapExceptions; | }
public void setMapExceptions(List<MapExceptionEntry> mapExceptions) {
this.mapExceptions = mapExceptions;
}
public void setValues(Activity otherActivity) {
super.setValues(otherActivity);
setFailedJobRetryTimeCycleValue(otherActivity.getFailedJobRetryTimeCycleValue());
setDefaultFlow(otherActivity.getDefaultFlow());
setForCompensation(otherActivity.isForCompensation());
if (otherActivity.getLoopCharacteristics() != null) {
setLoopCharacteristics(otherActivity.getLoopCharacteristics().clone());
}
if (otherActivity.getIoSpecification() != null) {
setIoSpecification(otherActivity.getIoSpecification().clone());
}
dataInputAssociations = new ArrayList<DataAssociation>();
if (otherActivity.getDataInputAssociations() != null && !otherActivity.getDataInputAssociations().isEmpty()) {
for (DataAssociation association : otherActivity.getDataInputAssociations()) {
dataInputAssociations.add(association.clone());
}
}
dataOutputAssociations = new ArrayList<DataAssociation>();
if (otherActivity.getDataOutputAssociations() != null && !otherActivity.getDataOutputAssociations().isEmpty()) {
for (DataAssociation association : otherActivity.getDataOutputAssociations()) {
dataOutputAssociations.add(association.clone());
}
}
boundaryEvents.clear();
for (BoundaryEvent event : otherActivity.getBoundaryEvents()) {
boundaryEvents.add(event);
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\Activity.java | 1 |
请完成以下Java代码 | public boolean containsKey (final IValidationContext evalCtx, final Object key)
{
return getLocation(key, ITrx.TRXNAME_None) != null;
} // containsKey
/**************************************************************************
* Get Location
* @param key ID as string or integer
* @param trxName transaction
* @return Location
*/
public MLocation getLocation (Object key, String trxName)
{
if (key == null)
return null;
int C_Location_ID = 0;
if (key instanceof Integer)
C_Location_ID = ((Integer)key).intValue();
else if (key != null)
C_Location_ID = Integer.parseInt(key.toString());
//
return getLocation(C_Location_ID, trxName);
} // getLocation
/**
* Get Location
* @param C_Location_ID id
* @param trxName transaction
* @return Location
*/
public MLocation getLocation (int C_Location_ID, String trxName)
{
return MLocation.get(m_ctx, C_Location_ID, trxName);
} // getC_Location_ID
@Override
public String getTableName()
{ | return I_C_Location.Table_Name;
}
@Override
public String getColumnName()
{
return I_C_Location.Table_Name + "." + I_C_Location.COLUMNNAME_C_Location_ID;
} // getColumnName
@Override
public String getColumnNameNotFQ()
{
return I_C_Location.COLUMNNAME_C_Location_ID;
}
/**
* Return data as sorted Array - not implemented
* @param mandatory mandatory
* @param onlyValidated only validated
* @param onlyActive only active
* @param temporary force load for temporary display
* @return null
*/
@Override
public List<Object> getData (boolean mandatory, boolean onlyValidated, boolean onlyActive, boolean temporary)
{
log.error("not implemented");
return null;
} // getArray
} // MLocation | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MLocationLookup.java | 1 |
请完成以下Java代码 | public Builder setInvalid(final String invalidReason)
{
Check.assumeNotEmpty(invalidReason, "invalidReason is not empty");
this.invalidReason = invalidReason;
logger.trace("Layout section was marked as invalid: {}", this);
return this;
}
public Builder setClosableMode(@NonNull final ClosableMode closableMode)
{
this.closableMode = closableMode;
return this;
}
public Builder setCaptionMode(@NonNull final CaptionMode captionMode)
{
this.captionMode = captionMode;
return this;
}
public boolean isValid()
{
return invalidReason == null;
}
public boolean isInvalid() | {
return invalidReason != null;
}
public boolean isNotEmpty()
{
return streamElementBuilders().findAny().isPresent();
}
private Stream<DocumentLayoutElementDescriptor.Builder> streamElementBuilders()
{
return columnsBuilders.stream().flatMap(DocumentLayoutColumnDescriptor.Builder::streamElementBuilders);
}
public Builder setExcludeSpecialFields()
{
streamElementBuilders().forEach(elementBuilder -> elementBuilder.setExcludeSpecialFields());
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutSectionDescriptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public at.erpel.schemas._1p0.documents.extensions.edifact.DocumentExtensionType getDocumentExtension() {
return documentExtension;
}
/**
* Sets the value of the documentExtension property.
*
* @param value
* allowed object is
* {@link at.erpel.schemas._1p0.documents.extensions.edifact.DocumentExtensionType }
*
*/
public void setDocumentExtension(at.erpel.schemas._1p0.documents.extensions.edifact.DocumentExtensionType value) {
this.documentExtension = value;
}
/**
* Gets the value of the erpelDocumentExtension property.
*
* @return | * possible object is
* {@link ErpelDocumentExtensionType }
*
*/
public ErpelDocumentExtensionType getErpelDocumentExtension() {
return erpelDocumentExtension;
}
/**
* Sets the value of the erpelDocumentExtension property.
*
* @param value
* allowed object is
* {@link ErpelDocumentExtensionType }
*
*/
public void setErpelDocumentExtension(ErpelDocumentExtensionType value) {
this.erpelDocumentExtension = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ext\DocumentExtensionType.java | 2 |
请完成以下Java代码 | public class IPOnlineUtil {
private static RestTemplate restTemplate;
private final RestTemplate template;
public static final String IP_API_URL = "http://ip-api.com/json/";
public IPOnlineUtil(RestTemplate restTemplate) {
this.template = restTemplate;
}
/**
* init RestTemplate
*/
@PostConstruct
public void init() {
setRestTemplate(this.template);
}
/**
* init RestTemplate
*/
private static void setRestTemplate(RestTemplate template) {
restTemplate = template;
}
/** | * get country by ip
*
* @param ip
* @return
*/
public static CountryInfo getCountryByIpOnline(String ip) {
ResponseEntity<CountryInfo> entity = restTemplate.getForEntity(
IP_API_URL + ip + "?lang=zh-CN",
CountryInfo.class
);
return entity.getBody();
}
} | repos\springboot-demo-master\ipfilter\src\main\java\com\et\ipfilter\util\IPOnlineUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getResourceType() {
return this.resourceType;
}
public void setResourceType(String resourceType) {
this.resourceType = resourceType;
}
public @Nullable Map<String, String> getResourceLabels() {
return this.resourceLabels;
}
public void setResourceLabels(@Nullable Map<String, String> resourceLabels) {
this.resourceLabels = resourceLabels;
}
public boolean isUseSemanticMetricTypes() {
return this.useSemanticMetricTypes;
}
public void setUseSemanticMetricTypes(boolean useSemanticMetricTypes) {
this.useSemanticMetricTypes = useSemanticMetricTypes;
} | public String getMetricTypePrefix() {
return this.metricTypePrefix;
}
public void setMetricTypePrefix(String metricTypePrefix) {
this.metricTypePrefix = metricTypePrefix;
}
public boolean isAutoCreateMetricDescriptors() {
return this.autoCreateMetricDescriptors;
}
public void setAutoCreateMetricDescriptors(boolean autoCreateMetricDescriptors) {
this.autoCreateMetricDescriptors = autoCreateMetricDescriptors;
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\stackdriver\StackdriverProperties.java | 2 |
请完成以下Java代码 | final class ThreadLocalLoggableHolder
{
/**
* Temporary set the current thread level loggable to given one.
* The method is designed to be used in try-with-resources block, so the previous thread level loggable will be restored when the returned closeable will be closed.
*/
/* package */ IAutoCloseable temporarySetLoggable(@NonNull final ILoggable loggable)
{
final ILoggable loggableOld = loggableRef.get();
loggableRef.set(loggable);
return new IAutoCloseable()
{
boolean closed = false;
@Override
public void close()
{
if (closed)
{
return;
}
closed = true;
loggable.flush();
loggableRef.set(loggableOld);
}
};
}
/**
* @return current thread's {@link ILoggable} instance or the {@link NullLoggable}. Never returns <code>null</code>
*/
@NonNull
/* package */ ILoggable getLoggable()
{
return Objects.requireNonNull(getLoggableOr(Loggables.nop()));
}
/**
* @return current thread's {@link ILoggable} instance or <code>defaultLoggable</code> if there was no thread level {@link ILoggable}
*/ | @Nullable
/* package */ ILoggable getLoggableOr(@Nullable final ILoggable defaultLoggable)
{
final ILoggable loggable = loggableRef.get();
return loggable != null ? loggable : defaultLoggable;
}
/**
* Holds the {@link ILoggable} instance of current thread
*/
public static final ThreadLocalLoggableHolder instance = new ThreadLocalLoggableHolder();
private final ThreadLocal<ILoggable> loggableRef = new ThreadLocal<>();
private ThreadLocalLoggableHolder()
{
super();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\ThreadLocalLoggableHolder.java | 1 |
请完成以下Java代码 | public IAttributeValueCallout getAttributeValueCallout(final I_M_Attribute attribute)
{
throw new AttributeNotFoundException(attribute, this);
}
@Override
public void onChildAttributeStorageAdded(final IAttributeStorage childAttributeStorage)
{
throw new HUException("Null storage cannot have children");
}
@Override
public void onChildAttributeStorageRemoved(final IAttributeStorage childAttributeStorageRemoved)
{
throw new HUException("Null storage cannot have children");
}
@Override
public boolean isReadonlyUI(final IAttributeValueContext ctx, final I_M_Attribute attribute)
{
throw new AttributeNotFoundException(attribute, this);
}
@Override
public boolean isDisplayedUI(final I_M_Attribute attribute, final Set<ProductId> productIds)
{
return false;
}
@Override
public boolean isMandatory(final @NonNull I_M_Attribute attribute, final Set<ProductId> productIds, final boolean isMaterialReceipt)
{
return false;
}
@Override
public void pushUp()
{
// nothing
}
@Override
public void pushUpRollback()
{
// nothing
}
@Override
public void pushDown()
{
// nothing
}
@Override
public void saveChangesIfNeeded()
{
// nothing
// NOTE: not throwing UnsupportedOperationException because this storage contains no attributes so it will never have something to change
}
@Override
public void setSaveOnChange(final boolean saveOnChange)
{
// nothing
// NOTE: not throwing UnsupportedOperationException because this storage contains no attributes so it will never have something to change
}
@Override
public IAttributeStorageFactory getAttributeStorageFactory()
{
throw new UnsupportedOperationException();
}
@Nullable
@Override
public UOMType getQtyUOMTypeOrNull()
{
// no UOMType available
return null;
}
@Override
public String toString()
{ | return "NullAttributeStorage []";
}
@Override
public BigDecimal getStorageQtyOrZERO()
{
// no storage quantity available; assume ZERO
return BigDecimal.ZERO;
}
/**
* @return <code>false</code>.
*/
@Override
public boolean isVirtual()
{
return false;
}
@Override
public boolean isNew(final I_M_Attribute attribute)
{
throw new AttributeNotFoundException(attribute, this);
}
/**
* @return true, i.e. never disposed
*/
@Override
public boolean assertNotDisposed()
{
return true; // not disposed
}
@Override
public boolean assertNotDisposedTree()
{
return true; // not disposed
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\NullAttributeStorage.java | 1 |
请完成以下Java代码 | public long executeCount(CommandContext commandContext) {
return CommandContextUtil.getUserEntityManager(commandContext).findUserCountByQueryCriteria(this);
}
@Override
public List<User> executeList(CommandContext commandContext) {
return CommandContextUtil.getUserEntityManager(commandContext).findUserByQueryCriteria(this);
}
// getters //////////////////////////////////////////////////////////
@Override
public String getId() {
return id;
}
public List<String> getIds() {
return ids;
}
public String getIdIgnoreCase() {
return idIgnoreCase;
}
public String getFirstName() {
return firstName;
}
public String getFirstNameLike() {
return firstNameLike;
}
public String getFirstNameLikeIgnoreCase() {
return firstNameLikeIgnoreCase;
}
public String getLastName() {
return lastName;
}
public String getLastNameLike() {
return lastNameLike;
}
public String getLastNameLikeIgnoreCase() {
return lastNameLikeIgnoreCase;
}
public String getEmail() {
return email;
}
public String getEmailLike() {
return emailLike;
}
public String getGroupId() { | return groupId;
}
public List<String> getGroupIds() {
return groupIds;
}
public String getFullNameLike() {
return fullNameLike;
}
public String getFullNameLikeIgnoreCase() {
return fullNameLikeIgnoreCase;
}
public String getDisplayName() {
return displayName;
}
public String getDisplayNameLike() {
return displayNameLike;
}
public String getDisplayNameLikeIgnoreCase() {
return displayNameLikeIgnoreCase;
}
public String getTenantId() {
return tenantId;
}
} | repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\UserQueryImpl.java | 1 |
请完成以下Java代码 | public void onUserLogin(int AD_Org_ID, int AD_Role_ID, int AD_User_ID)
{
if (!isAvailable())
{
return;
}
// Don't start the printing client for System Administrators because we will clutter our migration scripts
if (AD_Role_ID == Env.CTXVALUE_AD_Role_ID_System)
{
return;
}
try
{
//
// Get HostKey
final Properties ctx = Env.getCtx();
final MFSession session = Services.get(ISessionBL.class).getCurrentSession(ctx);
final String hostKey = session.getOrCreateHostKey(ctx);
//
// Create/Start the printing client thread *if* we do not use another client's config
final I_AD_Printer_Config printerConfig = Services.get(IPrintingDAO.class).retrievePrinterConfig(hostKey, null/*userToPrintId*/);
if (printerConfig == null // no print config yet, so it can't be set to "use shared"
|| printerConfig.getAD_Printer_Config_Shared_ID() <= 0)
{
final IPrintingClientDelegate printingClient = Services.get(IPrintingClientDelegate.class);
if (!printingClient.isStarted())
{ | printingClient.start();
}
}
}
catch (Throwable t)
{
clientStartupIssue = t;
logger.warn(t.getLocalizedMessage(), t);
Services.get(IClientUI.class).error(Env.WINDOW_MAIN, "Printing client not available", t.getLocalizedMessage());
}
}
@Override
public void beforeLogout(final MFSession session)
{
// make sure printing client is stopped BEFORE logout, when session is still active and database accessible
final IPrintingClientDelegate printingClient = Services.get(IPrintingClientDelegate.class);
printingClient.stop();
}
@Override
public void afterLogout(final MFSession session)
{
// reset, because for another user/role, the client startup might be OK
clientStartupIssue = null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\model\validator\SwingPrintingClientValidator.java | 1 |
请完成以下Java代码 | public Stream<? extends IViewRow> streamByIds(final DocumentIdsSelection rowIds)
{
return rows.streamTopLevelRowsByIds(rowIds);
}
public List<PurchaseRow> getRows()
{
return rows.getAll();
}
@Override
public void notifyRecordsChanged(
@NonNull final TableRecordReferenceSet recordRefs,
final boolean watchedByFrontend)
{
}
@Override
public void patchViewRow(
@NonNull final RowEditingContext ctx,
@NonNull final List<JSONDocumentChangedEvent> fieldChangeRequests)
{
final PurchaseRowId idOfChangedRow = PurchaseRowId.fromDocumentId(ctx.getRowId());
final PurchaseRowChangeRequest rowChangeRequest = PurchaseRowChangeRequest.of(fieldChangeRequests);
patchViewRow(idOfChangedRow, rowChangeRequest);
}
public void patchViewRow(
@NonNull final PurchaseRowId idOfChangedRow,
@NonNull final PurchaseRowChangeRequest rowChangeRequest)
{
rows.patchRow(idOfChangedRow, rowChangeRequest); | // notify the frontend
final DocumentId groupRowDocumentId = idOfChangedRow.toGroupRowId().toDocumentId();
ViewChangesCollector
.getCurrentOrAutoflush()
.collectRowChanged(this, groupRowDocumentId);
}
@Override
public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors()
{
return additionalRelatedProcessDescriptors;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseView.java | 1 |
请完成以下Java代码 | public class SaveProcessDefinitionInfoCmd implements Command<Void>, Serializable {
private static final long serialVersionUID = 1L;
protected String processDefinitionId;
protected ObjectNode infoNode;
public SaveProcessDefinitionInfoCmd(String processDefinitionId, ObjectNode infoNode) {
this.processDefinitionId = processDefinitionId;
this.infoNode = infoNode;
}
public Void execute(CommandContext commandContext) {
if (processDefinitionId == null) {
throw new ActivitiIllegalArgumentException("process definition id is null");
}
if (infoNode == null) {
throw new ActivitiIllegalArgumentException("process definition info node is null");
}
ProcessDefinitionInfoEntityManager definitionInfoEntityManager =
commandContext.getProcessDefinitionInfoEntityManager(); | ProcessDefinitionInfoEntity definitionInfoEntity =
definitionInfoEntityManager.findProcessDefinitionInfoByProcessDefinitionId(processDefinitionId);
if (definitionInfoEntity == null) {
definitionInfoEntity = definitionInfoEntityManager.create();
definitionInfoEntity.setProcessDefinitionId(processDefinitionId);
commandContext.getProcessDefinitionInfoEntityManager().insertProcessDefinitionInfo(definitionInfoEntity);
}
if (infoNode != null) {
try {
ObjectWriter writer = commandContext.getProcessEngineConfiguration().getObjectMapper().writer();
commandContext
.getProcessDefinitionInfoEntityManager()
.updateInfoJson(definitionInfoEntity.getId(), writer.writeValueAsBytes(infoNode));
} catch (Exception e) {
throw new ActivitiException("Unable to serialize info node " + infoNode);
}
}
return null;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\SaveProcessDefinitionInfoCmd.java | 1 |
请完成以下Java代码 | public String getCategory() {
return category;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public String getKey() {
return key;
}
@Override
public String getDescription() {
return description;
}
@Override
public int getVersion() {
return version;
}
@Override
public String getResourceName() {
return resourceName;
}
@Override
public String getDeploymentId() {
return deploymentId;
}
@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 setTenantId(String tenantId) {
this.tenantId = tenantId;
}
} | repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\persistence\entity\AppDefinitionEntityImpl.java | 1 |
请完成以下Java代码 | public String getPrefix() {
return "spring.rabbit.stream.listener";
}
@Override
public KeyName[] getLowCardinalityKeyNames() {
return ListenerLowCardinalityTags.values();
}
};
/**
* Low cardinality tags.
*/
public enum ListenerLowCardinalityTags implements KeyName {
/**
* Listener id.
*/
LISTENER_ID {
@Override
public String asString() {
return "spring.rabbit.stream.listener.id";
}
}
}
/**
* Default {@link RabbitStreamListenerObservationConvention} for Rabbit listener key values. | */
public static class DefaultRabbitStreamListenerObservationConvention
implements RabbitStreamListenerObservationConvention {
/**
* A singleton instance of the convention.
*/
public static final DefaultRabbitStreamListenerObservationConvention INSTANCE =
new DefaultRabbitStreamListenerObservationConvention();
@Override
public KeyValues getLowCardinalityKeyValues(RabbitStreamMessageReceiverContext context) {
return KeyValues.of(RabbitStreamListenerObservation.ListenerLowCardinalityTags.LISTENER_ID.asString(),
context.getListenerId());
}
@Override
public String getContextualName(RabbitStreamMessageReceiverContext context) {
return context.getSource() + " receive";
}
}
} | repos\spring-amqp-main\spring-rabbit-stream\src\main\java\org\springframework\rabbit\stream\micrometer\RabbitStreamListenerObservation.java | 1 |
请完成以下Java代码 | public DecisionRequirementsDefinitionResource getDecisionRequirementsDefinitionByKey(String decisionRequirementsDefinitionKey) {
DecisionRequirementsDefinition decisionRequirementsDefinition = getProcessEngine().getRepositoryService()
.createDecisionRequirementsDefinitionQuery()
.decisionRequirementsDefinitionKey(decisionRequirementsDefinitionKey)
.withoutTenantId().latestVersion().singleResult();
if (decisionRequirementsDefinition == null) {
String errorMessage = String.format("No matching decision requirements definition with key: %s and no tenant-id", decisionRequirementsDefinitionKey);
throw new RestException(Status.NOT_FOUND, errorMessage);
} else {
return getDecisionRequirementsDefinitionById(decisionRequirementsDefinition.getId());
}
}
@Override | public DecisionRequirementsDefinitionResource getDecisionRequirementsDefinitionByKeyAndTenantId(String decisionRequirementsDefinitionKey, String tenantId) {
DecisionRequirementsDefinition decisionRequirementsDefinition = getProcessEngine().getRepositoryService()
.createDecisionRequirementsDefinitionQuery()
.decisionRequirementsDefinitionKey(decisionRequirementsDefinitionKey)
.tenantIdIn(tenantId).latestVersion().singleResult();
if (decisionRequirementsDefinition == null) {
String errorMessage = String.format("No matching decision requirements definition with key: %s and tenant-id: %s", decisionRequirementsDefinitionKey, tenantId);
throw new RestException(Status.NOT_FOUND, errorMessage);
} else {
return getDecisionRequirementsDefinitionById(decisionRequirementsDefinition.getId());
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\DecisionRequirementsDefinitionRestServiceImpl.java | 1 |
请完成以下Java代码 | public Date resolveDuedate(String duedate, int maxIterations) {
try {
DurationHelper dh = new DurationHelper(duedate, clockReader);
return dh.getDateAfter();
} catch (Exception e) {
throw new FlowableException("couldn't resolve duedate: " + e.getMessage(), e);
}
}
// Code below just left in for a while just in case it would be needed
// again.
//
// private static Map<String, Integer> units = new HashMap<String,
// Integer>();
// static {
// units.put("millis", Calendar.MILLISECOND);
// units.put("seconds", Calendar.SECOND);
// units.put("second", Calendar.SECOND);
// units.put("minute", Calendar.MINUTE);
// units.put("minutes", Calendar.MINUTE);
// units.put("hour", Calendar.HOUR);
// units.put("hours", Calendar.HOUR);
// units.put("day", Calendar.DAY_OF_YEAR);
// units.put("days", Calendar.DAY_OF_YEAR);
// units.put("week", Calendar.WEEK_OF_YEAR);
// units.put("weeks", Calendar.WEEK_OF_YEAR);
// units.put("month", Calendar.MONTH);
// units.put("months", Calendar.MONTH);
// units.put("year", Calendar.YEAR);
// units.put("years", Calendar.YEAR);
// }
//
// public Date resolveDuedate(String duedate) {
// Date resolvedDuedate = Clock.getCurrentTime();
//
// StringTokenizer tokenizer = new StringTokenizer(duedate, " and ");
// while (tokenizer.hasMoreTokens()) {
// String singleUnitQuantity = tokenizer.nextToken();
// resolvedDuedate = addSingleUnitQuantity(resolvedDuedate,
// singleUnitQuantity);
// }
//
// return resolvedDuedate;
// } | //
// protected Date addSingleUnitQuantity(Date startDate, String
// singleUnitQuantity) {
// int spaceIndex = singleUnitQuantity.indexOf(' ');
// if (spaceIndex==-1 || singleUnitQuantity.length() > spaceIndex+1) {
// throw new
// ActivitiException("invalid duedate format: "+singleUnitQuantity);
// }
//
// String quantityText = singleUnitQuantity.substring(0, spaceIndex);
// Integer quantity = Integer.valueOf(quantityText);
//
// String unitText = singleUnitQuantity
// .substring(spaceIndex+1)
// .trim()
// .toLowerCase();
//
// int unit = units.get(unitText);
//
// GregorianCalendar calendar = new GregorianCalendar();
// calendar.setTime(startDate);
// calendar.add(unit, quantity);
//
// return calendar.getTime();
// }
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\calendar\DurationBusinessCalendar.java | 1 |
请完成以下Java代码 | protected ExecutionEntity intersect(Set<ExecutionEntity> executions, String[] executionIds) {
Set<String> executionIdSet = new HashSet<String>();
for (String executionId : executionIds) {
executionIdSet.add(executionId);
}
for (ExecutionEntity execution : executions) {
if (executionIdSet.contains(execution.getId())) {
return execution;
}
}
throw new ProcessEngineException("Could not determine execution");
}
protected void initialize() {
ExecutionEntity processInstance = commandContext.getExecutionManager().findExecutionById(processInstanceId);
this.processDefinition = processInstance.getProcessDefinition();
List<ExecutionEntity> executions = fetchExecutionsForProcessInstance(processInstance);
executions.add(processInstance);
List<ExecutionEntity> leaves = findLeaves(executions);
assignExecutionsToActivities(leaves);
}
protected void assignExecutionsToActivities(List<ExecutionEntity> leaves) {
for (ExecutionEntity leaf : leaves) {
ScopeImpl activity = leaf.getActivity();
if (activity != null) {
if (leaf.getActivityInstanceId() != null) {
EnsureUtil.ensureNotNull("activity", activity);
submitExecution(leaf, activity);
}
mergeScopeExecutions(leaf);
}
else if (leaf.isProcessInstanceExecution()) {
submitExecution(leaf, leaf.getProcessDefinition());
}
}
}
protected void mergeScopeExecutions(ExecutionEntity leaf) {
Map<ScopeImpl, PvmExecutionImpl> mapping = leaf.createActivityExecutionMapping();
for (Map.Entry<ScopeImpl, PvmExecutionImpl> mappingEntry : mapping.entrySet()) {
ScopeImpl scope = mappingEntry.getKey();
ExecutionEntity scopeExecution = (ExecutionEntity) mappingEntry.getValue();
submitExecution(scopeExecution, scope);
}
}
protected List<ExecutionEntity> fetchExecutionsForProcessInstance(ExecutionEntity execution) {
List<ExecutionEntity> executions = new ArrayList<ExecutionEntity>();
executions.addAll(execution.getExecutions());
for (ExecutionEntity child : execution.getExecutions()) {
executions.addAll(fetchExecutionsForProcessInstance(child)); | }
return executions;
}
protected List<ExecutionEntity> findLeaves(List<ExecutionEntity> executions) {
List<ExecutionEntity> leaves = new ArrayList<ExecutionEntity>();
for (ExecutionEntity execution : executions) {
if (isLeaf(execution)) {
leaves.add(execution);
}
}
return leaves;
}
/**
* event-scope executions are not considered in this mapping and must be ignored
*/
protected boolean isLeaf(ExecutionEntity execution) {
if (CompensationBehavior.isCompensationThrowing(execution)) {
return true;
}
else {
return !execution.isEventScope() && execution.getNonEventScopeExecutions().isEmpty();
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ActivityExecutionTreeMapping.java | 1 |
请完成以下Java代码 | public void setQtyOrdered (BigDecimal QtyOrdered)
{
set_Value (COLUMNNAME_QtyOrdered, QtyOrdered);
}
/** Get Bestellte Menge.
@return Bestellte Menge
*/
public BigDecimal getQtyOrdered ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOrdered);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Reservierte Menge.
@param QtyReserved
Reservierte Menge
*/
public void setQtyReserved (BigDecimal QtyReserved)
{
set_Value (COLUMNNAME_QtyReserved, QtyReserved);
}
/** Get Reservierte Menge.
@return Reservierte Menge
*/
public BigDecimal getQtyReserved ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyReserved);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Revenue Recognition Amt.
@param RRAmt
Revenue Recognition Amount
*/
public void setRRAmt (BigDecimal RRAmt)
{
set_Value (COLUMNNAME_RRAmt, RRAmt);
}
/** Get Revenue Recognition Amt.
@return Revenue Recognition Amount
*/
public BigDecimal getRRAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RRAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Revenue Recognition Start.
@param RRStartDate
Revenue Recognition Start Date
*/
public void setRRStartDate (Timestamp RRStartDate)
{
set_Value (COLUMNNAME_RRStartDate, RRStartDate);
}
/** Get Revenue Recognition Start.
@return Revenue Recognition Start Date
*/
public Timestamp getRRStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_RRStartDate);
}
public org.compiere.model.I_C_OrderLine getRef_OrderLine() throws RuntimeException
{
return (org.compiere.model.I_C_OrderLine)MTable.get(getCtx(), org.compiere.model.I_C_OrderLine.Table_Name)
.getPO(getRef_OrderLine_ID(), get_TrxName()); }
/** Set Referenced Order Line.
@param Ref_OrderLine_ID
Reference to corresponding Sales/Purchase Order
*/
public void setRef_OrderLine_ID (int Ref_OrderLine_ID)
{
if (Ref_OrderLine_ID < 1)
set_Value (COLUMNNAME_Ref_OrderLine_ID, null); | else
set_Value (COLUMNNAME_Ref_OrderLine_ID, Integer.valueOf(Ref_OrderLine_ID));
}
/** Get Referenced Order Line.
@return Reference to corresponding Sales/Purchase Order
*/
public int getRef_OrderLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Ref_OrderLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Ressourcenzuordnung.
@param S_ResourceAssignment_ID
Ressourcenzuordnung
*/
public void setS_ResourceAssignment_ID (int S_ResourceAssignment_ID)
{
if (S_ResourceAssignment_ID < 1)
set_Value (COLUMNNAME_S_ResourceAssignment_ID, null);
else
set_Value (COLUMNNAME_S_ResourceAssignment_ID, Integer.valueOf(S_ResourceAssignment_ID));
}
/** Get Ressourcenzuordnung.
@return Ressourcenzuordnung
*/
public int getS_ResourceAssignment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_ResourceAssignment_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_RV_C_OrderLine_Overview.java | 1 |
请完成以下Java代码 | public String getProperty(final String name, final String defaultValue)
{
final String value = getProperty(name);
if (value == null)
{
return defaultValue;
}
return value;
}
public int getPropertyAsInt(final String name, final int defaultValue)
{
final Object value = get(name);
if (value == null)
{
return defaultValue;
}
else if (value instanceof Number)
{
return ((Number)value).intValue();
}
else if (value instanceof String)
{
try
{
return Integer.parseInt(value.toString());
}
catch (final NumberFormatException e)
{
throw new RuntimeException("Property " + name + " has invalid integer value: " + value);
}
}
else
{
throw new RuntimeException("Property " + name + " cannot be converted to integer: " + value + " (class=" + value.getClass() + ")");
}
}
/**
*
* @param name
* @param interfaceClazz
* @return instance of given class/interface; never returns <code>null</code>
*/
public <T> T getInstance(final String name, final Class<T> interfaceClazz)
{
final Object value = get(name);
if (value == null)
{
throw new RuntimeException("No class of " + interfaceClazz + " found for property " + name);
}
else if (value instanceof String)
{
final String classname = value.toString();
return Util.getInstance(classname, interfaceClazz);
}
else if (value instanceof Class)
{
final Class<?> clazz = (Class<?>)value;
if (interfaceClazz.isAssignableFrom(clazz))
{
try
{
@SuppressWarnings("unchecked")
final T obj = (T)clazz.newInstance();
return obj;
}
catch (final Exception e)
{
throw new RuntimeException(e);
}
}
else
{
throw new RuntimeException("Invalid object " + value + " for property " + name + " (expected class: " + interfaceClazz + ")");
}
}
else if (interfaceClazz.isAssignableFrom(value.getClass()))
{
@SuppressWarnings("unchecked")
final T obj = (T)value;
return obj;
}
else
{
throw new RuntimeException("Invalid object " + value + " for property " + name + " (expected class: " + interfaceClazz + ")"); | }
}
public <T> T get(final String name)
{
if (props.containsKey(name))
{
@SuppressWarnings("unchecked")
final T value = (T)props.get(name);
return value;
}
// Check other sources
for (final IContext source : sources)
{
final String valueStr = source.getProperty(name);
if (valueStr != null)
{
@SuppressWarnings("unchecked")
final T value = (T)valueStr;
return value;
}
}
// Check defaults
@SuppressWarnings("unchecked")
final T value = (T)defaults.get(name);
return value;
}
@Override
public String toString()
{
return "Context["
+ "sources=" + sources
+ ", properties=" + props
+ ", defaults=" + defaults
+ "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\Context.java | 1 |
请完成以下Java代码 | public MutableAcl getFromCache(ObjectIdentity objectIdentity) {
Assert.notNull(objectIdentity, "ObjectIdentity required");
return getFromCache((Object) objectIdentity);
}
@Override
public MutableAcl getFromCache(Serializable pk) {
Assert.notNull(pk, "Primary key (identifier) required");
return getFromCache((Object) pk);
}
@Override
public void putInCache(MutableAcl acl) {
Assert.notNull(acl, "Acl required");
Assert.notNull(acl.getObjectIdentity(), "ObjectIdentity required");
Assert.notNull(acl.getId(), "ID required");
if ((acl.getParentAcl() != null) && (acl.getParentAcl() instanceof MutableAcl)) {
putInCache((MutableAcl) acl.getParentAcl());
}
this.cache.put(acl.getObjectIdentity(), acl);
this.cache.put(acl.getId(), acl);
}
private MutableAcl getFromCache(Object key) {
Cache.ValueWrapper element = this.cache.get(key);
if (element == null) {
return null;
}
return initializeTransientFields((MutableAcl) element.get());
} | private MutableAcl initializeTransientFields(MutableAcl value) {
if (value instanceof AclImpl) {
FieldUtils.setProtectedFieldValue("aclAuthorizationStrategy", value, this.aclAuthorizationStrategy);
FieldUtils.setProtectedFieldValue("permissionGrantingStrategy", value, this.permissionGrantingStrategy);
}
if (value.getParentAcl() != null) {
initializeTransientFields((MutableAcl) value.getParentAcl());
}
return value;
}
@Override
public void clearCache() {
this.cache.clear();
}
} | repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\domain\SpringCacheBasedAclCache.java | 1 |
请完成以下Java代码 | public class InfoProductSubstitute implements IInfoProductDetail
{
private final Logger log = LogManager.getLogger(getClass());
private IMiniTable substituteTbl = null;
private String m_sqlSubstitute;
public InfoProductSubstitute()
{
initUI();
init();
}
private void initUI()
{
MiniTable table = new MiniTable();
table.setRowSelectionAllowed(false);
substituteTbl = table;
}
private void init()
{
ColumnInfo[] s_layoutSubstitute = new ColumnInfo[] {
new ColumnInfo(Msg.translate(Env.getCtx(), "Warehouse"), "orgname", String.class),
new ColumnInfo(
Msg.translate(Env.getCtx(), "Value"),
"(Select Value from M_Product p where p.M_Product_ID=M_PRODUCT_SUBSTITUTERELATED_V.Substitute_ID)",
String.class),
new ColumnInfo(Msg.translate(Env.getCtx(), "Name"), "Name", String.class),
new ColumnInfo(Msg.translate(Env.getCtx(), "QtyAvailable"), "QtyAvailable", Double.class),
new ColumnInfo(Msg.translate(Env.getCtx(), "QtyOnHand"), "QtyOnHand", Double.class),
new ColumnInfo(Msg.translate(Env.getCtx(), "QtyReserved"), "QtyReserved", Double.class),
new ColumnInfo(Msg.translate(Env.getCtx(), "PriceStd"), "PriceStd", Double.class) };
String s_sqlFrom = "M_PRODUCT_SUBSTITUTERELATED_V";
String s_sqlWhere = "M_Product_ID = ? AND M_PriceList_Version_ID = ? and RowType = 'S'";
m_sqlSubstitute = substituteTbl.prepareTable(s_layoutSubstitute, s_sqlFrom, s_sqlWhere, false, "M_PRODUCT_SUBSTITUTERELATED_V");
substituteTbl.setMultiSelection(false);
// substituteTbl.addMouseListener(this);
// substituteTbl.getSelectionModel().addListSelectionListener(this);
substituteTbl.autoSize();
}
private void refresh(int M_Product_ID, int M_PriceList_Version_ID)
{
String sql = m_sqlSubstitute;
log.trace(sql);
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{ | pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, M_Product_ID);
pstmt.setInt(2, M_PriceList_Version_ID);
rs = pstmt.executeQuery();
substituteTbl.loadTable(rs);
rs.close();
}
catch (Exception e)
{
log.warn(sql, e);
}
finally
{
DB.close(rs, pstmt);
rs = null;
pstmt = null;
}
}
public java.awt.Component getComponent()
{
return (java.awt.Component)substituteTbl;
}
@Override
public void refresh(int M_Product_ID, int M_Warehouse_ID, int M_AttributeSetInstance_ID, int M_PriceList_Version_ID)
{
refresh(M_Product_ID, M_PriceList_Version_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\InfoProductSubstitute.java | 1 |
请完成以下Java代码 | public BPartnerLocation newLocation(@NonNull final ExternalIdentifier locationIdentifier)
{
final BPartnerLocationBuilder locationBuilder = BPartnerLocation.builder();
final BPartnerLocation location;
switch (locationIdentifier.getType())
{
case METASFRESH_ID:
throw new AdempiereException("No inserts are allowed with this type. External identifier: " + locationIdentifier.getRawValue());
case GLN:
final GLN gln = locationIdentifier.asGLN();
location = locationBuilder.gln(gln).build();
gln2Location.put(gln, location);
break;
case EXTERNAL_REFERENCE:
location = locationBuilder.build();
break;
default:
throw new InvalidIdentifierException(locationIdentifier.getRawValue());
}
bpartnerComposite
.getLocations()
.add(location);
return location;
}
public Collection<BPartnerLocation> getUnusedLocations() | {
return id2UnusedLocation.values();
}
public void resetBillToDefaultFlags()
{
for (final BPartnerLocation bpartnerLocation : getUnusedLocations())
{
bpartnerLocation.getLocationType().setBillToDefault(false);
}
}
public void resetShipToDefaultFlags()
{
for (final BPartnerLocation bpartnerLocation : getUnusedLocations())
{
bpartnerLocation.getLocationType().setShipToDefault(false);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\bpartner\bpartnercomposite\jsonpersister\ShortTermLocationIndex.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Adempiere adempiere(final WebRestApiContextProvider webuiContextProvider)
{
Env.setContextProvider(webuiContextProvider);
AdempiereException.enableCaptureLanguageOnConstructionTime(); // because usually at the time the message is (lazy) parsed the user session context is no longer available.
InterfaceWrapperHelper.registerHelper(new DocumentInterfaceWrapperHelper());
final IMigrationLogger migrationLogger = Services.get(IMigrationLogger.class);
migrationLogger.addTablesToIgnoreList(
I_T_WEBUI_ViewSelection.Table_Name,
I_T_WEBUI_ViewSelectionLine.Table_Name,
I_T_WEBUI_ViewSelection_ToDelete.Table_Name
);
return Env.getSingleAdempiereInstance(applicationContext);
}
@Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> servletContainerCustomizer()
{
return tomcatContainerFactory -> tomcatContainerFactory.addConnectorCustomizers(connector -> {
final AbstractHttp11Protocol<?> httpProtocol = (AbstractHttp11Protocol<?>)connector.getProtocolHandler();
httpProtocol.setCompression("on");
httpProtocol.setCompressionMinSize(256);
final String mimeTypes = httpProtocol.getCompressibleMimeType();
final String mimeTypesWithJson = mimeTypes + "," + MediaType.APPLICATION_JSON_VALUE + ",application/javascript";
httpProtocol.setCompressibleMimeType(mimeTypesWithJson); | });
}
@Bean(ConfigConstants.BEANNAME_WebuiTaskScheduler)
public TaskScheduler webuiTaskScheduler()
{
final ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setThreadNamePrefix("webui-task-scheduler-");
taskScheduler.setDaemon(true);
taskScheduler.setPoolSize(10);
return taskScheduler;
}
private static void setDefaultProperties()
{
if (Check.isEmpty(System.getProperty("PropertyFile"), true))
{
System.setProperty("PropertyFile", "./metasfresh.properties");
}
if (Check.isBlank(System.getProperty(SYSTEM_PROPERTY_APP_NAME)))
{
System.setProperty(SYSTEM_PROPERTY_APP_NAME, WebRestApiApplication.class.getSimpleName());
}
}
} | repos\metasfresh-new_dawn_uat\backend\metasfresh-webui-api\src\main\java\de\metas\ui\web\WebRestApiApplication.java | 2 |
请完成以下Java代码 | public Set<String> getRequestedScopes() {
Set<String> requestedScopes = getAuthorization().getAttribute(OAuth2ParameterNames.SCOPE);
return (requestedScopes != null) ? requestedScopes : Collections.emptySet();
}
/**
* Constructs a new {@link Builder} with the provided
* {@link OAuth2DeviceVerificationAuthenticationToken}.
* @param authentication the {@link OAuth2DeviceVerificationAuthenticationToken}
* @return the {@link Builder}
*/
public static Builder with(OAuth2DeviceVerificationAuthenticationToken authentication) {
return new Builder(authentication);
}
/**
* A builder for {@link OAuth2DeviceVerificationAuthenticationContext}.
*/
public static final class Builder extends AbstractBuilder<OAuth2DeviceVerificationAuthenticationContext, Builder> {
private Builder(OAuth2DeviceVerificationAuthenticationToken authentication) {
super(authentication);
}
/**
* Sets the {@link RegisteredClient registered client}.
* @param registeredClient the {@link RegisteredClient}
* @return the {@link Builder} for further configuration
*/
public Builder registeredClient(RegisteredClient registeredClient) {
return put(RegisteredClient.class, registeredClient);
}
/**
* Sets the {@link OAuth2Authorization authorization}.
* @param authorization the {@link OAuth2Authorization}
* @return the {@link Builder} for further configuration
*/
public Builder authorization(OAuth2Authorization authorization) {
return put(OAuth2Authorization.class, authorization); | }
/**
* Sets the {@link OAuth2AuthorizationConsent authorization consent}.
* @param authorizationConsent the {@link OAuth2AuthorizationConsent}
* @return the {@link Builder} for further configuration
*/
public Builder authorizationConsent(OAuth2AuthorizationConsent authorizationConsent) {
return put(OAuth2AuthorizationConsent.class, authorizationConsent);
}
/**
* Builds a new {@link OAuth2DeviceVerificationAuthenticationContext}.
* @return the {@link OAuth2DeviceVerificationAuthenticationContext}
*/
@Override
public OAuth2DeviceVerificationAuthenticationContext build() {
Assert.notNull(get(RegisteredClient.class), "registeredClient cannot be null");
Assert.notNull(get(OAuth2Authorization.class), "authorization cannot be null");
return new OAuth2DeviceVerificationAuthenticationContext(getContext());
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2DeviceVerificationAuthenticationContext.java | 1 |
请完成以下Java代码 | private I_C_BP_PurchaseSchedule createOrUpdateRecord(@NonNull final BPPurchaseSchedule schedule)
{
final I_C_BP_PurchaseSchedule scheduleRecord;
if (schedule.getBpPurchaseScheduleId() != null)
{
final int repoId = schedule.getBpPurchaseScheduleId().getRepoId();
scheduleRecord = load(repoId, I_C_BP_PurchaseSchedule.class);
}
else
{
scheduleRecord = newInstance(I_C_BP_PurchaseSchedule.class);
}
scheduleRecord.setC_BPartner_ID(BPartnerId.toRepoIdOr(schedule.getBpartnerId(), 0));
scheduleRecord.setValidFrom(TimeUtil.asTimestamp(schedule.getValidFrom()));
scheduleRecord.setReminderTimeInMin((int)schedule.getReminderTime().toMinutes());
final Frequency frequency = schedule.getFrequency();
scheduleRecord.setFrequencyType(toFrequencyTypeString(frequency.getType()));
if (frequency.getType() == FrequencyType.Weekly)
{
scheduleRecord.setFrequency(frequency.getEveryNthWeek());
}
else if (frequency.getType() == FrequencyType.Monthly)
{
scheduleRecord.setFrequency(frequency.getEveryNthMonth());
scheduleRecord.setMonthDay(frequency.getOnlyDaysOfMonth()
.stream()
.findFirst()
.orElseThrow(() -> new AdempiereException("No month of the day " + Frequency.class + ": " + frequency)));
}
final ImmutableSet<DayOfWeek> daysOfWeek = frequency.getOnlyDaysOfWeek();
setDaysOfWeek(scheduleRecord, daysOfWeek);
return scheduleRecord;
}
private static void setDaysOfWeek(@NonNull final I_C_BP_PurchaseSchedule scheduleRecord, @NonNull final ImmutableSet<DayOfWeek> daysOfWeek)
{
if (daysOfWeek.contains(DayOfWeek.MONDAY))
{
scheduleRecord.setOnMonday(true);
} | if (daysOfWeek.contains(DayOfWeek.TUESDAY))
{
scheduleRecord.setOnTuesday(true);
}
if (daysOfWeek.contains(DayOfWeek.WEDNESDAY))
{
scheduleRecord.setOnWednesday(true);
}
if (daysOfWeek.contains(DayOfWeek.THURSDAY))
{
scheduleRecord.setOnThursday(true);
}
if (daysOfWeek.contains(DayOfWeek.FRIDAY))
{
scheduleRecord.setOnFriday(true);
}
if (daysOfWeek.contains(DayOfWeek.SATURDAY))
{
scheduleRecord.setOnSaturday(true);
}
if (daysOfWeek.contains(DayOfWeek.SUNDAY))
{
scheduleRecord.setOnSunday(true);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\BPPurchaseScheduleRepository.java | 1 |
请完成以下Java代码 | public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
initStartTimeAsDate();
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
initEndTimeAsDate();
}
public Date getStartTimeAsDate() {
return startTimeAsDate;
}
public Date getEndTimeAsDate() {
return endTimeAsDate;
} | @Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
BatchWindowConfiguration that = (BatchWindowConfiguration) o;
if (startTime != null ? !startTime.equals(that.startTime) : that.startTime != null)
return false;
return endTime != null ? endTime.equals(that.endTime) : that.endTime == null;
}
@Override
public int hashCode() {
int result = startTime != null ? startTime.hashCode() : 0;
result = 31 * result + (endTime != null ? endTime.hashCode() : 0);
return result;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\BatchWindowConfiguration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public SSLEngine createClientSslEngine(String peerHost, int peerPort, String endpointIdentification) {
SslBundle sslBundle = this.sslBundle;
Assert.state(sslBundle != null, "'sslBundle' must not be null");
SSLEngine sslEngine = sslBundle.createSslContext().createSSLEngine(peerHost, peerPort);
sslEngine.setUseClientMode(true);
SSLParameters sslParams = sslEngine.getSSLParameters();
sslParams.setEndpointIdentificationAlgorithm(endpointIdentification);
sslEngine.setSSLParameters(sslParams);
return sslEngine;
}
@Override
public SSLEngine createServerSslEngine(String peerHost, int peerPort) {
SslBundle sslBundle = this.sslBundle;
Assert.state(sslBundle != null, "'sslBundle' must not be null");
SSLEngine sslEngine = sslBundle.createSslContext().createSSLEngine(peerHost, peerPort);
sslEngine.setUseClientMode(false);
return sslEngine;
}
@Override
public boolean shouldBeRebuilt(Map<String, Object> nextConfigs) {
return !nextConfigs.equals(this.configs);
} | @Override
public Set<String> reconfigurableConfigs() {
return Set.of(SSL_BUNDLE_CONFIG_NAME);
}
@Override
public @Nullable KeyStore keystore() {
SslBundle sslBundle = this.sslBundle;
Assert.state(sslBundle != null, "'sslBundle' must not be null");
return sslBundle.getStores().getKeyStore();
}
@Override
public @Nullable KeyStore truststore() {
SslBundle sslBundle = this.sslBundle;
Assert.state(sslBundle != null, "'sslBundle' must not be null");
return sslBundle.getStores().getTrustStore();
}
} | repos\spring-boot-4.0.1\module\spring-boot-kafka\src\main\java\org\springframework\boot\kafka\autoconfigure\SslBundleSslEngineFactory.java | 2 |
请完成以下Java代码 | public BigDecimal calculateBaseAmt(@NonNull final BigDecimal amount, final boolean taxIncluded, final int scale)
{
try (final MDC.MDCCloseable ignored = TableRecordMDC.putTableRecordReference(I_C_Tax.Table_Name, taxId))
{
if (isWholeTax)
{
log.debug("C_Tax has isWholeTax=true; -> return ZERO");
return BigDecimal.ZERO;
}
if (!taxIncluded)
{
// the given amount is without tax => don't subtract the tax that is no included
log.debug("Parameter taxIncluded=false; -> return given param amount={}", amount);
return amount;
}
final BigDecimal taxAmt = calculateTax(amount, taxIncluded, scale).getTaxAmount();
return amount.subtract(taxAmt);
}
}
/**
* Calculate Tax - no rounding
*
* @param taxIncluded if true tax is calculated from gross otherwise from net
* @return tax amount
*/
public CalculateTaxResult calculateTax(final BigDecimal amount, final boolean taxIncluded, final int scale)
{
// Null Tax
if (rate.signum() == 0)
{
return CalculateTaxResult.ZERO;
}
BigDecimal multiplier = rate.divide(Env.ONEHUNDRED, 12, RoundingMode.HALF_UP);
final BigDecimal taxAmt;
final BigDecimal reverseChargeAmt;
if (isWholeTax)
{
Check.assume(taxIncluded, "TaxIncluded shall be set when IsWholeTax is set");
taxAmt = amount;
reverseChargeAmt = BigDecimal.ZERO; | }
else if (isReverseCharge)
{
Check.assume(!taxIncluded, "TaxIncluded shall NOT be set when IsReverseCharge is set");
taxAmt = BigDecimal.ZERO;
reverseChargeAmt = amount.multiply(multiplier);
}
else if (!taxIncluded) // $100 * 6 / 100 == $6 == $100 * 0.06
{
taxAmt = amount.multiply(multiplier);
reverseChargeAmt = BigDecimal.ZERO;
}
else
// $106 - ($106 / (100+6)/100) == $6 == $106 - ($106/1.06)
{
multiplier = multiplier.add(BigDecimal.ONE);
final BigDecimal base = amount.divide(multiplier, 12, RoundingMode.HALF_UP);
taxAmt = amount.subtract(base);
reverseChargeAmt = BigDecimal.ZERO;
}
final BigDecimal taxAmtFinal = taxAmt.setScale(scale, RoundingMode.HALF_UP);
final BigDecimal reverseChargeTaxAmtFinal = reverseChargeAmt.setScale(scale, RoundingMode.HALF_UP);
log.debug("calculateTax: amount={} (incl={}, multiplier={}, scale={}) = {} [{}] / reverse charge = {} [{}]",
amount, taxIncluded, multiplier, scale, taxAmtFinal, taxAmt, reverseChargeAmt, reverseChargeTaxAmtFinal);
return CalculateTaxResult.builder()
.taxAmount(taxAmtFinal)
.reverseChargeAmt(reverseChargeTaxAmtFinal)
.build();
} // calculateTax
@NonNull
public BigDecimal calculateGross(@NonNull final BigDecimal netAmount, final int scale)
{
return netAmount.add(calculateTax(netAmount, false, scale).getTaxAmount());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\tax\api\Tax.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getTaskCandidateGroup() {
return taskCandidateGroup;
}
public void setTaskCandidateGroup(String taskCandidateGroup) {
this.taskCandidateGroup = taskCandidateGroup;
}
public boolean isIgnoreTaskAssignee() {
return ignoreTaskAssignee;
}
public void setIgnoreTaskAssignee(boolean ignoreTaskAssignee) {
this.ignoreTaskAssignee = ignoreTaskAssignee;
}
public String getRootScopeId() {
return rootScopeId;
}
public void setRootScopeId(String rootScopeId) { | this.rootScopeId = rootScopeId;
}
public String getParentScopeId() {
return parentScopeId;
}
public void setParentScopeId(String parentScopeId) {
this.parentScopeId = parentScopeId;
}
public Set<String> getScopeIds() {
return scopeIds;
}
public void setScopeIds(Set<String> scopeIds) {
this.scopeIds = scopeIds;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskInstanceQueryRequest.java | 2 |
请完成以下Java代码 | private Mono<FindArticlesRequest> createFindArticleRequest(String tag, String author, String favoritedByUser, int offset, int limit) {
var request = new FindArticlesRequest()
.setOffset(offset)
.setLimit(limit)
.setTag(tag);
return addToRequestAuthorId(author, request)
.then(addToRequestFavoritedBy(favoritedByUser, request))
.thenReturn(request);
}
private Mono<User> addToRequestFavoritedBy(String favoritedByUser, FindArticlesRequest request) {
return getFavoritedBy(favoritedByUser).doOnNext(request::setFavoritedBy);
}
private Mono<String> addToRequestAuthorId(String author, FindArticlesRequest request) {
return getAuthorId(author).doOnNext(request::setAuthorId);
} | private Mono<String> getAuthorId(String author) {
if (author == null) {
return Mono.empty();
}
return userRepository.findByUsername(author).map(User::getId);
}
private Mono<User> getFavoritedBy(String favoritedBy) {
if (favoritedBy == null) {
return Mono.empty();
}
return userRepository.findByUsername(favoritedBy);
}
} | repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\article\ArticlesFinder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DTRSD1 getDTRSD1() {
return dtrsd1;
}
/**
* Sets the value of the dtrsd1 property.
*
* @param value
* allowed object is
* {@link DTRSD1 }
*
*/
public void setDTRSD1(DTRSD1 value) {
this.dtrsd1 = value;
}
/**
* Gets the value of the dmark1 property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the dmark1 property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDMARK1().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DMARK1 }
*
*
*/
public List<DMARK1> getDMARK1() {
if (dmark1 == null) {
dmark1 = new ArrayList<DMARK1>();
}
return this.dmark1;
} | /**
* Gets the value of the dqvar1 property.
*
* @return
* possible object is
* {@link DQVAR1 }
*
*/
public DQVAR1 getDQVAR1() {
return dqvar1;
}
/**
* Sets the value of the dqvar1 property.
*
* @param value
* allowed object is
* {@link DQVAR1 }
*
*/
public void setDQVAR1(DQVAR1 value) {
this.dqvar1 = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DETAILXlief.java | 2 |
请完成以下Java代码 | public void windowClosing(WindowEvent e)
{
findPanel.doCancel();
}
});
AEnv.showCenterWindow(builder.getParentFrame(), this);
} // Find
@Override
public void dispose()
{
findPanel.dispose();
removeAll();
super.dispose();
} // dispose | /**************************************************************************
* Get Query - Retrieve result
*
* @return String representation of query
*/
public MQuery getQuery()
{
return findPanel.getQuery();
} // getQuery
/**
* @return true if cancel button pressed
*/
public boolean isCancel()
{
return findPanel.isCancel();
}
} // Find | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\Find.java | 1 |
请完成以下Java代码 | public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public Customer(Integer id, String name, Long phone, String locality, String city, String zip) {
super();
this.id = id;
this.name = name;
this.phone = phone;
this.locality = locality;
this.city = city;
this.zip = zip;
}
public Customer(Integer id, String name, Long phone) {
super();
this.id = id;
this.name = name;
this.phone = phone;
}
public Customer(String name) {
super();
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31; | int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Customer other = (Customer) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public int compareTo(Customer o) {
return this.name.compareTo(o.getName());
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Customer [id=").append(id).append(", name=").append(name).append(", phone=").append(phone).append("]");
return builder.toString();
}
} | repos\tutorials-master\libraries-apache-commons-collections\src\main\java\com\baeldung\commons\collections\collectionutils\Customer.java | 1 |
请完成以下Java代码 | public class WEBUI_Picking_ForcePickToExistingHU extends WEBUI_Picking_PickQtyToExistingHU
implements IProcessPrecondition
{
@Override
protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
final Optional<ProcessPreconditionsResolution> preconditionsResolution = checkValidSelection();
if (preconditionsResolution.isPresent())
{
return ProcessPreconditionsResolution.rejectWithInternalReason(preconditionsResolution.get().getRejectReason());
}
if (!isForceDelivery())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Use WEBUI_Picking_PickQtyToExistingHU for non force shipping cases!");
} | return ProcessPreconditionsResolution.accept();
}
protected String doIt() throws Exception
{
validatePickingToHU();
forcePick(getQtyToPack(), getPackToHuId());
invalidateView();
invalidateParentView();
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\process\WEBUI_Picking_ForcePickToExistingHU.java | 1 |
请完成以下Java代码 | public boolean containsKey(Object key) {
return outputValues.containsKey(key);
}
@Override
public Set<String> keySet() {
return outputValues.keySet();
}
@Override
public Collection<Object> values() {
List<Object> values = new ArrayList<Object>();
for (TypedValue typedValue : outputValues.values()) {
values.add(typedValue.getValue());
}
return values;
}
@Override
public String toString() {
return outputValues.toString();
}
@Override
public boolean containsValue(Object value) {
return values().contains(value);
}
@Override
public Object get(Object key) {
TypedValue typedValue = outputValues.get(key);
if (typedValue != null) {
return typedValue.getValue();
} else {
return null;
}
}
@Override
public Object put(String key, Object value) {
throw new UnsupportedOperationException("decision output is immutable");
}
@Override
public Object remove(Object key) {
throw new UnsupportedOperationException("decision output is immutable");
}
@Override
public void putAll(Map<? extends String, ?> m) { | throw new UnsupportedOperationException("decision output is immutable");
}
@Override
public void clear() {
throw new UnsupportedOperationException("decision output is immutable");
}
@Override
public Set<Entry<String, Object>> entrySet() {
Set<Entry<String, Object>> entrySet = new HashSet<Entry<String, Object>>();
for (Entry<String, TypedValue> typedEntry : outputValues.entrySet()) {
DmnDecisionRuleOutputEntry entry = new DmnDecisionRuleOutputEntry(typedEntry.getKey(), typedEntry.getValue());
entrySet.add(entry);
}
return entrySet;
}
protected class DmnDecisionRuleOutputEntry implements Entry<String, Object> {
protected final String key;
protected final TypedValue typedValue;
public DmnDecisionRuleOutputEntry(String key, TypedValue typedValue) {
this.key = key;
this.typedValue = typedValue;
}
@Override
public String getKey() {
return key;
}
@Override
public Object getValue() {
if (typedValue != null) {
return typedValue.getValue();
} else {
return null;
}
}
@Override
public Object setValue(Object value) {
throw new UnsupportedOperationException("decision output entry is immutable");
}
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnDecisionResultEntriesImpl.java | 1 |
请完成以下Java代码 | public void deleteTenants() {
log.trace("Executing deleteTenants");
tenantsRemover.removeEntities(TenantId.SYS_TENANT_ID, TenantId.SYS_TENANT_ID);
}
@Override
public PageData<TenantId> findTenantsIds(PageLink pageLink) {
log.trace("Executing findTenantsIds");
Validator.validatePageLink(pageLink);
return tenantDao.findTenantsIds(pageLink);
}
@Override
public List<Tenant> findTenantsByIds(TenantId callerId, List<TenantId> tenantIds) {
log.trace("Executing findTenantsByIds, callerId [{}], tenantIds [{}]", callerId, tenantIds);
return tenantDao.findTenantsByIds(callerId.getId(), toUUIDs(tenantIds));
}
@Override
public boolean tenantExists(TenantId tenantId) {
return existsTenantCache.getAndPutInTransaction(tenantId, () -> tenantDao.existsById(tenantId, tenantId.getId()), false);
}
private final PaginatedRemover<TenantId, Tenant> tenantsRemover = new PaginatedRemover<>() {
@Override
protected PageData<Tenant> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) {
return tenantDao.findTenants(tenantId, pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, Tenant entity) {
deleteTenant(TenantId.fromUUID(entity.getUuidId()));
} | };
@Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findTenantById(TenantId.fromUUID(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(findTenantByIdAsync(tenantId, TenantId.fromUUID(entityId.getId())))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public EntityType getEntityType() {
return EntityType.TENANT;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\tenant\TenantServiceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ConfigDataLocationNotFoundException extends ConfigDataNotFoundException {
private final ConfigDataLocation location;
/**
* Create a new {@link ConfigDataLocationNotFoundException} instance.
* @param location the location that could not be found
*/
public ConfigDataLocationNotFoundException(ConfigDataLocation location) {
this(location, null);
}
/**
* Create a new {@link ConfigDataLocationNotFoundException} instance.
* @param location the location that could not be found
* @param cause the exception cause
*/
public ConfigDataLocationNotFoundException(ConfigDataLocation location, @Nullable Throwable cause) {
this(location, getMessage(location), cause);
}
/**
* Create a new {@link ConfigDataLocationNotFoundException} instance.
* @param location the location that could not be found
* @param message the exception message
* @param cause the exception cause
* @since 2.4.7
*/
public ConfigDataLocationNotFoundException(ConfigDataLocation location, String message, @Nullable Throwable cause) {
super(message, cause);
Assert.notNull(location, "'location' must not be null");
this.location = location;
}
/**
* Return the location that could not be found.
* @return the location | */
public ConfigDataLocation getLocation() {
return this.location;
}
@Override
public @Nullable Origin getOrigin() {
return Origin.from(this.location);
}
@Override
public String getReferenceDescription() {
return getReferenceDescription(this.location);
}
private static String getMessage(ConfigDataLocation location) {
return String.format("Config data %s cannot be found", getReferenceDescription(location));
}
private static String getReferenceDescription(ConfigDataLocation location) {
return String.format("location '%s'", location);
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigDataLocationNotFoundException.java | 2 |
请完成以下Java代码 | public Set<String> getMetrics() {
return metrics;
}
@CamundaQueryParam(value = "subscriptionStartDate", converter = DateConverter.class)
public void setSubscriptionStartDate(Date subscriptionStartDate) {
this.subscriptionStartDate = subscriptionStartDate;
if (subscriptionStartDate != null) {
// calculate subscription year and month
Calendar cal = Calendar.getInstance();
cal.setTime(subscriptionStartDate);
subscriptionMonth = cal.get(Calendar.MONTH) + 1;
subscriptionDay = cal.get(Calendar.DAY_OF_MONTH);
}
}
@CamundaQueryParam(value = "startDate", converter = DateConverter.class)
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
@CamundaQueryParam(value = "endDate", converter = DateConverter.class)
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
@Override
protected String getOrderByValue(String sortBy) {
return null;
}
@Override
protected boolean isValidSortByValue(String value) {
return false;
} | public void validateAndPrepareQuery() {
if (subscriptionStartDate == null || !subscriptionStartDate.before(ClockUtil.now())) {
throw new InvalidRequestException(Response.Status.BAD_REQUEST,
"subscriptionStartDate parameter has invalid value: " + subscriptionStartDate);
}
if (startDate != null && endDate != null && !endDate.after(startDate)) {
throw new InvalidRequestException(Response.Status.BAD_REQUEST, "endDate parameter must be after startDate");
}
if (!VALID_GROUP_BY_VALUES.contains(groupBy)) {
throw new InvalidRequestException(Response.Status.BAD_REQUEST, "groupBy parameter has invalid value: " + groupBy);
}
if (metrics == null || metrics.isEmpty()) {
metrics = VALID_METRIC_VALUES;
}
// convert metrics to internal names
this.metrics = metrics.stream()
.map(MetricsUtil::resolveInternalName)
.collect(Collectors.toSet());
}
public int getSubscriptionMonth() {
return subscriptionMonth;
}
public int getSubscriptionDay() {
return subscriptionDay;
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\admin\impl\plugin\base\dto\MetricsAggregatedQueryDto.java | 1 |
请完成以下Java代码 | public void setManualActual (BigDecimal ManualActual)
{
set_Value (COLUMNNAME_ManualActual, ManualActual);
}
/** Get Manual Actual.
@return Manually entered actual value
*/
public BigDecimal getManualActual ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ManualActual);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set 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 |
请完成以下Java代码 | public PartyIdentification32CHNameAndId getInitgPty() {
return initgPty;
}
/**
* Sets the value of the initgPty property.
*
* @param value
* allowed object is
* {@link PartyIdentification32CHNameAndId }
*
*/
public void setInitgPty(PartyIdentification32CHNameAndId value) {
this.initgPty = value;
}
/**
* Gets the value of the fwdgAgt property.
*
* @return | * possible object is
* {@link BranchAndFinancialInstitutionIdentification4 }
*
*/
public BranchAndFinancialInstitutionIdentification4 getFwdgAgt() {
return fwdgAgt;
}
/**
* Sets the value of the fwdgAgt property.
*
* @param value
* allowed object is
* {@link BranchAndFinancialInstitutionIdentification4 }
*
*/
public void setFwdgAgt(BranchAndFinancialInstitutionIdentification4 value) {
this.fwdgAgt = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\GroupHeader32CH.java | 1 |
请完成以下Java代码 | public void checkPath(TreePath path) {
this.model.checkSubTree(path);
this.model.updatePathGreyness(path);
this.model.updateAncestorsGreyness(path);
}
@Override
public void uncheckPath(TreePath path) {
this.model.uncheckSubTree(path);
this.model.updatePathGreyness(path);
this.model.updateAncestorsGreyness(path);
}
/*
* (non-Javadoc)
*
* @see it.cnr.imaa.essi.lablib.gui.checkboxtree.TreeCheckingMode#updateCheckAfterChildrenInserted(javax.swing.tree.TreePath)
*/
@Override
public void updateCheckAfterChildrenInserted(TreePath parent) {
if (this.model.isPathChecked(parent)) {
this.model.checkSubTree(parent);
} else {
this.model.uncheckSubTree(parent);
}
}
/*
* (non-Javadoc)
*
* @see it.cnr.imaa.essi.lablib.gui.checkboxtree.TreeCheckingMode#updateCheckAfterChildrenRemoved(javax.swing.tree.TreePath)
*/
@Override
public void updateCheckAfterChildrenRemoved(TreePath parent) { | this.model.updatePathGreyness(parent);
this.model.updateAncestorsGreyness(parent);
}
/*
* (non-Javadoc)
*
* @see it.cnr.imaa.essi.lablib.gui.checkboxtree.TreeCheckingMode#updateCheckAfterStructureChanged(javax.swing.tree.TreePath)
*/
@Override
public void updateCheckAfterStructureChanged(TreePath parent) {
if (this.model.isPathChecked(parent)) {
this.model.checkSubTree(parent);
} else {
this.model.uncheckSubTree(parent);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\it\cnr\imaa\essi\lablib\gui\checkboxtree\PropagateTreeCheckingMode.java | 1 |
请完成以下Java代码 | void changeBio(String bio) {
profile.changeBio(bio);
}
void changeImage(Image image) {
profile.changeImage(image);
}
public Long getId() {
return id;
}
public Email getEmail() {
return email;
}
public UserName getName() {
return profile.getUserName();
}
String getBio() { | return profile.getBio();
}
Image getImage() {
return profile.getImage();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final var user = (User) o;
return email.equals(user.email);
}
@Override
public int hashCode() {
return Objects.hash(email);
}
} | repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\user\User.java | 1 |
请完成以下Java代码 | public static CacheInvalidateMultiRequest fromTableNameAndRecordId(final String tableName, final int recordId)
{
if (tableName == null)
{
return all();
}
else if (recordId < 0)
{
return allRecordsForTable(tableName);
}
else
{
return rootRecord(tableName, recordId);
}
}
public static CacheInvalidateMultiRequest fromTableNameAndRecordIds(
@NonNull final String tableName,
@NonNull final Collection<Integer> recordIds)
{
final ImmutableSet<CacheInvalidateRequest> requests = recordIds.stream()
.distinct()
.map(recordId -> CacheInvalidateRequest.rootRecord(tableName, recordId))
.collect(ImmutableSet.toImmutableSet());
return of(requests);
}
public static CacheInvalidateMultiRequest fromTableNameAndRepoIdAwares(
@NonNull final String tableName,
@NonNull final Collection<? extends RepoIdAware> recordIds)
{
final ImmutableSet<CacheInvalidateRequest> requests = recordIds.stream()
.distinct()
.filter(Objects::nonNull)
.map(recordId -> CacheInvalidateRequest.rootRecord(tableName, recordId.getRepoId()))
.collect(ImmutableSet.toImmutableSet());
return of(requests);
}
private static final CacheInvalidateMultiRequest ALL = new CacheInvalidateMultiRequest(ImmutableSet.of(CacheInvalidateRequest.all()));
@JsonProperty("requests") Set<CacheInvalidateRequest> requests;
@Builder
@JsonCreator
private CacheInvalidateMultiRequest(@JsonProperty("requests") @Singular @NonNull final Set<CacheInvalidateRequest> requests)
{
Check.assumeNotEmpty(requests, "requests is not empty");
this.requests = ImmutableSet.copyOf(requests);
}
@Override | public String toString()
{
final int requestsCount = requests.size();
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("requestsCount", requestsCount)
.add("requests", requestsCount > 0 ? requests : null)
.toString();
}
public boolean isResetAll()
{
return requests.stream().anyMatch(CacheInvalidateRequest::isAll);
}
public Set<String> getTableNamesEffective()
{
return requests.stream()
.filter(request -> !request.isAll())
.map(CacheInvalidateRequest::getTableNameEffective)
.collect(ImmutableSet.toImmutableSet());
}
public TableRecordReferenceSet getRecordsEffective()
{
return requests.stream()
.map(CacheInvalidateRequest::getRecordEffective)
.collect(TableRecordReferenceSet.collect());
}
public TableRecordReferenceSet getRootRecords()
{
return requests.stream()
.map(CacheInvalidateRequest::getRootRecordOrNull)
.filter(Objects::nonNull)
.collect(TableRecordReferenceSet.collect());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\CacheInvalidateMultiRequest.java | 1 |
请完成以下Java代码 | private void fireLocalAndRemoteListenersAfterTrxCommit(final @NonNull SumUpTransactionStatusChangedEvent event)
{
trxManager.accumulateAndProcessAfterCommit(
SumUpEventsDispatcher.class.getSimpleName(),
ImmutableList.of(event),
this::fireLocalAndRemoteListenersNow);
}
private void fireLocalAndRemoteListenersNow(@NonNull final List<SumUpTransactionStatusChangedEvent> events)
{
final IEventBus eventBus = getEventBus();
// NOTE: we don't have to fireLocalListeners
// because we assume we will also get back this event and then we will handle it
events.forEach(eventBus::enqueueObject);
}
public void fireNewTransaction(@NonNull final SumUpTransaction trx)
{
fireLocalAndRemoteListenersAfterTrxCommit(SumUpTransactionStatusChangedEvent.ofNewTransaction(trx));
} | public void fireStatusChangedIfNeeded(
@NonNull final SumUpTransaction trx,
@NonNull final SumUpTransaction trxPrev)
{
if (!isForceSendingChangeEvents() && hasChanges(trx, trxPrev))
{
return;
}
fireLocalAndRemoteListenersAfterTrxCommit(SumUpTransactionStatusChangedEvent.ofChangedTransaction(trx, trxPrev));
}
private static boolean hasChanges(final @NonNull SumUpTransaction trx, final @NonNull SumUpTransaction trxPrev)
{
return SumUpTransactionStatus.equals(trx.getStatus(), trxPrev.getStatus())
&& trx.isRefunded() == trxPrev.isRefunded();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\SumUpEventsDispatcher.java | 1 |
请完成以下Java代码 | public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Suchschluessel.
@param Value
Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschluessel.
@return Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein
*/
public String getValue ()
{ | return (String)get_Value(COLUMNNAME_Value);
}
/** Set Breite.
@param Width Breite */
public void setWidth (BigDecimal Width)
{
set_Value (COLUMNNAME_Width, Width);
}
/** Get Breite.
@return Breite */
public BigDecimal getWidth ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Width);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_M_PackagingContainer.java | 1 |
请完成以下Java代码 | public void setSubject (String Subject)
{
set_Value (COLUMNNAME_Subject, Subject);
}
/** Get Subject.
@return Email Message Subject
*/
public String getSubject ()
{
return (String)get_Value(COLUMNNAME_Subject);
}
public I_W_MailMsg getW_MailMsg() throws RuntimeException
{
return (I_W_MailMsg)MTable.get(getCtx(), I_W_MailMsg.Table_Name)
.getPO(getW_MailMsg_ID(), get_TrxName()); }
/** Set Mail Message.
@param W_MailMsg_ID
Web Store Mail Message Template
*/ | public void setW_MailMsg_ID (int W_MailMsg_ID)
{
if (W_MailMsg_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_MailMsg_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_MailMsg_ID, Integer.valueOf(W_MailMsg_ID));
}
/** Get Mail Message.
@return Web Store Mail Message Template
*/
public int getW_MailMsg_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_MailMsg_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserMail.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ApiResponse<ArticleMapping> updateInsuranceContractWithHttpInfo(String albertaApiKey, String tenant, String id, Article body) throws ApiException {
com.squareup.okhttp.Call call = updateInsuranceContractValidateBeforeCall(albertaApiKey, tenant, id, body, null, null);
Type localVarReturnType = new TypeToken<ArticleMapping>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* Krankenkassenvertrag in Alberta ändern (asynchronously)
* ändert einen Krankenkassenvertrag in Alberta
* @param albertaApiKey (required)
* @param tenant (required)
* @param id (required)
* @param body article to update (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call updateInsuranceContractAsync(String albertaApiKey, String tenant, String id, Article body, final ApiCallback<ArticleMapping> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() { | @Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = updateInsuranceContractValidateBeforeCall(albertaApiKey, tenant, id, body, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<ArticleMapping>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\api\DefaultApi.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class HardwarePrinterId implements RepoIdAware
{
@JsonCreator
public static HardwarePrinterId ofRepoId(final int repoId)
{
return new HardwarePrinterId(repoId);
}
public static HardwarePrinterId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new HardwarePrinterId(repoId) : null;
}
public static int toRepoId(final HardwarePrinterId hardwarePrinterId)
{ | return hardwarePrinterId != null ? hardwarePrinterId.getRepoId() : -1;
}
int repoId;
private HardwarePrinterId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "AD_PrinterHW_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\HardwarePrinterId.java | 2 |
请完成以下Java代码 | public class HistoricProcessInstanceQueryProperty implements QueryProperty {
private static final long serialVersionUID = 1L;
private static final Map<String, HistoricProcessInstanceQueryProperty> properties = new HashMap<
String,
HistoricProcessInstanceQueryProperty
>();
public static final HistoricProcessInstanceQueryProperty PROCESS_INSTANCE_ID_ =
new HistoricProcessInstanceQueryProperty("RES.PROC_INST_ID_");
public static final HistoricProcessInstanceQueryProperty PROCESS_DEFINITION_ID =
new HistoricProcessInstanceQueryProperty("RES.PROC_DEF_ID_");
public static final HistoricProcessInstanceQueryProperty PROCESS_DEFINITION_KEY =
new HistoricProcessInstanceQueryProperty("DEF.KEY_");
public static final HistoricProcessInstanceQueryProperty BUSINESS_KEY = new HistoricProcessInstanceQueryProperty(
"RES.BUSINESS_KEY_"
);
public static final HistoricProcessInstanceQueryProperty START_TIME = new HistoricProcessInstanceQueryProperty(
"RES.START_TIME_"
);
public static final HistoricProcessInstanceQueryProperty END_TIME = new HistoricProcessInstanceQueryProperty(
"RES.END_TIME_"
);
public static final HistoricProcessInstanceQueryProperty DURATION = new HistoricProcessInstanceQueryProperty(
"RES.DURATION_"
);
public static final HistoricProcessInstanceQueryProperty TENANT_ID = new HistoricProcessInstanceQueryProperty( | "RES.TENANT_ID_"
);
public static final HistoricProcessInstanceQueryProperty INCLUDED_VARIABLE_TIME =
new HistoricProcessInstanceQueryProperty("VAR.LAST_UPDATED_TIME_");
private String name;
public HistoricProcessInstanceQueryProperty(String name) {
this.name = name;
properties.put(name, this);
}
public String getName() {
return name;
}
public static HistoricProcessInstanceQueryProperty findByName(String propertyName) {
return properties.get(propertyName);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoricProcessInstanceQueryProperty.java | 1 |
请完成以下Java代码 | public String toString()
{
StringBuffer sb = new StringBuffer ("X_W_CounterCount[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_C_BPartner getC_BPartner() throws RuntimeException
{
return (I_C_BPartner)MTable.get(getCtx(), I_C_BPartner.Table_Name)
.getPO(getC_BPartner_ID(), get_TrxName()); }
/** Set Business Partner .
@param C_BPartner_ID
Identifies a Business Partner
*/
public void setC_BPartner_ID (int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_Value (COLUMNNAME_C_BPartner_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID));
}
/** Get Business Partner .
@return Identifies a Business Partner
*/
public int getC_BPartner_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Counter.
@param Counter
Count Value
*/
public void setCounter (int Counter)
{
throw new IllegalArgumentException ("Counter is virtual column"); }
/** Get Counter.
@return Count Value
*/
public int getCounter ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Counter);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Name. | @param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Page URL.
@param PageURL Page URL */
public void setPageURL (String PageURL)
{
set_Value (COLUMNNAME_PageURL, PageURL);
}
/** Get Page URL.
@return Page URL */
public String getPageURL ()
{
return (String)get_Value(COLUMNNAME_PageURL);
}
/** Set Counter Count.
@param W_CounterCount_ID
Web Counter Count Management
*/
public void setW_CounterCount_ID (int W_CounterCount_ID)
{
if (W_CounterCount_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, Integer.valueOf(W_CounterCount_ID));
}
/** Get Counter Count.
@return Web Counter Count Management
*/
public int getW_CounterCount_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_CounterCount_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_CounterCount.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SpringProcessEngineConfigurator extends ProcessEngineConfigurator {
@Override
public void configure(AbstractEngineConfiguration engineConfiguration) {
if (processEngineConfiguration == null) {
processEngineConfiguration = new SpringProcessEngineConfiguration();
}
if (!(processEngineConfiguration instanceof SpringProcessEngineConfiguration)) {
throw new FlowableException("SpringProcessEngineConfigurator accepts only SpringProcessEngineConfiguration. " + processEngineConfiguration.getClass().getName());
}
initialiseCommonProperties(engineConfiguration, processEngineConfiguration);
SpringEngineConfiguration springEngineConfiguration = (SpringEngineConfiguration) engineConfiguration;
SpringProcessEngineConfiguration springProcessEngineConfiguration = (SpringProcessEngineConfiguration) processEngineConfiguration;
springProcessEngineConfiguration.setTransactionManager(springEngineConfiguration.getTransactionManager());
if (springProcessEngineConfiguration.getBeans() == null) { | springProcessEngineConfiguration.setBeans(springProcessEngineConfiguration.getBeans());
}
initEngine();
initServiceConfigurations(engineConfiguration, processEngineConfiguration);
}
@Override
public SpringProcessEngineConfiguration getProcessEngineConfiguration() {
return (SpringProcessEngineConfiguration) processEngineConfiguration;
}
public SpringProcessEngineConfigurator setProcessEngineConfiguration(SpringProcessEngineConfiguration processEngineConfiguration) {
this.processEngineConfiguration = processEngineConfiguration;
return this;
}
} | repos\flowable-engine-main\modules\flowable-spring-configurator\src\main\java\org\flowable\engine\spring\configurator\SpringProcessEngineConfigurator.java | 2 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("No Selection");
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
List<I_C_Payment> payments = getSelectedPayments();
List<I_C_Payment> filteredPayments = payments | .stream()
.filter(p -> !p.isAllocated() && DocStatus.ofCode(p.getDocStatus()).isCompleted())
.collect(Collectors.toList());
paymentBL.setPaymentOrderAndInvoiceIdsAndAllocateItIfNecessary(filteredPayments);
return MSG_OK;
}
private List<I_C_Payment> getSelectedPayments()
{
return retrieveSelectedRecordsQueryBuilder(I_C_Payment.class)
.create()
.list();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\process\C_Payment_UpdateOrderAndInvoiceId.java | 1 |
请完成以下Java代码 | public class MovementDAO implements IMovementDAO
{
final private IQueryBL queryBL = Services.get(IQueryBL.class);
@Override
public I_M_MovementLine getLineById(@NonNull final MovementLineId movementLineId)
{
return load(movementLineId, I_M_MovementLine.class);
}
@Override
public List<I_M_MovementLine> retrieveLines(final I_M_Movement movement)
{
return retrieveLines(movement, I_M_MovementLine.class);
}
@Override
public <MovementLineType extends I_M_MovementLine> List<MovementLineType> retrieveLines(@NonNull final I_M_Movement movement, @NonNull final Class<MovementLineType> movementLineClass)
{
final IQueryBuilder<MovementLineType> queryBuilder = queryBL.createQueryBuilder(movementLineClass, movement);
queryBuilder.getCompositeFilter()
.addEqualsFilter(I_M_MovementLine.COLUMNNAME_M_Movement_ID, movement.getM_Movement_ID());
queryBuilder.orderBy()
.addColumn(I_M_MovementLine.COLUMNNAME_Line, Direction.Ascending, Nulls.Last);
return queryBuilder
.create()
.list(movementLineClass);
}
@Override
public IQueryBuilder<I_M_Movement> retrieveMovementsForInventoryQuery(@NonNull final InventoryId inventoryId)
{
return queryBL.createQueryBuilder(I_M_Movement.class)
.addEqualsFilter(I_M_Movement.COLUMN_M_Inventory_ID, inventoryId);
} | @Override
public List<I_M_Movement> retrieveMovementsForDDOrder(final int ddOrderId)
{
return queryBL.createQueryBuilder(I_M_Movement.class)
.addEqualsFilter(I_M_Movement.COLUMN_DD_Order_ID, ddOrderId)
.create()
.list();
}
@Override
public void save(@NonNull final I_M_Movement movement)
{
saveRecord(movement);
}
@Override
public void save(@NonNull final I_M_MovementLine movementLine)
{
saveRecord(movementLine);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mmovement\api\impl\MovementDAO.java | 1 |
请完成以下Java代码 | public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCurrentDevice() {
return currentDevice;
}
public void setCurrentDevice(String currentDevice) {
this.currentDevice = currentDevice;
}
@Override
public String toString() {
return new StringJoiner(", ", User.class.getSimpleName() + "[", "]").add("id=" + id)
.add("email='" + email + "'") | .add("password='" + password + "'")
.add("currentDevice='" + currentDevice + "'")
.toString();
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof User))
return false;
User user = (User) o;
return email.equals(user.email);
}
} | repos\tutorials-master\persistence-modules\java-jpa-3\src\main\java\com\baeldung\ignorable\fields\User.java | 1 |
请完成以下Java代码 | public class WordCountRoute extends RouteBuilder {
public static final String receiveTextUri = "seda:receiveText?concurrentConsumers=5";
public static final String splitWordsUri = "seda:splitWords?concurrentConsumers=5";
public static final String toLowerCaseUri = "seda:toLowerCase?concurrentConsumers=5";
public static final String countWordsUri = "seda:countWords?concurrentConsumers=5";
public static final String returnResponse = "mock:result";
@Override
public void configure() throws Exception {
from(receiveTextUri).to(splitWordsUri);
from(splitWordsUri).transform(ExpressionBuilder.bodyExpression(s -> s.toString()
.split(" ")))
.to(toLowerCaseUri);
from(toLowerCaseUri).split(body(), new StringListAggregationStrategy()) | .transform(ExpressionBuilder.bodyExpression(body -> body.toString()
.toLowerCase()))
.end()
.to(countWordsUri);
from(countWordsUri).transform(ExpressionBuilder.bodyExpression(List.class, body -> body.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))))
.to(returnResponse);
}
}
class StringListAggregationStrategy extends AbstractListAggregationStrategy<String> {
@Override
public String getValue(Exchange exchange) {
return exchange.getIn()
.getBody(String.class);
}
} | repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\seda\apachecamel\WordCountRoute.java | 1 |
请完成以下Java代码 | private ContextPath newChild(@NonNull final ContextPathElement element)
{
return new ContextPath(ImmutableList.<ContextPathElement>builder()
.addAll(elements)
.add(element)
.build());
}
public AdWindowId getAdWindowId()
{
return AdWindowId.ofRepoId(elements.get(0).getId());
}
@Override
public int compareTo(@NonNull final ContextPath other)
{
return toJson().compareTo(other.toJson());
}
}
@Value
class ContextPathElement
{
@NonNull String name;
int id;
@JsonCreator
public static ContextPathElement ofJson(@NonNull final String json)
{
try
{
final int idx = json.indexOf("/");
if (idx > 0)
{
String name = json.substring(0, idx);
int id = Integer.parseInt(json.substring(idx + 1)); | return new ContextPathElement(name, id);
}
else
{
return new ContextPathElement(json, -1);
}
}
catch (final Exception ex)
{
throw new AdempiereException("Failed parsing: " + json, ex);
}
}
public static ContextPathElement ofName(@NonNull final String name) {return new ContextPathElement(name, -1);}
public static ContextPathElement ofNameAndId(@NonNull final String name, final int id) {return new ContextPathElement(name, id > 0 ? id : -1);}
@Override
public String toString() {return toJson();}
@JsonValue
public String toJson() {return id > 0 ? name + "/" + id : name;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\ContextPath.java | 1 |
请完成以下Java代码 | public HistoricDetailQuery orderPartiallyByOccurrence() {
orderBy(HistoricDetailQueryProperty.SEQUENCE_COUNTER);
return this;
}
public HistoricDetailQuery orderByTenantId() {
return orderBy(HistoricDetailQueryProperty.TENANT_ID);
}
// getters and setters //////////////////////////////////////////////////////
public String getProcessInstanceId() {
return processInstanceId;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String getExecutionId() {
return executionId;
}
public String getCaseExecutionId() {
return caseExecutionId;
}
public String getTaskId() {
return taskId;
}
public String getActivityId() {
return activityId;
}
public String getType() {
return type;
} | public boolean getExcludeTaskRelated() {
return excludeTaskRelated;
}
public String getDetailId() {
return detailId;
}
public String[] getProcessInstanceIds() {
return processInstanceIds;
}
public Date getOccurredBefore() {
return occurredBefore;
}
public Date getOccurredAfter() {
return occurredAfter;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
public boolean isInitial() {
return initial;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricDetailQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | CommandLineRunner seedUsersAndGroups(final IdmIdentityService identityService) {
return new CommandLineRunner() {
@Override
public void run(String... strings) throws Exception {
// install groups & users
Group adminGroup = identityService.newGroup("admin");
adminGroup.setName("admin");
adminGroup.setType("security-role");
identityService.saveGroup(adminGroup);
Group group = identityService.newGroup("user");
group.setName("users");
group.setType("security-role");
identityService.saveGroup(group);
Privilege userPrivilege = identityService.createPrivilege("user-privilege");
identityService.addGroupPrivilegeMapping(userPrivilege.getId(), group.getId());
Privilege adminPrivilege = identityService.createPrivilege("admin-privilege");
User joram = identityService.newUser("jbarrez");
joram.setFirstName("Joram");
joram.setLastName("Barrez");
joram.setPassword("password");
identityService.saveUser(joram);
identityService.addUserPrivilegeMapping(adminPrivilege.getId(), joram.getId());
User filip = identityService.newUser("filiphr");
filip.setFirstName("Filip");
filip.setLastName("Hrisafov");
filip.setPassword("password");
identityService.saveUser(filip);
User josh = identityService.newUser("jlong");
josh.setFirstName("Josh");
josh.setLastName("Long");
josh.setPassword("password");
identityService.saveUser(josh); | identityService.createMembership("jbarrez", "user");
identityService.createMembership("jbarrez", "admin");
identityService.createMembership("filiphr", "user");
identityService.createMembership("jlong", "user");
}
};
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Configuration
@EnableWebSecurity
public static class SecurityConfiguration {
@Bean
public AuthenticationProvider authenticationProvider() {
return new BasicAuthenticationProvider();
}
@Bean
public SecurityFilterChain defaultSecurity(HttpSecurity http, AuthenticationProvider authenticationProvider) throws Exception {
http
.authenticationProvider(authenticationProvider)
.csrf(CsrfConfigurer::disable)
.authorizeHttpRequests(authorizeRequests -> authorizeRequests.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
}
} | repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-samples\flowable-spring-boot-sample-rest-api-security\src\main\java\flowable\Application.java | 2 |
请完成以下Java代码 | protected String doIt()
{
final Set<SumUpTransactionId> ids = getSelectedIdsAsSet();
if (ids.isEmpty())
{
throw new AdempiereException("@NoSelection@");
}
final BulkUpdateByQueryResult result = sumUpService.bulkUpdateTransactions(SumUpTransactionQuery.ofLocalIds(ids), true);
return result.getSummary().translate(Env.getADLanguageOrBaseLanguage());
}
private Set<SumUpTransactionId> getSelectedIdsAsSet()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
if (selectedRowIds.isEmpty()) | {
return ImmutableSet.of();
}
else if (selectedRowIds.isAll())
{
return getView().streamByIds(selectedRowIds)
.map(row -> row.getId().toId(SumUpTransactionId::ofRepoId))
.collect(ImmutableSet.toImmutableSet());
}
else
{
return selectedRowIds.toIds(SumUpTransactionId::ofRepoId);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup.webui\src\main\java\de\metas\payment\sumup\webui\process\SUMUP_Transaction_UpdateSelectedRows.java | 1 |
请完成以下Java代码 | public static class SqlServerTimelyExecutor implements InitializingBean, SmartLifecycle {
private final ExecutorService executor = ThreadPoolEnum.INSTANCE.getInstance();
private DebeziumEngine<?> debeziumEngine;
@Override
public void start() {
log.warn(ThreadPoolEnum.SQL_SERVER_LISTENER_POOL + "线程池开始执行 debeziumEngine 实时监听任务!");
executor.execute(debeziumEngine);
}
@SneakyThrows
@Override
public void stop() {
log.warn("debeziumEngine 监听实例关闭!");
debeziumEngine.close();
Thread.sleep(2000);
log.warn(ThreadPoolEnum.SQL_SERVER_LISTENER_POOL + "线程池关闭!");
executor.shutdown();
}
@Override
public boolean isRunning() {
return false;
}
@Override
public void afterPropertiesSet() {
Assert.notNull(debeziumEngine, "DebeZiumEngine 不能为空!");
}
public enum ThreadPoolEnum {
/**
* 实例
*/
INSTANCE;
public static final String SQL_SERVER_LISTENER_POOL = "sql-server-listener-pool";
/**
* 线程池单例
*/ | private final ExecutorService es;
/**
* 枚举 (构造器默认为私有)
*/
ThreadPoolEnum() {
final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(SQL_SERVER_LISTENER_POOL + "-%d").build();
es = new ThreadPoolExecutor(8, 16, 60,
TimeUnit.SECONDS, new ArrayBlockingQueue<>(256),
threadFactory, new ThreadPoolExecutor.DiscardPolicy());
}
/**
* 公有方法
*
* @return ExecutorService
*/
public ExecutorService getInstance() {
return es;
}
}
}
} | repos\springboot-demo-master\debezium\src\main\java\com\et\debezium\config\ChangeEventConfig.java | 1 |
请完成以下Java代码 | public Map<RefundConfig, BigDecimal> retrieveAssignedQuantities(
@NonNull final InvoiceCandidateId invoiceCandidateId)
{
if (Adempiere.isUnitTestMode())
{
return retrieveAssignedQuantityUnitTestMode(invoiceCandidateId);
}
final IQueryBL queryBL = Services.get(IQueryBL.class);
final List<I_C_Invoice_Candidate_Assignment_Aggregate_V> aggregates = queryBL
.createQueryBuilder(I_C_Invoice_Candidate_Assignment_Aggregate_V.class)
.addEqualsFilter(I_C_Invoice_Candidate_Assignment_Aggregate_V.COLUMN_C_Invoice_Candidate_Term_ID, invoiceCandidateId)
.create() // note: the view has no IsActive column, but its whereclause filters by isactive
.list(I_C_Invoice_Candidate_Assignment_Aggregate_V.class);
final ImmutableMap.Builder<RefundConfig, BigDecimal> result = ImmutableMap.builder();
for (final I_C_Invoice_Candidate_Assignment_Aggregate_V aggregate : aggregates)
{
final RefundConfigId refundConfigId = RefundConfigId.ofRepoId(aggregate.getC_Flatrate_RefundConfig_ID());
final RefundConfig refundConfig = refundConfigRepository.getById(refundConfigId);
result.put(
refundConfig,
aggregate.getAssignedQuantity());
}
return result.build();
}
private Map<RefundConfig, BigDecimal> retrieveAssignedQuantityUnitTestMode(
@NonNull final InvoiceCandidateId invoiceCandidateId)
{ | final IQueryBL queryBL = Services.get(IQueryBL.class);
final List<I_C_Invoice_Candidate_Assignment> assignmentRecords = queryBL
.createQueryBuilder(I_C_Invoice_Candidate_Assignment.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Invoice_Candidate_Assignment.COLUMN_C_Invoice_Candidate_Term_ID, invoiceCandidateId)
.create()
.list();
final Map<RefundConfig, BigDecimal> result = new HashMap<>();
for (final I_C_Invoice_Candidate_Assignment assignmentRecord : assignmentRecords)
{
final RefundConfigId refundConfigId = RefundConfigId.ofRepoId(assignmentRecord.getC_Flatrate_RefundConfig_ID());
final RefundConfig refundConfig = refundConfigRepository.getById(refundConfigId);
final BigDecimal assignedQuantity = assignmentRecord.isAssignedQuantityIncludedInSum()
? assignmentRecord.getAssignedQuantity()
: ZERO;
result.merge(refundConfig, assignedQuantity, (oldVal, newVal) -> oldVal.add(newVal));
}
return result;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\AssignmentAggregateService.java | 1 |
请完成以下Java代码 | public String home() {
return String.format("%s is running!",
environment.getProperty("spring.application.name", "UNKNOWN"));
}
public static class CustomerHolder {
public static CustomerHolder from(Customer customer) {
return new CustomerHolder(customer);
}
private boolean cacheMiss = true;
private final Customer customer;
protected CustomerHolder(Customer customer) {
Assert.notNull(customer, "Customer must not be null");
this.customer = customer;
} | public CustomerHolder setCacheMiss(boolean cacheMiss) {
this.cacheMiss = cacheMiss;
return this;
}
public boolean isCacheMiss() {
return this.cacheMiss;
}
public Customer getCustomer() {
return customer;
}
}
}
// end::class[] | repos\spring-boot-data-geode-main\spring-geode-samples\caching\multi-site\src\main\java\example\app\caching\multisite\client\web\CustomerController.java | 1 |
请完成以下Java代码 | public String getProperty(String key)
{
return getDelegate().getProperty(key);
}
@Override
public String getProperty(String key, String defaultValue)
{
return getDelegate().getProperty(key, defaultValue);
}
@Override
public Enumeration<?> propertyNames()
{
return getDelegate().propertyNames();
} | @Override
public Set<String> stringPropertyNames()
{
return getDelegate().stringPropertyNames();
}
@Override
public void list(PrintStream out)
{
getDelegate().list(out);
}
@Override
public void list(PrintWriter out)
{
getDelegate().list(out);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\AbstractPropertiesProxy.java | 1 |
请完成以下Java代码 | public class OrderDropShipLocationAdapter
implements IDocumentDeliveryLocationAdapter, RecordBasedLocationAdapter<OrderDropShipLocationAdapter>
{
private final I_C_Order delegate;
OrderDropShipLocationAdapter(@NonNull final I_C_Order delegate)
{
this.delegate = delegate;
}
@Override
public int getDropShip_BPartner_ID()
{
return delegate.getDropShip_BPartner_ID();
}
@Override
public void setDropShip_BPartner_ID(final int DropShip_BPartner_ID)
{
delegate.setDropShip_BPartner_ID(DropShip_BPartner_ID);
}
@Override
public int getDropShip_Location_ID()
{
return delegate.getDropShip_Location_ID();
}
@Override
public void setDropShip_Location_ID(final int DropShip_Location_ID)
{
delegate.setDropShip_Location_ID(DropShip_Location_ID);
}
@Override
public int getDropShip_Location_Value_ID()
{
return delegate.getDropShip_Location_Value_ID();
}
@Override
public void setDropShip_Location_Value_ID(final int DropShip_Location_Value_ID)
{
delegate.setDropShip_Location_Value_ID(DropShip_Location_Value_ID);
}
@Override
public int getDropShip_User_ID()
{
return delegate.getDropShip_User_ID();
}
@Override
public void setDropShip_User_ID(final int DropShip_User_ID)
{
delegate.setDropShip_User_ID(DropShip_User_ID);
}
@Override
public int getM_Warehouse_ID()
{
return delegate.getM_Warehouse_ID();
}
@Override
public boolean isDropShip()
{
return delegate.isDropShip();
}
@Override
public String getDeliveryToAddress()
{
return delegate.getDeliveryToAddress();
}
@Override
public void setDeliveryToAddress(final String address)
{ | delegate.setDeliveryToAddress(address);
}
@Override
public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentDeliveryLocationAdapter.super.setRenderedAddressAndCapturedLocation(from);
}
@Override
public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentDeliveryLocationAdapter.super.setRenderedAddress(from);
}
public void setFromDeliveryLocation(@NonNull final I_C_Order from)
{
setFrom(new OrderDropShipLocationAdapter(from).toDocumentLocation());
}
public void setFromShipLocation(@NonNull final I_C_Order from)
{
setFrom(OrderDocumentLocationAdapterFactory.locationAdapter(from).toDocumentLocation());
}
@Override
public I_C_Order getWrappedRecord()
{
return delegate;
}
@Override
public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL)
{
return documentLocationBL.toPlainDocumentLocation(this);
}
@Override
public OrderDropShipLocationAdapter toOldValues()
{
InterfaceWrapperHelper.assertNotOldValues(delegate);
return new OrderDropShipLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_Order.class));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\location\adapter\OrderDropShipLocationAdapter.java | 1 |
请完成以下Java代码 | public PPOrderQuantities reduce(@NonNull final OrderQtyChangeRequest request)
{
return toBuilder()
.qtyReceived(getQtyReceived().add(request.getQtyReceivedToAdd()))
.qtyScrapped(getQtyScrapped().add(request.getQtyScrappedToAdd()))
.qtyRejected(getQtyRejected().add(request.getQtyRejectedToAdd()))
.qtyReserved(getQtyReserved().subtract(request.getQtyReceivedToAdd()))
.build();
}
public PPOrderQuantities close()
{
return toBuilder()
.qtyRequiredToProduce(getQtyReceived())
.qtyRequiredToProduceBeforeClose(getQtyRequiredToProduce())
.build();
}
public PPOrderQuantities unclose()
{
return toBuilder()
.qtyRequiredToProduce(getQtyRequiredToProduceBeforeClose())
.qtyRequiredToProduceBeforeClose(getQtyRequiredToProduceBeforeClose().toZero())
.build();
}
public PPOrderQuantities voidQtys()
{
return toBuilder()
.qtyRequiredToProduce(getQtyRequiredToProduce().toZero())
.build();
}
public PPOrderQuantities convertQuantities(@NonNull final UnaryOperator<Quantity> converter) | {
return toBuilder()
.qtyRequiredToProduce(converter.apply(getQtyRequiredToProduce()))
.qtyRequiredToProduceBeforeClose(converter.apply(getQtyRequiredToProduceBeforeClose()))
.qtyReceived(converter.apply(getQtyReceived()))
.qtyScrapped(converter.apply(getQtyScrapped()))
.qtyRejected(converter.apply(getQtyRejected()))
.qtyReserved(converter.apply(getQtyReserved()))
.build();
}
public boolean isSomethingReported()
{
return getQtyReceived().signum() != 0
|| getQtyScrapped().signum() != 0
|| getQtyRejected().signum() != 0;
}
public PPOrderQuantities withQtyRequiredToProduce(@NonNull final Quantity qtyRequiredToProduce)
{
return toBuilder().qtyRequiredToProduce(qtyRequiredToProduce).build();
}
public boolean isSomethingReceived()
{
return qtyReceived.signum() > 0;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\PPOrderQuantities.java | 1 |
请完成以下Java代码 | public void setRequeueOnRollback(boolean requeueOnRollback) {
this.requeueOnRollback = requeueOnRollback;
}
public final void addConnection(Connection connection) {
Assert.notNull(connection, "Connection must not be null");
if (!this.connections.contains(connection)) {
this.connections.add(connection);
}
}
public final void addChannel(Channel channel) {
addChannel(channel, null);
}
public final void addChannel(Channel channel, @Nullable Connection connection) {
Assert.notNull(channel, "Channel must not be null");
if (!this.channels.contains(channel)) {
this.channels.add(channel);
if (connection != null) {
List<Channel> channelsForConnection =
this.channelsPerConnection.computeIfAbsent(connection, k -> new LinkedList<>());
channelsForConnection.add(channel);
}
}
}
public boolean containsChannel(Channel channel) {
return this.channels.contains(channel);
}
public @Nullable Connection getConnection() {
return (!this.connections.isEmpty() ? this.connections.get(0) : null);
}
public @Nullable Channel getChannel() {
return (!this.channels.isEmpty() ? this.channels.get(0) : null);
}
public void commitAll() throws AmqpException {
try {
for (Channel channel : this.channels) {
if (this.deliveryTags.containsKey(channel)) {
for (Long deliveryTag : this.deliveryTags.get(channel)) {
channel.basicAck(deliveryTag, false);
}
}
channel.txCommit();
}
}
catch (IOException e) {
throw new AmqpException("failed to commit RabbitMQ transaction", e);
}
}
public void closeAll() {
for (Channel channel : this.channels) {
try { | if (channel != ConsumerChannelRegistry.getConsumerChannel()) { // NOSONAR
channel.close();
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Skipping close of consumer channel: " + channel.toString());
}
}
}
catch (Exception ex) {
logger.debug("Could not close synchronized Rabbit Channel after transaction", ex);
}
}
for (Connection con : this.connections) { //NOSONAR
RabbitUtils.closeConnection(con);
}
this.connections.clear();
this.channels.clear();
this.channelsPerConnection.clear();
}
public void addDeliveryTag(Channel channel, long deliveryTag) {
this.deliveryTags.add(channel, deliveryTag);
}
public void rollbackAll() {
for (Channel channel : this.channels) {
if (logger.isDebugEnabled()) {
logger.debug("Rolling back messages to channel: " + channel);
}
RabbitUtils.rollbackIfNecessary(channel);
if (this.deliveryTags.containsKey(channel)) {
for (Long deliveryTag : this.deliveryTags.get(channel)) {
try {
channel.basicReject(deliveryTag, this.requeueOnRollback);
}
catch (IOException ex) {
throw new AmqpIOException(ex);
}
}
// Need to commit the reject (=nack)
RabbitUtils.commitIfNecessary(channel);
}
}
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\connection\RabbitResourceHolder.java | 1 |
请完成以下Java代码 | public void deleteInvoiceCandidates(@NonNull final I_C_Flatrate_Term term)
{
Services.get(IInvoiceCandDAO.class).deleteAllReferencingInvoiceCandidates(term);
}
/**
* Does nothing; Feel free to override.
*/
@Override
public void afterSaveOfNextTermForPredecessor(final I_C_Flatrate_Term next, final I_C_Flatrate_Term predecessor)
{
// nothing
}
/**
* Does nothing; Feel free to override. | */
@Override
public void afterFlatrateTermEnded(final I_C_Flatrate_Term term)
{
// nothing
}
/**
* Does nothing; Feel free to override.
*/
@Override
public void beforeSaveOfNextTermForPredecessor(final I_C_Flatrate_Term next, final I_C_Flatrate_Term predecessor)
{
// nothing
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\spi\FallbackFlatrateTermEventListener.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
} | public String getYearPublished() {
return yearPublished;
}
public void setYearPublished(String yearPublished) {
this.yearPublished = yearPublished;
}
public float[] getEmbedding() {
return embedding;
}
public void setEmbedding(float[] embedding) {
this.embedding = embedding;
}
} | repos\tutorials-master\persistence-modules\spring-data-vector\src\main\java\com\baeldung\springdata\pgvector\Book.java | 1 |
请完成以下Java代码 | private Map<String, Integer> getProdIdCountMap(OrderProcessContext orderProcessContext) {
OrderInsertReq orderInsertReq = (OrderInsertReq) orderProcessContext.getOrderProcessReq().getReqData();
return orderInsertReq.getProdIdCountMap();
}
/**
* 查询产品详情
* @param prodIdCountMap 产品ID-库存 映射
* @return 产品列表
*/
private List<ProductEntity> queryProduct(Map<String, Integer> prodIdCountMap) {
// 查询结果集
List<ProductEntity> productEntityList = Lists.newArrayList();
// 构建查询请求
List<ProdQueryReq> prodQueryReqList = buildProdQueryReq(prodIdCountMap);
// 批量查询
for (ProdQueryReq prodQueryReq : prodQueryReqList) {
List<ProductEntity> productEntitys = productService.findProducts(prodQueryReq).getData();
// 产品ID不存在
if (productEntitys.size() <= 0) {
logger.error("查询产品详情时,上线中 & 产品ID=" + prodQueryReq.getId() + "的产品不存在!");
throw new CommonBizException(ExpCodeEnum.PRODUCT_NO_EXISTENT);
}
productEntityList.add(productEntitys.get(0));
}
return productEntityList;
} | /**
* 构建产品查询请求
* @param prodIdCountMap 产品ID-库存 映射
* @return 产品查询请求列表
*/
private List<ProdQueryReq> buildProdQueryReq(Map<String, Integer> prodIdCountMap) {
List<ProdQueryReq> prodQueryReqList = Lists.newArrayList();
for (String prodId : prodIdCountMap.keySet()) {
ProdQueryReq prodQueryReq = new ProdQueryReq();
prodQueryReq.setId(prodId);
// 必须是"上线中"的产品
prodQueryReq.setProdStateCode(ProdStateEnum.OPEN.getCode());
prodQueryReqList.add(prodQueryReq);
}
return prodQueryReqList;
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\component\datatransfer\ProdCountMapTransferComponent.java | 1 |
请完成以下Java代码 | public class StringBuilderBenchmark {
@Benchmark
public void testStringAdd() {
String a = "";
for (int i = 0; i < 10; i++) {
a += i;
}
print(a);
}
@Benchmark
public void testStringBuilderAdd() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
sb.append(i); | }
print(sb.toString());
}
private void print(String a) {
}
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder()
.include(StringBuilderBenchmark.class.getSimpleName())
.output("E:/Benchmark.log")
.build();
new Runner(options).run();
}
} | repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\benchmark\string\StringBuilderBenchmark.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Result<List<String>> loadDictItem(@RequestParam(name = "ids") String ids, @RequestParam(name = "delNotExist", required = false, defaultValue = "true") boolean delNotExist) {
Result<List<String>> result = new Result<>();
// 非空判断
if (StringUtils.isBlank(ids)) {
result.setSuccess(false);
result.setMessage("ids 不能为空");
return result;
}
// 查询数据
List<String> textList = sysCategoryService.loadDictItem(ids, delNotExist);
result.setSuccess(true);
result.setResult(textList);
return result;
}
/**
* [列表页面]加载分类字典数据 用于值的替换
* @param code
* @return
*/
@RequestMapping(value = "/loadAllData", method = RequestMethod.GET)
public Result<List<DictModel>> loadAllData(@RequestParam(name="code",required = true) String code) {
Result<List<DictModel>> result = new Result<List<DictModel>>();
LambdaQueryWrapper<SysCategory> query = new LambdaQueryWrapper<SysCategory>();
if(oConvertUtils.isNotEmpty(code) && !CATEGORY_ROOT_CODE.equals(code)){
query.likeRight(SysCategory::getCode,code);
}
List<SysCategory> list = this.sysCategoryService.list(query);
if(list==null || list.size()==0) {
result.setMessage("无数据,参数有误.[code]");
result.setSuccess(false);
return result;
}
List<DictModel> rdList = new ArrayList<DictModel>();
for (SysCategory c : list) {
rdList.add(new DictModel(c.getId(),c.getName()));
} | result.setSuccess(true);
result.setResult(rdList);
return result;
}
/**
* 根据父级id批量查询子节点
* @param parentIds
* @return
*/
@GetMapping("/getChildListBatch")
public Result getChildListBatch(@RequestParam("parentIds") String parentIds) {
try {
QueryWrapper<SysCategory> queryWrapper = new QueryWrapper<>();
List<String> parentIdList = Arrays.asList(parentIds.split(","));
queryWrapper.in("pid", parentIdList);
List<SysCategory> list = sysCategoryService.list(queryWrapper);
IPage<SysCategory> pageList = new Page<>(1, 10, list.size());
pageList.setRecords(list);
return Result.OK(pageList);
} catch (Exception e) {
log.error(e.getMessage(), e);
return Result.error("批量查询子节点失败:" + e.getMessage());
}
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysCategoryController.java | 2 |
请完成以下Java代码 | public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
public Integer getMatchStrategy() {
return matchStrategy;
}
public void setMatchStrategy(Integer matchStrategy) {
this.matchStrategy = matchStrategy;
}
@Override
public boolean equals(Object o) {
if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; }
GatewayParamFlowItemEntity that = (GatewayParamFlowItemEntity) o;
return Objects.equals(parseStrategy, that.parseStrategy) &&
Objects.equals(fieldName, that.fieldName) &&
Objects.equals(pattern, that.pattern) &&
Objects.equals(matchStrategy, that.matchStrategy); | }
@Override
public int hashCode() {
return Objects.hash(parseStrategy, fieldName, pattern, matchStrategy);
}
@Override
public String toString() {
return "GatewayParamFlowItemEntity{" +
"parseStrategy=" + parseStrategy +
", fieldName='" + fieldName + '\'' +
", pattern='" + pattern + '\'' +
", matchStrategy=" + matchStrategy +
'}';
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\gateway\GatewayParamFlowItemEntity.java | 1 |
请完成以下Java代码 | public static OrgId ofRepoId(final int repoId)
{
final OrgId orgId = ofRepoIdOrNull(repoId);
if (orgId == null)
{
throw new AdempiereException("Invalid AD_Org_ID: " + repoId);
}
return orgId;
}
/**
* @return {@link #ANY} if the given {@code repoId} is zero; {@code null} if it is less than zero.
*/
@Nullable
public static OrgId ofRepoIdOrNull(final int repoId)
{
if (repoId == ANY.repoId)
{
return ANY;
}
else if (repoId == MAIN.repoId)
{
return MAIN;
}
else if (repoId < 0)
{
return null;
}
else
{
return new OrgId(repoId);
}
}
/**
* @return {@link #ANY} even if the given {@code repoId} is less than zero.
*/
public static OrgId ofRepoIdOrAny(final int repoId)
{
final OrgId orgId = ofRepoIdOrNull(repoId);
return orgId != null ? orgId : ANY;
}
public static Optional<OrgId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static int toRepoId(@Nullable final OrgId orgId)
{
return orgId != null ? orgId.getRepoId() : -1;
}
public static int toRepoIdOrAny(@Nullable final OrgId orgId)
{
return orgId != null ? orgId.getRepoId() : ANY.repoId;
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
} | public boolean isAny()
{
return repoId == Env.CTXVALUE_AD_Org_ID_Any;
}
/**
* @return {@code true} if the org in question is not {@code *} (i.e. "ANY"), but a specific organisation's ID
*/
public boolean isRegular()
{
return !isAny();
}
public void ifRegular(@NonNull final Consumer<OrgId> consumer)
{
if (isRegular())
{
consumer.accept(this);
}
}
@Nullable
public OrgId asRegularOrNull() {return isRegular() ? this : null;}
public static boolean equals(@Nullable final OrgId id1, @Nullable final OrgId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\OrgId.java | 1 |
请完成以下Java代码 | public static AcctSchemaElementType ofCode(@NonNull final String code)
{
final AcctSchemaElementType type = ofCodeOrNull(code);
if (type == null)
{
throw new AdempiereException("No " + AcctSchemaElementType.class + " found for code: " + code);
}
return type;
}
public static AcctSchemaElementType ofCodeOrNull(@NonNull final String code)
{
return typesByCode.get(code);
}
private static final ImmutableMap<String, AcctSchemaElementType> typesByCode = Maps.uniqueIndex(Arrays.asList(values()), AcctSchemaElementType::getCode); | public boolean isDeletable()
{
// Acct Schema Elements "Account" and "Org" should be mandatory - teo_sarca BF [ 1795817 ]
return this != Account && this != Organization;
}
public boolean isUserDefinedElements()
{
return this == AcctSchemaElementType.UserList1
|| this == AcctSchemaElementType.UserList2
|| this == AcctSchemaElementType.UserElement1
|| this == AcctSchemaElementType.UserElement2;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\AcctSchemaElementType.java | 1 |
请完成以下Java代码 | public class AuthenticatedVoter implements AccessDecisionVoter<Object> {
public static final String IS_AUTHENTICATED_FULLY = "IS_AUTHENTICATED_FULLY";
public static final String IS_AUTHENTICATED_REMEMBERED = "IS_AUTHENTICATED_REMEMBERED";
public static final String IS_AUTHENTICATED_ANONYMOUSLY = "IS_AUTHENTICATED_ANONYMOUSLY";
private AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl();
private boolean isFullyAuthenticated(Authentication authentication) {
return this.authenticationTrustResolver.isFullyAuthenticated(authentication);
}
public void setAuthenticationTrustResolver(AuthenticationTrustResolver authenticationTrustResolver) {
Assert.notNull(authenticationTrustResolver, "AuthenticationTrustResolver cannot be set to null");
this.authenticationTrustResolver = authenticationTrustResolver;
}
@Override
public boolean supports(ConfigAttribute attribute) {
return (attribute.getAttribute() != null) && (IS_AUTHENTICATED_FULLY.equals(attribute.getAttribute())
|| IS_AUTHENTICATED_REMEMBERED.equals(attribute.getAttribute())
|| IS_AUTHENTICATED_ANONYMOUSLY.equals(attribute.getAttribute()));
}
/**
* This implementation supports any type of class, because it does not query the
* presented secure object.
* @param clazz the secure object type
* @return always {@code true}
*/
@Override
public boolean supports(Class<?> clazz) {
return true;
}
@Override
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
int result = ACCESS_ABSTAIN;
for (ConfigAttribute attribute : attributes) {
if (this.supports(attribute)) {
result = ACCESS_DENIED;
if (IS_AUTHENTICATED_FULLY.equals(attribute.getAttribute())) { | if (isFullyAuthenticated(authentication)) {
return ACCESS_GRANTED;
}
}
if (IS_AUTHENTICATED_REMEMBERED.equals(attribute.getAttribute())) {
if (this.authenticationTrustResolver.isRememberMe(authentication)
|| isFullyAuthenticated(authentication)) {
return ACCESS_GRANTED;
}
}
if (IS_AUTHENTICATED_ANONYMOUSLY.equals(attribute.getAttribute())) {
if (this.authenticationTrustResolver.isAnonymous(authentication)
|| isFullyAuthenticated(authentication)
|| this.authenticationTrustResolver.isRememberMe(authentication)) {
return ACCESS_GRANTED;
}
}
}
}
return result;
}
} | repos\spring-security-main\access\src\main\java\org\springframework\security\access\vote\AuthenticatedVoter.java | 1 |
请完成以下Java代码 | public boolean isUserInChargeUserEditable()
{
return false;
}
/**
* <ul>
* <li>QtyEntered := C_OLCand.Qty
* <li>C_UOM_ID := C_OLCand's effective UOM
* <li>QtyOrdered := C_OLCand.Qty's converted to effective product's UOM
* <li>DateOrdered := C_OLCand.DateCandidate
* <li>C_Order_ID: untouched
* </ul>
*
* @see IInvoiceCandidateHandler#setDeliveredData(I_C_Invoice_Candidate)
*/
@Override
public void setOrderedData(@NonNull final I_C_Invoice_Candidate ic)
{
final I_C_OLCand olc = getOLCand(ic);
setOrderedData(ic, olc);
}
private void setOrderedData(
@NonNull final I_C_Invoice_Candidate ic,
@NonNull final I_C_OLCand olc)
{
ic.setDateOrdered(olc.getDateCandidate());
final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class);
final Quantity olCandQuantity = Quantity.of(olCandEffectiveValuesBL.getEffectiveQtyEntered(olc), olCandEffectiveValuesBL.getC_UOM_Effective(olc));
ic.setQtyEntered(olCandQuantity.toBigDecimal());
ic.setC_UOM_ID(UomId.toRepoId(olCandQuantity.getUomId()));
final ProductId productId = olCandEffectiveValuesBL.getM_Product_Effective_ID(olc);
final Quantity qtyInProductUOM = uomConversionBL.convertToProductUOM(olCandQuantity, productId);
ic.setQtyOrdered(qtyInProductUOM.toBigDecimal());
}
private I_C_OLCand getOLCand(@NonNull final I_C_Invoice_Candidate ic)
{
return TableRecordCacheLocal.getReferencedValue(ic, I_C_OLCand.class);
}
/**
* <ul>
* <li>QtyDelivered := QtyOrdered
* <li>DeliveryDate := DateOrdered
* <li>M_InOut_ID: untouched
* </ul>
*
* @see IInvoiceCandidateHandler#setDeliveredData(I_C_Invoice_Candidate)
*/
@Override
public void setDeliveredData(@NonNull final I_C_Invoice_Candidate ic)
{ | ic.setQtyDelivered(ic.getQtyOrdered()); // when changing this, make sure to threat ProductType.Service specially
ic.setQtyDeliveredInUOM(ic.getQtyEntered());
ic.setDeliveryDate(ic.getDateOrdered());
}
@Override
public PriceAndTax calculatePriceAndTax(@NonNull final I_C_Invoice_Candidate ic)
{
final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(ic.getAD_Org_ID()));
final I_C_OLCand olc = getOLCand(ic);
final IPricingResult pricingResult = Services.get(IOLCandBL.class).computePriceActual(
olc,
null,
PricingSystemId.NULL,
TimeUtil.asLocalDate(olCandEffectiveValuesBL.getDatePromised_Effective(olc), timeZone));
return PriceAndTax.builder()
.priceUOMId(pricingResult.getPriceUomId())
.priceActual(pricingResult.getPriceStd())
.taxIncluded(pricingResult.isTaxIncluded())
.invoicableQtyBasedOn(pricingResult.getInvoicableQtyBasedOn())
.build();
}
@Override
public void setBPartnerData(@NonNull final I_C_Invoice_Candidate ic)
{
final I_C_OLCand olc = getOLCand(ic);
InvoiceCandidateLocationAdapterFactory
.billLocationAdapter(ic)
.setFrom(olCandEffectiveValuesBL.getBuyerPartnerInfo(olc));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\invoicecandidate\spi\impl\C_OLCand_Handler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BookstoreService {
private final AuthorRepository authorRepository;
public BookstoreService(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
@Transactional
public void doTimeConsumingTask() throws InterruptedException {
System.out.println("Waiting for a time-consuming task that doesn't need a database connection ...");
// we use a sleep of 40 seconds just to capture HikariCP logging status
// which take place at every 30 seconds - this will reveal if the connection | // was opened (acquired from the connection pool) or not
Thread.sleep(40000);
System.out.println("Done, now query the database ...");
System.out.println("The database connection should be acquired now ...");
Author author = authorRepository.findById(1L).get();
// at this point, the connection should be open
Thread.sleep(40000);
author.setAge(44);
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootDelayConnection\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | public static String getFileName(File file, FileFilter filter)
{
return getFile(file, filter).getAbsolutePath();
} // getFileName
/**
* Verify file with filter
* @param file file
* @param filter filter
* @return file
*/
public static File getFile(File file, FileFilter filter)
{
String fName = file.getAbsolutePath();
if (fName == null || fName.equals(""))
fName = "Adempiere";
//
ExtensionFileFilter eff = null;
if (filter instanceof ExtensionFileFilter)
eff = (ExtensionFileFilter)filter;
else
return file;
//
int pos = fName.lastIndexOf('.');
// No extension
if (pos == -1)
{ | fName += '.' + eff.getExtension();
return new File(fName);
}
String ext = fName.substring(pos+1);
// correct extension
if (ext.equalsIgnoreCase(eff.getExtension()))
return file;
fName += '.' + eff.getExtension();
return new File(fName);
} // getFile
} // ExtensionFileFilter | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\ExtensionFileFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DefaultHousekeeperClient implements HousekeeperClient {
private final HousekeeperConfig config;
private final TbQueueProducer<TbProtoQueueMsg<ToHousekeeperServiceMsg>> producer;
private final TopicPartitionInfo submitTpi;
private final TbQueueCallback submitCallback;
public DefaultHousekeeperClient(HousekeeperConfig config,
TbQueueProducerProvider producerProvider) {
this.config = config;
this.producer = producerProvider.getHousekeeperMsgProducer();
this.submitTpi = TopicPartitionInfo.builder().topic(producer.getDefaultTopic()).build();
this.submitCallback = new TbQueueCallback() {
@Override
public void onSuccess(TbQueueMsgMetadata metadata) {
log.trace("Submitted Housekeeper task");
}
@Override
public void onFailure(Throwable t) {
log.error("Failed to submit Housekeeper task", t);
}
};
}
@Override
public void submitTask(HousekeeperTask task) {
HousekeeperTaskType taskType = task.getTaskType();
if (config.getDisabledTaskTypes().contains(taskType)) { | log.trace("Task type {} is disabled, ignoring {}", taskType, task);
return;
}
log.debug("[{}][{}][{}] Submitting task: {}", task.getTenantId(), task.getEntityId().getEntityType(), task.getEntityId(), task);
/*
* using msg key as entity id so that msgs related to certain entity are pushed to same partition,
* e.g. on tenant deletion (entity id is tenant id), we need to clean up tenant entities in certain order
* */
try {
producer.send(submitTpi, new TbProtoQueueMsg<>(task.getEntityId().getId(), ToHousekeeperServiceMsg.newBuilder()
.setTask(TransportProtos.HousekeeperTaskProto.newBuilder()
.setValue(JacksonUtil.toString(task))
.setTs(task.getTs())
.setAttempt(0)
.build())
.build()), submitCallback);
} catch (Throwable t) {
log.error("Failed to submit Housekeeper task {}", task, t);
}
}
} | repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\housekeeper\DefaultHousekeeperClient.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class FlowableAppProperties {
/**
* The location where the App resources are located.
* Default is {@code classpath*:/apps/}
*/
private String resourceLocation = "classpath*:/apps/";
/**
* The suffixes for the resources that need to be scanned.
* Default is {@code **.zip, **.bar}
*/
private List<String> resourceSuffixes = Arrays.asList("**.zip", "**.bar");
/**
* Whether to perform deployment of resources, default is {@code true}.
*/
private boolean deployResources = true;
/**
* The servlet configuration for the Process Rest API.
*/
@NestedConfigurationProperty
private final FlowableServlet servlet = new FlowableServlet("/app-api", "Flowable App Rest API");
public FlowableServlet getServlet() {
return servlet;
}
/**
* Whether the App engine needs to be started.
*/
private boolean enabled = true;
public String getResourceLocation() {
return resourceLocation;
}
public void setResourceLocation(String resourceLocation) {
this.resourceLocation = resourceLocation;
}
public List<String> getResourceSuffixes() {
return resourceSuffixes;
} | public void setResourceSuffixes(List<String> resourceSuffixes) {
this.resourceSuffixes = resourceSuffixes;
}
public boolean isDeployResources() {
return deployResources;
}
public void setDeployResources(boolean deployResources) {
this.deployResources = deployResources;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
} | repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\app\FlowableAppProperties.java | 2 |
请完成以下Java代码 | public void setRequestType (String RequestType)
{
set_Value (COLUMNNAME_RequestType, RequestType);
}
/** Get Request Type.
@return Request Type */
public String getRequestType ()
{
return (String)get_Value(COLUMNNAME_RequestType);
}
/** Set Status Code.
@param StatusCode Status Code */
public void setStatusCode (int StatusCode)
{
set_Value (COLUMNNAME_StatusCode, Integer.valueOf(StatusCode));
}
/** Get Status Code.
@return Status Code */
public int getStatusCode ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_StatusCode);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set User Agent.
@param UserAgent
Browser Used
*/
public void setUserAgent (String UserAgent)
{ | set_Value (COLUMNNAME_UserAgent, UserAgent);
}
/** Get User Agent.
@return Browser Used
*/
public String getUserAgent ()
{
return (String)get_Value(COLUMNNAME_UserAgent);
}
/** Set Web Session.
@param WebSession
Web Session ID
*/
public void setWebSession (String WebSession)
{
set_Value (COLUMNNAME_WebSession, WebSession);
}
/** Get Web Session.
@return Web Session ID
*/
public String getWebSession ()
{
return (String)get_Value(COLUMNNAME_WebSession);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_WebAccessLog.java | 1 |
请完成以下Java代码 | public void setnetdate (final @Nullable java.sql.Timestamp netdate)
{
set_Value (COLUMNNAME_netdate, netdate);
}
@Override
public java.sql.Timestamp getnetdate()
{
return get_ValueAsTimestamp(COLUMNNAME_netdate);
}
@Override
public void setNetDays (final int NetDays)
{
set_Value (COLUMNNAME_NetDays, NetDays);
}
@Override
public int getNetDays()
{
return get_ValueAsInt(COLUMNNAME_NetDays);
}
@Override
public void setsinglevat (final @Nullable BigDecimal singlevat)
{ | set_Value (COLUMNNAME_singlevat, singlevat);
}
@Override
public BigDecimal getsinglevat()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_singlevat);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void settaxfree (final boolean taxfree)
{
set_Value (COLUMNNAME_taxfree, taxfree);
}
@Override
public boolean istaxfree()
{
return get_ValueAsBoolean(COLUMNNAME_taxfree);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_120_v.java | 1 |
请完成以下Java代码 | public void on(Message message, Channel channel) throws IOException {
channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
log.debug("FANOUT_QUEUE_A " + new String(message.getBody()));
}
/**
* FANOUT广播队列监听二.
*
* @param message the message
* @param channel the channel
* @throws IOException the io exception 这里异常需要处理
*/
@RabbitListener(queues = {"FANOUT_QUEUE_B"})
public void t(Message message, Channel channel) throws IOException {
channel.basicAck(message.getMessageProperties().getDeliveryTag(), true); | log.debug("FANOUT_QUEUE_B " + new String(message.getBody()));
}
/**
* DIRECT模式.
*
* @param message the message
* @param channel the channel
* @throws IOException the io exception 这里异常需要处理
*/
@RabbitListener(queues = {"DIRECT_QUEUE"})
public void message(Message message, Channel channel) throws IOException {
channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
log.debug("DIRECT " + new String(message.getBody()));
}
} | repos\SpringBootBucket-master\springboot-rabbitmq\src\main\java\com\xncoding\pos\mq\Receiver.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setIsAllowIssuingAnyHU (final boolean IsAllowIssuingAnyHU)
{
set_Value (COLUMNNAME_IsAllowIssuingAnyHU, IsAllowIssuingAnyHU);
}
@Override
public boolean isAllowIssuingAnyHU()
{
return get_ValueAsBoolean(COLUMNNAME_IsAllowIssuingAnyHU);
}
@Override
public void setIsScanResourceRequired (final boolean IsScanResourceRequired)
{
set_Value (COLUMNNAME_IsScanResourceRequired, IsScanResourceRequired);
}
@Override
public boolean isScanResourceRequired()
{ | return get_ValueAsBoolean(COLUMNNAME_IsScanResourceRequired);
}
@Override
public void setMobileUI_MFG_Config_ID (final int MobileUI_MFG_Config_ID)
{
if (MobileUI_MFG_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_MobileUI_MFG_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MobileUI_MFG_Config_ID, MobileUI_MFG_Config_ID);
}
@Override
public int getMobileUI_MFG_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_MobileUI_MFG_Config_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_MFG_Config.java | 1 |
请完成以下Java代码 | public final class DefaultPrintingRecordTextProvider implements IRecordTextProvider
{
public static final transient DefaultPrintingRecordTextProvider instance = new DefaultPrintingRecordTextProvider();
public static final String MSG_CLIENT_REPORTS_PRINT_ERROR = "de.metas.printing.C_Print_Job_Instructions.ClientReportsPrintError";
private DefaultPrintingRecordTextProvider()
{
super();
}
@Override
public Optional<String> getTextMessageIfApplies(ITableRecordReference referencedRecord)
{
// the default printing ctx provider only applies to I_C_Print_Job_Instructions entries
if (referencedRecord.getAD_Table_ID() != InterfaceWrapperHelper.getTableId(I_C_Print_Job_Instructions.class))
{
return Optional.absent(); | }
final IContextAware context = PlainContextAware.newOutOfTrxAllowThreadInherited(Env.getCtx());
final I_C_Print_Job_Instructions printJobInstructions = referencedRecord.getModel(context, I_C_Print_Job_Instructions.class);
return getTextMessage(printJobInstructions);
}
public Optional<String> getTextMessage(final I_C_Print_Job_Instructions printJobInstructions)
{
if (printJobInstructions == null)
{
// shall never happen
return Optional.absent();
}
final String errorMsg = printJobInstructions.getErrorMsg();
return Optional.of(CoalesceUtil.coalesce(errorMsg, ""));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\spi\impl\DefaultPrintingRecordTextProvider.java | 1 |
请完成以下Java代码 | public class ScriptExecutionListener implements ExecutionListener {
private static final long serialVersionUID = 1L;
private Expression script;
private Expression language;
private Expression resultVariable;
@Override
public void notify(DelegateExecution execution) {
if (script == null) {
throw new IllegalArgumentException("The field 'script' should be set on the ExecutionListener");
}
if (language == null) {
throw new IllegalArgumentException("The field 'language' should be set on the ExecutionListener");
}
ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines();
Object result = scriptingEngines.evaluate(script.getExpressionText(), language.getExpressionText(), execution); | if (resultVariable != null) {
execution.setVariable(resultVariable.getExpressionText(), result);
}
}
public void setScript(Expression script) {
this.script = script;
}
public void setLanguage(Expression language) {
this.language = language;
}
public void setResultVariable(Expression resultVariable) {
this.resultVariable = resultVariable;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\listener\ScriptExecutionListener.java | 1 |
请完成以下Java代码 | public class OutboundChannelModel extends ChannelModel {
protected String serializerType;
protected String serializerDelegateExpression;
protected String pipelineDelegateExpression;
@JsonIgnore
protected Object outboundEventChannelAdapter;
@JsonIgnore
protected Object outboundEventProcessingPipeline;
public OutboundChannelModel() {
setChannelType("outbound");
}
public String getSerializerType() {
return serializerType;
}
public void setSerializerType(String serializerType) {
this.serializerType = serializerType;
}
public String getSerializerDelegateExpression() {
return serializerDelegateExpression;
} | public void setSerializerDelegateExpression(String serializerDelegateExpression) {
this.serializerDelegateExpression = serializerDelegateExpression;
}
public String getPipelineDelegateExpression() {
return pipelineDelegateExpression;
}
public void setPipelineDelegateExpression(String pipelineDelegateExpression) {
this.pipelineDelegateExpression = pipelineDelegateExpression;
}
public Object getOutboundEventChannelAdapter() {
return outboundEventChannelAdapter;
}
public void setOutboundEventChannelAdapter(Object outboundEventChannelAdapter) {
this.outboundEventChannelAdapter = outboundEventChannelAdapter;
}
public Object getOutboundEventProcessingPipeline() {
return outboundEventProcessingPipeline;
}
public void setOutboundEventProcessingPipeline(Object outboundEventProcessingPipeline) {
this.outboundEventProcessingPipeline = outboundEventProcessingPipeline;
}
} | repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\OutboundChannelModel.java | 1 |
请完成以下Java代码 | public void setDynAttrProductPriceAttributeAware(final IAttributeSetInstanceAware asiAware, final Optional<IProductPriceAware> productPriceAware)
{
if (asiAware == null)
{
return; // nothing to do
}
DYN_ATTR_IProductPriceAware.setValue(asiAware, productPriceAware.orElse(null));
}
@Override
public void setDynAttrProductPriceAttributeAware(final IAttributeSetInstanceAware asiAware, final IProductPriceAware productPriceAware)
{
if (asiAware == null)
{
return; // nothing to do
} | DYN_ATTR_IProductPriceAware.setValue(asiAware, productPriceAware);
}
@Override
public Optional<IProductPriceAware> getDynAttrProductPriceAttributeAware(final IAttributeSetInstanceAware asiAware)
{
return DYN_ATTR_IProductPriceAware.getValueIfExists(asiAware);
}
@Value
private static class PricingAttribute implements IPricingAttribute
{
@Nullable AttributeListValue attributeValue;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\attributebased\impl\AttributePricingBL.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DatasourceSelectorAspect {
@Pointcut("execution(public * com.xkcoding.dynamic.datasource.controller.*.*(..))")
public void datasourcePointcut() {
}
/**
* 前置操作,拦截具体请求,获取header里的数据源id,设置线程变量里,用于后续切换数据源
*/
@Before("datasourcePointcut()")
public void doBefore(JoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
// 排除不可切换数据源的方法
DefaultDatasource annotation = method.getAnnotation(DefaultDatasource.class);
if (null != annotation) {
DatasourceConfigContextHolder.setDefaultDatasource();
} else {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
HttpServletRequest request = attributes.getRequest();
String configIdInHeader = request.getHeader("Datasource-Config-Id"); | if (StringUtils.hasText(configIdInHeader)) {
long configId = Long.parseLong(configIdInHeader);
DatasourceConfigContextHolder.setCurrentDatasourceConfig(configId);
} else {
DatasourceConfigContextHolder.setDefaultDatasource();
}
}
}
/**
* 后置操作,设置回默认的数据源id
*/
@AfterReturning("datasourcePointcut()")
public void doAfter() {
DatasourceConfigContextHolder.setDefaultDatasource();
}
} | repos\spring-boot-demo-master\demo-dynamic-datasource\src\main\java\com\xkcoding\dynamic\datasource\aspect\DatasourceSelectorAspect.java | 2 |
请完成以下Java代码 | public void setValues(UserTask otherElement) {
super.setValues(otherElement);
setAssignee(otherElement.getAssignee());
setOwner(otherElement.getOwner());
setFormKey(otherElement.getFormKey());
setSameDeployment(otherElement.isSameDeployment());
setDueDate(otherElement.getDueDate());
setPriority(otherElement.getPriority());
setCategory(otherElement.getCategory());
setTaskIdVariableName(otherElement.getTaskIdVariableName());
setTaskCompleterVariableName(otherElement.getTaskCompleterVariableName());
setExtensionId(otherElement.getExtensionId());
setSkipExpression(otherElement.getSkipExpression());
setValidateFormFields(otherElement.getValidateFormFields());
setCandidateGroups(new ArrayList<>(otherElement.getCandidateGroups()));
setCandidateUsers(new ArrayList<>(otherElement.getCandidateUsers()));
setCustomGroupIdentityLinks(otherElement.customGroupIdentityLinks);
setCustomUserIdentityLinks(otherElement.customUserIdentityLinks); | formProperties = new ArrayList<>();
if (otherElement.getFormProperties() != null && !otherElement.getFormProperties().isEmpty()) {
for (FormProperty property : otherElement.getFormProperties()) {
formProperties.add(property.clone());
}
}
taskListeners = new ArrayList<>();
if (otherElement.getTaskListeners() != null && !otherElement.getTaskListeners().isEmpty()) {
for (FlowableListener listener : otherElement.getTaskListeners()) {
taskListeners.add(listener.clone());
}
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\UserTask.java | 1 |
请完成以下Java代码 | public DeploymentQueryImpl createDeploymentQuery() {
return new DeploymentQueryImpl();
}
public ModelQueryImpl createModelQueryImpl() {
return new ModelQueryImpl();
}
public ProcessDefinitionQueryImpl createProcessDefinitionQuery() {
return new ProcessDefinitionQueryImpl();
}
public ProcessInstanceQueryImpl createProcessInstanceQuery() {
return new ProcessInstanceQueryImpl();
}
public ExecutionQueryImpl createExecutionQuery() {
return new ExecutionQueryImpl();
}
public TaskQueryImpl createTaskQuery() {
return new TaskQueryImpl();
}
public JobQueryImpl createJobQuery() {
return new JobQueryImpl();
}
public HistoricProcessInstanceQueryImpl createHistoricProcessInstanceQuery() {
return new HistoricProcessInstanceQueryImpl();
} | public HistoricActivityInstanceQueryImpl createHistoricActivityInstanceQuery() {
return new HistoricActivityInstanceQueryImpl();
}
public HistoricTaskInstanceQueryImpl createHistoricTaskInstanceQuery() {
return new HistoricTaskInstanceQueryImpl();
}
public HistoricDetailQueryImpl createHistoricDetailQuery() {
return new HistoricDetailQueryImpl();
}
public HistoricVariableInstanceQueryImpl createHistoricVariableInstanceQuery() {
return new HistoricVariableInstanceQueryImpl();
}
// getters and setters
// //////////////////////////////////////////////////////
public SqlSession getSqlSession() {
return sqlSession;
}
public DbSqlSessionFactory getDbSqlSessionFactory() {
return dbSqlSessionFactory;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\db\DbSqlSession.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Connector discardTextConnector() {
return integrationContext -> {
String contentToDiscard = (String) integrationContext.getInBoundVariables().get("content");
contentToDiscard += " :( ";
integrationContext.addOutBoundVariable("content", contentToDiscard);
logger.info("Final Content: " + contentToDiscard);
return integrationContext;
};
}
@Bean
public ProcessRuntimeEventListener<ProcessCompletedEvent> processCompletedListener() {
return processCompleted ->
logger.info(
">>> Process Completed: '" +
processCompleted.getEntity().getName() +
"' We can send a notification to the initiator: " +
processCompleted.getEntity().getInitiator() | );
}
private String pickRandomString() {
String[] texts = {
"hello from london",
"Hi there from activiti!",
"all good news over here.",
"I've tweeted about activiti today.",
"other boring projects.",
"activiti cloud - Cloud Native Java BPM",
};
return texts[new Random().nextInt(texts.length)];
}
} | repos\Activiti-develop\activiti-examples\activiti-api-basic-process-example\src\main\java\org\activiti\examples\DemoApplication.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class DATEV_ExportFile extends JavaProcess implements IProcessPrecondition
{
@Autowired
private DATEVExportFormatRepository exportFormatRepo;
@Param(parameterName = I_DATEV_ExportFormat.COLUMNNAME_DATEV_ExportFormat_ID, mandatory = true)
private int datevExportFormatId;
public DATEV_ExportFile()
{
SpringContextHolder.instance.autowire(this);
}
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
else if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final DATEVExportFormat exportFormat = exportFormatRepo.getById(datevExportFormatId);
final I_DATEV_Export datevExport = getRecord(I_DATEV_Export.class);
final IExportDataSource dataSource = createDataSource(exportFormat, datevExport.getDATEV_Export_ID());
final ByteArrayOutputStream out = new ByteArrayOutputStream();
DATEVCsvExporter.builder()
.exportFormat(exportFormat)
.dataSource(dataSource)
.build()
.export(out);
getResult().setReportData(
new ByteArrayResource(out.toByteArray()), // data
buildFilename(datevExport), // filename
"text/csv"); // content type
return MSG_OK; | }
private IExportDataSource createDataSource(@NonNull final DATEVExportFormat exportFormat, final int datevExportId)
{
Check.assume(datevExportId > 0, "datevExportId > 0");
final JdbcExporterBuilder builder = new JdbcExporterBuilder(I_DATEV_ExportLine.Table_Name)
.addEqualsWhereClause(I_DATEV_ExportLine.COLUMNNAME_DATEV_Export_ID, datevExportId)
.addEqualsWhereClause(I_DATEV_ExportLine.COLUMNNAME_IsActive, true)
.addOrderBy(I_DATEV_ExportLine.COLUMNNAME_DocumentNo)
.addOrderBy(I_DATEV_ExportLine.COLUMNNAME_DATEV_ExportLine_ID);
exportFormat
.getColumns()
.forEach(formatColumn -> builder.addField(formatColumn.getCsvHeaderName(), formatColumn.getColumnName()));
return builder.createDataSource();
}
private static String buildFilename(final I_DATEV_Export datevExport)
{
final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
final Timestamp dateAcctFrom = datevExport.getDateAcctFrom();
final Timestamp dateAcctTo = datevExport.getDateAcctTo();
return Joiner.on("_")
.skipNulls()
.join("datev",
dateAcctFrom != null ? dateFormatter.format(TimeUtil.asLocalDate(dateAcctFrom)) : null,
dateAcctTo != null ? dateFormatter.format(TimeUtil.asLocalDate(dateAcctTo)) : null)
+ ".csv";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java\de\metas\datev\process\DATEV_ExportFile.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Roo implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID")
private Long id;
@Column(name = "NAME")
private String name;
public Roo() {
}
public Roo(final String name) {
this.name = name;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Roo other = (Roo) obj;
if (name == null) {
if (other.name != null) {
return false; | }
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public void setId(final Long id) {
this.id = id;
}
@Override
public String toString() {
return "Roo [id=" + id + ", name=" + name + "]";
}
} | repos\tutorials-master\persistence-modules\spring-hibernate-6\src\main\java\com\baeldung\hibernate\cache\model\Roo.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public PmsOperator findOperatorByLoginName(String loginName) {
return pmsOperatorDao.findByLoginName(loginName);
}
/**
* 保存操作員信息及其关联的角色.
*
* @param pmsOperator
* .
* @param roleOperatorStr
* .
*/
@Transactional
public void saveOperator(PmsOperator pmsOperator, String roleOperatorStr) {
// 保存操作员信息
pmsOperatorDao.insert(pmsOperator);
// 保存角色关联信息
if (StringUtils.isNotBlank(roleOperatorStr) && roleOperatorStr.length() > 0) {
saveOrUpdateOperatorRole(pmsOperator, roleOperatorStr);
}
}
/**
* 保存用户和角色之间的关联关系
*/
private void saveOrUpdateOperatorRole(PmsOperator pmsOperator, String roleIdsStr) {
// 删除原来的角色与操作员关联
List<PmsOperatorRole> listPmsOperatorRoles = pmsOperatorRoleDao.listByOperatorId(pmsOperator.getId());
Map<Long, PmsOperatorRole> delMap = new HashMap<Long, PmsOperatorRole>();
for (PmsOperatorRole pmsOperatorRole : listPmsOperatorRoles) {
delMap.put(pmsOperatorRole.getRoleId(), pmsOperatorRole);
}
if (StringUtils.isNotBlank(roleIdsStr)) {
// 创建新的关联
String[] roleIds = roleIdsStr.split(",");
for (int i = 0; i < roleIds.length; i++) {
long roleId = Long.parseLong(roleIds[i]);
if (delMap.get(roleId) == null) {
PmsOperatorRole pmsOperatorRole = new PmsOperatorRole();
pmsOperatorRole.setOperatorId(pmsOperator.getId());
pmsOperatorRole.setRoleId(roleId);
pmsOperatorRole.setCreater(pmsOperator.getCreater());
pmsOperatorRole.setCreateTime(new Date());
pmsOperatorRole.setStatus(PublicStatusEnum.ACTIVE.name());
pmsOperatorRoleDao.insert(pmsOperatorRole);
} else {
delMap.remove(roleId); | }
}
}
Iterator<Long> iterator = delMap.keySet().iterator();
while (iterator.hasNext()) {
long roleId = iterator.next();
pmsOperatorRoleDao.deleteByRoleIdAndOperatorId(roleId, pmsOperator.getId());
}
}
/**
* 修改操作員信息及其关联的角色.
*
* @param pmsOperator
* .
* @param roleOperatorStr
* .
*/
public void updateOperator(PmsOperator pmsOperator, String roleOperatorStr) {
pmsOperatorDao.update(pmsOperator);
// 更新角色信息
this.saveOrUpdateOperatorRole(pmsOperator, roleOperatorStr);
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\service\impl\PmsOperatorServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Branch {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
public Branch() {
}
public Branch(String name) {
this.name = name;
}
@OneToMany(mappedBy = "mainBranch")
@LazyCollection(LazyCollectionOption.TRUE)
private List<Employee> mainEmployees;
@OneToMany(mappedBy = "subBranch")
@LazyCollection(LazyCollectionOption.FALSE)
private List<Employee> subEmployees;
@OneToMany(mappedBy = "additionalBranch")
@LazyCollection(LazyCollectionOption.EXTRA)
@OrderColumn(name = "order_id")
private List<Employee> additionalEmployees;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Employee> getMainEmployees() {
return mainEmployees;
} | public void setMainEmployees(List<Employee> mainEmployees) {
this.mainEmployees = mainEmployees;
}
public List<Employee> getSubEmployees() {
return subEmployees;
}
public void setSubEmployees(List<Employee> subEmployees) {
this.subEmployees = subEmployees;
}
public List<Employee> getAdditionalEmployees() {
return additionalEmployees;
}
public void setAdditionalEmployees(List<Employee> additionalEmployees) {
this.additionalEmployees = additionalEmployees;
}
public void addMainEmployee(Employee employee) {
if (this.mainEmployees == null) {
this.mainEmployees = new ArrayList<>();
}
this.mainEmployees.add(employee);
}
public void addSubEmployee(Employee employee) {
if (this.subEmployees == null) {
this.subEmployees = new ArrayList<>();
}
this.subEmployees.add(employee);
}
public void addAdditionalEmployee(Employee employee) {
if (this.additionalEmployees == null) {
this.additionalEmployees = new ArrayList<>();
}
this.additionalEmployees.add(employee);
}
} | repos\tutorials-master\persistence-modules\hibernate-annotations-2\src\main\java\com\baeldung\hibernate\lazycollection\model\Branch.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.