instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public String getNamespace(String prefix) {
return namespaceMap.get(prefix);
}
public Map<String, String> getNamespaces() {
return namespaceMap;
}
public Map<String, List<ExtensionAttribute>> getDefinitionsAttributes() {
return definitionsAttributes;
}
public String getDefinitionsAttributeValue(String namespace, String name) {
List<ExtensionAttribute> attributes = getDefinitionsAttributes().get(name);
if (attributes != null && !attributes.isEmpty()) {
for (ExtensionAttribute attribute : attributes) {
if (namespace.equals(attribute.getNamespace())) {
return attribute.getValue();
}
}
}
return null;
} | public void addDefinitionsAttribute(ExtensionAttribute attribute) {
if (attribute != null && StringUtils.isNotEmpty(attribute.getName())) {
List<ExtensionAttribute> attributeList = null;
if (!this.definitionsAttributes.containsKey(attribute.getName())) {
attributeList = new ArrayList<>();
this.definitionsAttributes.put(attribute.getName(), attributeList);
}
this.definitionsAttributes.get(attribute.getName()).add(attribute);
}
}
public void setDefinitionsAttributes(Map<String, List<ExtensionAttribute>> attributes) {
this.definitionsAttributes = attributes;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\CmmnModel.java | 1 |
请完成以下Java代码 | protected String getPropertyTable() {
return IDM_PROPERTY_TABLE;
}
@Override
protected String getUpgradeStartVersion() {
return "5.99.0.0";
}
@Override
protected void internalDbSchemaCreate() {
// User and Group tables can already have been created by the process engine in an earlier version
if (isIdmGroupTablePresent()) {
schemaUpdate();
} else {
super.internalDbSchemaCreate();
}
}
@Override
protected boolean isUpdateNeeded() {
boolean propertyTablePresent = isTablePresent(IDM_PROPERTY_TABLE);
if (!propertyTablePresent) {
return isIdmGroupTablePresent();
}
return true;
}
public boolean isIdmGroupTablePresent() {
return isTablePresent("ACT_ID_GROUP");
}
@Override
public void schemaCheckVersion() {
try {
String dbVersion = getSchemaVersion();
if (!IdmEngine.VERSION.equals(dbVersion)) {
throw new FlowableWrongDbException(IdmEngine.VERSION, dbVersion);
}
String errorMessage = null;
if (!isTablePresent(IDM_PROPERTY_TABLE)) {
errorMessage = addMissingComponent(errorMessage, "engine");
}
if (errorMessage != null) {
throw new FlowableException("Flowable IDM database problem: " + errorMessage);
} | } catch (Exception e) {
if (isMissingTablesException(e)) {
throw new FlowableException(
"no flowable tables in db. set <property name=\"databaseSchemaUpdate\" to value=\"true\" or value=\"create-drop\" (use create-drop for testing only!) in bean processEngineConfiguration in flowable.cfg.xml for automatic schema creation",
e);
} else {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
throw new FlowableException("couldn't get db schema version", e);
}
}
}
logger.debug("flowable idm db schema check successful");
}
protected String addMissingComponent(String missingComponents, String component) {
if (missingComponents == null) {
return "Tables missing for component(s) " + component;
}
return missingComponents + ", " + component;
}
@Override
public String getContext() {
return SCHEMA_COMPONENT;
}
} | repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\db\IdmDbSchemaManager.java | 1 |
请完成以下Java代码 | public int getAD_BusinessRule_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_BusinessRule_ID);
}
@Override
public void setAD_BusinessRule_Trigger_ID (final int AD_BusinessRule_Trigger_ID)
{
if (AD_BusinessRule_Trigger_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_BusinessRule_Trigger_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_BusinessRule_Trigger_ID, AD_BusinessRule_Trigger_ID);
}
@Override
public int getAD_BusinessRule_Trigger_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_BusinessRule_Trigger_ID);
}
@Override
public void setConditionSQL (final @Nullable java.lang.String ConditionSQL)
{
set_Value (COLUMNNAME_ConditionSQL, ConditionSQL);
}
@Override
public java.lang.String getConditionSQL()
{
return get_ValueAsString(COLUMNNAME_ConditionSQL);
}
@Override
public void setOnDelete (final boolean OnDelete)
{
set_Value (COLUMNNAME_OnDelete, OnDelete);
}
@Override
public boolean isOnDelete()
{
return get_ValueAsBoolean(COLUMNNAME_OnDelete);
}
@Override
public void setOnNew (final boolean OnNew)
{
set_Value (COLUMNNAME_OnNew, OnNew);
}
@Override | public boolean isOnNew()
{
return get_ValueAsBoolean(COLUMNNAME_OnNew);
}
@Override
public void setOnUpdate (final boolean OnUpdate)
{
set_Value (COLUMNNAME_OnUpdate, OnUpdate);
}
@Override
public boolean isOnUpdate()
{
return get_ValueAsBoolean(COLUMNNAME_OnUpdate);
}
@Override
public void setSource_Table_ID (final int Source_Table_ID)
{
if (Source_Table_ID < 1)
set_Value (COLUMNNAME_Source_Table_ID, null);
else
set_Value (COLUMNNAME_Source_Table_ID, Source_Table_ID);
}
@Override
public int getSource_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_Source_Table_ID);
}
@Override
public void setTargetRecordMappingSQL (final java.lang.String TargetRecordMappingSQL)
{
set_Value (COLUMNNAME_TargetRecordMappingSQL, TargetRecordMappingSQL);
}
@Override
public java.lang.String getTargetRecordMappingSQL()
{
return get_ValueAsString(COLUMNNAME_TargetRecordMappingSQL);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_BusinessRule_Trigger.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Product extends AbstractEntity
{
public static Product build(final String name, final String packingInfo)
{
return new Product(name, packingInfo);
}
public static final Comparator<Product> COMPARATOR_Id = (o1, o2) -> {
final Long id1 = o1.getId() != null ? o1.getId() : 0;
final Long id2 = o2.getId() != null ? o2.getId() : 0;
return id1.compareTo(id2);
};
private String name;
@Nullable
private String packingInfo;
private boolean shared;
@OneToMany(fetch = FetchType.EAGER, mappedBy = ProductTrl.COLUMNNAME_Record)
@MapKey(name = "language")
private Map<String, ProductTrl> translations;
public Product()
{
}
public Product(@NonNull final String name, @Nullable final String packingInfo)
{
this.name = name;
this.packingInfo = packingInfo;
}
@Override
protected void toString(final MoreObjects.ToStringHelper toStringHelper)
{
toStringHelper
.add("name", name)
.add("packingInfo", packingInfo)
.add("shared", shared);
}
public void setName(final String name)
{
this.name = name;
}
public String getName(final Locale locale)
{
final ProductTrl productTrl = TranslationHelper.getTranslation(translations, locale);
if (productTrl != null)
{
return productTrl.getName();
} | return name;
}
public void setPackingInfo(@Nullable final String packingInfo)
{
this.packingInfo = packingInfo;
}
@Nullable
public String getPackingInfo(final Locale locale)
{
return packingInfo;
}
public void setShared(final boolean shared)
{
this.shared = shared;
}
public boolean isShared()
{
return shared;
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\Product.java | 2 |
请完成以下Java代码 | public void setTax(@NonNull final org.compiere.model.I_C_OrderLine orderLine)
{
final I_C_Order orderRecord = orderBL().getById(OrderId.ofRepoId(orderLine.getC_Order_ID()));
final TaxCategoryId taxCategoryId = getTaxCategoryId(orderLine);
final WarehouseId warehouseId = warehouseAdvisor.evaluateWarehouse(orderLine);
final CountryId countryFromId = warehouseBL.getCountryId(warehouseId);
final BPartnerLocationAndCaptureId bpLocationId = OrderLineDocumentLocationAdapterFactory.locationAdapter(orderLine).getBPartnerLocationAndCaptureId();
final boolean isSOTrx = orderRecord.isSOTrx();
final Timestamp taxDate = orderLine.getDatePromised();
final BPartnerId effectiveBillPartnerId = orderBL().getEffectiveBillPartnerId(orderRecord);
// if we set the tax for a sales order, consider whether the customer is exempt from taxes
final Boolean isTaxExempt;
if (isSOTrx && effectiveBillPartnerId != null)
{
final I_C_BPartner billBPartnerRecord = bpartnerDAO.getById(effectiveBillPartnerId);
// Only set if TRUE - otherwise leave null (don't filter)
isTaxExempt = billBPartnerRecord.isTaxExempt() ? Boolean.TRUE : null;
}
else
{
isTaxExempt = null;
}
final Tax tax = taxDAO.getBy(TaxQuery.builder()
.fromCountryId(countryFromId)
.orgId(OrgId.ofRepoId(orderLine.getAD_Org_ID()))
.bPartnerLocationId(bpLocationId)
.warehouseId(warehouseId) | .dateOfInterest(taxDate)
.taxCategoryId(taxCategoryId)
.soTrx(SOTrx.ofBoolean(isSOTrx))
.isTaxExempt(isTaxExempt)
.build());
if (tax == null)
{
TaxNotFoundException.builder()
.taxCategoryId(taxCategoryId)
.isSOTrx(isSOTrx)
.isTaxExempt(isTaxExempt)
.billDate(taxDate)
.billFromCountryId(countryFromId)
.billToC_Location_ID(bpLocationId.getLocationCaptureId())
.build()
.throwOrLogWarning(true, logger);
}
orderLine.setC_Tax_ID(tax.getTaxId().getRepoId());
orderLine.setC_TaxCategory_ID(tax.getTaxCategoryId().getRepoId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\OrderLineBL.java | 1 |
请完成以下Java代码 | public Jsp getJsp() {
return this.jsp;
}
public Map<Locale, Charset> getLocaleCharsetMappings() {
return this.localeCharsetMappings;
}
public Map<String, String> getInitParameters() {
return this.initParameters;
}
public List<? extends CookieSameSiteSupplier> getCookieSameSiteSuppliers() {
return this.cookieSameSiteSuppliers;
}
public void setMimeMappings(MimeMappings mimeMappings) {
Assert.notNull(mimeMappings, "'mimeMappings' must not be null");
this.mimeMappings = new MimeMappings(mimeMappings);
}
public void addMimeMappings(MimeMappings mimeMappings) {
mimeMappings.forEach((mapping) -> this.mimeMappings.add(mapping.getExtension(), mapping.getMimeType()));
}
public void setInitializers(List<? extends ServletContextInitializer> initializers) {
Assert.notNull(initializers, "'initializers' must not be null");
this.initializers = new ArrayList<>(initializers);
}
public void addInitializers(ServletContextInitializer... initializers) {
Assert.notNull(initializers, "'initializers' must not be null");
this.initializers.addAll(Arrays.asList(initializers));
}
public void setLocaleCharsetMappings(Map<Locale, Charset> localeCharsetMappings) {
Assert.notNull(localeCharsetMappings, "'localeCharsetMappings' must not be null");
this.localeCharsetMappings = localeCharsetMappings;
}
public void setInitParameters(Map<String, String> initParameters) {
this.initParameters = initParameters;
} | public void setCookieSameSiteSuppliers(List<? extends CookieSameSiteSupplier> cookieSameSiteSuppliers) {
Assert.notNull(cookieSameSiteSuppliers, "'cookieSameSiteSuppliers' must not be null");
this.cookieSameSiteSuppliers = new ArrayList<>(cookieSameSiteSuppliers);
}
public void addCookieSameSiteSuppliers(CookieSameSiteSupplier... cookieSameSiteSuppliers) {
Assert.notNull(cookieSameSiteSuppliers, "'cookieSameSiteSuppliers' must not be null");
this.cookieSameSiteSuppliers.addAll(Arrays.asList(cookieSameSiteSuppliers));
}
public void addWebListenerClassNames(String... webListenerClassNames) {
this.webListenerClassNames.addAll(Arrays.asList(webListenerClassNames));
}
public Set<String> getWebListenerClassNames() {
return this.webListenerClassNames;
}
public List<URL> getStaticResourceUrls() {
return this.staticResourceJars.getUrls();
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\ServletWebServerSettings.java | 1 |
请完成以下Java代码 | protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
@Override
protected UserQuery createNewQuery(ProcessEngine engine) {
return engine.getIdentityService().createUserQuery();
}
@Override
protected void applyFilters(UserQuery query) {
if (id != null) {
query.userId(id);
}
if(idIn != null) {
query.userIdIn(idIn);
}
if (firstName != null) {
query.userFirstName(firstName);
}
if (firstNameLike != null) {
query.userFirstNameLike(firstNameLike);
}
if (lastName != null) {
query.userLastName(lastName);
}
if (lastNameLike != null) {
query.userLastNameLike(lastNameLike);
}
if (email != null) {
query.userEmail(email);
}
if (emailLike != null) {
query.userEmailLike(emailLike);
}
if (memberOfGroup != null) {
query.memberOfGroup(memberOfGroup);
}
if (potentialStarter != null) { | query.potentialStarter(potentialStarter);
}
if (tenantId != null) {
query.memberOfTenant(tenantId);
}
}
@Override
protected void applySortBy(UserQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_USER_ID_VALUE)) {
query.orderByUserId();
} else if (sortBy.equals(SORT_BY_USER_FIRSTNAME_VALUE)) {
query.orderByUserFirstName();
} else if (sortBy.equals(SORT_BY_USER_LASTNAME_VALUE)) {
query.orderByUserLastName();
} else if (sortBy.equals(SORT_BY_USER_EMAIL_VALUE)) {
query.orderByUserEmail();
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\identity\UserQueryDto.java | 1 |
请完成以下Java代码 | public class ApplicationStartedEvent extends SpringApplicationEvent {
private final ConfigurableApplicationContext context;
private final @Nullable Duration timeTaken;
/**
* Create a new {@link ApplicationStartedEvent} instance.
* @param application the current application
* @param args the arguments the application is running with
* @param context the context that was being created
* @param timeTaken the time taken to start the application
* @since 2.6.0
*/
public ApplicationStartedEvent(SpringApplication application, String[] args, ConfigurableApplicationContext context,
@Nullable Duration timeTaken) {
super(application, args);
this.context = context;
this.timeTaken = timeTaken; | }
/**
* Return the application context.
* @return the context
*/
public ConfigurableApplicationContext getApplicationContext() {
return this.context;
}
/**
* Return the time taken to start the application, or {@code null} if unknown.
* @return the startup time
* @since 2.6.0
*/
public @Nullable Duration getTimeTaken() {
return this.timeTaken;
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\event\ApplicationStartedEvent.java | 1 |
请完成以下Java代码 | public byte[] getToken() {
return this.token;
}
/**
* Gets the ticket validation
* @return the ticket validation (which will be null if the token is unauthenticated)
*/
public KerberosTicketValidation getTicketValidation() {
return this.ticketValidation;
}
/**
* Determines whether an authenticated token has a response token
* @return whether a response token is available
*/
public boolean hasResponseToken() {
return this.ticketValidation != null && this.ticketValidation.responseToken() != null;
}
/**
* Gets the (Base64) encoded response token assuming one is available.
* @return encoded response token
*/
public String getEncodedResponseToken() {
if (!hasResponseToken()) {
throw new IllegalStateException("Unauthenticated or no response token");
}
return Base64.getEncoder().encodeToString(this.ticketValidation.responseToken());
}
/**
* Unwraps an encrypted message using the gss context
* @param data the data
* @param offset data offset
* @param length data length
* @return the decrypted message
* @throws PrivilegedActionException if jaas throws and error
*/
public byte[] decrypt(final byte[] data, final int offset, final int length) throws PrivilegedActionException {
return Subject.doAs(getTicketValidation().subject(), new PrivilegedExceptionAction<byte[]>() {
public byte[] run() throws Exception {
final GSSContext context = getTicketValidation().getGssContext();
return context.unwrap(data, offset, length, new MessageProp(true));
}
});
} | /**
* Unwraps an encrypted message using the gss context
* @param data the data
* @return the decrypted message
* @throws PrivilegedActionException if jaas throws and error
*/
public byte[] decrypt(final byte[] data) throws PrivilegedActionException {
return decrypt(data, 0, data.length);
}
/**
* Wraps an message using the gss context
* @param data the data
* @param offset data offset
* @param length data length
* @return the encrypted message
* @throws PrivilegedActionException if jaas throws and error
*/
public byte[] encrypt(final byte[] data, final int offset, final int length) throws PrivilegedActionException {
return Subject.doAs(getTicketValidation().subject(), new PrivilegedExceptionAction<byte[]>() {
public byte[] run() throws Exception {
final GSSContext context = getTicketValidation().getGssContext();
return context.wrap(data, offset, length, new MessageProp(true));
}
});
}
/**
* Wraps an message using the gss context
* @param data the data
* @return the encrypted message
* @throws PrivilegedActionException if jaas throws and error
*/
public byte[] encrypt(final byte[] data) throws PrivilegedActionException {
return encrypt(data, 0, data.length);
}
@Override
public JaasSubjectHolder getJaasSubjectHolder() {
return this.jaasSubjectHolder;
}
} | repos\spring-security-main\kerberos\kerberos-core\src\main\java\org\springframework\security\kerberos\authentication\KerberosServiceRequestToken.java | 1 |
请完成以下Java代码 | public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException {
var originator = msg.getOriginator();
var msgDataAsObjectNode = TbMsgSource.DATA.equals(fetchTo) ? getMsgDataAsObjectNode(msg) : null;
if (!EntityType.DEVICE.equals(originator.getEntityType())) {
ctx.tellFailure(msg, new RuntimeException("Unsupported originator type: " + originator.getEntityType() + "!"));
return;
}
var deviceId = new DeviceId(msg.getOriginator().getId());
var deviceCredentials = ctx.getDeviceCredentialsService().findDeviceCredentialsByDeviceId(ctx.getTenantId(), deviceId);
if (deviceCredentials == null) {
ctx.tellFailure(msg, new RuntimeException("Failed to get Device Credentials for device: " + deviceId + "!"));
return;
}
var credentialsType = deviceCredentials.getCredentialsType();
var credentialsInfo = ctx.getDeviceCredentialsService().toCredentialsInfo(deviceCredentials);
var metaData = msg.getMetaData().copy();
if (TbMsgSource.METADATA.equals(fetchTo)) {
metaData.putValue(CREDENTIALS_TYPE, credentialsType.name());
if (credentialsType.equals(DeviceCredentialsType.ACCESS_TOKEN) || credentialsType.equals(DeviceCredentialsType.X509_CERTIFICATE)) {
metaData.putValue(CREDENTIALS, credentialsInfo.asText());
} else {
metaData.putValue(CREDENTIALS, JacksonUtil.toString(credentialsInfo)); | }
} else if (TbMsgSource.DATA.equals(fetchTo)) {
msgDataAsObjectNode.put(CREDENTIALS_TYPE, credentialsType.name());
msgDataAsObjectNode.set(CREDENTIALS, credentialsInfo);
}
TbMsg transformedMsg = transformMessage(msg, msgDataAsObjectNode, metaData);
ctx.tellSuccess(transformedMsg);
}
@Override
public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException {
return fromVersion == 0 ?
upgradeRuleNodesWithOldPropertyToUseFetchTo(
oldConfiguration,
"fetchToMetadata",
TbMsgSource.METADATA.name(),
TbMsgSource.DATA.name()) :
new TbPair<>(false, oldConfiguration);
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\metadata\TbFetchDeviceCredentialsNode.java | 1 |
请完成以下Java代码 | public final I_C_Contract_Change retrieveChangeConditions(
@NonNull final I_C_Flatrate_Term term,
@NonNull final String newStatus,
@NonNull final Timestamp changeDate)
{
final List<I_C_Contract_Change> entries = retrieveAllForTermAndNewStatus(term, newStatus);
final I_C_Contract_Change earliestEntryForRefDate = getEarliestEntryForRefDate(entries, changeDate, term.getEndDate());
if (earliestEntryForRefDate == null)
{
throw new SubscriptionChangeException(term.getC_Flatrate_Conditions_ID(), newStatus, changeDate);
}
return earliestEntryForRefDate;
}
private List<I_C_Contract_Change> retrieveAllForTermAndNewStatus(
@NonNull final I_C_Flatrate_Term term,
@NonNull final String newStatus)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final List<I_C_Contract_Change> entries = queryBL.createQueryBuilder(I_C_Contract_Change.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Contract_Change.COLUMN_C_Flatrate_Transition_ID, term.getC_Flatrate_Conditions().getC_Flatrate_Transition_ID())
.addEqualsFilter(I_C_Contract_Change.COLUMN_Action, X_C_Contract_Change.ACTION_Statuswechsel)
.addEqualsFilter(I_C_Contract_Change.COLUMN_ContractStatus, newStatus)
.addInArrayFilter(I_C_Contract_Change.COLUMN_C_Flatrate_Conditions_ID, term.getC_Flatrate_Conditions_ID(), 0, null)
.orderBy().addColumn(I_C_Contract_Change.COLUMN_C_Contract_Change_ID).endOrderBy()
.create()
.list();
return entries;
}
/**
* If the given list is empty or if there is no entry that has a deadline before the given
* <code>referenceDate</code>, then the method returns <code>null</code>.
*
* @param entries
* the entries to evaluate. May be empty, but is assumed to be not <code>null</code>
* @param referenceDate
* @param termEndDate
* @return
*/
protected final I_C_Contract_Change getEarliestEntryForRefDate(
@NonNull final List<I_C_Contract_Change> entries,
final Timestamp referenceDate,
final Timestamp termEndDate) | {
I_C_Contract_Change applicableEntry = null;
for (final I_C_Contract_Change entry : entries)
{
final Timestamp deadLineForEntry =
Services.get(ISubscriptionBL.class).mkNextDate(entry.getDeadLineUnit(), entry.getDeadLine() * -1, termEndDate);
if (referenceDate.after(deadLineForEntry))
{
// 'changeDate' is after the deadline set for 'entry'
continue;
}
if (applicableEntry == null)
{
// we found the first entry that is still before the deadline
applicableEntry = entry;
continue;
}
final Timestamp deadLineForCurrentApplicableEntry =
Services.get(ISubscriptionBL.class).mkNextDate(entry.getDeadLineUnit(), entry.getDeadLine() * -1, termEndDate);
if (deadLineForEntry.before(deadLineForCurrentApplicableEntry))
{
applicableEntry = entry;
}
}
return applicableEntry;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\AbstractContractChangeDAO.java | 1 |
请完成以下Java代码 | public void setSW6_Customer_Group (final @Nullable java.lang.String SW6_Customer_Group)
{
set_Value (COLUMNNAME_SW6_Customer_Group, SW6_Customer_Group);
}
@Override
public java.lang.String getSW6_Customer_Group()
{
return get_ValueAsString(COLUMNNAME_SW6_Customer_Group);
}
/**
* SW6_Payment_Method AD_Reference_ID=541295
* Reference name: _SW6_Payment_Method
*/
public static final int SW6_PAYMENT_METHOD_AD_Reference_ID=541295;
/** Nachnahme = cash_payment */
public static final String SW6_PAYMENT_METHOD_Nachnahme = "cash_payment";
/** Vorkasse = pre_payment */
public static final String SW6_PAYMENT_METHOD_Vorkasse = "pre_payment"; | /** Rechnung = invoice_payment */
public static final String SW6_PAYMENT_METHOD_Rechnung = "invoice_payment";
/** SEPA = debit_payment */
public static final String SW6_PAYMENT_METHOD_SEPA = "debit_payment";
/** PayPal = pay_pal_payment_handler */
public static final String SW6_PAYMENT_METHOD_PayPal = "pay_pal_payment_handler";
/** Rechnungskauf Paypal = pay_pal_pui_payment_handler */
public static final String SW6_PAYMENT_METHOD_RechnungskaufPaypal = "pay_pal_pui_payment_handler";
@Override
public void setSW6_Payment_Method (final @Nullable java.lang.String SW6_Payment_Method)
{
set_Value (COLUMNNAME_SW6_Payment_Method, SW6_Payment_Method);
}
@Override
public java.lang.String getSW6_Payment_Method()
{
return get_ValueAsString(COLUMNNAME_SW6_Payment_Method);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_Shopware6Mapping.java | 1 |
请完成以下Java代码 | public class DoublePrimitiveLookup extends Lookup {
private double[] elements;
private final double pivot = 2;
@Setup
@Override
public void prepare() {
double common = 1;
elements = new double[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@TearDown
@Override
public void clean() {
elements = null;
} | @Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
while (pivot != elements[index]) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return DoublePrimitiveLookup.class.getSimpleName();
}
} | repos\tutorials-master\core-java-modules\core-java-lang-2\src\main\java\com\baeldung\primitive\DoublePrimitiveLookup.java | 1 |
请完成以下Java代码 | public boolean isCompleted() {
return Context.getCommandContext().getProcessEngineConfiguration()
.getManagementService()
.createJobQuery()
.jobDefinitionId(batchJobDefinitionId)
.count() == 0;
}
public String toString() {
return "BatchEntity{" +
"batchHandler=" + batchJobHandler +
", id='" + id + '\'' +
", type='" + type + '\'' +
", size=" + totalJobs +
", jobCreated=" + jobsCreated +
", batchJobsPerSeed=" + batchJobsPerSeed +
", invocationsPerBatchJob=" + invocationsPerBatchJob +
", seedJobDefinitionId='" + seedJobDefinitionId + '\'' +
", monitorJobDefinitionId='" + seedJobDefinitionId + '\'' +
", batchJobDefinitionId='" + batchJobDefinitionId + '\'' +
", configurationId='" + configuration.getByteArrayId() + '\'' +
'}';
} | @Override
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<>();
return referencedEntityIds;
}
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<>();
if (seedJobDefinitionId != null) {
referenceIdAndClass.put(seedJobDefinitionId, JobDefinitionEntity.class);
}
if (batchJobDefinitionId != null) {
referenceIdAndClass.put(batchJobDefinitionId, JobDefinitionEntity.class);
}
if (monitorJobDefinitionId != null) {
referenceIdAndClass.put(monitorJobDefinitionId, JobDefinitionEntity.class);
}
return referenceIdAndClass;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\BatchEntity.java | 1 |
请完成以下Java代码 | public RestartProcessInstanceBuilder startAfterActivity(String activityId) {
ensureNotNull(NotValidException.class, "activityId", activityId);
instructions.add(new ActivityAfterInstantiationCmd(null, activityId));
return this;
}
@Override
public RestartProcessInstanceBuilder startTransition(String transitionId) {
ensureNotNull(NotValidException.class, "activityId", transitionId);
instructions.add(new TransitionInstantiationCmd(null, transitionId));
return this;
}
public void execute() {
commandExecutor.execute(new RestartProcessInstancesCmd(commandExecutor, this));
}
public Batch executeAsync() {
return commandExecutor.execute(new RestartProcessInstancesBatchCmd(commandExecutor, this));
}
public List<AbstractProcessInstanceModificationCommand> getInstructions() {
return instructions;
}
public List<String> getProcessInstanceIds() {
return processInstanceIds;
}
@Override
public RestartProcessInstanceBuilder processInstanceIds(String... processInstanceIds) {
this.processInstanceIds.addAll(Arrays.asList(processInstanceIds));
return this;
}
@Override
public RestartProcessInstanceBuilder historicProcessInstanceQuery(HistoricProcessInstanceQuery query) {
this.query = query;
return this;
}
public HistoricProcessInstanceQuery getHistoricProcessInstanceQuery() {
return query;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setInstructions(List<AbstractProcessInstanceModificationCommand> instructions) {
this.instructions = instructions;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
@Override
public RestartProcessInstanceBuilder processInstanceIds(List<String> processInstanceIds) {
this.processInstanceIds.addAll(processInstanceIds);
return this;
} | @Override
public RestartProcessInstanceBuilder initialSetOfVariables() {
this.initialVariables = true;
return this;
}
public boolean isInitialVariables() {
return initialVariables;
}
@Override
public RestartProcessInstanceBuilder skipCustomListeners() {
this.skipCustomListeners = true;
return this;
}
@Override
public RestartProcessInstanceBuilder skipIoMappings() {
this.skipIoMappings = true;
return this;
}
public boolean isSkipCustomListeners() {
return skipCustomListeners;
}
public boolean isSkipIoMappings() {
return skipIoMappings;
}
@Override
public RestartProcessInstanceBuilder withoutBusinessKey() {
withoutBusinessKey = true;
return this;
}
public boolean isWithoutBusinessKey() {
return withoutBusinessKey;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\RestartProcessInstanceBuilderImpl.java | 1 |
请完成以下Java代码 | public abstract class DelegateInvocation {
protected Object invocationResult;
protected Object[] invocationParameters;
/**
* make the invocation proceed, performing the actual invocation of the user code.
*
* @throws Exception
* the exception thrown by the user code
*/
public void proceed() {
invoke();
}
protected abstract void invoke();
/**
* @return the result of the invocation (can be null if the invocation does not return a result) | */
public Object getInvocationResult() {
return invocationResult;
}
/**
* @return an array of invocation parameters (null if the invocation takes no parameters)
*/
public Object[] getInvocationParameters() {
return invocationParameters;
}
/**
* returns the target of the current invocation, ie. JavaDelegate, ValueExpression ...
*/
public abstract Object getTarget();
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\delegate\invocation\DelegateInvocation.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<UmsMenu> list(Long parentId, Integer pageSize, Integer pageNum) {
PageHelper.startPage(pageNum, pageSize);
UmsMenuExample example = new UmsMenuExample();
example.setOrderByClause("sort desc");
example.createCriteria().andParentIdEqualTo(parentId);
return menuMapper.selectByExample(example);
}
@Override
public List<UmsMenuNode> treeList() {
List<UmsMenu> menuList = menuMapper.selectByExample(new UmsMenuExample());
List<UmsMenuNode> result = menuList.stream()
.filter(menu -> menu.getParentId().equals(0L))
.map(menu -> covertMenuNode(menu, menuList))
.collect(Collectors.toList());
return result;
}
@Override
public int updateHidden(Long id, Integer hidden) { | UmsMenu umsMenu = new UmsMenu();
umsMenu.setId(id);
umsMenu.setHidden(hidden);
return menuMapper.updateByPrimaryKeySelective(umsMenu);
}
/**
* 将UmsMenu转化为UmsMenuNode并设置children属性
*/
private UmsMenuNode covertMenuNode(UmsMenu menu, List<UmsMenu> menuList) {
UmsMenuNode node = new UmsMenuNode();
BeanUtils.copyProperties(menu, node);
List<UmsMenuNode> children = menuList.stream()
.filter(subMenu -> subMenu.getParentId().equals(menu.getId()))
.map(subMenu -> covertMenuNode(subMenu, menuList)).collect(Collectors.toList());
node.setChildren(children);
return node;
}
} | repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\UmsMenuServiceImpl.java | 2 |
请完成以下Java代码 | public int runBinarySearchRecursively(int[] sortedArray, int key, int low, int high) {
int middle = low + ((high - low) / 2);
if (high < low) {
return -1;
}
if (key == sortedArray[middle]) {
return middle;
} else if (key < sortedArray[middle]) {
return runBinarySearchRecursively(sortedArray, key, low, middle - 1);
} else {
return runBinarySearchRecursively(sortedArray, key, middle + 1, high);
}
}
public int runBinarySearchUsingJavaArrays(int[] sortedArray, Integer key) {
int index = Arrays.binarySearch(sortedArray, key);
return index;
}
public int runBinarySearchUsingJavaCollections(List<Integer> sortedList, Integer key) {
int index = Collections.binarySearch(sortedList, key);
return index;
}
public List<Integer> runBinarySearchOnSortedArraysWithDuplicates(int[] sortedArray, Integer key) {
int startIndex = startIndexSearch(sortedArray, key);
int endIndex = endIndexSearch(sortedArray, key);
return IntStream.rangeClosed(startIndex, endIndex)
.boxed()
.collect(Collectors.toList());
}
private int endIndexSearch(int[] sortedArray, int target) {
int left = 0;
int right = sortedArray.length - 1; | int result = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (sortedArray[mid] == target) {
result = mid;
left = mid + 1;
} else if (sortedArray[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}
private int startIndexSearch(int[] sortedArray, int target) {
int left = 0;
int right = sortedArray.length - 1;
int result = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (sortedArray[mid] == target) {
result = mid;
right = mid - 1;
} else if (sortedArray[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}
} | repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\binarysearch\BinarySearch.java | 1 |
请完成以下Java代码 | public String toString()
{
StringBuffer sb = new StringBuffer ("X_GL_Category[")
.append(get_ID()).append("]");
return sb.toString();
}
/** CategoryType AD_Reference_ID=207 */
public static final int CATEGORYTYPE_AD_Reference_ID=207;
/** Manual = M */
public static final String CATEGORYTYPE_Manual = "M";
/** Import = I */
public static final String CATEGORYTYPE_Import = "I";
/** Document = D */
public static final String CATEGORYTYPE_Document = "D";
/** System generated = S */
public static final String CATEGORYTYPE_SystemGenerated = "S";
/** Set Category Type.
@param CategoryType
Source of the Journal with this category
*/
public void setCategoryType (String CategoryType)
{
set_Value (COLUMNNAME_CategoryType, CategoryType);
}
/** Get Category Type.
@return Source of the Journal with this category
*/
public String getCategoryType ()
{
return (String)get_Value(COLUMNNAME_CategoryType);
}
/** 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 GL Category.
@param GL_Category_ID
General Ledger Category
*/
public void setGL_Category_ID (int GL_Category_ID)
{
if (GL_Category_ID < 1)
set_ValueNoCheck (COLUMNNAME_GL_Category_ID, null);
else
set_ValueNoCheck (COLUMNNAME_GL_Category_ID, Integer.valueOf(GL_Category_ID));
}
/** Get GL Category.
@return General Ledger Category | */
public int getGL_Category_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GL_Category_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Default.
@param IsDefault
Default value
*/
public void setIsDefault (boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
}
/** Get Default.
@return Default value
*/
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
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_Category.java | 1 |
请完成以下Java代码 | public DocTypeInvoicingPool getById(@NonNull final DocTypeInvoicingPoolId docTypeInvoicingPoolId)
{
return docTypeInvoicingPoolById.getOrLoad(docTypeInvoicingPoolId, this::retrieveDocTypeInvoicingPoolById);
}
@NonNull
public DocTypeInvoicingPool create(@NonNull final DocTypeInvoicingPoolCreateRequest request)
{
final I_C_DocType_Invoicing_Pool docTypeInvoicingPoolRecord = newInstance(I_C_DocType_Invoicing_Pool.class);
docTypeInvoicingPoolRecord.setName(request.getName());
docTypeInvoicingPoolRecord.setPositive_Amt_C_DocType_ID(DocTypeId.toRepoId(request.getPositiveAmountDocTypeId()));
docTypeInvoicingPoolRecord.setNegative_Amt_C_DocType_ID(DocTypeId.toRepoId(request.getNegativeAmountDocTypeId()));
docTypeInvoicingPoolRecord.setIsSOTrx(request.getIsSoTrx().toBoolean());
docTypeInvoicingPoolRecord.setIsActive(request.isActive());
saveRecord(docTypeInvoicingPoolRecord);
return ofRecord(docTypeInvoicingPoolRecord);
}
@NonNull
private DocTypeInvoicingPool retrieveDocTypeInvoicingPoolById(@NonNull final DocTypeInvoicingPoolId docTypeInvoicingPoolId)
{
final I_C_DocType_Invoicing_Pool docTypeInvoicingPoolRecord = load(docTypeInvoicingPoolId, I_C_DocType_Invoicing_Pool.class);
if (docTypeInvoicingPoolRecord == null)
{
throw new AdempiereException("No C_DocType_Invoicing_Pool record found for ID!")
.appendParametersToMessage()
.setParameter("DocTypeInvoicingPoolId", docTypeInvoicingPoolId);
}
return ofRecord(docTypeInvoicingPoolRecord);
} | @NonNull
private static DocTypeInvoicingPool ofRecord(@NonNull final I_C_DocType_Invoicing_Pool docTypeInvoicingPoolRecord)
{
return DocTypeInvoicingPool.builder()
.id(DocTypeInvoicingPoolId.ofRepoId(docTypeInvoicingPoolRecord.getC_DocType_Invoicing_Pool_ID()))
.name(docTypeInvoicingPoolRecord.getName())
.positiveAmountDocTypeId(DocTypeId.ofRepoId(docTypeInvoicingPoolRecord.getPositive_Amt_C_DocType_ID()))
.negativeAmountDocTypeId(DocTypeId.ofRepoId(docTypeInvoicingPoolRecord.getNegative_Amt_C_DocType_ID()))
.isSoTrx(SOTrx.ofBoolean(docTypeInvoicingPoolRecord.isSOTrx()))
.isOnDistinctICTypes(docTypeInvoicingPoolRecord.isOnDistinctICTypes())
.isActive(docTypeInvoicingPoolRecord.isActive())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\invoicingpool\DocTypeInvoicingPoolRepository.java | 1 |
请完成以下Java代码 | public static CostDetailCreateResultsList of(@NonNull final CostDetailCreateResult result) {return ofList(ImmutableList.of(result));}
public static Collector<CostDetailCreateResult, ?, CostDetailCreateResultsList> collect() {return GuavaCollectors.collectUsingListAccumulator(CostDetailCreateResultsList::ofList);}
public Stream<CostDetailCreateResult> stream() {return list.stream();}
public CostDetailCreateResult getSingleResult() {return CollectionUtils.singleElement(list);}
public Optional<CostAmountAndQty> getAmtAndQtyToPost(@NonNull final CostAmountType type, @NonNull AcctSchema as)
{
return list.stream()
.filter(result -> isAccountable(result, as))
.map(result -> result.getAmtAndQty(type))
.reduce(CostAmountAndQty::add);
}
public CostAmount getMainAmountToPost(@NonNull final AcctSchema as)
{
return getAmtAndQtyToPost(CostAmountType.MAIN, as)
.map(CostAmountAndQty::getAmt)
.orElseThrow(() -> new NoSuchElementException("No value present"));
}
public CostAmountDetailed getTotalAmountToPost(@NonNull final AcctSchema as)
{ | return toAggregatedCostAmount().getTotalAmountToPost(as);
}
public AggregatedCostAmount toAggregatedCostAmount()
{
final CostSegment costSegment = CollectionUtils.extractSingleElement(list, CostDetailCreateResult::getCostSegment);
final Map<CostElement, CostAmountDetailed> amountsByCostElement = list.stream()
.collect(Collectors.toMap(
CostDetailCreateResult::getCostElement, // keyMapper
CostDetailCreateResult::getAmt, // valueMapper
CostAmountDetailed::add)); // mergeFunction
return AggregatedCostAmount.builder()
.costSegment(costSegment)
.amounts(amountsByCostElement)
.build();
}
private static boolean isAccountable(@NonNull CostDetailCreateResult result, @NonNull final AcctSchema as)
{
return result.getCostElement().isAccountable(as.getCosting());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostDetailCreateResultsList.java | 1 |
请完成以下Java代码 | public abstract class NeedsActiveExecutionCmd<T> implements Command<T>, Serializable {
private static final long serialVersionUID = 1L;
protected String executionId;
public NeedsActiveExecutionCmd(String executionId) {
this.executionId = executionId;
}
public T execute(CommandContext commandContext) {
if (executionId == null) {
throw new ActivitiIllegalArgumentException("executionId is null");
}
ExecutionEntity execution = commandContext.getExecutionEntityManager().findById(executionId);
if (execution == null) {
throw new ActivitiObjectNotFoundException("execution " + executionId + " doesn't exist", Execution.class);
}
if (execution.isSuspended()) { | throw new ActivitiException(getSuspendedExceptionMessage());
}
return execute(commandContext, execution);
}
/**
* Subclasses should implement this method. The provided {@link ExecutionEntity} is guaranteed to be active (ie. not suspended).
*/
protected abstract T execute(CommandContext commandContext, ExecutionEntity execution);
/**
* Subclasses can override this to provide a more detailed exception message that will be thrown when the execution is suspended.
*/
protected String getSuspendedExceptionMessage() {
return "Cannot execution operation because execution '" + executionId + "' is suspended";
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\NeedsActiveExecutionCmd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class TRAILR {
@XmlElement(name = "DOCUMENTID", required = true)
protected String documentid;
@XmlElement(name = "CONTROLQUAL")
protected String controlqual;
@XmlElement(name = "CONTROLVALUE")
protected String controlvalue;
@XmlElement(name = "MEASUREMENTUNIT")
protected String measurementunit;
@XmlElement(name = "TAMOU1")
protected TAMOU1 tamou1;
/**
* Gets the value of the documentid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDOCUMENTID() {
return documentid;
}
/**
* Sets the value of the documentid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDOCUMENTID(String value) {
this.documentid = value;
}
/**
* Gets the value of the controlqual property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCONTROLQUAL() {
return controlqual;
}
/**
* Sets the value of the controlqual property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCONTROLQUAL(String value) {
this.controlqual = value;
}
/**
* Gets the value of the controlvalue property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCONTROLVALUE() {
return controlvalue;
}
/**
* Sets the value of the controlvalue property.
*
* @param value
* allowed object is
* {@link String } | *
*/
public void setCONTROLVALUE(String value) {
this.controlvalue = value;
}
/**
* Gets the value of the measurementunit property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMEASUREMENTUNIT() {
return measurementunit;
}
/**
* Sets the value of the measurementunit property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMEASUREMENTUNIT(String value) {
this.measurementunit = value;
}
/**
* Gets the value of the tamou1 property.
*
* @return
* possible object is
* {@link TAMOU1 }
*
*/
public TAMOU1 getTAMOU1() {
return tamou1;
}
/**
* Sets the value of the tamou1 property.
*
* @param value
* allowed object is
* {@link TAMOU1 }
*
*/
public void setTAMOU1(TAMOU1 value) {
this.tamou1 = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_orders\de\metas\edi\esb\jaxb\stepcom\orders\TRAILR.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected void applyToResource(ClassPathResource resource, RuntimeHints hints) {
super.applyToResource(resource, hints);
CmmnXmlConverter cmmXmlConverter = new CmmnXmlConverter();
CmmnModel cmmnModel = cmmXmlConverter.convertToCmmnModel(() -> {
try {
return resource.getInputStream();
} catch (IOException e) {
throw new UncheckedIOException("Failed to read resource " + resource, e);
}
}, false, false);
Collection<ServiceTask> serviceTasks = cmmnModel.getPrimaryCase().findPlanItemDefinitionsOfType(ServiceTask.class);
for (ServiceTask serviceTask : serviceTasks) {
if (ImplementationType.IMPLEMENTATION_TYPE_DELEGATEEXPRESSION.equals(serviceTask.getImplementationType())) {
String expression = serviceTask.getImplementation();
String expressionWithoutDelimiters = expression.substring(2);
expressionWithoutDelimiters = expressionWithoutDelimiters.substring(0, expressionWithoutDelimiters.length() - 1);
String beanName = expressionWithoutDelimiters;
try {
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
String beanClassName = beanDefinition.getBeanClassName();
if (StringUtils.isNotEmpty(beanClassName)) {
hints.reflection().registerType(TypeReference.of(beanClassName), MemberCategory.values()); | logger.debug("Registering hint for bean name [{}] for service task {} in {}", beanName, serviceTask.getId(), resource);
} else {
logger.debug("No bean class name for bean name [{}] for service task {} in {}", beanName, serviceTask.getId(), resource);
}
} catch (Throwable throwable) {
logger.error("Couldn't find bean named [{}] for service task {} in {}", beanName, serviceTask.getId(), resource);
}
}
}
}
}
} | repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\aot\cmmn\FlowableCmmnAutoDeployBeanFactoryInitializationAotProcessor.java | 2 |
请完成以下Java代码 | public boolean containsAllIgnoreCase(String... matchers) {
for (String matcher : matchers) {
if (contains(matcher) == false) {
return false;
}
}
return true;
}
public NonCaseString trim() {
return NonCaseString.of(this.value.trim());
}
public NonCaseString replace(char oldChar, char newChar) {
return NonCaseString.of(this.value.replace(oldChar, newChar));
}
public NonCaseString replaceAll(String regex, String replacement) {
return NonCaseString.of(this.value.replaceAll(regex, replacement));
}
public NonCaseString substring(int beginIndex) {
return NonCaseString.of(this.value.substring(beginIndex));
}
public NonCaseString substring(int beginIndex, int endIndex) {
return NonCaseString.of(this.value.substring(beginIndex, endIndex));
}
public boolean isNotEmpty() {
return !this.value.isEmpty();
}
@Override
public int length() {
return this.value.length();
}
@Override
public char charAt(int index) {
return this.value.charAt(index);
}
@Override
public CharSequence subSequence(int start, int end) { | return this.value.subSequence(start, end);
}
public String[] split(String regex) {
return this.value.split(regex);
}
/**
* @return 原始字符串
*/
public String get() {
return this.value;
}
@Override
public String toString() {
return this.value;
}
} | repos\SpringBootCodeGenerator-master\src\main\java\com\softdev\system\generator\entity\NonCaseString.java | 1 |
请完成以下Java代码 | public Set<CtxName> getParameters()
{
return PARAMETERS;
}
@Override
public String evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException
{
Integer adClientId = ctx.get_ValueAsInt(PARAMETER_AD_Client_ID, null);
if (adClientId == null || adClientId < 0)
{
adClientId = Env.getAD_Client_ID(Env.getCtx());
}
Integer adOrgId = ctx.get_ValueAsInt(PARAMETER_AD_Org_ID, null);
if (adOrgId == null || adOrgId < 0)
{
adOrgId = Env.getAD_Org_ID(Env.getCtx()); | }
final IDocumentNoBuilderFactory documentNoFactory = Services.get(IDocumentNoBuilderFactory.class);
final String value = documentNoFactory.forTableName(tableName, adClientId, adOrgId)
.setFailOnError(onVariableNotFound == OnVariableNotFound.Fail)
.setUsePreliminaryDocumentNo(true)
.build();
if (value == null && onVariableNotFound == OnVariableNotFound.Fail)
{
throw new AdempiereException("No auto value sequence found for " + tableName + ", AD_Client_ID=" + adClientId + ", AD_Org_ID=" + adOrgId);
}
return value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\AutoSequenceDefaultValueExpression.java | 1 |
请完成以下Java代码 | public static class BankStatementLineAmountsCallout implements AmountsCallout
{
@Override
public void onStmtAmtChanged(final I_C_BankStatementLine bsl)
{
updateTrxAmt(bsl);
}
@Override
public void onTrxAmtChanged(final I_C_BankStatementLine bsl)
{
bsl.setBankFeeAmt(BankStatementLineAmounts.of(bsl)
.addDifferenceToBankFeeAmt()
.getBankFeeAmt());
}
@Override
public void onBankFeeAmtChanged(final I_C_BankStatementLine bsl)
{
updateTrxAmt(bsl);
}
@Override
public void onChargeAmtChanged(final I_C_BankStatementLine bsl)
{
updateTrxAmt(bsl);
}
@Override
public void onInterestAmtChanged(final I_C_BankStatementLine bsl)
{
updateTrxAmt(bsl);
}
}
public static class CashJournalLineAmountsCallout implements AmountsCallout
{
@Override
public void onStmtAmtChanged(final I_C_BankStatementLine bsl)
{
updateTrxAmt(bsl);
}
@Override
public void onTrxAmtChanged(final I_C_BankStatementLine bsl)
{
// i.e. set the TrxAmt back.
// user shall not be allowed to change it
// instead, StmtAmt can be changed | updateTrxAmt(bsl);
}
@Override
public void onBankFeeAmtChanged(final I_C_BankStatementLine bsl)
{
bsl.setBankFeeAmt(BigDecimal.ZERO);
updateTrxAmt(bsl);
}
@Override
public void onChargeAmtChanged(final I_C_BankStatementLine bsl)
{
bsl.setChargeAmt(BigDecimal.ZERO);
updateTrxAmt(bsl);
}
@Override
public void onInterestAmtChanged(final I_C_BankStatementLine bsl)
{
bsl.setInterestAmt(BigDecimal.ZERO);
updateTrxAmt(bsl);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\callout\C_BankStatementLine.java | 1 |
请完成以下Java代码 | private static boolean hasPemKeyStoreProperties(Ssl ssl) {
return Ssl.isEnabled(ssl) && ssl.getCertificate() != null && ssl.getCertificatePrivateKey() != null;
}
private static boolean hasPemTrustStoreProperties(Ssl ssl) {
return Ssl.isEnabled(ssl) && ssl.getTrustCertificate() != null;
}
private static boolean hasJksKeyStoreProperties(Ssl ssl) {
return Ssl.isEnabled(ssl) && (ssl.getKeyStore() != null
|| (ssl.getKeyStoreType() != null && ssl.getKeyStoreType().equals("PKCS11")));
}
private static boolean hasJksTrustStoreProperties(Ssl ssl) {
return Ssl.isEnabled(ssl) && (ssl.getTrustStore() != null
|| (ssl.getTrustStoreType() != null && ssl.getTrustStoreType().equals("PKCS11")));
}
@Override
public String toString() {
ToStringCreator creator = new ToStringCreator(this);
creator.append("key", this.key);
creator.append("protocol", this.protocol);
creator.append("stores", this.stores);
creator.append("options", this.options);
return creator.toString();
}
private static final class WebServerSslStoreBundle implements SslStoreBundle {
private final @Nullable KeyStore keyStore;
private final @Nullable KeyStore trustStore;
private final @Nullable String keyStorePassword; | private WebServerSslStoreBundle(@Nullable KeyStore keyStore, @Nullable KeyStore trustStore,
@Nullable String keyStorePassword) {
Assert.state(keyStore != null || trustStore != null,
"SSL is enabled but no trust material is configured for the default host");
this.keyStore = keyStore;
this.trustStore = trustStore;
this.keyStorePassword = keyStorePassword;
}
@Override
public @Nullable KeyStore getKeyStore() {
return this.keyStore;
}
@Override
public @Nullable KeyStore getTrustStore() {
return this.trustStore;
}
@Override
public @Nullable String getKeyStorePassword() {
return this.keyStorePassword;
}
@Override
public String toString() {
ToStringCreator creator = new ToStringCreator(this);
creator.append("keyStore.type", (this.keyStore != null) ? this.keyStore.getType() : "none");
creator.append("keyStorePassword", (this.keyStorePassword != null) ? "******" : null);
creator.append("trustStore.type", (this.trustStore != null) ? this.trustStore.getType() : "none");
return creator.toString();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\WebServerSslBundle.java | 1 |
请完成以下Java代码 | public class DefaultCommunicator implements Communicator {
private CommunicationMode defaultCommsMode;
@Inject
@Named("SMSComms")
CommunicationMode smsCommsMode;
@Inject
@Named("EmailComms")
CommunicationMode emailCommsMode;
@Inject
@Named("IMComms")
CommunicationMode imCommsMode;
protected DefaultCommunicator(CommunicationMode defaultComms) {
this.defaultCommsMode = defaultComms;
}
public DefaultCommunicator() {
}
public boolean sendMessage(String message) {
boolean sent = false;
if (defaultCommsMode != null) { | sent = sendMessageByDefault(message);
} else {
sent = smsCommsMode.sendMessage(message);
}
return sent;
}
private boolean sendMessageByDefault(String message) {
boolean sent = false;
if (message != null && !message.trim().equals("")) {
return defaultCommsMode.sendMessage(message);
}
return sent;
}
} | repos\tutorials-master\di-modules\guice\src\main\java\com\baeldung\guice\DefaultCommunicator.java | 1 |
请完成以下Java代码 | public void setTransfertTime (final @Nullable BigDecimal TransfertTime)
{
set_Value (COLUMNNAME_TransfertTime, TransfertTime);
}
@Override
public BigDecimal getTransfertTime()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TransfertTime);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom() | {
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_DD_NetworkDistributionLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public <T extends AbstractSaml2AuthenticationRequest> T resolve(HttpServletRequest request) {
return this.delegate.resolve(request);
}
/**
* Set a {@link Consumer} for modifying the OpenSAML {@link AuthnRequest}
* @param contextConsumer a consumer that accepts an {@link AuthnRequestContext}
*/
public void setAuthnRequestCustomizer(Consumer<AuthnRequestContext> contextConsumer) {
Assert.notNull(contextConsumer, "contextConsumer cannot be null");
this.delegate.setParametersConsumer(
(parameters) -> contextConsumer.accept(new AuthnRequestContext(parameters.getRequest(),
parameters.getRelyingPartyRegistration(), parameters.getAuthnRequest())));
}
/**
* Set the {@link RequestMatcher} to use for setting the
* {@link BaseOpenSamlAuthenticationRequestResolver#setRequestMatcher(RequestMatcher)}
* (RequestMatcher)}
* @param requestMatcher the {@link RequestMatcher} to identify authentication
* requests.
* @since 5.8
*/
public void setRequestMatcher(RequestMatcher requestMatcher) {
Assert.notNull(requestMatcher, "requestMatcher cannot be null");
this.delegate.setRequestMatcher(requestMatcher);
}
/**
* Use this {@link Clock} for generating the issued {@link Instant}
* @param clock the {@link Clock} to use
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock must not be null");
this.delegate.setClock(clock);
}
/**
* Use this {@link Converter} to compute the RelayState
* @param relayStateResolver the {@link Converter} to use
* @since 5.8
*/
public void setRelayStateResolver(Converter<HttpServletRequest, String> relayStateResolver) {
Assert.notNull(relayStateResolver, "relayStateResolver cannot be null");
this.delegate.setRelayStateResolver(relayStateResolver);
}
public static final class AuthnRequestContext { | private final HttpServletRequest request;
private final RelyingPartyRegistration registration;
private final AuthnRequest authnRequest;
public AuthnRequestContext(HttpServletRequest request, RelyingPartyRegistration registration,
AuthnRequest authnRequest) {
this.request = request;
this.registration = registration;
this.authnRequest = authnRequest;
}
public HttpServletRequest getRequest() {
return this.request;
}
public RelyingPartyRegistration getRelyingPartyRegistration() {
return this.registration;
}
public AuthnRequest getAuthnRequest() {
return this.authnRequest;
}
}
} | repos\spring-security-main\saml2\saml2-service-provider\src\opensaml5Main\java\org\springframework\security\saml2\provider\service\web\authentication\OpenSaml5AuthenticationRequestResolver.java | 2 |
请完成以下Java代码 | protected String getEndpointId(ChannelModel channelModel, String tenantId) {
String channelDefinitionKey = channelModel.getKey();
if (!StringUtils.hasText(tenantId)) {
return CHANNEL_ID_PREFIX + channelDefinitionKey;
}
return CHANNEL_ID_PREFIX + tenantId + "#" + channelDefinitionKey;
}
protected String resolve(String value) {
if (embeddedValueResolver != null) {
return embeddedValueResolver.resolveStringValue(value);
} else {
return value;
}
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
if (beanFactory instanceof ConfigurableBeanFactory) {
this.embeddedValueResolver = new EmbeddedValueResolver((ConfigurableBeanFactory) beanFactory);
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (event.getApplicationContext() == this.applicationContext) {
this.contextRefreshed = true;
}
}
public JmsOperations getJmsOperations() {
return jmsOperations;
}
public void setJmsOperations(JmsOperations jmsOperations) {
this.jmsOperations = jmsOperations; | }
public JmsListenerEndpointRegistry getEndpointRegistry() {
return endpointRegistry;
}
public void setEndpointRegistry(JmsListenerEndpointRegistry endpointRegistry) {
this.endpointRegistry = endpointRegistry;
}
public String getContainerFactoryBeanName() {
return containerFactoryBeanName;
}
public void setContainerFactoryBeanName(String containerFactoryBeanName) {
this.containerFactoryBeanName = containerFactoryBeanName;
}
public JmsListenerContainerFactory<?> getContainerFactory() {
return containerFactory;
}
public void setContainerFactory(JmsListenerContainerFactory<?> containerFactory) {
this.containerFactory = containerFactory;
}
} | repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\jms\JmsChannelModelProcessor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void pushMsg(String msgType, String jsonData) {
SocketIOClient targetClient = this.server.getClient(UUID.fromString(sessionId));
if (targetClient == null) {
logger.error("sessionId=" + sessionId + "在server中获取不到client");
} else {
targetClient.sendEvent(msgType, jsonData);
}
// queue.offer(jsonData);
}
// public String popJson() {
// try {
// return queue.poll(100L, TimeUnit.MILLISECONDS);
// } catch (InterruptedException e) {
// e.printStackTrace();
// return null;
// }
// }
/**
* 解析Base64位信息并输出到某个目录下面.
*
* @param base64Info base64串
* @return 文件地址
*/
public String saveBase64Pic(String base64Info) {
if (StringUtils.isEmpty(base64Info)) {
return "";
}
// 数据中:data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABI4AAAEsCAYAAAClh/jbAAA ... 在"base64,"之后的才是图片信息
String[] arr = base64Info.split("base64,"); | // 将图片输出到系统某目录.
OutputStream out = null;
String now = FastDateFormat.getInstance("yyyyMMddHHmmss").format(new Date());
String destFile = p.getImageDir() + now + ".png";
try {
// 使用了Apache commons codec的包来解析Base64
byte[] buffer = Base64.decodeBase64(arr[1]);
out = new FileOutputStream(destFile);
out.write(buffer);
} catch (IOException e) {
logger.error("解析Base64图片信息并保存到某目录下出错!", e);
return "";
} finally {
IOUtils.closeQuietly(out);
}
return destFile;
}
} | repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\echarts\service\ApiService.java | 2 |
请完成以下Java代码 | public class ReplacingTokens {
public static final Pattern TITLE_CASE_PATTERN = Pattern.compile("(?<=^|[^A-Za-z])([A-Z][a-z]*)(?=[^A-Za-z]|$)");
/**
* Iterate over the title case tokens in the input and replace them with lowercase
* @param original the original string
* @return a string with words replaced with their lowercase equivalents
*/
public static String replaceTitleCaseWithLowerCase(String original) {
int lastIndex = 0;
StringBuilder output = new StringBuilder();
Matcher matcher = TITLE_CASE_PATTERN.matcher(original);
while (matcher.find()) {
output.append(original, lastIndex, matcher.start())
.append(convert(matcher.group(1)));
lastIndex = matcher.end();
}
if (lastIndex < original.length()) {
output.append(original, lastIndex, original.length());
}
return output.toString();
}
/**
* Convert a token found into its desired lowercase
* @param token the token to convert
* @return the converted token
*/ | private static String convert(String token) {
return token.toLowerCase();
}
/**
* Replace all the tokens in an input using the algorithm provided for each
* @param original original string
* @param tokenPattern the pattern to match with
* @param converter the conversion to apply
* @return the substituted string
*/
public static String replaceTokens(String original, Pattern tokenPattern,
Function<Matcher, String> converter) {
int lastIndex = 0;
StringBuilder output = new StringBuilder();
Matcher matcher = tokenPattern.matcher(original);
while (matcher.find()) {
output.append(original, lastIndex, matcher.start())
.append(converter.apply(matcher));
lastIndex = matcher.end();
}
if (lastIndex < original.length()) {
output.append(original, lastIndex, original.length());
}
return output.toString();
}
} | repos\tutorials-master\core-java-modules\core-java-regex-2\src\main\java\com\baeldung\replacetokens\ReplacingTokens.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_AD_Column getLink_Column()
{
return get_ValueAsPO(COLUMNNAME_Link_Column_ID, org.compiere.model.I_AD_Column.class);
}
@Override
public void setLink_Column(org.compiere.model.I_AD_Column Link_Column)
{
set_ValueFromPO(COLUMNNAME_Link_Column_ID, org.compiere.model.I_AD_Column.class, Link_Column);
}
/** Set Link Column.
@param Link_Column_ID Link Column */
@Override
public void setLink_Column_ID (int Link_Column_ID)
{
if (Link_Column_ID < 1)
set_Value (COLUMNNAME_Link_Column_ID, null);
else
set_Value (COLUMNNAME_Link_Column_ID, Integer.valueOf(Link_Column_ID));
}
/** Get Link Column.
@return Link Column */
@Override
public int getLink_Column_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Link_Column_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Column getSource_Column()
{
return get_ValueAsPO(COLUMNNAME_Source_Column_ID, org.compiere.model.I_AD_Column.class);
}
@Override
public void setSource_Column(org.compiere.model.I_AD_Column Source_Column)
{
set_ValueFromPO(COLUMNNAME_Source_Column_ID, org.compiere.model.I_AD_Column.class, Source_Column);
}
/** Set Source Column.
@param Source_Column_ID Source Column */
@Override
public void setSource_Column_ID (int Source_Column_ID)
{
if (Source_Column_ID < 1)
set_Value (COLUMNNAME_Source_Column_ID, null);
else
set_Value (COLUMNNAME_Source_Column_ID, Integer.valueOf(Source_Column_ID)); | }
/** Get Source Column.
@return Source Column */
@Override
public int getSource_Column_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Source_Column_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Source Table.
@param Source_Table_ID Source Table */
@Override
public void setSource_Table_ID (int Source_Table_ID)
{
if (Source_Table_ID < 1)
set_Value (COLUMNNAME_Source_Table_ID, null);
else
set_Value (COLUMNNAME_Source_Table_ID, Integer.valueOf(Source_Table_ID));
}
/** Get Source Table.
@return Source Table */
@Override
public int getSource_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Source_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set SQL to get Target Record IDs by Source Record IDs.
@param SQL_GetTargetRecordIdBySourceRecordId SQL to get Target Record IDs by Source Record IDs */
@Override
public void setSQL_GetTargetRecordIdBySourceRecordId (java.lang.String SQL_GetTargetRecordIdBySourceRecordId)
{
set_Value (COLUMNNAME_SQL_GetTargetRecordIdBySourceRecordId, SQL_GetTargetRecordIdBySourceRecordId);
}
/** Get SQL to get Target Record IDs by Source Record IDs.
@return SQL to get Target Record IDs by Source Record IDs */
@Override
public java.lang.String getSQL_GetTargetRecordIdBySourceRecordId ()
{
return (java.lang.String)get_Value(COLUMNNAME_SQL_GetTargetRecordIdBySourceRecordId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_SQLColumn_SourceTableColumn.java | 1 |
请完成以下Spring Boot application配置 | spring:
security:
oauth2:
client:
provider:
baeldung:
issuer-uri: http://localhost:8085
registration:
pkce:
provider: baeldung
| client-id: pkce-client
client-secret: obscura
scope: openid,email | repos\tutorials-master\spring-security-modules\spring-security-pkce\pkce-client\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | public boolean equals(Object anObject)
{
if (this == anObject)
{
return true;
}
if (anObject instanceof SString)
{
SString anotherString = (SString) anObject;
int n = value.length;
if (n == anotherString.value.length)
{
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0)
{
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
@Override
public int length()
{
return e - b;
}
@Override
public char charAt(int index)
{
return value[b + index];
}
@Override
public CharSequence subSequence(int start, int end)
{
return new SString(value, b + start, b + end);
}
@Override
public String toString()
{
return new String(value, b, e - b);
}
@Override
public int compareTo(SString anotherString)
{
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2);
char v1[] = value; | char v2[] = anotherString.value;
int k = 0;
while (k < lim)
{
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2)
{
return c1 - c2;
}
k++;
}
return len1 - len2;
}
public char[] toCharArray()
{
return Arrays.copyOfRange(value, b, e);
}
public static SString valueOf(char word)
{
SString s = new SString(new char[]{word}, 0, 1);
return s;
}
public SString add(SString other)
{
char[] value = new char[length() + other.length()];
System.arraycopy(this.value, b, value, 0, length());
System.arraycopy(other.value, other.b, value, length(), other.length());
b = 0;
e = length() + other.length();
this.value = value;
return this;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\sequence\SString.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SnmpTransportBalancingService {
private final PartitionService partitionService;
private final ApplicationEventPublisher eventPublisher;
private final SnmpTransportService snmpTransportService;
private int snmpTransportsCount = 1;
private Integer currentTransportPartitionIndex = 0;
public void onServiceListChanged(ServiceListChangedEvent event) {
log.trace("Got service list changed event: {}", event);
recalculatePartitions(event.getOtherServices(), event.getCurrentService());
}
public boolean isManagedByCurrentTransport(UUID entityId) {
boolean isManaged = resolvePartitionIndexForEntity(entityId) == currentTransportPartitionIndex;
if (!isManaged) {
log.trace("Entity {} is not managed by current SNMP transport node", entityId);
}
return isManaged;
}
private int resolvePartitionIndexForEntity(UUID entityId) {
return partitionService.resolvePartitionIndex(entityId, snmpTransportsCount);
}
private void recalculatePartitions(List<ServiceInfo> otherServices, ServiceInfo currentService) {
log.info("Recalculating partitions for SNMP transports");
List<ServiceInfo> snmpTransports = Stream.concat(otherServices.stream(), Stream.of(currentService))
.filter(service -> service.getTransportsList().contains(snmpTransportService.getName()))
.sorted(Comparator.comparing(ServiceInfo::getServiceId))
.collect(Collectors.toList());
log.trace("Found SNMP transports: {}", snmpTransports);
int previousCurrentTransportPartitionIndex = currentTransportPartitionIndex;
int previousSnmpTransportsCount = snmpTransportsCount; | if (!snmpTransports.isEmpty()) {
for (int i = 0; i < snmpTransports.size(); i++) {
if (snmpTransports.get(i).equals(currentService)) {
currentTransportPartitionIndex = i;
break;
}
}
snmpTransportsCount = snmpTransports.size();
}
if (snmpTransportsCount != previousSnmpTransportsCount || currentTransportPartitionIndex != previousCurrentTransportPartitionIndex) {
log.info("SNMP transports partitions have changed: transports count = {}, current transport partition index = {}", snmpTransportsCount, currentTransportPartitionIndex);
eventPublisher.publishEvent(new SnmpTransportListChangedEvent());
} else {
log.info("SNMP transports partitions have not changed");
}
}
} | repos\thingsboard-master\common\transport\snmp\src\main\java\org\thingsboard\server\transport\snmp\service\SnmpTransportBalancingService.java | 2 |
请完成以下Java代码 | private HttpServletRequest getActualHttpServletRequest()
{
return Services.get(IHttpSessionProvider.class).getCurrentRequest();
}
private HttpServletResponse getActualHttpServletResponse()
{
return Services.get(IHttpSessionProvider.class).getCurrentResponse();
}
@Override
public void setHostKey(final String hostkey)
{
final HttpServletResponse httpResponse = getActualHttpServletResponse();
// Always set back the cookie, because we want to renew the expire date
if (!CookieUtil.setCookie(httpResponse, COOKIE_Name, hostkey, COOKIE_Description, COOKIE_MaxAge))
{ | logger.warn("Cannot set cookie " + COOKIE_Name + ": " + hostkey);
}
}
@Override
public String getHostKey()
{
final HttpServletRequest httpRequest = getActualHttpServletRequest();
final String hostkey = CookieUtil.getCookie(httpRequest, COOKIE_Name);
if (Check.isEmpty(hostkey, true))
{
logger.info("No host key found");
}
return hostkey;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\hostkey\spi\impl\HttpCookieHostKeyStorage.java | 1 |
请完成以下Java代码 | public void setIsAutoSendDocument (final boolean IsAutoSendDocument)
{
set_Value (COLUMNNAME_IsAutoSendDocument, IsAutoSendDocument);
}
@Override
public boolean isAutoSendDocument()
{
return get_ValueAsBoolean(COLUMNNAME_IsAutoSendDocument);
}
@Override
public void setIsDirectEnqueue (final boolean IsDirectEnqueue)
{
set_Value (COLUMNNAME_IsDirectEnqueue, IsDirectEnqueue);
}
@Override
public boolean isDirectEnqueue() | {
return get_ValueAsBoolean(COLUMNNAME_IsDirectEnqueue);
}
@Override
public void setIsDirectProcessQueueItem (final boolean IsDirectProcessQueueItem)
{
set_Value (COLUMNNAME_IsDirectProcessQueueItem, IsDirectProcessQueueItem);
}
@Override
public boolean isDirectProcessQueueItem()
{
return get_ValueAsBoolean(COLUMNNAME_IsDirectProcessQueueItem);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java-gen\de\metas\document\archive\model\X_C_Doc_Outbound_Config.java | 1 |
请完成以下Java代码 | public void setAD_Attachment_MultiRef_ID (final int AD_Attachment_MultiRef_ID)
{
if (AD_Attachment_MultiRef_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Attachment_MultiRef_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Attachment_MultiRef_ID, AD_Attachment_MultiRef_ID);
}
@Override
public int getAD_Attachment_MultiRef_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Attachment_MultiRef_ID);
}
@Override
public org.compiere.model.I_AD_AttachmentEntry getAD_AttachmentEntry()
{
return get_ValueAsPO(COLUMNNAME_AD_AttachmentEntry_ID, org.compiere.model.I_AD_AttachmentEntry.class);
}
@Override
public void setAD_AttachmentEntry(final org.compiere.model.I_AD_AttachmentEntry AD_AttachmentEntry)
{
set_ValueFromPO(COLUMNNAME_AD_AttachmentEntry_ID, org.compiere.model.I_AD_AttachmentEntry.class, AD_AttachmentEntry);
}
@Override
public void setAD_AttachmentEntry_ID (final int AD_AttachmentEntry_ID)
{
if (AD_AttachmentEntry_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_AttachmentEntry_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_AttachmentEntry_ID, AD_AttachmentEntry_ID);
}
@Override
public int getAD_AttachmentEntry_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_AttachmentEntry_ID);
}
@Override
public void setAD_Table_ID (final int AD_Table_ID)
{
if (AD_Table_ID < 1) | set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID);
}
@Override
public int getAD_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Table_ID);
}
@Override
public void setFileName_Override (final @Nullable java.lang.String FileName_Override)
{
set_Value (COLUMNNAME_FileName_Override, FileName_Override);
}
@Override
public java.lang.String getFileName_Override()
{
return get_ValueAsString(COLUMNNAME_FileName_Override);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attachment_MultiRef.java | 1 |
请完成以下Java代码 | public void run(String... args) throws Exception {
List<String> params = Arrays.stream(args)
.collect(Collectors.toList());
if (verifyArguments(params)) {
double singlePrice = Double.valueOf(params.get(0));
int quantity = Integer.valueOf(params.get(1));
priceCalculationService.productTotalPrice(singlePrice, quantity);
} else {
logger.warn("Invalid arguments " + params.toString());
}
}
private boolean verifyArguments(List<String> args) {
boolean successful = true; | if (args.size() != 2) {
successful = false;
return successful;
}
try {
double singlePrice = Double.valueOf(args.get(0));
int quantity = Integer.valueOf(args.get(1));
} catch (NumberFormatException e) {
successful = false;
}
return successful;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-environment\src\main\java\com\baeldung\environmentpostprocessor\PriceCalculationApplication.java | 1 |
请完成以下Java代码 | public void add(final IncidentHandler incidentHandler) {
EnsureUtil.ensureNotNull("Incident handler", incidentHandler);
String incidentHandlerType = getIncidentHandlerType();
if (!incidentHandlerType.equals(incidentHandler.getIncidentHandlerType())) {
throw new ProcessEngineException(
"Incorrect incident type handler in composite handler with type: " + incidentHandlerType);
}
this.incidentHandlers.add(incidentHandler);
}
@Override
public String getIncidentHandlerType() {
return mainIncidentHandler.getIncidentHandlerType();
}
@Override
public Incident handleIncident(IncidentContext context, String message) {
Incident incident = mainIncidentHandler.handleIncident(context, message);
for (IncidentHandler incidentHandler : this.incidentHandlers) {
incidentHandler.handleIncident(context, message);
}
return incident;
} | @Override
public void resolveIncident(IncidentContext context) {
mainIncidentHandler.resolveIncident(context);
for (IncidentHandler incidentHandler : this.incidentHandlers) {
incidentHandler.resolveIncident(context);
}
}
@Override
public void deleteIncident(IncidentContext context) {
mainIncidentHandler.deleteIncident(context);
for (IncidentHandler incidentHandler : this.incidentHandlers) {
incidentHandler.deleteIncident(context);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\incident\CompositeIncidentHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public HikariDataSource firstDataSource(@Qualifier("configMySql") DataSourceProperties properties) {
return properties.initializeDataSourceBuilder().type(HikariDataSource.class)
.build();
}
@Primary
@FlywayDataSource
@Bean(initMethod = "migrate")
public Flyway primaryFlyway(@Qualifier("dataSourceMySql") HikariDataSource primaryDataSource,
@Qualifier("configFlywayMySql") FlywayDs1Properties properties) {
return Flyway.configure()
.dataSource(primaryDataSource)
.locations(properties.getLocation())
.load();
}
// configure PostgreSQL data source and Flyway migration for "booksdb"
@Bean(name = "configPostgreSql")
@ConfigurationProperties("app.datasource.ds2")
public DataSourceProperties secondDataSourceProperties() {
return new DataSourceProperties();
} | @Bean(name = "configFlywayPostgreSql")
public FlywayDs2Properties secondFlywayProperties() {
return new FlywayDs2Properties();
}
@Bean(name = "dataSourcePostgreSql")
@ConfigurationProperties("app.datasource.ds2")
public HikariDataSource secondDataSource(@Qualifier("configPostgreSql") DataSourceProperties properties) {
return properties.initializeDataSourceBuilder().type(HikariDataSource.class)
.build();
}
@FlywayDataSource
@Bean(initMethod = "migrate")
public Flyway secondFlyway(@Qualifier("dataSourcePostgreSql") HikariDataSource secondDataSource,
@Qualifier("configFlywayPostgreSql") FlywayDs2Properties properties) {
return Flyway.configure()
.dataSource(secondDataSource)
.schemas(properties.getSchema())
.locations(properties.getLocation())
.load();
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootFlywayTwoVendors\src\main\java\com\bookstore\config\ConfigureDataSources.java | 2 |
请完成以下Java代码 | public Iterator<IScript> get()
{
final List<IScript> lexiagraphicallySortedScripts = new ArrayList<>();
while (getInternalScanner().hasNext())
{
final IScript next = getInternalScanner().next();
lexiagraphicallySortedScripts.add(next);
}
// note that we used to have a TreeSet here, but some times some scripts were not applied.
// I replaced the TreeSet with this list and pay the cost of the extra ordering step to rule out the possibility that some items are not added to the treeSet because the comparator considers them to be equal
Collections.sort(lexiagraphicallySortedScripts, lexiographicallyOrderedComparator);
// dumpTofile(lexiagraphicallySortedScripts);
return lexiagraphicallySortedScripts.iterator();
}
});
/**
* Examples:
* <ul>
* <li>"1234_sys_test.sql" => "1234"
* <li>"1234-sys-test.sql" => "1234-sys-test.sql"
* <li>"" => ""
* <li>"_sys_test.sql" => "_sys_test.sql"
* </ul>
*
* @param fileName
* @return
*/
@VisibleForTesting
/* package */static String extractSequenceNumber(final String fileName)
{
final int indexOf = fileName.indexOf("_");
if (indexOf <= 0)
{
// no '_' or empty prefix => return full name
return fileName;
}
return fileName.substring(0, indexOf);
}
public GloballyOrderedScannerDecorator(final IScriptScanner scanner)
{
super(scanner);
}
@Override
public boolean hasNext()
{
return lexiographicallyOrderedScriptsSupplier.get().hasNext();
}
@Override
public IScript next()
{
return lexiographicallyOrderedScriptsSupplier.get().next();
}
@Override
public void remove()
{
lexiographicallyOrderedScriptsSupplier.get().remove(); | }
@SuppressWarnings("unused")
private void dumpTofile(SortedSet<IScript> lexiagraphicallySortedScripts)
{
FileWriter writer;
try
{
writer = new FileWriter(GloballyOrderedScannerDecorator.class.getName() + "_sorted_scripts.txt");
for (final IScript script : lexiagraphicallySortedScripts)
{
writer.write(script.toString() + "\n");
}
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.addValue(getInternalScanner())
.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\GloballyOrderedScannerDecorator.java | 1 |
请完成以下Java代码 | public void setIsDefault (boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
}
/** Get Default.
@return Default value
*/
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Demand.
@param M_Demand_ID
Material Demand
*/
public void setM_Demand_ID (int M_Demand_ID)
{
if (M_Demand_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Demand_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Demand_ID, Integer.valueOf(M_Demand_ID));
}
/** Get Demand.
@return Material Demand
*/
public int getM_Demand_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Demand_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
} | /** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Demand.java | 1 |
请完成以下Java代码 | public static class KeyValuePair {
private String key;
@JsonDeserialize(using = ValueDeserializer.class)
private Object value;
public KeyValuePair() {
}
public KeyValuePair(String key, Object value) {
this.key = key;
this.value = value;
}
public String getKey() { | return key;
}
public void setKey(String key) {
this.key = key;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
} | repos\tutorials-master\jackson-modules\jackson-conversions-3\src\main\java\com\baeldung\jackson\specifictype\dtos\PersonDTOWithCustomDeserializer.java | 1 |
请完成以下Java代码 | public class SwingPrintingClientValidator extends AbstractModuleInterceptor
{
private static final transient Logger logger = LogManager.getLogger(SwingPrintingClientValidator.class);
private Throwable clientStartupIssue = null;
private boolean isAvailable()
{
if (!Printing_Constants.isEnabled())
{
return false;
}
return Ini.isSwingClient() && clientStartupIssue == null;
}
@Override
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 class Person {
private long id;
private String name;
private String email;
private String dateOfBirth;
@NotEmpty
private String password;
private String sex;
private String country;
private String book;
private String job;
private boolean receiveNewsletter;
private String[] hobbies;
private List<String> favouriteLanguage;
private List<String> fruit;
private String notes;
private MultipartFile file;
public Person() {
super();
}
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(final String email) {
this.email = email;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(final String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getPassword() {
return password;
}
public void setPassword(final String password) {
this.password = password;
}
public String getSex() {
return sex;
}
public void setSex(final String sex) {
this.sex = sex;
}
public String getCountry() {
return country;
}
public void setCountry(final String country) {
this.country = country;
}
public String getJob() {
return job;
}
public void setJob(final String job) {
this.job = job;
}
public boolean isReceiveNewsletter() {
return receiveNewsletter;
} | public void setReceiveNewsletter(final boolean receiveNewsletter) {
this.receiveNewsletter = receiveNewsletter;
}
public String[] getHobbies() {
return hobbies;
}
public void setHobbies(final String[] hobbies) {
this.hobbies = hobbies;
}
public List<String> getFavouriteLanguage() {
return favouriteLanguage;
}
public void setFavouriteLanguage(final List<String> favouriteLanguage) {
this.favouriteLanguage = favouriteLanguage;
}
public String getNotes() {
return notes;
}
public void setNotes(final String notes) {
this.notes = notes;
}
public List<String> getFruit() {
return fruit;
}
public void setFruit(final List<String> fruit) {
this.fruit = fruit;
}
public String getBook() {
return book;
}
public void setBook(final String book) {
this.book = book;
}
public MultipartFile getFile() {
return file;
}
public void setFile(final MultipartFile file) {
this.file = file;
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-xml-2\src\main\java\com\baeldung\spring\taglibrary\Person.java | 1 |
请完成以下Java代码 | public ProcessInstanceChangeState setProcessInstanceVariables(Map<String, Object> processVariables) {
this.processVariables = processVariables;
return this;
}
public Map<String, Map<String, Object>> getLocalVariables() {
return localVariables;
}
public ProcessInstanceChangeState setLocalVariables(Map<String, Map<String, Object>> localVariables) {
this.localVariables = localVariables;
return this;
}
public List<EnableActivityContainer> getEnableActivityContainers() {
return enableActivityContainers;
}
public ProcessInstanceChangeState setEnableActivityContainers(List<EnableActivityContainer> enableActivityContainers) {
this.enableActivityContainers = enableActivityContainers;
return this;
}
public List<MoveExecutionEntityContainer> getMoveExecutionEntityContainers() {
return moveExecutionEntityContainers;
}
public ProcessInstanceChangeState setMoveExecutionEntityContainers(List<MoveExecutionEntityContainer> moveExecutionEntityContainers) {
this.moveExecutionEntityContainers = moveExecutionEntityContainers;
return this;
}
public HashMap<String, ExecutionEntity> getCreatedEmbeddedSubProcesses() {
return createdEmbeddedSubProcess;
}
public Optional<ExecutionEntity> getCreatedEmbeddedSubProcessByKey(String key) {
return Optional.ofNullable(createdEmbeddedSubProcess.get(key));
} | public void addCreatedEmbeddedSubProcess(String key, ExecutionEntity executionEntity) {
this.createdEmbeddedSubProcess.put(key, executionEntity);
}
public HashMap<String, ExecutionEntity> getCreatedMultiInstanceRootExecution() {
return createdMultiInstanceRootExecution;
}
public void setCreatedMultiInstanceRootExecution(HashMap<String, ExecutionEntity> createdMultiInstanceRootExecution) {
this.createdMultiInstanceRootExecution = createdMultiInstanceRootExecution;
}
public void addCreatedMultiInstanceRootExecution(String key, ExecutionEntity executionEntity) {
this.createdMultiInstanceRootExecution.put(key, executionEntity);
}
public Map<String, List<ExecutionEntity>> getProcessInstanceActiveEmbeddedExecutions() {
return processInstanceActiveEmbeddedExecutions;
}
public ProcessInstanceChangeState setProcessInstanceActiveEmbeddedExecutions(Map<String, List<ExecutionEntity>> processInstanceActiveEmbeddedExecutions) {
this.processInstanceActiveEmbeddedExecutions = processInstanceActiveEmbeddedExecutions;
return this;
}
public HashMap<StartEvent, ExecutionEntity> getPendingEventSubProcessesStartEvents() {
return pendingEventSubProcessesStartEvents;
}
public void addPendingEventSubProcessStartEvent(StartEvent startEvent, ExecutionEntity eventSubProcessParent) {
this.pendingEventSubProcessesStartEvents.put(startEvent, eventSubProcessParent);
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\dynamic\ProcessInstanceChangeState.java | 1 |
请完成以下Java代码 | private boolean shouldRevalidate(ServerWebExchange exchange) {
return LocalResponseCacheUtils.isNoCacheRequest(exchange.getRequest());
}
private class CachingResponseDecorator extends ServerHttpResponseDecorator {
private final String metadataKey;
private final ServerWebExchange exchange;
CachingResponseDecorator(String metadataKey, ServerWebExchange exchange) {
super(exchange.getResponse());
this.metadataKey = metadataKey;
this.exchange = exchange;
}
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
final ServerHttpResponse response = exchange.getResponse(); | Flux<DataBuffer> decoratedBody;
if (responseCacheManager.isResponseCacheable(response)
&& !responseCacheManager.isNoCacheRequestWithoutUpdate(exchange.getRequest())) {
decoratedBody = responseCacheManager.processFromUpstream(metadataKey, exchange, Flux.from(body));
}
else {
decoratedBody = Flux.from(body);
}
return super.writeWith(decoratedBody);
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\ResponseCacheGatewayFilter.java | 1 |
请完成以下Java代码 | public void setWindowSize(final Dimension size)
{
if (size != null)
{
setWinWidth(size.width);
setWinHeight(size.height);
}
}
private MTab[] m_tabs = null;
public MTab[] getTabs(final boolean reload, final String trxName)
{
if (m_tabs != null && !reload)
{
return m_tabs;
}
final String sql = "SELECT * FROM AD_Tab WHERE AD_Window_ID=? ORDER BY SeqNo";
final ArrayList<MTab> list = new ArrayList<>();
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, trxName);
pstmt.setInt(1, getAD_Window_ID());
rs = pstmt.executeQuery();
while (rs.next())
{
list.add(new MTab(getCtx(), rs, trxName));
}
}
catch (final Exception e)
{
log.error(sql, e);
}
finally
{
DB.close(rs, pstmt);
}
//
m_tabs = new MTab[list.size()];
list.toArray(m_tabs);
return m_tabs;
} // getFields
@Override
protected boolean afterSave(final boolean newRecord, final boolean success)
{
if (newRecord) // Add to all automatic roles
{
// Add to all automatic roles ... handled elsewhere
}
// Menu/Workflow update
else if (is_ValueChanged("IsActive") || is_ValueChanged("Name")
|| is_ValueChanged("Description") || is_ValueChanged("Help"))
{
final MMenu[] menues = MMenu.get(getCtx(), "AD_Window_ID=" + getAD_Window_ID(), get_TrxName());
for (final MMenu menue : menues)
{
menue.setName(getName());
menue.setDescription(getDescription());
menue.setIsActive(isActive());
menue.save();
}
//
final X_AD_WF_Node[] nodes = getWFNodes(getCtx(), "AD_Window_ID=" + getAD_Window_ID(), get_TrxName());
for (final X_AD_WF_Node node : nodes)
{
boolean changed = false;
if (node.isActive() != isActive())
{
node.setIsActive(isActive());
changed = true;
}
if (node.isCentrallyMaintained()) | {
node.setName(getName());
node.setDescription(getDescription());
node.setHelp(getHelp());
changed = true;
}
if (changed)
{
node.save();
}
}
}
return success;
}
public static X_AD_WF_Node[] getWFNodes(final Properties ctx, final String whereClause, final String trxName)
{
String sql = "SELECT * FROM AD_WF_Node";
if (whereClause != null && whereClause.length() > 0)
{
sql += " WHERE " + whereClause;
}
final ArrayList<X_AD_WF_Node> list = new ArrayList<>();
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, trxName);
rs = pstmt.executeQuery();
while (rs.next())
{
list.add(new X_AD_WF_Node(ctx, rs, trxName));
}
}
catch (final Exception e)
{
s_log.error(sql, e);
}
finally
{
DB.close(rs, pstmt);
}
final X_AD_WF_Node[] retValue = new X_AD_WF_Node[list.size()];
list.toArray(retValue);
return retValue;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MWindow.java | 1 |
请完成以下Java代码 | private void deleteAndFireEvent(final String id, boolean expired)
{
final MapSession deletedSession = sessions.remove(id);
// Fire event
if (deletedSession != null)
{
if (expired)
{
applicationEventPublisher.publishEvent(new SessionExpiredEvent(this, deletedSession));
}
else
{
applicationEventPublisher.publishEvent(new SessionDeletedEvent(this, deletedSession));
}
}
}
@Override
public MapSession createSession()
{
final MapSession result = new MapSession();
if (defaultMaxInactiveInterval != null)
{
result.setMaxInactiveInterval(defaultMaxInactiveInterval);
}
// Fire event
applicationEventPublisher.publishEvent(new SessionCreatedEvent(this, result));
return result;
}
public void purgeExpiredSessionsNoFail()
{
try
{
purgeExpiredSessions();
}
catch (final Throwable ex)
{
logger.warn("Failed purging expired sessions. Ignored.", ex);
}
} | public void purgeExpiredSessions()
{
final Stopwatch stopwatch = Stopwatch.createStarted();
int countExpiredSessions = 0;
final List<MapSession> sessionsToCheck = new ArrayList<>(sessions.values());
for (final MapSession session : sessionsToCheck)
{
if (session.isExpired())
{
deleteAndFireEvent(session.getId(), true /* expired */);
countExpiredSessions++;
}
}
logger.debug("Purged {}/{} expired sessions in {}", countExpiredSessions, sessionsToCheck.size(), stopwatch);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\FixedMapSessionRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public de.codecentric.boot.admin.server.ui.web.reactive.HomepageForwardingFilter homepageForwardFilter(
HomepageForwardingFilterConfig homepageForwardingFilterConfig) {
return new de.codecentric.boot.admin.server.ui.web.reactive.HomepageForwardingFilter(
homepageForwardingFilterConfig);
}
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public static class ServletUiConfiguration {
@Configuration(proxyBeanMethods = false)
public static class AdminUiWebMvcConfig implements WebMvcConfigurer {
private final AdminServerUiProperties adminUi;
private final AdminServerProperties adminServer;
private final ApplicationContext applicationContext;
public AdminUiWebMvcConfig(AdminServerUiProperties adminUi, AdminServerProperties adminServer,
ApplicationContext applicationContext) {
this.adminUi = adminUi;
this.adminServer = adminServer;
this.applicationContext = applicationContext;
}
@Bean
public HomepageForwardingFilterConfig homepageForwardingFilterConfig() throws IOException {
String homepage = normalizeHomepageUrl(this.adminServer.path("/"));
List<String> extensionRoutes = new UiRoutesScanner(this.applicationContext)
.scan(this.adminUi.getExtensionResourceLocations());
List<String> routesIncludes = Stream
.concat(DEFAULT_UI_ROUTES.stream(), Stream.concat(extensionRoutes.stream(), Stream.of("/")))
.map(this.adminServer::path)
.toList();
List<String> routesExcludes = Stream
.concat(DEFAULT_UI_ROUTE_EXCLUDES.stream(), this.adminUi.getAdditionalRouteExcludes().stream())
.map(this.adminServer::path)
.toList(); | return new HomepageForwardingFilterConfig(homepage, routesIncludes, routesExcludes);
}
@Override
public void addResourceHandlers(
org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry registry) {
registry.addResourceHandler(this.adminServer.path("/**"))
.addResourceLocations(this.adminUi.getResourceLocations())
.setCacheControl(this.adminUi.getCache().toCacheControl());
registry.addResourceHandler(this.adminServer.path("/extensions/**"))
.addResourceLocations(this.adminUi.getExtensionResourceLocations())
.setCacheControl(this.adminUi.getCache().toCacheControl());
}
@Bean
@ConditionalOnMissingBean
public de.codecentric.boot.admin.server.ui.web.servlet.HomepageForwardingFilter homepageForwardFilter(
HomepageForwardingFilterConfig homepageForwardingFilterConfig) {
return new de.codecentric.boot.admin.server.ui.web.servlet.HomepageForwardingFilter(
homepageForwardingFilterConfig);
}
}
}
} | repos\spring-boot-admin-master\spring-boot-admin-server-ui\src\main\java\de\codecentric\boot\admin\server\ui\config\AdminServerUiAutoConfiguration.java | 2 |
请完成以下Java代码 | private static boolean isProjectsGroupDir(final File dir)
{
return dir.isDirectory() && "backend".equals(dir.getName()); // metasfresh/backend
}
private static boolean isMavenProjectDir(final File dir)
{
return dir.isDirectory() && new File(dir, "pom.xml").exists();
}
private List<IScript> getScriptFilesFromProjectDir(final File projectDir, final String defaultProjectName)
{
final File scriptsRootDir = new File(projectDir, "src/main/sql/postgresql/system");
if (!scriptsRootDir.isDirectory())
{
return ImmutableList.of();
}
final ArrayList<IScript> scripts = new ArrayList<>();
//
// Script files in subfolders
// e.g. .../src/main/sql/postgresql/system/10-de.metas.adempiere
for (final File subProjectDir : scriptsRootDir.listFiles(File::isDirectory))
{
final String projectName = subProjectDir.getName();
for (final File scriptFile : subProjectDir.listFiles(this::isSupportedScriptFile))
{
scripts.add(new LocalScript(projectName, scriptFile));
}
}
//
// Script files directly in .../src/main/sql/postgresql/system/ folder
for (final File scriptFile : scriptsRootDir.listFiles(File::isFile))
{
scripts.add(new LocalScript(defaultProjectName, scriptFile));
}
logger.info("Considering {} ({} scripts)", projectDir, scripts.size());
return scripts;
}
private boolean isSupportedScriptFile(final File file)
{ | if (!file.exists() || !file.isFile())
{
return false;
}
final String fileExtLC = FileUtils.getFileExtension(file.getName(), false).toLowerCase();
return supportedFileExtensionsLC.contains(fileExtLC);
}
private static String getDefaultProjectName(final File projectDir)
{
final File mavenPOMFile = new File(projectDir, "pom.xml");
if (mavenPOMFile.exists())
{
final Document xmlDocument = XmlUtils.loadDocument(mavenPOMFile);
try
{
return XmlUtils.getString("/project/properties/migration-sql-basedir", xmlDocument);
}
catch (Exception ex)
{
ex.printStackTrace(); // FIXME remove
return null;
}
}
else
{
return null;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\workspace_migrate\WorkspaceScriptScanner.java | 1 |
请完成以下Java代码 | public IPaymentStringDataProvider getQRDataProvider(@NonNull final String qrCode) throws PaymentStringParseException
{
Check.assumeNotEmpty(qrCode, "paymentStringText not empty");
final IPaymentStringParser paymentStringParser = paymentStringParserFactory.getParser(PaymentParserType.QRCode.getType());
final PaymentString paymentString;
try
{
paymentString = paymentStringParser.parse(qrCode);
}
catch (final IndexOutOfBoundsException ex)
{
throw new PaymentStringParseException(ERR_InvalidPaymentStringLength, ex);
}
final List<String> collectedErrors = paymentString.getCollectedErrors(); | if (!collectedErrors.isEmpty())
{
final StringBuilder exceptions = new StringBuilder();
for (final String exception : collectedErrors)
{
exceptions.append(exception)
.append("\n");
}
throw new PaymentStringParseException(exceptions.toString());
}
final IPaymentStringDataProvider dataProvider = paymentString.getDataProvider();
return dataProvider;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\impl\PaymentStringBL.java | 1 |
请完成以下Java代码 | public final class ViewEvaluationCtx
{
public static ViewEvaluationCtx newInstanceFromCurrentContext()
{
final Properties ctx = Env.getCtx();
return _builder()
.loggedUserId(Env.getLoggedUserIdIfExists(ctx))
.adLanguage(Env.getAD_Language(ctx))
.timeZone(UserSession.getTimeZoneOrSystemDefault())
.permissionsKey(UserRolePermissionsKey.fromContext(ctx))
.orgId(Env.getOrgId(ctx))
.build();
}
@Getter
private final Optional<UserId> loggedUserId;
@Getter
private final OrgId orgId;
@Getter
private final String adLanguage;
@Getter
private final ZoneId timeZone;
@Getter
private final UserRolePermissionsKey permissionsKey;
private transient Evaluatee _evaluatee; // lazy
private transient JSONOptions _jsonOptions; // lazy
@Builder(builderMethodName = "_builder")
private ViewEvaluationCtx(
@NonNull final Optional<UserId> loggedUserId,
@NonNull final OrgId orgId,
@NonNull final String adLanguage,
@NonNull final ZoneId timeZone,
@NonNull final UserRolePermissionsKey permissionsKey)
{
this.loggedUserId = loggedUserId;
this.orgId = orgId;
this.adLanguage = adLanguage;
this.timeZone = timeZone;
this.permissionsKey = permissionsKey;
}
public Evaluatee toEvaluatee()
{
Evaluatee evaluatee = _evaluatee;
if (evaluatee == null)
{
evaluatee = _evaluatee = createEvaluatee();
}
return evaluatee;
} | private Evaluatee createEvaluatee()
{
return Evaluatees.mapBuilder()
.put(Env.CTXNAME_AD_User_ID, loggedUserId.map(UserId::getRepoId).orElse(-1))
.put(Env.CTXNAME_AD_Org_ID, OrgId.toRepoIdOrAny(orgId))
.put(Env.CTXNAME_AD_Language, adLanguage)
.put(AccessSqlStringExpression.PARAM_UserRolePermissionsKey.getName(), permissionsKey.toPermissionsKeyString())
.build();
}
public JSONOptions toJSONOptions()
{
JSONOptions jsonOptions = this._jsonOptions;
if (jsonOptions == null)
{
jsonOptions = _jsonOptions = createJSONOptions();
}
return jsonOptions;
}
private JSONOptions createJSONOptions()
{
return JSONOptions.builder()
.adLanguage(adLanguage)
.zoneId(timeZone)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewEvaluationCtx.java | 1 |
请完成以下Java代码 | public BigDecimal getInterestAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_InterestAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set In Dispute.
@param IsInDispute
Document is in dispute
*/
public void setIsInDispute (boolean IsInDispute)
{
set_Value (COLUMNNAME_IsInDispute, Boolean.valueOf(IsInDispute));
}
/** Get In Dispute.
@return Document is in dispute
*/
public boolean isInDispute ()
{
Object oo = get_Value(COLUMNNAME_IsInDispute);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Open Amount.
@param OpenAmt
Open item amount
*/
public void setOpenAmt (BigDecimal OpenAmt)
{
set_Value (COLUMNNAME_OpenAmt, OpenAmt);
}
/** Get Open Amount.
@return Open item amount
*/
public BigDecimal getOpenAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
} | /** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Times Dunned.
@param TimesDunned
Number of times dunned previously
*/
public void setTimesDunned (int TimesDunned)
{
set_Value (COLUMNNAME_TimesDunned, Integer.valueOf(TimesDunned));
}
/** Get Times Dunned.
@return Number of times dunned previously
*/
public int getTimesDunned ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_TimesDunned);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Total Amount.
@param TotalAmt
Total Amount
*/
public void setTotalAmt (BigDecimal TotalAmt)
{
set_Value (COLUMNNAME_TotalAmt, TotalAmt);
}
/** Get Total Amount.
@return Total Amount
*/
public BigDecimal getTotalAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DunningRunLine.java | 1 |
请完成以下Java代码 | public void setPrice (java.math.BigDecimal Price)
{
set_ValueNoCheck (COLUMNNAME_Price, Price);
}
/** Get Preis.
@return Price
*/
@Override
public java.math.BigDecimal getPrice ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Price);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Produktschlüssel.
@param ProductValue
Key of the Product
*/
@Override
public void setProductValue (java.lang.String ProductValue)
{
set_ValueNoCheck (COLUMNNAME_ProductValue, ProductValue);
}
/** Get Produktschlüssel.
@return Key of the Product
*/
@Override
public java.lang.String getProductValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_ProductValue);
}
/** Set Menge.
@param Qty
Quantity
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_ValueNoCheck (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Quantity
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set SKU.
@param SKU
Stock Keeping Unit
*/
@Override
public void setSKU (java.lang.String SKU)
{
set_ValueNoCheck (COLUMNNAME_SKU, SKU);
}
/** Get SKU.
@return Stock Keeping Unit
*/
@Override
public java.lang.String getSKU ()
{
return (java.lang.String)get_Value(COLUMNNAME_SKU);
} | /** Set Symbol.
@param UOMSymbol
Symbol for a Unit of Measure
*/
@Override
public void setUOMSymbol (java.lang.String UOMSymbol)
{
set_ValueNoCheck (COLUMNNAME_UOMSymbol, UOMSymbol);
}
/** Get Symbol.
@return Symbol for a Unit of Measure
*/
@Override
public java.lang.String getUOMSymbol ()
{
return (java.lang.String)get_Value(COLUMNNAME_UOMSymbol);
}
/** Set UPC/EAN.
@param UPC
Bar Code (Universal Product Code or its superset European Article Number)
*/
@Override
public void setUPC (java.lang.String UPC)
{
set_ValueNoCheck (COLUMNNAME_UPC, UPC);
}
/** Get UPC/EAN.
@return Bar Code (Universal Product Code or its superset European Article Number)
*/
@Override
public java.lang.String getUPC ()
{
return (java.lang.String)get_Value(COLUMNNAME_UPC);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponseLine_v.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
} | public String getModification() {
return modification;
}
public void setModification(String modification) {
this.modification = modification;
}
public Chapter getChapter() {
return chapter;
}
public void setChapter(Chapter chapter) {
this.chapter = chapter;
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootOptimisticForceIncrement\src\main\java\com\bookstore\entity\Modification.java | 1 |
请完成以下Java代码 | public void checkRegisterProcessApplication() {
}
@Override
public void checkUnregisterProcessApplication() {
}
@Override
public void checkReadRegisteredDeployments() {
}
@Override
public void checkReadProcessApplicationForDeployment() {
}
@Override
public void checkRegisterDeployment() {
}
@Override
public void checkUnregisterDeployment() {
}
@Override
public void checkDeleteMetrics() {
}
@Override
public void checkDeleteTaskMetrics() {
}
@Override
public void checkReadSchemaLog() {
} | // helper //////////////////////////////////////////////////
protected TenantManager getTenantManager() {
return Context.getCommandContext().getTenantManager();
}
protected ProcessDefinitionEntity findLatestProcessDefinitionById(String processDefinitionId) {
return Context.getCommandContext().getProcessDefinitionManager().findLatestProcessDefinitionById(processDefinitionId);
}
protected DecisionDefinitionEntity findLatestDecisionDefinitionById(String decisionDefinitionId) {
return Context.getCommandContext().getDecisionDefinitionManager().findDecisionDefinitionById(decisionDefinitionId);
}
protected ExecutionEntity findExecutionById(String processInstanceId) {
return Context.getCommandContext().getExecutionManager().findExecutionById(processInstanceId);
}
protected DeploymentEntity findDeploymentById(String deploymentId) {
return Context.getCommandContext().getDeploymentManager().findDeploymentById(deploymentId);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\multitenancy\TenantCommandChecker.java | 1 |
请完成以下Java代码 | public void setCacheSecurityContext(boolean cacheSecurityContext) {
this.cacheSecurityContext = cacheSecurityContext;
}
@Override
public Mono<Void> save(ServerWebExchange exchange, @Nullable SecurityContext context) {
return exchange.getSession().doOnNext((session) -> {
if (context == null) {
session.getAttributes().remove(this.springSecurityContextAttrName);
logger.debug(LogMessage.format("Removed SecurityContext stored in WebSession: '%s'", session));
}
else {
session.getAttributes().put(this.springSecurityContextAttrName, context);
logger.debug(LogMessage.format("Saved SecurityContext '%s' in WebSession: '%s'", context, session));
} | }).flatMap(WebSession::changeSessionId);
}
@Override
public Mono<SecurityContext> load(ServerWebExchange exchange) {
Mono<SecurityContext> result = exchange.getSession().flatMap((session) -> {
SecurityContext context = (SecurityContext) session.getAttribute(this.springSecurityContextAttrName);
logger.debug((context != null)
? LogMessage.format("Found SecurityContext '%s' in WebSession: '%s'", context, session)
: LogMessage.format("No SecurityContext found in WebSession: '%s'", session));
return Mono.justOrEmpty(context);
});
return (this.cacheSecurityContext) ? result.cache() : result;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\context\WebSessionServerSecurityContextRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public CommonResult paySuccess(@RequestParam Long orderId,@RequestParam Integer payType) {
Integer count = portalOrderService.paySuccess(orderId,payType);
return CommonResult.success(count, "支付成功");
}
@ApiOperation("自动取消超时订单")
@RequestMapping(value = "/cancelTimeOutOrder", method = RequestMethod.POST)
@ResponseBody
public CommonResult cancelTimeOutOrder() {
portalOrderService.cancelTimeOutOrder();
return CommonResult.success(null);
}
@ApiOperation("取消单个超时订单")
@RequestMapping(value = "/cancelOrder", method = RequestMethod.POST)
@ResponseBody
public CommonResult cancelOrder(Long orderId) {
portalOrderService.sendDelayMessageCancelOrder(orderId);
return CommonResult.success(null);
}
@ApiOperation("按状态分页获取用户订单列表")
@ApiImplicitParam(name = "status", value = "订单状态:-1->全部;0->待付款;1->待发货;2->已发货;3->已完成;4->已关闭",
defaultValue = "-1", allowableValues = "-1,0,1,2,3,4", paramType = "query", dataType = "int")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<OmsOrderDetail>> list(@RequestParam Integer status,
@RequestParam(required = false, defaultValue = "1") Integer pageNum,
@RequestParam(required = false, defaultValue = "5") Integer pageSize) {
CommonPage<OmsOrderDetail> orderPage = portalOrderService.list(status,pageNum,pageSize);
return CommonResult.success(orderPage);
}
@ApiOperation("根据ID获取订单详情")
@RequestMapping(value = "/detail/{orderId}", method = RequestMethod.GET)
@ResponseBody | public CommonResult<OmsOrderDetail> detail(@PathVariable Long orderId) {
OmsOrderDetail orderDetail = portalOrderService.detail(orderId);
return CommonResult.success(orderDetail);
}
@ApiOperation("用户取消订单")
@RequestMapping(value = "/cancelUserOrder", method = RequestMethod.POST)
@ResponseBody
public CommonResult cancelUserOrder(Long orderId) {
portalOrderService.cancelOrder(orderId);
return CommonResult.success(null);
}
@ApiOperation("用户确认收货")
@RequestMapping(value = "/confirmReceiveOrder", method = RequestMethod.POST)
@ResponseBody
public CommonResult confirmReceiveOrder(Long orderId) {
portalOrderService.confirmReceiveOrder(orderId);
return CommonResult.success(null);
}
@ApiOperation("用户删除订单")
@RequestMapping(value = "/deleteOrder", method = RequestMethod.POST)
@ResponseBody
public CommonResult deleteOrder(Long orderId) {
portalOrderService.deleteOrder(orderId);
return CommonResult.success(null);
}
} | repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\controller\OmsPortalOrderController.java | 2 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getAddress() { | return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
} | repos\spring-boot-leaning-master\1.x\第04课:Spring Data Jpa 的使用\spring-boot-Jpa\src\main\java\com\neo\domain\UserDetail.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ArrayOfAttachments extends ArrayList<Attachment> {
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
return super.equals(o);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ArrayOfAttachments {\n");
sb.append(" ").append(toIndentedString(super.toString())).append("\n"); | sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-document-api\src\main\java\io\swagger\client\model\ArrayOfAttachments.java | 2 |
请在Spring Boot框架中完成以下Java代码 | default Flux<Article> findNewestArticlesFilteredBy(FindArticlesRequest request) {
return findNewestArticlesFilteredBy(request.getTag(),
request.getAuthorId(),
request.getFavoritedBy(),
request.getLimit(),
request.getOffset());
}
}
@RequiredArgsConstructor
class ArticleManualRepositoryImpl implements ArticleManualRepository {
private final ReactiveMongoTemplate mongoTemplate;
@Override
public Flux<Article> findNewestArticlesFilteredBy(@Nullable String tag,
@Nullable String authorId,
@Nullable User favoritedBy,
int limit,
int offset) {
var query = new Query()
.skip(offset)
.limit(limit) | .with(ArticleRepository.NEWEST_ARTICLE_SORT);
ofNullable(favoritedBy)
.ifPresent(user -> query.addCriteria(isFavoriteArticleByUser(user)));
ofNullable(tag)
.ifPresent(it -> query.addCriteria(tagsContains(it)));
ofNullable(authorId)
.ifPresent(it -> query.addCriteria(authorIdEquals(it)));
return mongoTemplate.find(query, Article.class);
}
private Criteria authorIdEquals(String it) {
return where(Article.AUTHOR_ID_FIELD_NAME).is(it);
}
private Criteria tagsContains(String it) {
return where(Article.TAGS_FIELD_NAME).all(it);
}
private Criteria isFavoriteArticleByUser(User it) {
return where(Article.ID_FIELD_NAME).in(it.getFavoriteArticleIds());
}
} | repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\article\repository\ArticleManualRepository.java | 2 |
请完成以下Java代码 | public final class CleanWhitespaceQueryFilterModifier implements IQueryFilterModifier
{
@Getter
private static final transient CleanWhitespaceQueryFilterModifier instance = new CleanWhitespaceQueryFilterModifier();
private CleanWhitespaceQueryFilterModifier()
{
}
@Override
public @NonNull String getColumnSql(@NonNull String columnName)
{
final String columnSqlNew = "REPLACE(" + columnName + ", ' ', '')";
return columnSqlNew;
}
@Override
public String getValueSql(Object value, List<Object> params)
{
final String valueSql;
if (value instanceof ModelColumnNameValue<?>)
{
final ModelColumnNameValue<?> modelValue = (ModelColumnNameValue<?>)value;
valueSql = modelValue.getColumnName();
}
else
{ | valueSql = "?";
params.add(value);
}
return "REPLACE(" + valueSql + ", ' ', '')";
}
@Nullable
@Override
public Object convertValue(@Nullable final String columnName, @Nullable final Object value, final @Nullable Object model)
{
if (value == null)
{
return null;
}
final String str = (String)value;
return StringUtils.cleanWhitespace(str);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\CleanWhitespaceQueryFilterModifier.java | 1 |
请完成以下Java代码 | public BigDecimal getTotal_Qty_Six_Weeks_Ago()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Total_Qty_Six_Weeks_Ago);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotal_Qty_Three_Weeks_Ago (final @Nullable BigDecimal Total_Qty_Three_Weeks_Ago)
{
set_ValueNoCheck (COLUMNNAME_Total_Qty_Three_Weeks_Ago, Total_Qty_Three_Weeks_Ago);
}
@Override
public BigDecimal getTotal_Qty_Three_Weeks_Ago()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Total_Qty_Three_Weeks_Ago); | return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotal_Qty_Two_Weeks_Ago (final @Nullable BigDecimal Total_Qty_Two_Weeks_Ago)
{
set_ValueNoCheck (COLUMNNAME_Total_Qty_Two_Weeks_Ago, Total_Qty_Two_Weeks_Ago);
}
@Override
public BigDecimal getTotal_Qty_Two_Weeks_Ago()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Total_Qty_Two_Weeks_Ago);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\replenishment\X_M_Material_Needs_Planner_V.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MemcachedBuilder {
protected static Logger logger = LoggerFactory.getLogger(MemcachedBuilder.class);
@Resource
private XMemcachedProperties xMemcachedProperties;
@Bean
public MemcachedClient getMemcachedClient() {
MemcachedClient memcachedClient = null;
try {
MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(xMemcachedProperties.getServers()));
// 设置集群权重
// MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(memcacheConfig.getServers()),new int[]{3,2,1});
// 开启/关闭failure模式
builder.setFailureMode(false);
// 多 Memcached 时启用 一致性哈希 算法
builder.setSessionLocator(new KetamaMemcachedSessionLocator());
// 多 Memcached 时启用 选举散列 算法
// builder.setSessionLocator(new ElectionMemcachedSessionLocator());
builder.setConnectionPoolSize(xMemcachedProperties.getPoolSize()); | //操作超时时间
builder.setOpTimeout(xMemcachedProperties.getOpTimeout());
// 进行数据压缩,大于1KB时进行压缩
builder.getTranscoder().setCompressionThreshold(1024);
// 使用序列化传输编码
builder.setTranscoder(new SerializingTranscoder());
// use binary protocol
builder.setCommandFactory(new BinaryCommandFactory());
memcachedClient = builder.build();
} catch (IOException e) {
logger.error("inint MemcachedClient failed ",e);
}
return memcachedClient;
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 4-1 课:Spring Boot 操作 Memcache\spring-boot-memcache\src\main\java\com\neo\config\MemcachedBuilder.java | 2 |
请完成以下Java代码 | /* package */class CountIfQueryAggregateColumnBuilder<SourceModelType, TargetModelType> implements IQueryAggregateColumnBuilder<SourceModelType, TargetModelType, Integer>
{
private final ICompositeQueryFilter<SourceModelType> filters = new CompositeQueryFilter<>();
private ModelDynAttributeAccessor<TargetModelType, Integer> dynAttribute;
/* package */CountIfQueryAggregateColumnBuilder()
{
super();
}
@Override
public ICompositeQueryFilter<SourceModelType> filter()
{
return this.filters;
}
@Override
public String getSql(final Properties ctx, final List<Object> sqlParamsOut)
{
final List<IQueryFilter<SourceModelType>> nonSqlFilters = filters.getNonSqlFilters();
Check.assume(nonSqlFilters == null || nonSqlFilters.isEmpty(), "Non-SQL filters are not supported: {}", nonSqlFilters);
final String sqlWhereClause = filters.getSqlFiltersWhereClause();
final StringBuilder sql = new StringBuilder()
.append("SUM(CASE WHEN (").append(sqlWhereClause).append(") THEN +1 ELSE 0 END)");
final List<Object> sqlWhereClauseParams = filters.getSqlFiltersParams(ctx);
sqlParamsOut.addAll(sqlWhereClauseParams);
return sql.toString();
}
@Override
public CountIfQueryAggregateColumnBuilder<SourceModelType, TargetModelType> setDynAttribute(final ModelDynAttributeAccessor<TargetModelType, Integer> dynAttribute)
{
this.dynAttribute = dynAttribute;
return this;
}
@Override
public ModelDynAttributeAccessor<TargetModelType, Integer> getDynAttribute()
{
return dynAttribute;
}
@Override
public IAggregator<Integer, SourceModelType> createAggregator(final TargetModelType targetModel)
{ | Check.assumeNotNull(targetModel, "targetModel not null");
return new IAggregator<Integer, SourceModelType>()
{
private final ICompositeQueryFilter<SourceModelType> filters = CountIfQueryAggregateColumnBuilder.this.filters.copy();
private ModelDynAttributeAccessor<TargetModelType, Integer> dynAttribute = CountIfQueryAggregateColumnBuilder.this.dynAttribute;
private int counter = 0;
@Override
public void add(final SourceModelType value)
{
if (filters.accept(value))
{
counter++;
}
// Update target model's dynamic attribute
dynAttribute.setValue(targetModel, counter);
}
@Override
public Integer getValue()
{
return counter;
}
};
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\CountIfQueryAggregateColumnBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Integer getTimeFrom() {
return timeFrom;
}
/**
* Sets the value of the timeFrom property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setTimeFrom(Integer value) {
this.timeFrom = value;
}
/**
* Gets the value of the timeTo property.
*
* @return
* possible object is
* {@link Integer }
* | */
public Integer getTimeTo() {
return timeTo;
}
/**
* Sets the value of the timeTo property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setTimeTo(Integer value) {
this.timeTo = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\Delivery.java | 2 |
请完成以下Java代码 | public void onChangeNewsletter(final I_AD_User userRecord)
{
if (!isCreateMarketingContact(userRecord.getAD_Client_ID(), userRecord.getAD_Org_ID()))
{
return;
}
final IMsgBL msgBL = Services.get(IMsgBL.class);
final boolean isNewsletter = userRecord.isNewsletter();
final Optional<CampaignId> defaultcampaignId = campaignRepository.getDefaultNewsletterCampaignId(userRecord.getAD_Org_ID());
if (isNewsletter)
{
if (!defaultcampaignId.isPresent())
{
final String orgName = orgDAO.retrieveOrgName(userRecord.getAD_Org_ID());
throw new AdempiereException(MRG_MKTG_Campaign_NewsletterGroup_Missing_For_Org, orgName);
}
final User user = userRepository.ofRecord(userRecord);
campaignService.addToCampaignIfHasEmailAddress(user, defaultcampaignId.get());
}
else
{
if (!defaultcampaignId.isPresent())
{ | return; // nothing to do
}
final User user = userRepository.ofRecord(userRecord);
campaignService.removeUserFromCampaign(user, defaultcampaignId.get());
}
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE, //
ifColumnsChanged = { I_AD_User.COLUMNNAME_EMail, I_AD_User.COLUMNNAME_AD_Language })
public void onChangeEmail(final I_AD_User userRecord)
{
final User user = userRepository.ofRecord(userRecord);
final I_AD_User oldUser = InterfaceWrapperHelper.createOld(userRecord, I_AD_User.class);
final String oldEmail = oldUser.getEMail();
final Language oldLanguage = Language.asLanguage(oldUser.getAD_Language());
contactPersonService.updateContactPersonsEmailFromUser(user, oldEmail, oldLanguage);
}
private boolean isCreateMarketingContact(final int clientID, final int orgID)
{
return sysConfigBL.getBooleanValue(SYS_CONFIG_CREATE_MARKETING_CONTACT, false, clientID, orgID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\model\interceptor\AD_User.java | 1 |
请完成以下Java代码 | private static MSV3User toMSV3User(@NonNull final JpaUser jpaUser)
{
return MSV3User.builder()
.metasfreshMSV3UserId(MSV3MetasfreshUserId.of(jpaUser.getMfMSV3UserId()))
.username(jpaUser.getMfUsername())
.password(jpaUser.getMfPassword())
.bpartnerId(BPartnerId.of(jpaUser.getMfBpartnerId(), jpaUser.getMfBpartnerLocationId()))
.build();
}
@Deprecated
public void assertValidClientSoftwareId(final String clientSoftwareId)
{
// TODO implement
}
public void assertValidClientSoftwareId(final ClientSoftwareId clientSoftwareId)
{
// TODO implement
}
public BPartnerId getCurrentBPartner()
{
return getCurrentUser().getBpartnerId();
}
public MSV3User getCurrentUser()
{
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null)
{
throw new IllegalStateException("No authentication found");
}
return loadUserByUsername(authentication.getName());
}
public List<MSV3User> getAllUsers()
{
return usersRepo.findAll()
.stream()
.map(jpaUser -> toMSV3User(jpaUser))
.collect(ImmutableList.toImmutableList());
}
@Transactional
public void handleEvent(@NonNull final MSV3UserChangedBatchEvent batchEvent)
{
final String mfSyncToken = batchEvent.getId();
// | // Update/Delete
{
final AtomicInteger countUpdated = new AtomicInteger();
for (final MSV3UserChangedEvent event : batchEvent.getEvents())
{
handleEvent(event, mfSyncToken);
countUpdated.incrementAndGet();
}
logger.debug("Updated/Deleted {} users", countUpdated);
}
//
// Delete
if (batchEvent.isDeleteAllOtherUsers())
{
final long countDeleted = usersRepo.deleteInBatchByMfSyncTokenNot(mfSyncToken);
logger.debug("Deleted {} users", countDeleted);
}
}
private void handleEvent(@NonNull final MSV3UserChangedEvent event, final String mfSyncToken)
{
if (event.getChangeType() == ChangeType.CREATED_OR_UPDATED)
{
final String username = event.getUsername();
JpaUser user = usersRepo.findByMfMSV3UserId(event.getMsv3MetasfreshUserId().getId());
if (user == null)
{
user = new JpaUser();
user.setMfMSV3UserId(event.getMsv3MetasfreshUserId().getId());
}
user.setMfUsername(username);
user.setMfPassword(event.getPassword());
user.setMfBpartnerId(event.getBpartnerId());
user.setMfBpartnerLocationId(event.getBpartnerLocationId());
user.setMfSyncToken(mfSyncToken);
usersRepo.save(user);
}
else if (event.getChangeType() == ChangeType.DELETED)
{
usersRepo.deleteByMfMSV3UserId(event.getMsv3MetasfreshUserId().getId());
}
else
{
throw new IllegalArgumentException("Unknown change type: " + event);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\security\MSV3ServerAuthenticationService.java | 1 |
请完成以下Java代码 | public class IOUtility extends IOUtil
{
private static Pattern PATTERN_SPACE = Pattern.compile("\\s+");
public static String[] readLineToArray(String line)
{
line = line.trim();
if (line.length() == 0) return new String[0];
return PATTERN_SPACE.split(line);
}
public static int loadInstance(final String path, InstanceHandler handler) throws IOException
{
ConsoleLogger logger = new ConsoleLogger();
int size = 0;
File root = new File(path);
File allFiles[];
if (root.isDirectory())
{
allFiles = root.listFiles(new FileFilter()
{
@Override
public boolean accept(File pathname)
{
return pathname.isFile() && pathname.getName().endsWith(".txt");
}
});
}
else
{
allFiles = new File[]{root};
}
for (File file : allFiles)
{
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String line;
while ((line = br.readLine()) != null)
{
line = line.trim();
if (line.length() == 0)
{
continue;
}
Sentence sentence = Sentence.create(line);
if (sentence.wordList.size() == 0) continue;
++size;
if (size % 1000 == 0)
{
logger.err("%c语料: %dk...", 13, size / 1000);
}
// debug
// if (size == 100) break;
if (handler.process(sentence)) break;
}
}
return size; | }
public static double[] evaluate(Instance[] instances, LinearModel model)
{
int[] stat = new int[2];
for (int i = 0; i < instances.length; i++)
{
evaluate(instances[i], model, stat);
if (i % 100 == 0 || i == instances.length - 1)
{
System.err.printf("%c进度: %.2f%%", 13, (i + 1) / (float) instances.length * 100);
System.err.flush();
}
}
return new double[]{stat[1] / (double) stat[0] * 100};
}
public static void evaluate(Instance instance, LinearModel model, int[] stat)
{
int[] predLabel = new int[instance.length()];
model.viterbiDecode(instance, predLabel);
stat[0] += instance.tagArray.length;
for (int i = 0; i < predLabel.length; i++)
{
if (predLabel[i] == instance.tagArray[i])
{
++stat[1];
}
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\utility\IOUtility.java | 1 |
请完成以下Java代码 | public void refresh(final @NotNull Document document)
{
final AttributesIncludedTabDataKey key = extractKey(document);
final AttributesIncludedTabData data = attributesIncludedTabService.getData(key);
refreshDocumentFromData(document, data);
}
@Override
public SaveResult save(final @NotNull Document document)
{
final AttributesIncludedTabEntityBinding entityBinding = extractEntityBinding(document);
final AttributesIncludedTabData data = attributesIncludedTabService.updateByKey(
extractKey(document),
entityBinding.getAttributeIds(),
(attributeId, field) -> {
final String fieldName = entityBinding.getFieldNameByAttributeId(attributeId);
final IDocumentFieldView documentField = document.getFieldView(fieldName);
if (!documentField.hasChangesToSave())
{
return field;
}
final AttributesIncludedTabFieldBinding fieldBinding = extractFieldBinding(document, fieldName);
return fieldBinding.updateData(
field != null ? field : newDataField(fieldBinding),
documentField);
});
refreshDocumentFromData(document, data);
// Notify the parent document that one of its children were saved (copied from SqlDocumentsRepository)
document.getParentDocument().onChildSaved(document);
return SaveResult.SAVED;
}
private static AttributesIncludedTabDataField newDataField(final AttributesIncludedTabFieldBinding fieldBinding)
{
return AttributesIncludedTabDataField.builder()
.attributeId(fieldBinding.getAttributeId())
.valueType(fieldBinding.getAttributeValueType())
.build(); | }
private void refreshDocumentFromData(@NonNull final Document document, @NonNull final AttributesIncludedTabData data)
{
document.refreshFromSupplier(new AttributesIncludedTabDataAsDocumentValuesSupplier(data));
}
@Override
public void delete(final @NotNull Document document)
{
throw new UnsupportedOperationException();
}
@Override
public String retrieveVersion(final DocumentEntityDescriptor entityDescriptor, final int documentIdAsInt) {return AttributesIncludedTabDataAsDocumentValuesSupplier.VERSION_DEFAULT;}
@Override
public int retrieveLastLineNo(final DocumentQuery query)
{
throw new UnsupportedOperationException();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\attributes_included_tab\AttributesIncludedTabDocumentsRepository.java | 1 |
请完成以下Java代码 | private Money extractESRPaymentAmt(@NonNull final I_ESR_ImportLine esrLine)
{
final BankAccountId bankAccountId = BankAccountId.ofRepoId(esrLine.getESR_Import().getC_BP_BankAccount_ID());
final BankAccount bankAccount = bpBankAccountDAO.getById(bankAccountId);
return Money.of(esrLine.getAmount(), bankAccount.getCurrencyId());
}
@Override
public I_ESR_ImportFile createESRImportFile(@NonNull final I_ESR_Import header)
{
final I_ESR_ImportFile esrImportFile = newInstance(I_ESR_ImportFile.class);
esrImportFile.setESR_Import_ID(header.getESR_Import_ID());
esrImportFile.setAD_Org_ID(header.getAD_Org_ID());
esrImportFile.setC_BP_BankAccount_ID(header.getC_BP_BankAccount_ID());
esrImportFile.setESR_Control_Amount(BigDecimal.ZERO);
saveRecord(esrImportFile);
return esrImportFile;
}
@Override
public ImmutableList<I_ESR_ImportFile> retrieveActiveESRImportFiles(@NonNull final I_ESR_Import esrImport)
{
return queryBL.createQueryBuilder(I_ESR_ImportFile.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_ESR_ImportFile.COLUMNNAME_ESR_Import_ID, esrImport.getESR_Import_ID())
.create()
.listImmutable(I_ESR_ImportFile.class);
}
@Override
public ImmutableList<I_ESR_ImportLine> retrieveActiveESRImportLinesFromFile(@NonNull final I_ESR_ImportFile esrImportFile)
{
return queryBL.createQueryBuilder(I_ESR_ImportLine.class) | .addOnlyActiveRecordsFilter()
.addEqualsFilter(I_ESR_ImportLine.COLUMNNAME_ESR_ImportFile_ID, esrImportFile.getESR_ImportFile_ID())
.create()
.listImmutable(I_ESR_ImportLine.class);
}
@Override
public I_ESR_ImportFile getImportFileById(final int esrImportFileId)
{
return load(esrImportFileId, I_ESR_ImportFile.class);
}
@Override
public void validateEsrImport(final I_ESR_Import esrImport)
{
final ImmutableList<I_ESR_ImportFile> esrImportFiles = retrieveActiveESRImportFiles(esrImport);
final boolean isValid = esrImportFiles.stream()
.allMatch(I_ESR_ImportFile::isValid);
esrImport.setIsValid(isValid);
save(esrImport);
}
@Override
public I_ESR_Import getById(final ESRImportId esrImportId)
{
return load(esrImportId.getRepoId(), I_ESR_Import.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\api\impl\ESRImportDAO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Address {
@Id
@Column(name = "user_id")
private Long id;
@Column(name = "street")
private String street;
@Column(name = "city")
private String city;
@OneToOne
@MapsId
@JoinColumn(name = "user_id")
private User user;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStreet() {
return street;
} | public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
} | repos\tutorials-master\persistence-modules\hibernate-jpa\src\main\java\com\baeldung\hibernate\onetoone\sharedkeybased\Address.java | 2 |
请完成以下Spring Boot application配置 | server:
servlet:
contextPath: /nacos
tomcat:
accesslog:
enabled: true
pattern: '%h %l %u %t "%r" %s %b %D %{User-Agent}i %{Request-Source}i'
basedir: ''
spring:
sql:
init:
platform: mysql
db:
num: 1
password:
'0': ${MYSQL-PWD:root}
url:
'0': jdbc:mysql://${MYSQL-HOST:jeecg-boot-mysql}:${MYSQL-PORT:3306}/${MYSQL-DB:nacos}?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
user:
'0': ${MYSQL-USER:root}
management:
metrics:
export:
elastic:
enabled: false
influx:
enabled: false
nacos:
core:
auth:
enabled: false
caching:
enabled: true
server:
identity:
key: nacos
value: nacos
plugin:
nacos:
token:
expire:
seconds: 18000
secret:
key: VGhpc0lzTXlDdXN0b21TZWNyZXRLZXkwMTIzNDU2Nzg=
| system:
type: nacos
istio:
mcp:
server:
enabled: false
naming:
empty-service:
auto-clean: true
clean:
initial-delay-ms: 50000
period-time-ms: 30000
security:
ignore:
urls: /,/error,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-ui/public/**,/v1/auth/**,/v1/console/health/**,/actuator/**,/v1/console/server/**
standalone: true | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-cloud-nacos\src\main\resources\application-mysql.yml | 2 |
请完成以下Java代码 | public class JsonValueImpl extends SpinValueImpl implements JsonValue {
private static final long serialVersionUID = 1L;
public JsonValueImpl(String value) {
this(null, value, DataFormats.JSON_DATAFORMAT_NAME, false);
}
public JsonValueImpl(SpinJsonNode value) {
this(value, null, value.getDataFormatName(), true);
}
public JsonValueImpl(String value, String dataFormatName) {
this(null, value, dataFormatName, false);
}
public JsonValueImpl(
SpinJsonNode value,
String serializedValue,
String dataFormatName,
boolean isDeserialized) {
this(value, serializedValue, dataFormatName, isDeserialized, false);
}
public JsonValueImpl(
SpinJsonNode value,
String serializedValue,
String dataFormatName,
boolean isDeserialized,
boolean isTransient) { | super(value, serializedValue, dataFormatName, isDeserialized, SpinValueType.JSON, isTransient);
}
@SuppressWarnings("unchecked")
public DataFormat<SpinJsonNode> getDataFormat() {
return (DataFormat<SpinJsonNode>) super.getDataFormat();
}
public JsonValueType getType() {
return (JsonValueType) super.getType();
}
public SpinJsonNode getValue() {
return (SpinJsonNode) super.getValue();
}
} | repos\camunda-bpm-platform-master\engine-plugins\spin-plugin\src\main\java\org\camunda\spin\plugin\variable\value\impl\JsonValueImpl.java | 1 |
请完成以下Java代码 | public StringBuffer get_rss2ChannelCode(StringBuffer xmlCode, boolean showFutureItems)
{
if (this != null) // never null ??
{
xmlCode.append ("<channel>");
xmlCode.append (" <title><![CDATA[" + this.getName ()
+ "]]></title>");
xmlCode.append (" <link>" + this.getLink ()
+ "</link>");
xmlCode.append (" <description><![CDATA["
+ this.getDescription () + "]]></description>");
xmlCode.append (" <language>"
+ this.getAD_Language () + "</language>");
xmlCode.append (" <copyright>" + "" + "</copyright>");
xmlCode.append (" <pubDate>"
+ this.getCreated () + "</pubDate>");
xmlCode.append (" <image>");
xmlCode.append (" <url>" + "" + "</url>");
xmlCode.append (" <title><![CDATA[" + "" + "]]></title>");
xmlCode.append (" <link>" + "" + "</link>");
xmlCode.append (" </image>");
String whereClause = "";
if (!showFutureItems) whereClause = "now()>pubdate";
MNewsItem[] theseItems = getNewsItems(whereClause);
for(int i=0;i<theseItems.length;i++)
xmlCode=theseItems[i].get_rss2ItemCode(xmlCode,this);
xmlCode.append ("</channel>");
} | return xmlCode;
}
/**
* After Save.
* Insert
* - create / update index
* @param newRecord insert
* @param success save success
* @return true if saved
*/
protected boolean afterSave (boolean newRecord, boolean success)
{
if (!success)
return success;
reIndex(newRecord);
return success;
} // afterSave
public void reIndex(boolean newRecord)
{
String [] toBeIndexed = new String[2];
toBeIndexed[0] = this.getName();
toBeIndexed[1] = this.getDescription();
MIndex.reIndex (newRecord, toBeIndexed, getCtx(), getAD_Client_ID(), get_Table_ID(), get_ID(), getCM_WebProject_ID(), this.getUpdated());
}
} // | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MNewsChannel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static MaterialDescriptorQuery forDescriptor(
@NonNull final MaterialDescriptor materialDescriptor,
@NonNull final CustomerIdOperator customerIdOperator,
@Nullable final DateAndSeqNo timeRangeStart,
@Nullable final DateAndSeqNo timeRangeEnd)
{
Check.errorIf(timeRangeStart == null && timeRangeEnd == null, "At least one of timeRangeStart or timeRangeEnd need to be not-null");
return MaterialDescriptorQuery
.builder()
.warehouseId(materialDescriptor.getWarehouseId())
.productId(materialDescriptor.getProductId())
.storageAttributesKey(materialDescriptor.getStorageAttributesKey())
.customer(BPartnerClassifier.specificOrAny(materialDescriptor.getCustomerId()))
.customerIdOperator(customerIdOperator)
.timeRangeStart(timeRangeStart)
.timeRangeEnd(timeRangeEnd)
.build();
}
WarehouseId warehouseId;
int productId;
AttributesKey storageAttributesKey;
BPartnerClassifier customer;
CustomerIdOperator customerIdOperator;
DateAndSeqNo atTime;
DateAndSeqNo timeRangeStart;
DateAndSeqNo timeRangeEnd;
@Builder(toBuilder = true)
private MaterialDescriptorQuery(
final WarehouseId warehouseId,
final int productId,
final AttributesKey storageAttributesKey,
final BPartnerClassifier customer,
final CustomerIdOperator customerIdOperator,
final DateAndSeqNo atTime,
final DateAndSeqNo timeRangeStart,
final DateAndSeqNo timeRangeEnd) | {
this.warehouseId = warehouseId;
this.productId = productId;
this.storageAttributesKey = storageAttributesKey != null
? storageAttributesKey
: AttributesKey.ALL;
this.customerIdOperator = CoalesceUtil.coalesce(customerIdOperator, CustomerIdOperator.GIVEN_ID_ONLY);
this.customer = customer != null ? customer : BPartnerClassifier.any();
if (atTime != null)
{
Check.errorIf(timeRangeStart != null, "If atTime != null, then timeRangeStart needs to be null");
Check.errorIf(timeRangeEnd != null, "If atTime != null, then timeRangeEnd needs to be null");
Check.errorIf(atTime.getOperator() != null, "The instance given as atTime needs to have no operator");
}
if (timeRangeStart != null)
{
Check.errorIf(atTime != null, "If timeRangeStart != null, then atTime needs to be null");
Check.errorIf(timeRangeStart.getOperator() == null, "If timeRangeStart is given, then its operator may not be null");
}
if (timeRangeEnd != null)
{
Check.errorIf(atTime != null, "If timeRangeEnd != null, then atTime needs to be null");
Check.errorIf(timeRangeEnd.getOperator() == null, "If timeRangeEnd is given, then its operator may not be null");
}
this.atTime = atTime;
this.timeRangeStart = timeRangeStart;
this.timeRangeEnd = timeRangeEnd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\query\MaterialDescriptorQuery.java | 2 |
请完成以下Java代码 | public void setA_Asset_Use_ID (int A_Asset_Use_ID)
{
if (A_Asset_Use_ID < 1)
set_ValueNoCheck (COLUMNNAME_A_Asset_Use_ID, null);
else
set_ValueNoCheck (COLUMNNAME_A_Asset_Use_ID, Integer.valueOf(A_Asset_Use_ID));
}
/** Get A_Asset_Use_ID.
@return A_Asset_Use_ID */
public int getA_Asset_Use_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_Asset_Use_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getA_Asset_Use_ID()));
}
/** 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 UseDate.
@param UseDate UseDate */
public void setUseDate (Timestamp UseDate)
{
set_Value (COLUMNNAME_UseDate, UseDate);
}
/** Get UseDate.
@return UseDate */
public Timestamp getUseDate ()
{
return (Timestamp)get_Value(COLUMNNAME_UseDate);
}
/** Set Use units.
@param UseUnits
Currently used units of the assets
*/
public void setUseUnits (int UseUnits)
{
set_Value (COLUMNNAME_UseUnits, Integer.valueOf(UseUnits));
}
/** Get Use units.
@return Currently used units of the assets
*/
public int getUseUnits ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseUnits);
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_A_Asset_Use.java | 1 |
请完成以下Java代码 | public java.lang.String getPostingType ()
{
return (java.lang.String)get_Value(COLUMNNAME_PostingType);
}
/** Set Verarbeiten.
@param Processing Verarbeiten */
@Override
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Verarbeiten.
@return Verarbeiten */
@Override
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public org.compiere.model.I_C_ElementValue getUser1() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser1(org.compiere.model.I_C_ElementValue User1)
{
set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1);
}
/** Set Nutzer 1.
@param User1_ID
User defined list element #1
*/
@Override
public void setUser1_ID (int User1_ID)
{
if (User1_ID < 1)
set_Value (COLUMNNAME_User1_ID, null);
else
set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID));
}
/** Get Nutzer 1. | @return User defined list element #1
*/
@Override
public int getUser1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ElementValue getUser2() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser2(org.compiere.model.I_C_ElementValue User2)
{
set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2);
}
/** Set Nutzer 2.
@param User2_ID
User defined list element #2
*/
@Override
public void setUser2_ID (int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID));
}
/** Get Nutzer 2.
@return User defined list element #2
*/
@Override
public int getUser2_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User2_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_Distribution.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void putPInstanceId(final PInstanceId pinstanceId)
{
map.put(PARAM_AD_PINSTANCE_ID, PInstanceId.toRepoId(pinstanceId));
}
public void putOutputType(final OutputType outputType)
{
put(PARAM_OUTPUTTYPE, outputType);
}
/**
* Gets desired output type
*
* @return {@link OutputType}; never returns null
*/
public OutputType getOutputTypeEffective()
{
final Object outputTypeObj = get(PARAM_OUTPUTTYPE);
if (outputTypeObj instanceof OutputType)
{
return (OutputType)outputTypeObj;
}
else if (outputTypeObj instanceof String)
{
return OutputType.valueOf(outputTypeObj.toString());
}
else
{
return OutputType.JasperPrint;
}
}
public void putReportLanguage(String adLanguage)
{
put(PARAM_REPORT_LANGUAGE, adLanguage);
}
/**
* Extracts {@link Language} parameter
*
* @return {@link Language}; never returns null
*/
public Language getReportLanguageEffective()
{
final Object languageObj = get(PARAM_REPORT_LANGUAGE);
Language currLang = null;
if (languageObj instanceof String)
{
currLang = Language.getLanguage((String)languageObj);
}
else if (languageObj instanceof Language)
{
currLang = (Language)languageObj;
} | if (currLang == null)
{
currLang = Env.getLanguage(Env.getCtx());
}
return currLang;
}
public void putLocale(@Nullable final Locale locale)
{
put(JRParameter.REPORT_LOCALE, locale);
}
@Nullable
public Locale getLocale()
{
return (Locale)get(JRParameter.REPORT_LOCALE);
}
public void putRecordId(final int recordId)
{
put(PARAM_RECORD_ID, recordId);
}
public void putTableId(final int tableId)
{
put(PARAM_AD_Table_ID, tableId);
}
public void putBarcodeURL(final String barcodeURL)
{
put(PARAM_BARCODE_URL, barcodeURL);
}
@Nullable
public String getBarcodeUrl()
{
final Object barcodeUrl = get(PARAM_BARCODE_URL);
return barcodeUrl != null ? barcodeUrl.toString() : null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\JRParametersCollector.java | 2 |
请完成以下Java代码 | public RoleId getRoleId()
{
return roleId;
}
@Override
public int getSeqNo()
{
return seqNo;
}
@Override
public List<IRolesTreeNode> getChildren()
{
return childrenSupplier.get();
}
private ImmutableList<IRolesTreeNode> retrieveChildren()
{
final IRoleDAO roleDAO = Services.get(IRoleDAO.class);
ImmutableList.Builder<IRolesTreeNode> childrenBuilder = ImmutableList.builder();
for (final RoleInclude roleIncludeLink : roleDAO.retrieveRoleIncludes(getRoleId()))
{
final RoleId childRoleId = roleIncludeLink.getChildRoleId();
final int childSeqNo = roleIncludeLink.getSeqNo();
final RolesTreeNode child = new RolesTreeNode(childRoleId, childSeqNo);
childrenBuilder.add(child);
}
//
// Load roles which are temporary assigned to given user
if (substituteForUserId != null)
{
for (final RoleId childRoleId : roleDAO.getSubstituteRoleIds(substituteForUserId, substituteDate))
{
final int childSeqNo = -1; // no particular sequence number
final RolesTreeNode child = new RolesTreeNode(childRoleId, childSeqNo);
childrenBuilder.add(child);
}
}
return childrenBuilder.build();
}
@Override
public <ValueType, AggregatedValueType> ValueType aggregateBottomUp(final BottomUpAggregator<ValueType, AggregatedValueType> aggregator)
{
final LinkedHashMap<RoleId, RolesTreeNode> trace = new LinkedHashMap<>();
return aggregateBottomUp(aggregator, trace); | }
private <ValueType, AggregatedValueType> ValueType aggregateBottomUp(
final BottomUpAggregator<ValueType, AggregatedValueType> aggregator,
final LinkedHashMap<RoleId, RolesTreeNode> trace)
{
// Skip already evaluated notes
final RoleId nodeId = getRoleId();
if (trace.containsKey(nodeId))
{
return null;
}
trace.put(nodeId, this);
//
// If this is a leaf node, return it's leaf value
final List<IRolesTreeNode> children = getChildren();
final boolean isLeaf = children.isEmpty();
if (isLeaf)
{
ValueType value = aggregator.leafValue(this);
return value;
}
final AggregatedValueType valueAgg = aggregator.initialValue(this);
Check.assumeNotNull(valueAgg, "valueAgg shall not be null");
for (final IRolesTreeNode child : children)
{
final RolesTreeNode childImpl = (RolesTreeNode)child;
final ValueType childValue = childImpl.aggregateBottomUp(aggregator, trace);
if (childValue == null)
{
// do nothing
continue;
}
aggregator.aggregateValue(valueAgg, child, childValue);
}
final ValueType value = aggregator.finalValue(valueAgg);
return value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\RolesTreeNode.java | 1 |
请完成以下Java代码 | public class PvmAtomicOperationProcessStart extends AbstractPvmEventAtomicOperation {
@Override
public boolean isAsync(PvmExecutionImpl execution) {
return execution.getActivity().isAsyncBefore();
}
public boolean isAsyncCapable() {
return true;
}
protected ScopeImpl getScope(PvmExecutionImpl execution) {
return execution.getProcessDefinition();
}
protected String getEventName() {
return ExecutionListener.EVENTNAME_START;
}
protected PvmExecutionImpl eventNotificationsStarted(PvmExecutionImpl execution) {
// restoring the starting flag in case this operation is executed
// asynchronously
execution.setProcessInstanceStarting(true);
if (execution.getActivity() != null && execution.getActivity().isAsyncBefore()) {
LegacyBehavior.createMissingHistoricVariables(execution);
} | return execution;
}
protected void eventNotificationsCompleted(PvmExecutionImpl execution) {
execution.continueIfExecutionDoesNotAffectNextOperation(new Callback<PvmExecutionImpl, Void>() {
@Override
public Void callback(PvmExecutionImpl execution) {
execution.dispatchEvent(null);
return null;
}
}, new Callback<PvmExecutionImpl, Void>() {
@Override
public Void callback(PvmExecutionImpl execution) {
execution.setIgnoreAsync(true);
execution.performOperation(ACTIVITY_START_CREATE_SCOPE);
return null;
}
}, execution);
}
public String getCanonicalName() {
return "process-start";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\PvmAtomicOperationProcessStart.java | 1 |
请完成以下Java代码 | public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setShipment_DocumentNo (final @Nullable java.lang.String Shipment_DocumentNo)
{
throw new IllegalArgumentException ("Shipment_DocumentNo is virtual column"); }
@Override
public java.lang.String getShipment_DocumentNo()
{
return get_ValueAsString(COLUMNNAME_Shipment_DocumentNo);
}
@Override
public void setSumDeliveredInStockingUOM (final BigDecimal SumDeliveredInStockingUOM)
{
set_Value (COLUMNNAME_SumDeliveredInStockingUOM, SumDeliveredInStockingUOM);
}
@Override
public BigDecimal getSumDeliveredInStockingUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SumDeliveredInStockingUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSumOrderedInStockingUOM (final BigDecimal SumOrderedInStockingUOM) | {
set_Value (COLUMNNAME_SumOrderedInStockingUOM, SumOrderedInStockingUOM);
}
@Override
public BigDecimal getSumOrderedInStockingUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SumOrderedInStockingUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setUserFlag (final @Nullable java.lang.String UserFlag)
{
set_Value (COLUMNNAME_UserFlag, UserFlag);
}
@Override
public java.lang.String getUserFlag()
{
return get_ValueAsString(COLUMNNAME_UserFlag);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_Desadv.java | 1 |
请完成以下Java代码 | public Optional<AlbertaPatient> getByBPartnerId(@NonNull final BPartnerId bPartnerId)
{
return queryBL.createQueryBuilder(I_C_BPartner_AlbertaPatient.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_BPartner_AlbertaPatient.COLUMNNAME_C_BPartner_ID, bPartnerId)
.create()
.firstOnlyOptional(I_C_BPartner_AlbertaPatient.class)
.map(this::toAlbertaPatient);
}
@NonNull
public AlbertaPatient toAlbertaPatient(@NonNull final I_C_BPartner_AlbertaPatient record)
{
final BPartnerAlbertaPatientId bPartnerAlbertaPatientId = BPartnerAlbertaPatientId.ofRepoId(record.getC_BPartner_AlbertaPatient_ID());
final BPartnerId bPartnerId = BPartnerId.ofRepoId(record.getC_BPartner_ID());
final BPartnerId hospitalId = BPartnerId.ofRepoIdOrNull(record.getC_BPartner_Hospital_ID());
final BPartnerId payerId = BPartnerId.ofRepoIdOrNull(record.getC_BPartner_Payer_ID());
final UserId fieldNurseId = UserId.ofRepoIdOrNull(record.getAD_User_FieldNurse_ID());
final UserId createdById = UserId.ofRepoIdOrNull(record.getAD_User_CreatedBy_ID());
final UserId updatedById = UserId.ofRepoIdOrNull(record.getAD_User_UpdatedBy_ID());
return AlbertaPatient.builder()
.bPartnerAlbertaPatientId(bPartnerAlbertaPatientId)
.bPartnerId(bPartnerId)
.hospitalId(hospitalId)
.dischargeDate(TimeUtil.asLocalDate(record.getDischargeDate(), SystemTime.zoneId()))
.payerId(payerId)
.payerType(PayerType.ofCodeNullable(record.getPayerType()))
.numberOfInsured(record.getNumberOfInsured())
.copaymentFrom(TimeUtil.asLocalDate(record.getCopaymentFrom(), SystemTime.zoneId()))
.copaymentTo(TimeUtil.asLocalDate(record.getCopaymentTo(), SystemTime.zoneId()))
.isTransferPatient(record.isTransferPatient())
.isIVTherapy(record.isIVTherapy())
.fieldNurseId(fieldNurseId)
.deactivationReason(DeactivationReasonType.ofCodeNullable(record.getDeactivationReason()))
.deactivationDate(TimeUtil.asLocalDate(record.getDeactivationDate(), SystemTime.zoneId()))
.deactivationComment(record.getDeactivationComment())
.classification(record.getClassification())
.careDegree(record.getCareDegree()) | .createdAt(TimeUtil.asInstant(record.getCreatedAt()))
.createdById(createdById)
.updatedAt(TimeUtil.asInstant(record.getUpdatedAt()))
.updatedById(updatedById)
.build();
}
private int repoIdFromNullable(@Nullable final RepoIdAware repoIdAware)
{
if (repoIdAware == null)
{
return -1;
}
return repoIdAware.getRepoId();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java\de\metas\vertical\healthcare\alberta\bpartner\patient\AlbertaPatientRepository.java | 1 |
请完成以下Java代码 | default IView getView(@NonNull final ViewId viewId)
{
final IView view = getView(viewId.getViewId());
// Make sure the windowId matches the view's windowId.
// NOTE: for now, if the windowId is not provided, let's not validate it because deprecate API cannot provide the windowId
if (!Objects.equals(viewId.getWindowId(), view.getViewId().getWindowId()))
{
throw new IllegalArgumentException("View's windowId is not matching the expected one."
+ "\n Expected windowId: " + viewId.getWindowId()
+ "\n View: " + view);
}
return view;
}
default <T extends IView> T getView(
final ViewId viewId,
@SuppressWarnings("unused") final Class<T> type)
{
@SuppressWarnings("unchecked") final T view = (T)getView(viewId);
return view;
}
IView createView(CreateViewRequest request);
IView filterView(ViewId viewId, JSONFilterViewRequest jsonRequest);
IView deleteStickyFilter(ViewId viewId, String filterId);
void closeView(ViewId viewId, ViewCloseAction closeAction);
void invalidateView(ViewId viewId);
void invalidateView(IView view); | List<IView> getViews();
/**
* Notify all views that given records was changed (asynchronously).
*/
void notifyRecordsChangedAsync(@NonNull TableRecordReferenceSet recordRefs);
default void notifyRecordsChangedAsync(@NonNull final String tableName, final int recordId)
{
notifyRecordsChangedAsync(TableRecordReferenceSet.of(tableName, recordId));
}
void notifyRecordsChangedNow(@NonNull TableRecordReferenceSet recordRefs);
boolean isWatchedByFrontend(ViewId viewId);
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\IViewsRepository.java | 1 |
请完成以下Java代码 | public class ContainerPartitionPausingBackOffManagerFactory extends AbstractKafkaBackOffManagerFactory {
private @Nullable BackOffHandler backOffHandler;
/**
* Construct an instance with the provided properties.
* @param listenerContainerRegistry the registry.
* @param applicationContext the application context.
*/
@SuppressWarnings("this-escape")
public ContainerPartitionPausingBackOffManagerFactory(@Nullable ListenerContainerRegistry listenerContainerRegistry,
ApplicationContext applicationContext) {
super(listenerContainerRegistry);
setApplicationContext(applicationContext);
} | @Override
protected KafkaConsumerBackoffManager doCreateManager(ListenerContainerRegistry registry) {
Assert.notNull(this.backOffHandler, "a BackOffHandler is required");
return new ContainerPartitionPausingBackOffManager(getListenerContainerRegistry(), this.backOffHandler);
}
/**
* Set the back off handler to use in the created handlers.
* @param backOffHandler the handler.
*/
public void setBackOffHandler(BackOffHandler backOffHandler) {
this.backOffHandler = backOffHandler;
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\ContainerPartitionPausingBackOffManagerFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BookMapper {
public static JsonObject map(Book book) {
JsonObjectBuilder builder = Json.createObjectBuilder();
addValue(builder, "id", book.getId());
addValue(builder, "isbn", book.getIsbn());
addValue(builder, "name", book.getName());
addValue(builder, "author", book.getAuthor());
addValue(builder, "pages", book.getPages());
return builder.build();
}
private static void addValue(JsonObjectBuilder builder, String key, Object value) {
if (value != null) {
builder.add(key, value.toString());
} else {
builder.addNull(key);
}
}
public static JsonArray map(List<Book> books) {
final JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
books.forEach(book -> {
JsonObject jsonObject = map(book);
arrayBuilder.add(jsonObject);
});
return arrayBuilder.build();
}
public static Book map(InputStream is) {
try(JsonReader jsonReader = Json.createReader(is)) {
JsonObject jsonObject = jsonReader.readObject();
Book book = new Book();
book.setId(getStringFromJson("id", jsonObject));
book.setIsbn(getStringFromJson("isbn", jsonObject));
book.setName(getStringFromJson("name", jsonObject));
book.setAuthor(getStringFromJson("author", jsonObject));
book.setPages(getIntFromJson("pages",jsonObject));
return book;
} | }
private static String getStringFromJson(String key, JsonObject json) {
String returnedString = null;
if (json.containsKey(key)) {
JsonString value = json.getJsonString(key);
if (value != null) {
returnedString = value.getString();
}
}
return returnedString;
}
private static Integer getIntFromJson(String key, JsonObject json) {
Integer returnedValue = null;
if (json.containsKey(key)) {
JsonNumber value = json.getJsonNumber(key);
if (value != null) {
returnedValue = value.intValue();
}
}
return returnedValue;
}
} | repos\tutorials-master\microservices-modules\helidon\helidon-mp\src\main\java\com\baeldung\microprofile\util\BookMapper.java | 2 |
请完成以下Java代码 | public void setEDI_Desadv_Parent_Pack_ID (final int EDI_Desadv_Parent_Pack_ID)
{
if (EDI_Desadv_Parent_Pack_ID < 1)
set_Value (COLUMNNAME_EDI_Desadv_Parent_Pack_ID, null);
else
set_Value (COLUMNNAME_EDI_Desadv_Parent_Pack_ID, EDI_Desadv_Parent_Pack_ID);
}
@Override
public int getEDI_Desadv_Parent_Pack_ID()
{
return get_ValueAsInt(COLUMNNAME_EDI_Desadv_Parent_Pack_ID);
}
@Override
public void setGTIN_PackingMaterial (final @Nullable java.lang.String GTIN_PackingMaterial)
{
set_Value (COLUMNNAME_GTIN_PackingMaterial, GTIN_PackingMaterial);
}
@Override
public java.lang.String getGTIN_PackingMaterial()
{
return get_ValueAsString(COLUMNNAME_GTIN_PackingMaterial);
}
@Override
public void setIPA_SSCC18 (final java.lang.String IPA_SSCC18)
{
set_Value (COLUMNNAME_IPA_SSCC18, IPA_SSCC18);
}
@Override
public java.lang.String getIPA_SSCC18()
{
return get_ValueAsString(COLUMNNAME_IPA_SSCC18);
}
@Override
public void setIsManual_IPA_SSCC18 (final boolean IsManual_IPA_SSCC18)
{
set_Value (COLUMNNAME_IsManual_IPA_SSCC18, IsManual_IPA_SSCC18);
}
@Override
public boolean isManual_IPA_SSCC18()
{
return get_ValueAsBoolean(COLUMNNAME_IsManual_IPA_SSCC18);
}
@Override
public void setM_HU_ID (final int M_HU_ID)
{
if (M_HU_ID < 1)
set_Value (COLUMNNAME_M_HU_ID, null);
else
set_Value (COLUMNNAME_M_HU_ID, M_HU_ID);
}
@Override
public int getM_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_ID);
}
@Override
public void setM_HU_PackagingCode_ID (final int M_HU_PackagingCode_ID)
{
if (M_HU_PackagingCode_ID < 1)
set_Value (COLUMNNAME_M_HU_PackagingCode_ID, null);
else
set_Value (COLUMNNAME_M_HU_PackagingCode_ID, M_HU_PackagingCode_ID);
}
@Override
public int getM_HU_PackagingCode_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PackagingCode_ID);
}
@Override
public void setM_HU_PackagingCode_Text (final @Nullable java.lang.String M_HU_PackagingCode_Text)
{
throw new IllegalArgumentException ("M_HU_PackagingCode_Text is virtual column"); }
@Override | public java.lang.String getM_HU_PackagingCode_Text()
{
return get_ValueAsString(COLUMNNAME_M_HU_PackagingCode_Text);
}
@Override
public org.compiere.model.I_M_InOut getM_InOut()
{
return get_ValueAsPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class);
}
@Override
public void setM_InOut(final org.compiere.model.I_M_InOut M_InOut)
{
set_ValueFromPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class, M_InOut);
}
@Override
public void setM_InOut_ID (final int M_InOut_ID)
{
throw new IllegalArgumentException ("M_InOut_ID is virtual column"); }
@Override
public int getM_InOut_ID()
{
return get_ValueAsInt(COLUMNNAME_M_InOut_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_Desadv_Pack.java | 1 |
请完成以下Java代码 | public Optional<FAOpenItemTrxInfo> computeTrxInfo(@NonNull final FAOpenItemTrxInfoComputeRequest request)
{
final FAOpenItemsHandler handler = getHandler(request.getAccountConceptualName(), request.getTableName());
return handler.computeTrxInfo(request);
}
@NonNull
private FAOpenItemsHandler getHandler(@Nullable final AccountConceptualName accountConceptualName, @NonNull String docTableName)
{
if (accountConceptualName != null)
{
final FAOpenItemsHandler handler = handlersByKey.get(FAOpenItemsHandlerMatchingKey.of(accountConceptualName, docTableName));
if (handler != null)
{
return handler;
}
}
return genericOIHandler;
}
public int processScheduled()
{
final int batchSize = getProcessingBatchSize();
final Stopwatch stopwatch = Stopwatch.createStarted();
final int count = DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited,
"SELECT de_metas_acct.fact_acct_openItems_to_update_process(p_BatchSize:=?)",
batchSize);
stopwatch.stop();
logger.debug("Processed {} records in {} (batchSize={})", count, stopwatch, batchSize);
return count;
}
private int getProcessingBatchSize()
{
final int batchSize = sysConfigBL.getIntValue(SYSCONFIG_ProcessingBatchSize, -1);
return batchSize > 0 ? batchSize : DEFAULT_ProcessingBatchSize;
}
public void fireGLJournalCompleted(final SAPGLJournal glJournal)
{
for (SAPGLJournalLine line : glJournal.getLines())
{
final FAOpenItemTrxInfo openItemTrxInfo = line.getOpenItemTrxInfo();
if (openItemTrxInfo == null) | {
continue;
}
handlersByKey.values()
.stream()
.distinct()
.forEach(handler -> handler.onGLJournalLineCompleted(line));
}
}
public void fireGLJournalReactivated(final SAPGLJournal glJournal)
{
for (SAPGLJournalLine line : glJournal.getLines())
{
final FAOpenItemTrxInfo openItemTrxInfo = line.getOpenItemTrxInfo();
if (openItemTrxInfo == null)
{
continue;
}
handlersByKey.values().forEach(handler -> handler.onGLJournalLineReactivated(line));
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\open_items\FAOpenItemsService.java | 1 |
请完成以下Java代码 | class UserRequestModel {
String name;
String password;
public UserRequestModel() {
super();
}
UserRequestModel(String name, String password) {
super();
this.name = name;
this.password = password;
}
String getName() { | return name;
}
void setName(String name) {
this.name = name;
}
String getPassword() {
return password;
}
void setPassword(String password) {
this.password = password;
}
} | repos\tutorials-master\patterns-modules\clean-architecture\src\main\java\com\baeldung\pattern\cleanarchitecture\usercreation\UserRequestModel.java | 1 |
请完成以下Java代码 | public List<Exception> getExecutionErrors()
{
if (executionErrors == null)
{
return Collections.emptyList();
}
else
{
return new ArrayList<>(executionErrors);
}
}
private final void log(String msg, String resolution, boolean isError)
{
if (isError && !logger.isErrorEnabled())
{
return;
}
if (!isError && !logger.isInfoEnabled())
{
return;
}
final StringBuffer sb = new StringBuffer();
sb.append(Services.get(IMigrationBL.class).getSummary(migration));
if (!Check.isEmpty(msg, true)) | {
sb.append(": ").append(msg.trim());
}
if (resolution != null)
{
sb.append(" [").append(resolution).append("]");
}
if (isError)
{
logger.error(sb.toString());
}
else
{
logger.info(sb.toString());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\MigrationExecutor.java | 1 |
请完成以下Java代码 | private static ViewLayout.Builder newViewLayout()
{
return ViewLayout.builder()
//
.setHasTreeSupport(true)
.setTreeCollapsible(false)
.setTreeExpandedDepth(Integer.MAX_VALUE);
}
@Override
public ProductsToPickView createView(final @NonNull CreateViewRequest request)
{
throw new UnsupportedOperationException();
}
public ProductsToPickView createView(@NonNull final PackageableRow packageableRow)
{
final ViewId viewId = ViewId.random(PickingConstantsV2.WINDOWID_ProductsToPickView);
final ProductsToPickRowsData rowsData = rowsService.createProductsToPickRowsData(packageableRow);
final ProductsToPickView view = ProductsToPickView.builder()
.viewId(viewId)
.rowsData(rowsData)
.headerProperties(extractViewHeaderProperties(packageableRow))
//
// Picker processes:
.relatedProcessDescriptor(createProcessDescriptor(ProductsToPick_PickSelected.class))
.relatedProcessDescriptor(createProcessDescriptor(ProductsToPick_MarkWillNotPickSelected.class))
.relatedProcessDescriptor(createProcessDescriptor(ProductsToPick_SetPackingInstructions.class))
.relatedProcessDescriptor(createProcessDescriptor(ProductsToPick_Request4EyesReview.class))
.relatedProcessDescriptor(createProcessDescriptor(ProductsToPick_PickAndPackSelected.class))
//
// Reviewer processes:
.relatedProcessDescriptor(createProcessDescriptor(ProductsToPick_4EyesReview_ProcessAll.class))
//
.build();
viewsRepository.getViewsStorageFor(viewId).put(view);
return view;
} | private ViewHeaderProperties extractViewHeaderProperties(@NonNull final PackageableRow packageableRow)
{
final IMsgBL msgs = Services.get(IMsgBL.class);
return ViewHeaderProperties.builder()
.group(ViewHeaderPropertiesGroup.builder()
.entry(ViewHeaderProperty.builder()
.caption(msgs.translatable("OrderDocumentNo"))
.value(packageableRow.getOrderDocumentNo())
.build())
.entry(ViewHeaderProperty.builder()
.caption(msgs.translatable("C_BPartner_ID"))
.value(packageableRow.getCustomer().getDisplayNameTrl())
.build())
.entry(ViewHeaderProperty.builder()
.caption(msgs.translatable("PreparationDate"))
.value(packageableRow.getPreparationDate())
.build())
.build())
.build();
}
private RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass)
{
final IADProcessDAO adProcessDAO = Services.get(IADProcessDAO.class);
final AdProcessId processId = adProcessDAO.retrieveProcessIdByClass(processClass);
return RelatedProcessDescriptor.builder()
.processId(processId)
.anyTable()
.anyWindow()
.displayPlace(DisplayPlace.ViewQuickActions)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\ProductsToPickViewFactory.java | 1 |
请完成以下Java代码 | public class ListItem
{
/**
* ListItem
* @param ID
* @param Name
* @param Description
* @param summary
* @param ImageIndicator
*/
public ListItem (int ID, String Name, String Description,
boolean summary, String ImageIndicator)
{
id = ID;
name = Name;
description = Description;
isSummary = summary;
imageIndicator = ImageIndicator;
} // ListItem
/** ID */
public int id;
/** Name */
public String name;
/** Description */
public String description;
/** Summary */ | public boolean isSummary;
/** Indicator */
public String imageIndicator; // Menu - Action
/**
* To String
* @return String Representation
*/
@Override
public String toString ()
{
String retValue = name;
if (description != null && description.length() > 0)
retValue += " (" + description + ")";
return retValue;
} // toString
} // ListItem
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\TreeMaintenance.java | 1 |
请完成以下Java代码 | public ActivityImpl getCurrentActivity(CommandContext commandContext, JobEntity job) {
String type = job.getJobHandlerType();
ActivityImpl activity = null;
if (SUPPORTED_TYPES.contains(type)) {
DeploymentCache deploymentCache = Context.getProcessEngineConfiguration().getDeploymentCache();
ProcessDefinitionEntity processDefinitionEntity =
deploymentCache.findDeployedProcessDefinitionById(job.getProcessDefinitionId());
activity = processDefinitionEntity.findActivity(job.getActivityId());
} else {
// noop, because activity type is not supported
}
return activity;
}
protected ExecutionEntity fetchExecutionEntity(String executionId) {
return Context.getCommandContext()
.getExecutionManager()
.findExecutionById(executionId);
}
public FailedJobRetryConfiguration getFailedJobRetryConfiguration(JobEntity job, ActivityImpl activity) {
FailedJobRetryConfiguration retryConfiguration = activity.getProperties().get(DefaultFailedJobParseListener.FAILED_JOB_CONFIGURATION);
while (retryConfiguration != null && retryConfiguration.getExpression() != null) {
String retryIntervals = getFailedJobRetryTimeCycle(job, retryConfiguration.getExpression());
retryConfiguration = ParseUtil.parseRetryIntervals(retryIntervals);
}
return retryConfiguration;
}
protected String getFailedJobRetryTimeCycle(JobEntity job, Expression expression) {
String executionId = job.getExecutionId();
ExecutionEntity execution = null;
if (executionId != null) {
execution = fetchExecutionEntity(executionId);
}
Object value = null;
if (expression == null) {
return null;
}
try {
value = expression.getValue(execution, execution);
}
catch (Exception e) { | LOG.exceptionWhileParsingExpression(jobId, e.getCause().getMessage());
}
if (value instanceof String) {
return (String) value;
}
else
{
// default behavior
return null;
}
}
protected DurationHelper getDurationHelper(String failedJobRetryTimeCycle) throws Exception {
return new DurationHelper(failedJobRetryTimeCycle);
}
protected boolean isFirstJobExecution(JobEntity job) {
// check if this is jobs' first execution (recognize
// this because no exception is set. Only the first
// execution can be without exception - because if
// no exception occurred the job would have been completed)
// see https://app.camunda.com/jira/browse/CAM-1039
return job.getExceptionByteArrayId() == null && job.getExceptionMessage() == null;
}
protected void initializeRetries(JobEntity job, int retries) {
LOG.debugInitiallyAppyingRetryCycleForJob(job.getId(), retries);
job.setRetries(retries);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DefaultJobRetryCmd.java | 1 |
请完成以下Java代码 | public static class Builder<B extends Builder<B>>
extends AbstractOAuth2TokenAuthenticationBuilder<OAuth2AccessToken, B> {
private Map<String, Object> attributes;
protected Builder(BearerTokenAuthentication token) {
super(token);
this.attributes = token.getTokenAttributes();
}
/**
* Use this principal. Must be of type {@link OAuth2AuthenticatedPrincipal}
* @param principal the principal to use
* @return the {@link Builder} for further configurations
*/
@Override
public B principal(@Nullable Object principal) {
Assert.isInstanceOf(OAuth2AuthenticatedPrincipal.class, principal,
"principal must be of type OAuth2AuthenticatedPrincipal");
this.attributes = ((OAuth2AuthenticatedPrincipal) principal).getAttributes();
return super.principal(principal);
}
/**
* A synonym for {@link #token(OAuth2AccessToken)}
* @param token the token to use
* @return the {@link Builder} for further configurations
*/
@Override
public B credentials(@Nullable Object token) {
Assert.isInstanceOf(OAuth2AccessToken.class, token, "token must be of type OAuth2AccessToken");
return token((OAuth2AccessToken) token);
} | /**
* Use this token. Must have a {@link OAuth2AccessToken#getTokenType()} as
* {@link OAuth2AccessToken.TokenType#BEARER}.
* @param token the token to use
* @return the {@link Builder} for further configurations
*/
@Override
public B token(OAuth2AccessToken token) {
Assert.isTrue(token.getTokenType() == OAuth2AccessToken.TokenType.BEARER, "token must be a bearer token");
super.credentials(token);
return super.token(token);
}
/**
* {@inheritDoc}
*/
@Override
public BearerTokenAuthentication build() {
return new BearerTokenAuthentication(this);
}
}
} | repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\authentication\BearerTokenAuthentication.java | 1 |
请完成以下Java代码 | class BeanNamePlaceholderRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor, Ordered {
private Environment environment;
BeanNamePlaceholderRegistryPostProcessor(Environment environment) {
this.environment = environment;
}
/** {@inheritDoc} */
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
DefaultListableBeanFactory bf = (DefaultListableBeanFactory) registry;
Stream.of(bf.getBeanDefinitionNames())
//Look for beans with placeholders name format: '${placeholder}' or '${placeholder:defaultValue}'
.filter(name -> name.matches("\\$\\{[\\w.-]+(?>:[\\w.-]+)?\\}"))
.forEach(placeholder -> {
String actualName = environment.resolveRequiredPlaceholders(placeholder);
BeanDefinition bd = bf.getBeanDefinition(placeholder);
bf.removeBeanDefinition(placeholder);
bf.registerBeanDefinition(actualName, bd); | log.debug("Registering new name '{}' for Bean definition with placeholder name: {}", actualName, placeholder);
});
}
/** {@inheritDoc} */
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
/** {@inheritDoc} */
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE - 1;
}
} | repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\configuration\BeanNamePlaceholderRegistryPostProcessor.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.