instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public static class ConditionAndOutcome {
private final Condition condition;
private final ConditionOutcome outcome;
public ConditionAndOutcome(Condition condition, ConditionOutcome outcome) {
this.condition = condition;
this.outcome = outcome;
}
public Condition getCondition() {
return this.condition;
}
public ConditionOutcome getOutcome() {
return this.outcome;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
ConditionAndOutcome other = (ConditionAndOutcome) obj;
return (ObjectUtils.nullSafeEquals(this.condition.getClass(), other.condition.getClass())
&& ObjectUtils.nullSafeEquals(this.outcome, other.outcome));
}
@Override
public int hashCode() { | return this.condition.getClass().hashCode() * 31 + this.outcome.hashCode();
}
@Override
public String toString() {
return this.condition.getClass() + " " + this.outcome;
}
}
private static final class AncestorsMatchedCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
throw new UnsupportedOperationException();
}
}
} | repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\condition\ConditionEvaluationReport.java | 2 |
请完成以下Java代码 | public void checkIfEndsWithCalendarYear(final I_C_Flatrate_Transition transition)
{
final boolean endsWithCalendarYear = transition.isEndsWithCalendarYear();
if (endsWithCalendarYear == false)
{
// nothing to do
return;
}
/*
* If EndsWithCalendarYear='Y', then the selected C_Calendar_Contract_ID needs to meet the following conditions: for every C_Year of the calendar Length: DatenEnd of the C_Year's last period
* must be one year after DateStart of the C_Year's first period No gaps: For every period A of a given calendar, there must be either another period B with B's StartDate beeing A's EndDate
* plus one day or no later period (within the same calendar!) at all No overlap: for every C_Calendar and every point in time t, there may be at most one C_Period with StartDate <= t <=
* EndDate
*/
final ICalendarBL calendarBL = Services.get(ICalendarBL.class);
final I_C_Calendar calendarContract = transition.getC_Calendar_Contract();
calendarBL.checkCorrectCalendar(calendarContract);
final String termDurationUnit = transition.getTermDurationUnit(); | final int termDuration = transition.getTermDuration();
if (X_C_Flatrate_Transition.TERMDURATIONUNIT_JahrE.equals(termDurationUnit))
{
// Nothing to do
return;
}
else
{
if (X_C_Flatrate_Transition.TERMDURATIONUNIT_MonatE.equals(termDurationUnit))
{
if (termDuration % 12 == 0)
{
// This is correct, nothing to do
return;
}
}
}
// Not a suitable situation for a transition ending with calendar year
throw new AdempiereException("@" + MSG_TRANSITION_ERROR_ENDS_WITH_CALENDAR_YEAR + "@");
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\interceptor\C_Flatrate_Transition.java | 1 |
请完成以下Java代码 | protected ListenableFuture<TsKvLatestRemovingResult> getRemoveLatestFuture(TenantId tenantId, EntityId entityId, DeleteTsKvQuery query) {
ListenableFuture<TsKvEntry> latestFuture = service.submit(() -> doFindLatestSync(entityId, query.getKey()));
return Futures.transformAsync(latestFuture, latest -> {
if (latest == null) {
return Futures.immediateFuture(new TsKvLatestRemovingResult(query.getKey(), false));
}
boolean isRemoved = false;
Long version = null;
long ts = latest.getTs();
if (ts >= query.getStartTs() && ts < query.getEndTs()) {
version = transactionTemplate.execute(status -> jdbcTemplate.query("DELETE FROM ts_kv_latest WHERE entity_id = ? " +
"AND key = ? RETURNING nextval('ts_kv_latest_version_seq')",
rs -> rs.next() ? rs.getLong(1) : null, entityId.getId(), keyDictionaryDao.getOrSaveKeyId(query.getKey())));
isRemoved = true;
if (query.getRewriteLatestIfDeleted()) {
return getNewLatestEntryFuture(tenantId, entityId, query, version);
}
}
return Futures.immediateFuture(new TsKvLatestRemovingResult(query.getKey(), isRemoved, version));
}, MoreExecutors.directExecutor());
}
protected ListenableFuture<List<TsKvEntry>> getFindAllLatestFuture(EntityId entityId) {
return service.submit(() ->
DaoUtil.convertDataList(Lists.newArrayList(
searchTsKvLatestRepository.findAllByEntityId(entityId.getId()))));
}
protected ListenableFuture<Long> getSaveLatestFuture(EntityId entityId, TsKvEntry tsKvEntry) { | TsKvLatestEntity latestEntity = new TsKvLatestEntity();
latestEntity.setEntityId(entityId.getId());
latestEntity.setTs(tsKvEntry.getTs());
latestEntity.setKey(keyDictionaryDao.getOrSaveKeyId(tsKvEntry.getKey()));
latestEntity.setStrValue(tsKvEntry.getStrValue().orElse(null));
latestEntity.setDoubleValue(tsKvEntry.getDoubleValue().orElse(null));
latestEntity.setLongValue(tsKvEntry.getLongValue().orElse(null));
latestEntity.setBooleanValue(tsKvEntry.getBooleanValue().orElse(null));
latestEntity.setJsonValue(tsKvEntry.getJsonValue().orElse(null));
return tsLatestQueue.add(latestEntity);
}
protected TsKvEntry wrapNullTsKvEntry(final String key, final TsKvEntry latest) {
if (latest == null) {
return new BasicTsKvEntry(System.currentTimeMillis(), new StringDataEntry(key, null));
}
return latest;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sqlts\SqlTimeseriesLatestDao.java | 1 |
请完成以下Java代码 | public class TbSqlBlockingQueueWrapper<E, R> {
private final CopyOnWriteArrayList<TbSqlBlockingQueue<E, R>> queues = new CopyOnWriteArrayList<>();
private final TbSqlBlockingQueueParams params;
private final Function<E, Integer> hashCodeFunction;
private final int maxThreads;
private final StatsFactory statsFactory;
/**
* Starts TbSqlBlockingQueues.
*
* @param logExecutor executor that will be printing logs and statistics
* @param saveFunction function to save entities in database
* @param batchUpdateComparator comparator to sort entities by primary key to avoid deadlocks in cluster mode
* NOTE: you must use all of primary key parts in your comparator
*/
public void init(ScheduledLogExecutorComponent logExecutor, Consumer<List<E>> saveFunction, Comparator<E> batchUpdateComparator) {
init(logExecutor, l -> { saveFunction.accept(l); return null; }, batchUpdateComparator, l -> l);
}
public void init(ScheduledLogExecutorComponent logExecutor, Function<List<E>, List<R>> saveFunction, Comparator<E> batchUpdateComparator, Function<List<TbSqlQueueElement<E, R>>, List<TbSqlQueueElement<E, R>>> filter) {
for (int i = 0; i < maxThreads; i++) {
MessagesStats stats = statsFactory.createMessagesStats(params.getStatsNamePrefix() + ".queue." + i); | TbSqlBlockingQueue<E, R> queue = new TbSqlBlockingQueue<>(params, stats);
queues.add(queue);
queue.init(logExecutor, saveFunction, batchUpdateComparator, filter, i);
}
}
public ListenableFuture<R> add(E element) {
int queueIndex = element != null ? (hashCodeFunction.apply(element) & 0x7FFFFFFF) % maxThreads : 0;
return queues.get(queueIndex).add(element);
}
public void destroy() {
queues.forEach(TbSqlBlockingQueue::destroy);
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\TbSqlBlockingQueueWrapper.java | 1 |
请完成以下Java代码 | public void setTotal(int total) {
this.total = total;
}
public void setPage(int page) {
this.page = page;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public void setPageData(List pageData) {
this.pageData = pageData;
} | public long getTotal() {
return total;
}
public int getPage() {
return page;
}
public int getPageSize() {
return pageSize;
}
public List getPageData() {
return pageData;
}
} | repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\entity\PageListVO.java | 1 |
请完成以下Java代码 | public Object gridConvertAfterLoad(final Info_Column infoColumn, final int rowIndexModel, final int rowRecordId, final Object data)
{
return data;
}
@Override
public int getParameterCount()
{
return 0;
}
@Override
public String getLabel(final int index)
{
return null;
}
@Override
public Object getParameterComponent(final int index)
{
return null;
}
@Override
public Object getParameterToComponent(final int index)
{
return null;
}
@Override
public Object getParameterValue(final int index, final boolean returnValueTo)
{
return null;
}
@Override
public String[] getWhereClauses(final List<Object> params)
{
return new String[0];
}
@Override
public String getText()
{
return null;
}
@Override
public void save(final Properties ctx, final int windowNo, final IInfoWindowGridRowBuilders builders)
{
for (final Map.Entry<Integer, Integer> e : recordId2asi.entrySet())
{
final Integer recordId = e.getKey();
if (recordId == null || recordId <= 0)
{
continue;
}
final Integer asiId = e.getValue();
if (asiId == null || asiId <= 0)
{
continue;
} | final OrderLineProductASIGridRowBuilder productQtyBuilder = new OrderLineProductASIGridRowBuilder();
productQtyBuilder.setSource(recordId, asiId);
builders.addGridTabRowBuilder(recordId, productQtyBuilder);
}
}
@Override
public void prepareEditor(final CEditor editor, final Object value, final int rowIndexModel, final int columnIndexModel)
{
final VPAttributeContext attributeContext = new VPAttributeContext(rowIndexModel);
editor.putClientProperty(IVPAttributeContext.ATTR_NAME, attributeContext);
// nothing
}
@Override
public String getProductCombinations()
{
// nothing to do
return null;
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\InfoProductASIController.java | 1 |
请完成以下Java代码 | public int getCS_Creditpass_CP_Fallback_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CS_Creditpass_CP_Fallback_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* FallbackPaymentRule AD_Reference_ID=195
* Reference name: _Payment Rule
*/
public static final int FALLBACKPAYMENTRULE_AD_Reference_ID=195;
/** Cash = B */
public static final String FALLBACKPAYMENTRULE_Cash = "B";
/** CreditCard = K */
public static final String FALLBACKPAYMENTRULE_CreditCard = "K";
/** DirectDeposit = T */
public static final String FALLBACKPAYMENTRULE_DirectDeposit = "T";
/** Check = S */
public static final String FALLBACKPAYMENTRULE_Check = "S";
/** OnCredit = P */
public static final String FALLBACKPAYMENTRULE_OnCredit = "P";
/** DirectDebit = D */
public static final String FALLBACKPAYMENTRULE_DirectDebit = "D";
/** Mixed = M */
public static final String FALLBACKPAYMENTRULE_Mixed = "M";
/** Rückerstattung = E */
public static final String PAYMENTRULE_Reimbursement = "E";
/** Verrechnung = F */ | public static final String PAYMENTRULE_Settlement = "F";
/** Set Zahlart Rückgriff.
@param FallbackPaymentRule Zahlart Rückgriff */
@Override
public void setFallbackPaymentRule (java.lang.String FallbackPaymentRule)
{
set_Value (COLUMNNAME_FallbackPaymentRule, FallbackPaymentRule);
}
/** Get Zahlart Rückgriff.
@return Zahlart Rückgriff */
@Override
public java.lang.String getFallbackPaymentRule ()
{
return (java.lang.String)get_Value(COLUMNNAME_FallbackPaymentRule);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java-gen\de\metas\vertical\creditscore\creditpass\model\X_CS_Creditpass_CP_Fallback.java | 1 |
请完成以下Java代码 | private BPartner createRecipient(@NonNull final I_C_Invoice invoiceRecord)
{
final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class);
final I_C_BPartner_Location bPartnerLocationRecord = bpartnerDAO.getBPartnerLocationByIdEvenInactive(BPartnerLocationId.ofRepoId(invoiceRecord.getC_BPartner_ID(), invoiceRecord.getC_BPartner_Location_ID()));
final BPartnerId bPartnerId = BPartnerId.ofRepoId(invoiceRecord.getC_BPartner_ID());
final GLN gln; // may be null, but that's the specific ExportClient's business to check
if (Check.isBlank(bPartnerLocationRecord.getGLN()))
{
logger.debug("The given invoice's C_BPartner_Location has no GLN; -> unable to set a recipient GLN; invoiceRecord={}; bpartnerLocation={}",
invoiceRecord, bPartnerLocationRecord);
gln = null;
}
else
{
gln = GLN.of(bPartnerLocationRecord.getGLN());
}
final BPartner recipient = BPartner.builder()
.id(bPartnerId)
.gln(gln).build();
return recipient;
}
private BPartner createBiller(@NonNull final I_C_Invoice invoiceRecord)
{
final IBPartnerOrgBL bpartnerOrgBL = Services.get(IBPartnerOrgBL.class);
final I_C_BPartner orgBPartner = bpartnerOrgBL.retrieveLinkedBPartner(invoiceRecord.getAD_Org_ID());
Check.assumeNotNull(orgBPartner, InvoiceToExportFactoryException.class,
"The given invoice's org needs to have a linked bPartner; AD_Org_ID={}; invoiceRecord={};", invoiceRecord.getAD_Org_ID(), invoiceRecord);
final IBPartnerDAO bPartnerDAO = Services.get(IBPartnerDAO.class);
final BPartnerLocationQuery query = BPartnerLocationQuery
.builder()
.type(Type.REMIT_TO)
.bpartnerId(de.metas.bpartner.BPartnerId.ofRepoId(orgBPartner.getC_BPartner_ID()))
.build();
final I_C_BPartner_Location remittoLocation = bPartnerDAO.retrieveBPartnerLocation(query);
final GLN gln;
if (remittoLocation == null) | {
logger.debug("The given invoice's orgBPartner has no remit-to location; -> unable to set a biller GLN; orgBPartner={}; invoiceRecord={}",
orgBPartner, invoiceRecord);
gln = null;
}
else if (Check.isBlank(remittoLocation.getGLN()))
{
logger.debug("The given invoice's orgBPartner's remit-to location has no GLN; -> unable to set a biller GLN; orgBPartner={}; invoiceRecord={}; remittoLocation={}",
orgBPartner, invoiceRecord, remittoLocation);
gln = null;
}
else
{
gln = GLN.of(remittoLocation.getGLN());
}
final BPartner biller = BPartner.builder()
.id(BPartnerId.ofRepoId(orgBPartner.getC_BPartner_ID()))
.gln(gln).build();
return biller;
}
public static final class InvoiceToExportFactoryException extends AdempiereException implements ExceptionWithOwnHeaderMessage
{
private static final long serialVersionUID = 5678496542883367180L;
public InvoiceToExportFactoryException(@NonNull final String msg)
{
super(msg);
this.markAsUserValidationError(); // propagate error to the user
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\export\InvoiceToExportFactory.java | 1 |
请完成以下Java代码 | public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Boolean getSkipDownLoad() {
return skipDownLoad;
}
public void setSkipDownLoad(Boolean skipDownLoad) {
this.skipDownLoad = skipDownLoad;
}
public String getTifPreviewType() {
return tifPreviewType;
}
public void setTifPreviewType(String previewType) {
this.tifPreviewType = previewType; | }
public Boolean forceUpdatedCache() {
return forceUpdatedCache;
}
public void setForceUpdatedCache(Boolean forceUpdatedCache) {
this.forceUpdatedCache = forceUpdatedCache;
}
public String getKkProxyAuthorization() {
return kkProxyAuthorization;
}
public void setKkProxyAuthorization(String kkProxyAuthorization) {
this.kkProxyAuthorization = kkProxyAuthorization;
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\model\FileAttribute.java | 1 |
请完成以下Java代码 | public void onOccur(CmmnActivityExecution execution) {
String id = execution.getId();
throw LOG.illegalStateTransitionException("occur", id, getTypeName());
}
// sentry ///////////////////////////////////////////////////////////////
public void fireEntryCriteria(CmmnActivityExecution execution) {
boolean manualActivation = evaluateManualActivationRule(execution);
if (manualActivation) {
execution.enable();
} else {
execution.start();
}
}
// manual activation rule ////////////////////////////////////////////// | protected boolean evaluateManualActivationRule(CmmnActivityExecution execution) {
boolean manualActivation = false;
CmmnActivity activity = execution.getActivity();
Object manualActivationRule = activity.getProperty(PROPERTY_MANUAL_ACTIVATION_RULE);
if (manualActivationRule != null) {
CaseControlRule rule = (CaseControlRule) manualActivationRule;
manualActivation = rule.evaluate(execution);
}
return manualActivation;
}
// helper ///////////////////////////////////////////////////////////
protected abstract String getTypeName();
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\StageOrTaskActivityBehavior.java | 1 |
请完成以下Java代码 | public CostAmount round(@NonNull final Function<CurrencyId, CurrencyPrecision> precisionProvider)
{
final Money valueNew = value.round(precisionProvider);
final Money sourceValueNew = sourceValue != null ? sourceValue.round(precisionProvider) : null;
if (Money.equals(value, valueNew)
&& Money.equals(sourceValue, sourceValueNew))
{
return this;
}
else
{
return new CostAmount(valueNew, sourceValueNew);
}
}
public CostAmount roundToPrecisionIfNeeded(final CurrencyPrecision precision)
{
final Money valueRounded = value.roundIfNeeded(precision);
if (Money.equals(value, valueRounded))
{
return this;
}
else
{
return new CostAmount(valueRounded, sourceValue);
}
}
public CostAmount roundToCostingPrecisionIfNeeded(final AcctSchema acctSchema)
{
final AcctSchemaCosting acctSchemaCosting = acctSchema.getCosting();
final CurrencyPrecision precision = acctSchemaCosting.getCostingPrecision();
return roundToPrecisionIfNeeded(precision);
}
@NonNull
public CostAmount subtract(@NonNull final CostAmount amtToSubtract)
{
assertCurrencyMatching(amtToSubtract);
if (amtToSubtract.isZero())
{
return this;
}
return add(amtToSubtract.negate());
}
public CostAmount toZero()
{
if (isZero())
{
return this;
}
else
{
return new CostAmount(value.toZero(), sourceValue != null ? sourceValue.toZero() : null); | }
}
public Money toMoney()
{
return value;
}
@Nullable
public Money toSourceMoney()
{
return sourceValue;
}
public BigDecimal toBigDecimal() {return value.toBigDecimal();}
public boolean compareToEquals(@NonNull final CostAmount other)
{
return this.value.compareTo(other.value) == 0;
}
public static CurrencyId getCommonCurrencyIdOfAll(@Nullable final CostAmount... costAmounts)
{
return CurrencyId.getCommonCurrencyIdOfAll(CostAmount::getCurrencyId, "Amount", costAmounts);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostAmount.java | 1 |
请完成以下Java代码 | public java.lang.String getPostingType ()
{
return (java.lang.String)get_Value(COLUMNNAME_PostingType);
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
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 Menge.
@param Qty
Menge
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_ValueNoCheck (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Menge
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
} | /** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set SubLine ID.
@param SubLine_ID
Transaction sub line ID (internal)
*/
@Override
public void setSubLine_ID (int SubLine_ID)
{
if (SubLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_SubLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SubLine_ID, Integer.valueOf(SubLine_ID));
}
/** Get SubLine ID.
@return Transaction sub line ID (internal)
*/
@Override
public int getSubLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SubLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Fact_Acct_ActivityChangeRequest.java | 1 |
请完成以下Java代码 | public void setC_OrderLine_ID (final int C_OrderLine_ID)
{
if (C_OrderLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, C_OrderLine_ID);
}
@Override
public int getC_OrderLine_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OrderLine_ID);
}
@Override
public org.compiere.model.I_M_InOutLine getM_InOutLine()
{
return get_ValueAsPO(COLUMNNAME_M_InOutLine_ID, org.compiere.model.I_M_InOutLine.class);
}
@Override
public void setM_InOutLine(final org.compiere.model.I_M_InOutLine M_InOutLine)
{
set_ValueFromPO(COLUMNNAME_M_InOutLine_ID, org.compiere.model.I_M_InOutLine.class, M_InOutLine);
}
@Override
public void setM_InOutLine_ID (final int M_InOutLine_ID)
{
if (M_InOutLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_InOutLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_InOutLine_ID, M_InOutLine_ID);
}
@Override
public int getM_InOutLine_ID()
{
return get_ValueAsInt(COLUMNNAME_M_InOutLine_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); | else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setProductNo (final @Nullable java.lang.String ProductNo)
{
set_Value (COLUMNNAME_ProductNo, ProductNo);
}
@Override
public java.lang.String getProductNo()
{
return get_ValueAsString(COLUMNNAME_ProductNo);
}
@Override
public void setUPC (final @Nullable java.lang.String UPC)
{
set_Value (COLUMNNAME_UPC, UPC);
}
@Override
public java.lang.String getUPC()
{
return get_ValueAsString(COLUMNNAME_UPC);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_C_BPartner_Product_v.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void updateVariables(Map<String, Object> variables) {
restApiInterceptor.updatePlanItemInstanceVariables(planItemInstance, variables);
}
};
}
return NoopVariableInterceptor.INSTANCE;
}
protected VariableInterceptor createVariableInterceptor(CaseInstance caseInstance) {
if (restApiInterceptor != null) {
return new VariableInterceptor() {
@Override
public void createVariables(Map<String, Object> variables) {
restApiInterceptor.createCaseInstanceVariables(caseInstance, variables);
}
@Override
public void updateVariables(Map<String, Object> variables) {
restApiInterceptor.updateCaseInstanceVariables(caseInstance, variables);
}
};
}
return NoopVariableInterceptor.INSTANCE;
}
protected interface VariableInterceptor {
void createVariables(Map<String, Object> variables); | void updateVariables(Map<String, Object> variables);
}
protected static class NoopVariableInterceptor implements VariableInterceptor {
static final VariableInterceptor INSTANCE = new NoopVariableInterceptor();
@Override
public void createVariables(Map<String, Object> variables) {
// Nothing to do
}
@Override
public void updateVariables(Map<String, Object> variables) {
// Nothing to do
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\caze\BaseVariableResource.java | 2 |
请完成以下Java代码 | public class ProductCountDecrementedEvent {
private final String orderId;
private final String productId;
public ProductCountDecrementedEvent(String orderId, String productId) {
this.orderId = orderId;
this.productId = productId;
}
public String getOrderId() {
return orderId;
}
public String getProductId() {
return productId;
}
@Override
public boolean equals(Object o) {
if (this == o) { | return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ProductCountDecrementedEvent that = (ProductCountDecrementedEvent) o;
return Objects.equals(orderId, that.orderId) && Objects.equals(productId, that.productId);
}
@Override
public int hashCode() {
return Objects.hash(orderId, productId);
}
@Override
public String toString() {
return "ProductCountDecrementedEvent{" + "orderId='" + orderId + '\'' + ", productId='" + productId + '\'' + '}';
}
} | repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\coreapi\events\ProductCountDecrementedEvent.java | 1 |
请完成以下Java代码 | public String getStringBaseLanguage()
{
return string;
}
@Override
public String getStringTrlPattern()
{
return string;
}
@Override
public String translate()
{
return string;
}
@Override | public String translate(final String adLanguage)
{
return string;
}
@Override
public NoTranslatableParameterizedString transform(final Function<String, String> mappingFunction)
{
final String stringTransformed = mappingFunction.apply(string);
if (Objects.equals(string, stringTransformed))
{
return this;
}
return new NoTranslatableParameterizedString(adLanguageParamName, stringTransformed);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\TranslatableParameterizedString.java | 1 |
请完成以下Java代码 | public void doLeave(ActivityExecution execution) {
LOG.leavingActivity(execution.getActivity().getId());
PvmTransition outgoingSeqFlow = null;
String defaultSequenceFlow = (String) execution.getActivity().getProperty("default");
Iterator<PvmTransition> transitionIterator = execution.getActivity().getOutgoingTransitions().iterator();
while (outgoingSeqFlow == null && transitionIterator.hasNext()) {
PvmTransition seqFlow = transitionIterator.next();
Condition condition = (Condition) seqFlow.getProperty(BpmnParse.PROPERTYNAME_CONDITION);
if ( (condition == null && (defaultSequenceFlow == null || !defaultSequenceFlow.equals(seqFlow.getId())) )
|| (condition != null && condition.evaluate(execution)) ) {
LOG.outgoingSequenceFlowSelected(seqFlow.getId());
outgoingSeqFlow = seqFlow;
}
}
if (outgoingSeqFlow != null) {
execution.leaveActivityViaTransition(outgoingSeqFlow);
} else { | if (defaultSequenceFlow != null) {
PvmTransition defaultTransition = execution.getActivity().findOutgoingTransition(defaultSequenceFlow);
if (defaultTransition != null) {
execution.leaveActivityViaTransition(defaultTransition);
} else {
throw LOG.missingDefaultFlowException(execution.getActivity().getId(), defaultSequenceFlow);
}
} else {
//No sequence flow could be found, not even a default one
throw LOG.stuckExecutionException(execution.getActivity().getId());
}
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\ExclusiveGatewayActivityBehavior.java | 1 |
请完成以下Java代码 | public ChannelDefinitionEntity getMostRecentVersionOfChannelDefinition(ChannelDefinitionEntity channelDefinition) {
String key = channelDefinition.getKey();
String tenantId = channelDefinition.getTenantId();
ChannelDefinitionEntityManager channelDefinitionEntityManager = CommandContextUtil.getEventRegistryConfiguration().getChannelDefinitionEntityManager();
ChannelDefinitionEntity existingDefinition = null;
if (tenantId != null && !tenantId.equals(EventRegistryEngineConfiguration.NO_TENANT_ID)) {
existingDefinition = channelDefinitionEntityManager.findLatestChannelDefinitionByKeyAndTenantId(key, tenantId);
} else {
existingDefinition = channelDefinitionEntityManager.findLatestChannelDefinitionByKey(key);
}
return existingDefinition;
}
/**
* Gets the persisted version of the already-deployed channel definition.
*/
public ChannelDefinitionEntity getPersistedInstanceOfChannelDefinition(ChannelDefinitionEntity channelDefinition) { | String deploymentId = channelDefinition.getDeploymentId();
if (StringUtils.isEmpty(channelDefinition.getDeploymentId())) {
throw new FlowableIllegalArgumentException("Provided channel definition must have a deployment id.");
}
ChannelDefinitionEntityManager channelDefinitionEntityManager = CommandContextUtil.getEventRegistryConfiguration().getChannelDefinitionEntityManager();
ChannelDefinitionEntity persistedChannelDefinition = null;
if (channelDefinition.getTenantId() == null || EventRegistryEngineConfiguration.NO_TENANT_ID.equals(channelDefinition.getTenantId())) {
persistedChannelDefinition = channelDefinitionEntityManager.findChannelDefinitionByDeploymentAndKey(deploymentId, channelDefinition.getKey());
} else {
persistedChannelDefinition = channelDefinitionEntityManager.findChannelDefinitionByDeploymentAndKeyAndTenantId(deploymentId,
channelDefinition.getKey(), channelDefinition.getTenantId());
}
return persistedChannelDefinition;
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\deployer\ChannelDefinitionDeploymentHelper.java | 1 |
请完成以下Java代码 | public void setDLM_Partition_ID(final int DLM_Partition_ID)
{
if (DLM_Partition_ID < 1)
{
set_ValueNoCheck(COLUMNNAME_DLM_Partition_ID, null);
}
else
{
set_ValueNoCheck(COLUMNNAME_DLM_Partition_ID, Integer.valueOf(DLM_Partition_ID));
}
}
/**
* Get Partition.
*
* @return Partition
*/
@Override
public int getDLM_Partition_ID()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Partition_ID);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
/**
* Set DLM_Partition_Size_Per_Table_V.
*
* @param DLM_Partition_Size_Per_Table_V_ID DLM_Partition_Size_Per_Table_V
*/
@Override
public void setDLM_Partition_Size_Per_Table_V_ID(final int DLM_Partition_Size_Per_Table_V_ID)
{
if (DLM_Partition_Size_Per_Table_V_ID < 1)
{
set_ValueNoCheck(COLUMNNAME_DLM_Partition_Size_Per_Table_V_ID, null);
}
else
{
set_ValueNoCheck(COLUMNNAME_DLM_Partition_Size_Per_Table_V_ID, Integer.valueOf(DLM_Partition_Size_Per_Table_V_ID));
}
}
/**
* Get DLM_Partition_Size_Per_Table_V.
*
* @return DLM_Partition_Size_Per_Table_V
*/
@Override
public int getDLM_Partition_Size_Per_Table_V_ID()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Partition_Size_Per_Table_V_ID);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
/**
* Set Anz. zugeordneter Datensätze.
*
* @param PartitionSize Anz. zugeordneter Datensätze | */
@Override
public void setPartitionSize(final int PartitionSize)
{
set_ValueNoCheck(COLUMNNAME_PartitionSize, Integer.valueOf(PartitionSize));
}
/**
* Get Anz. zugeordneter Datensätze.
*
* @return Anz. zugeordneter Datensätze
*/
@Override
public int getPartitionSize()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_PartitionSize);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
/**
* Set Name der DB-Tabelle.
*
* @param TableName Name der DB-Tabelle
*/
@Override
public void setTableName(final java.lang.String TableName)
{
set_ValueNoCheck(COLUMNNAME_TableName, TableName);
}
/**
* Get Name der DB-Tabelle.
*
* @return Name der DB-Tabelle
*/
@Override
public java.lang.String getTableName()
{
return (java.lang.String)get_Value(COLUMNNAME_TableName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition_Size_Per_Table_V.java | 1 |
请完成以下Java代码 | public class PrintClientsBL implements IPrintClientsBL
{
@Override
public I_AD_Print_Clients createPrintClientsEntry(final Properties ctx, final String hostkey)
{
final String trxName = ITrx.TRXNAME_None;
I_AD_Print_Clients printClientsEntry = Services.get(IPrintingDAO.class).retrievePrintClientsEntry(ctx, hostkey);
if (printClientsEntry == null)
{
// task 08021: we want to create the record with AD_Client_ID=0 etc, because there shall be just one record per host, not different ones per user, client, role etc
final Properties sysContext = Env.createSysContext(ctx);
printClientsEntry = InterfaceWrapperHelper.create(sysContext, I_AD_Print_Clients.class, trxName);
printClientsEntry.setHostKey(hostkey);
}
printClientsEntry.setAD_Session_ID(Env.getContextAsInt(ctx, Env.CTXNAME_AD_Session_ID));
printClientsEntry.setDateLastPoll(SystemTime.asTimestamp()); | InterfaceWrapperHelper.save(printClientsEntry);
return printClientsEntry;
}
@Override
@Nullable
public String getHostKeyOrNull(@NonNull final Properties ctx)
{
// Check session
final MFSession session = Services.get(ISessionBL.class).getCurrentSession(ctx);
if (session != null)
{
return session.getOrCreateHostKey(ctx);
}
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\PrintClientsBL.java | 1 |
请完成以下Java代码 | public void setPrescriptionRequestCreatedAt (final @Nullable java.sql.Timestamp PrescriptionRequestCreatedAt)
{
set_Value (COLUMNNAME_PrescriptionRequestCreatedAt, PrescriptionRequestCreatedAt);
}
@Override
public java.sql.Timestamp getPrescriptionRequestCreatedAt()
{
return get_ValueAsTimestamp(COLUMNNAME_PrescriptionRequestCreatedAt);
}
@Override
public void setPrescriptionRequestCreatedBy (final int PrescriptionRequestCreatedBy)
{
set_Value (COLUMNNAME_PrescriptionRequestCreatedBy, PrescriptionRequestCreatedBy);
}
@Override
public int getPrescriptionRequestCreatedBy()
{
return get_ValueAsInt(COLUMNNAME_PrescriptionRequestCreatedBy);
}
@Override
public void setPrescriptionRequestTimestamp (final @Nullable java.sql.Timestamp PrescriptionRequestTimestamp)
{
set_Value (COLUMNNAME_PrescriptionRequestTimestamp, PrescriptionRequestTimestamp);
}
@Override
public java.sql.Timestamp getPrescriptionRequestTimestamp()
{
return get_ValueAsTimestamp(COLUMNNAME_PrescriptionRequestTimestamp);
}
@Override
public void setPrescriptionRequestUpdateAt (final @Nullable java.sql.Timestamp PrescriptionRequestUpdateAt)
{
set_Value (COLUMNNAME_PrescriptionRequestUpdateAt, PrescriptionRequestUpdateAt);
}
@Override
public java.sql.Timestamp getPrescriptionRequestUpdateAt()
{
return get_ValueAsTimestamp(COLUMNNAME_PrescriptionRequestUpdateAt);
}
/**
* PrescriptionType AD_Reference_ID=541296
* Reference name: Rezepttyp
*/
public static final int PRESCRIPTIONTYPE_AD_Reference_ID=541296;
/** Arzneimittel = 0 */
public static final String PRESCRIPTIONTYPE_Arzneimittel = "0";
/** Verbandstoffe = 1 */
public static final String PRESCRIPTIONTYPE_Verbandstoffe = "1";
/** BtM-Rezept = 2 */
public static final String PRESCRIPTIONTYPE_BtM_Rezept = "2";
/** Pflegehilfsmittel = 3 */
public static final String PRESCRIPTIONTYPE_Pflegehilfsmittel = "3";
/** Hilfsmittel zum Verbrauch bestimmt = 4 */
public static final String PRESCRIPTIONTYPE_HilfsmittelZumVerbrauchBestimmt = "4";
/** Hilfsmittel zum Gebrauch bestimmt = 5 */ | public static final String PRESCRIPTIONTYPE_HilfsmittelZumGebrauchBestimmt = "5";
@Override
public void setPrescriptionType (final @Nullable java.lang.String PrescriptionType)
{
set_Value (COLUMNNAME_PrescriptionType, PrescriptionType);
}
@Override
public java.lang.String getPrescriptionType()
{
return get_ValueAsString(COLUMNNAME_PrescriptionType);
}
@Override
public void setStartDate (final @Nullable java.sql.Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
@Override
public java.sql.Timestamp getStartDate()
{
return get_ValueAsTimestamp(COLUMNNAME_StartDate);
}
@Override
public void setTherapyTypeIds (final @Nullable java.lang.String TherapyTypeIds)
{
set_Value (COLUMNNAME_TherapyTypeIds, TherapyTypeIds);
}
@Override
public java.lang.String getTherapyTypeIds()
{
return get_ValueAsString(COLUMNNAME_TherapyTypeIds);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_Alberta_PrescriptionRequest.java | 1 |
请完成以下Java代码 | public String getProcessMsg()
{
return null;
}
/**
* Get Document Owner (Responsible)
*
* @return AD_User_ID
*/
@Override
public int getDoc_User_ID()
{
return getUpdatedBy();
}
/**
* Get Document Currency
*
* @return C_Currency_ID | */
@Override
public int getC_Currency_ID()
{
// MPriceList pl = MPriceList.get(getCtx(), getM_PriceList_ID());
// return pl.getC_Currency_ID();
return 0;
}
public boolean isComplete()
{
String ds = getDocStatus();
return DOCSTATUS_Completed.equals(ds)
|| DOCSTATUS_Closed.equals(ds)
|| DOCSTATUS_Reversed.equals(ds);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MInventory.java | 1 |
请完成以下Java代码 | public void setExternalId(final JsonExternalId externalId)
{
this.externalId = externalId;
this.externalIdSet = true;
}
public void setCode(final String code)
{
this.code = code;
this.codeSet = true;
}
public void setActive(final Boolean active)
{
this.active = active;
this.activeSet = true;
}
public void setName(final String name)
{
this.name = name;
this.nameSet = true;
}
public void setName2(final String name2)
{
this.name2 = name2;
this.name2Set = true;
}
public void setName3(final String name3)
{
this.name3 = name3;
this.name3Set = true;
}
public void setCompanyName(final String companyName)
{
this.companyName = companyName;
this.companyNameSet = true;
}
public void setVendor(final Boolean vendor)
{
this.vendor = vendor;
this.vendorSet = true;
}
public void setCustomer(final Boolean customer)
{
this.customer = customer;
this.customerSet = true;
}
public void setParentId(final JsonMetasfreshId parentId)
{
this.parentId = parentId;
this.parentIdSet = true;
}
public void setPhone(final String phone)
{
this.phone = phone;
this.phoneSet = true;
}
public void setLanguage(final String language)
{
this.language = language;
this.languageSet = true;
}
public void setInvoiceRule(final JsonInvoiceRule invoiceRule)
{
this.invoiceRule = invoiceRule;
this.invoiceRuleSet = true;
}
public void setUrl(final String url)
{ | this.url = url;
this.urlSet = true;
}
public void setUrl2(final String url2)
{
this.url2 = url2;
this.url2Set = true;
}
public void setUrl3(final String url3)
{
this.url3 = url3;
this.url3Set = true;
}
public void setGroup(final String group)
{
this.group = group;
this.groupSet = true;
}
public void setGlobalId(final String globalId)
{
this.globalId = globalId;
this.globalIdset = true;
}
public void setSyncAdvise(final SyncAdvise syncAdvise)
{
this.syncAdvise = syncAdvise;
this.syncAdviseSet = true;
}
public void setVatId(final String vatId)
{
this.vatId = vatId;
this.vatIdSet = true;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v1\request\JsonRequestBPartner.java | 1 |
请完成以下Java代码 | private List<IEventBus> getEventBusInstances(@Nullable final String topicName)
{
if (!Check.isBlank(topicName))
{
final ArrayList<IEventBus> eventBusInstances = new ArrayList<>();
{
final IEventBus remoteEventBus = eventBusFactory.getEventBusIfExists(Topic.distributed(topicName));
if (remoteEventBus != null)
{
eventBusInstances.add(remoteEventBus);
}
}
{
final IEventBus localEventBus = eventBusFactory.getEventBusIfExists(Topic.local(topicName));
if (localEventBus != null)
{
eventBusInstances.add(localEventBus);
}
}
return eventBusInstances;
}
else
{
return eventBusFactory.getAllEventBusInstances();
}
}
private static ImmutableList<JSONEventBusStats> toJSONEventBusStats(final List<IEventBus> eventBusInstances) | {
return eventBusInstances.stream()
.map(eventBus -> toJSONEventBusStats(eventBus))
.collect(ImmutableList.toImmutableList());
}
private static JSONEventBusStats toJSONEventBusStats(final IEventBus eventBus)
{
final EventBusStats stats = eventBus.getStats();
final Topic eventBusTopic = eventBus.getTopic();
return JSONEventBusStats.builder()
.topicName(eventBusTopic.getName())
.type(eventBusTopic.getType())
.async(eventBus.isAsync())
.destroyed(eventBus.isDestroyed())
//
.eventsEnqueued(stats.getEventsEnqueued())
.eventsDequeued(stats.getEventsDequeued())
.eventsToDequeue(stats.getEventsToDequeue())
//
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\rest\EventBusRestController.java | 1 |
请完成以下Java代码 | public int getGatewaySize() {
return gatewaySize;
}
public void setGatewaySize(int gatewaySize) {
this.gatewaySize = gatewaySize;
}
public int getTaskWidth() {
return taskWidth;
}
public void setTaskWidth(int taskWidth) {
this.taskWidth = taskWidth;
}
public int getTaskHeight() {
return taskHeight;
}
public void setTaskHeight(int taskHeight) {
this.taskHeight = taskHeight;
}
public int getSubProcessMargin() {
return subProcessMargin;
}
public void setSubProcessMargin(int subProcessMargin) {
this.subProcessMargin = subProcessMargin; | }
// Due to a bug (see
// http://forum.jgraph.com/questions/5952/mxhierarchicallayout-not-correct-when-using-child-vertex)
// We must extend the default hierarchical layout to tweak it a bit (see url
// link) otherwise the layouting crashes.
//
// Verify again with a later release if fixed (ie the mxHierarchicalLayout
// can be used directly)
static class CustomLayout extends mxHierarchicalLayout {
public CustomLayout(mxGraph graph, int orientation) {
super(graph, orientation);
this.traverseAncestors = false;
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-layout\src\main\java\org\activiti\bpmn\BpmnAutoLayout.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ScanPayResultVo implements Serializable {
/**
* 支付方式编码
*/
private String payWayCode;
/** 金额 **/
private BigDecimal orderAmount;
/** 产品名称 **/
private String productName;
/**
* 二维码地址
*/
private String codeUrl;
public String getCodeUrl() {
return codeUrl;
}
public void setCodeUrl(String codeUrl) {
this.codeUrl = codeUrl;
}
public String getPayWayCode() {
return payWayCode; | }
public void setPayWayCode(String payWayCode) {
this.payWayCode = payWayCode;
}
public BigDecimal getOrderAmount() {
return orderAmount;
}
public void setOrderAmount(BigDecimal orderAmount) {
this.orderAmount = orderAmount;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\ScanPayResultVo.java | 2 |
请完成以下Java代码 | public String getTableName()
{
return tableName;
}
@Override
public List<String> getDependsOnColumnNames()
{
return columnNamesRO;
}
@Override
public String buildKey(final ModelType model)
{
return buildAggregationKey(model)
.getAggregationKeyString();
}
@Override
public AggregationKey buildAggregationKey(final ModelType model)
{
if (aggregationKeyBuilders.isEmpty())
{
throw new AdempiereException("No aggregation key builders added");
}
final List<String> keyParts = new ArrayList<>();
final Set<AggregationId> aggregationIds = new HashSet<>();
for (final IAggregationKeyBuilder<ModelType> aggregationKeyBuilder : aggregationKeyBuilders)
{
final AggregationKey keyPart = aggregationKeyBuilder.buildAggregationKey(model);
keyParts.add(keyPart.getAggregationKeyString()); | aggregationIds.add(keyPart.getAggregationId());
}
final AggregationId aggregationId = CollectionUtils.singleElementOrDefault(aggregationIds, null);
return new AggregationKey(Util.mkKey(keyParts.toArray()), aggregationId);
}
@Override
public boolean isSame(final ModelType model1, final ModelType model2)
{
if (model1 == model2)
{
return true;
}
final String key1 = buildKey(model1);
final String key2 = buildKey(model2);
return Objects.equals(key1, key2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\api\CompositeAggregationKeyBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<Hospital> getNewAndUpdatedHospitals(String albertaApiKey, String updatedAfter) throws ApiException {
ApiResponse<List<Hospital>> resp = getNewAndUpdatedHospitalsWithHttpInfo(albertaApiKey, updatedAfter);
return resp.getData();
}
/**
* Daten der neuen und geänderten Kliniken abrufen
* Szenario - das WaWi fragt bei Alberta nach, wie ob es neue oder geänderte Kliniken gibt
* @param albertaApiKey (required)
* @param updatedAfter 2021-02-21T09:30:00.000Z (im UTC-Format) (required)
* @return ApiResponse<List<Hospital>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<List<Hospital>> getNewAndUpdatedHospitalsWithHttpInfo(String albertaApiKey, String updatedAfter) throws ApiException {
com.squareup.okhttp.Call call = getNewAndUpdatedHospitalsValidateBeforeCall(albertaApiKey, updatedAfter, null, null);
Type localVarReturnType = new TypeToken<List<Hospital>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* Daten der neuen und geänderten Kliniken abrufen (asynchronously)
* Szenario - das WaWi fragt bei Alberta nach, wie ob es neue oder geänderte Kliniken gibt
* @param albertaApiKey (required)
* @param updatedAfter 2021-02-21T09:30:00.000Z (im UTC-Format) (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call getNewAndUpdatedHospitalsAsync(String albertaApiKey, String updatedAfter, final ApiCallback<List<Hospital>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done); | }
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = getNewAndUpdatedHospitalsValidateBeforeCall(albertaApiKey, updatedAfter, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<Hospital>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\api\HospitalApi.java | 2 |
请完成以下Java代码 | public static boolean isInGroup(final I_C_OrderLine orderLine)
{
return orderLine.getC_Order_CompensationGroup_ID() > 0;
}
public static boolean isNotInGroup(final I_C_OrderLine orderLine)
{
return !isInGroup(orderLine);
}
public static BigDecimal adjustAmtByCompensationType(@NonNull final BigDecimal compensationAmt, @NonNull final GroupCompensationType compensationType)
{
if (compensationType == GroupCompensationType.Discount)
{
return compensationAmt.negate();
}
else if (compensationType == GroupCompensationType.Surcharge)
{
return compensationAmt;
}
else
{
throw new AdempiereException("Unknown compensationType: " + compensationType);
}
} | public static boolean isGeneratedLine(final I_C_OrderLine orderLine)
{
final GroupTemplateLineId groupSchemaLineId = extractGroupTemplateLineId(orderLine);
return isGeneratedLine(groupSchemaLineId);
}
@Nullable
public static GroupTemplateLineId extractGroupTemplateLineId(@NonNull final I_C_OrderLine orderLine)
{
return GroupTemplateLineId.ofRepoIdOrNull(orderLine.getC_CompensationGroup_SchemaLine_ID());
}
public static boolean isGeneratedLine(@Nullable final GroupTemplateLineId groupSchemaLineId)
{
return groupSchemaLineId != null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\compensationGroup\OrderGroupCompensationUtils.java | 1 |
请完成以下Java代码 | private boolean purchaseMatchesOrExceedsRequiredQty()
{
return getPurchasedQty().compareTo(getQtyToPurchase()) >= 0;
}
public void setPurchaseOrderLineId(@NonNull final OrderAndLineId purchaseOrderAndLineId)
{
this.purchaseOrderAndLineId = purchaseOrderAndLineId;
}
public void markPurchasedIfNeeded()
{
if (purchaseMatchesOrExceedsRequiredQty())
{
purchaseCandidate.markProcessed();
}
}
public void markReqCreatedIfNeeded()
{
if (purchaseMatchesOrExceedsRequiredQty())
{
purchaseCandidate.setReqCreated(true);
}
}
@Nullable
public BigDecimal getPrice()
{
return purchaseCandidate.getPriceEnteredEff();
}
@Nullable
public UomId getPriceUomId()
{
return purchaseCandidate.getPriceUomId();
}
@Nullable
public Percent getDiscount()
{
return purchaseCandidate.getDiscountEff();
}
@Nullable
public String getExternalPurchaseOrderUrl()
{
return purchaseCandidate.getExternalPurchaseOrderUrl();
} | @Nullable
public ExternalId getExternalHeaderId()
{
return purchaseCandidate.getExternalHeaderId();
}
@Nullable
public ExternalSystemId getExternalSystemId()
{
return purchaseCandidate.getExternalSystemId();
}
@Nullable
public ExternalId getExternalLineId()
{
return purchaseCandidate.getExternalLineId();
}
@Nullable
public String getPOReference()
{
return purchaseCandidate.getPOReference();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\remotepurchaseitem\PurchaseOrderItem.java | 1 |
请完成以下Java代码 | private ITranslatableString buildAttributeDescription(@NonNull final Attribute attribute)
{
final IStringExpression descriptionPattern = attribute.getDescriptionPattern();
if (descriptionPattern == null)
{
return getAttributeDisplayValue(attribute);
}
else
{
final @NonNull AttributeCode attributeCode = attribute.getAttributeCode();
final AttributeDescriptionPatternEvalCtx ctx = AttributeDescriptionPatternEvalCtx.builder()
.attributesRepo(attributesRepo)
.uomsRepo(uomsRepo)
.attribute(attribute)
.attributeValue(attributeSet.getValue(attributeCode))
.attributeValueId(attributeSet.getAttributeValueIdOrNull(attributeCode))
.adLanguage(adLanguage)
.verboseDescription(true)
.build();
final String description = descriptionPattern.evaluate(ctx, OnVariableNotFound.Preserve);
return TranslatableStrings.anyLanguage(description);
}
}
private ITranslatableString getAttributeDisplayValue(@NonNull final Attribute attribute)
{
final AttributeCode attributeCode = attribute.getAttributeCode();
final AttributeValueType attributeValueType = attribute.getValueType();
if (AttributeValueType.STRING.equals(attributeValueType))
{
final String valueStr = attributeSet.getValueAsString(attributeCode);
return ASIDescriptionBuilderCommand.formatStringValue(valueStr);
}
else if (AttributeValueType.NUMBER.equals(attributeValueType))
{
final BigDecimal valueBD = attributeSet.getValueAsBigDecimal(attributeCode);
if (valueBD != null)
{
return ASIDescriptionBuilderCommand.formatNumber(valueBD, attribute.getNumberDisplayType());
} | else
{
return null;
}
}
else if (AttributeValueType.DATE.equals(attributeValueType))
{
final LocalDate valueDate = attributeSet.getValueAsLocalDate(attributeCode);
return valueDate != null
? ASIDescriptionBuilderCommand.formatDateValue(valueDate)
: null;
}
else if (AttributeValueType.LIST.equals(attributeValueType))
{
final AttributeValueId attributeValueId = attributeSet.getAttributeValueIdOrNull(attributeCode);
final AttributeListValue attributeValue = attributeValueId != null
? attributesRepo.retrieveAttributeValueOrNull(attribute, attributeValueId)
: null;
if (attributeValue != null)
{
return attributeValue.getNameTrl();
}
else
{
final String valueStr = attributeSet.getValueAsString(attributeCode);
return ASIDescriptionBuilderCommand.formatStringValue(valueStr);
}
}
else
{
// Unknown attributeValueType
final String valueStr = attributeSet.getValueAsString(attributeCode);
return ASIDescriptionBuilderCommand.formatStringValue(valueStr);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\AttributeSetDescriptionBuilderCommand.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<MenuVO> buttons(String roleId) {
List<Menu> buttons = baseMapper.buttons(Func.toLongList(roleId));
MenuWrapper menuWrapper = new MenuWrapper();
return menuWrapper.listNodeVO(buttons);
}
@Override
public List<MenuVO> tree() {
return ForestNodeMerger.merge(baseMapper.tree());
}
@Override
public List<MenuVO> grantTree(BladeUser user) {
return ForestNodeMerger.merge(user.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID) ? baseMapper.grantTree() : baseMapper.grantTreeByRole(Func.toLongList(user.getRoleId())));
}
@Override
public List<MenuVO> grantDataScopeTree(BladeUser user) {
return ForestNodeMerger.merge(user.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID) ? baseMapper.grantDataScopeTree() : baseMapper.grantDataScopeTreeByRole(Func.toLongList(user.getRoleId())));
}
@Override
public List<String> roleTreeKeys(String roleIds) {
List<RoleMenu> roleMenus = roleMenuService.list(Wrappers.<RoleMenu>query().lambda().in(RoleMenu::getRoleId, Func.toLongList(roleIds)));
return roleMenus.stream().map(roleMenu -> Func.toStr(roleMenu.getMenuId())).collect(Collectors.toList());
}
@Override
public List<String> dataScopeTreeKeys(String roleIds) {
List<RoleScope> roleScopes = roleScopeService.list(Wrappers.<RoleScope>query().lambda().in(RoleScope::getRoleId, Func.toLongList(roleIds)));
return roleScopes.stream().map(roleScope -> Func.toStr(roleScope.getScopeId())).collect(Collectors.toList());
} | @Override
public List<Kv> authRoutes(BladeUser user) {
if (Func.isEmpty(user)) {
return null;
}
List<MenuDTO> routes = baseMapper.authRoutes(Func.toLongList(user.getRoleId()));
List<Kv> list = new ArrayList<>();
routes.forEach(route -> list.add(Kv.init().set(route.getPath(), Kv.init().set("authority", Func.toStrArray(route.getAlias())))));
return list;
}
@Override
public List<MenuVO> grantTopTree(BladeUser user) {
return ForestNodeMerger.merge(user.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID) ? baseMapper.grantTopTree() : baseMapper.grantTopTreeByRole(Func.toLongList(user.getRoleId())));
}
@Override
public List<String> topTreeKeys(String topMenuIds) {
List<TopMenuSetting> settings = topMenuSettingService.list(Wrappers.<TopMenuSetting>query().lambda().in(TopMenuSetting::getTopMenuId, Func.toLongList(topMenuIds)));
return settings.stream().map(setting -> Func.toStr(setting.getMenuId())).collect(Collectors.toList());
}
} | repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\service\impl\MenuServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected RequiresChannelUrl chainRequestMatchersInternal(List<RequestMatcher> requestMatchers) {
return new RequiresChannelUrl(requestMatchers);
}
/**
* Adds an {@link ObjectPostProcessor} for this class.
* @param objectPostProcessor
* @return the {@link ChannelSecurityConfigurer} for further customizations
*/
public ChannelRequestMatcherRegistry withObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) {
addObjectPostProcessor(objectPostProcessor);
return this;
}
/**
* Sets the {@link ChannelProcessor} instances to use in
* {@link ChannelDecisionManagerImpl}
* @param channelProcessors
* @return the {@link ChannelSecurityConfigurer} for further customizations
*/
public ChannelRequestMatcherRegistry channelProcessors(List<ChannelProcessor> channelProcessors) {
ChannelSecurityConfigurer.this.channelProcessors = channelProcessors;
return this;
}
/**
* Sets the {@link RedirectStrategy} instances to use in
* {@link RetryWithHttpEntryPoint} and {@link RetryWithHttpsEntryPoint}
* @param redirectStrategy
* @return the {@link ChannelSecurityConfigurer} for further customizations
*/
public ChannelRequestMatcherRegistry redirectStrategy(RedirectStrategy redirectStrategy) {
ChannelSecurityConfigurer.this.redirectStrategy = redirectStrategy;
return this;
}
}
/**
* @deprecated no replacement planned
*/
@Deprecated | public class RequiresChannelUrl {
protected List<? extends RequestMatcher> requestMatchers;
RequiresChannelUrl(List<? extends RequestMatcher> requestMatchers) {
this.requestMatchers = requestMatchers;
}
public ChannelRequestMatcherRegistry requiresSecure() {
return requires("REQUIRES_SECURE_CHANNEL");
}
public ChannelRequestMatcherRegistry requiresInsecure() {
return requires("REQUIRES_INSECURE_CHANNEL");
}
public ChannelRequestMatcherRegistry requires(String attribute) {
return addAttribute(attribute, this.requestMatchers);
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\ChannelSecurityConfigurer.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Money calculateProjectedOverUnderAmt(final Money amountToAllocate)
{
final Money discountAmt = purchaseInvoicePayableDoc.getAmountsToAllocateInitial().getDiscountAmt();
final Money openAmtWithDiscount = purchaseInvoicePayableDoc.getOpenAmtInitial().subtract(discountAmt);
final Money remainingOpenAmtWithDiscount = openAmtWithDiscount.subtract(purchaseInvoicePayableDoc.getTotalAllocatedAmount());
final Money adjustedAmountToAllocate = amountToAllocate.negate();
return remainingOpenAmtWithDiscount.subtract(adjustedAmountToAllocate);
}
@Override
public boolean canPay(@NonNull final PayableDocument payable)
{
// A purchase invoice can compensate only on a sales invoice
if (payable.getType() != PayableDocumentType.Invoice)
{
return false;
}
if (!payable.getSoTrx().isSales())
{
return false;
}
// if currency differs, do not allow payment
return CurrencyId.equals(payable.getCurrencyId(), purchaseInvoicePayableDoc.getCurrencyId());
}
@Override
public CurrencyId getCurrencyId()
{
return purchaseInvoicePayableDoc.getCurrencyId();
} | @Override
public LocalDate getDate()
{
return purchaseInvoicePayableDoc.getDate();
}
@Override
public PaymentCurrencyContext getPaymentCurrencyContext()
{
return PaymentCurrencyContext.builder()
.paymentCurrencyId(purchaseInvoicePayableDoc.getCurrencyId())
.currencyConversionTypeId(purchaseInvoicePayableDoc.getCurrencyConversionTypeId())
.build();
}
@Override
public Money getPaymentDiscountAmt()
{
return purchaseInvoicePayableDoc.getAmountsToAllocate().getDiscountAmt();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\service\PurchaseInvoiceAsInboundPaymentDocumentWrapper.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void delete(Set<Long> ids) {
jobRepository.deleteAllByIdIn(ids);
// 删除缓存
redisUtils.delByKeys(CacheKey.JOB_ID, ids);
}
@Override
public void download(List<JobDto> jobDtos, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (JobDto jobDTO : jobDtos) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("岗位名称", jobDTO.getName());
map.put("岗位状态", jobDTO.getEnabled() ? "启用" : "停用");
map.put("创建日期", jobDTO.getCreateTime());
list.add(map);
}
FileUtil.downloadExcel(list, response); | }
@Override
public void verification(Set<Long> ids) {
if(userRepository.countByJobs(ids) > 0){
throw new BadRequestException("所选的岗位中存在用户关联,请解除关联再试!");
}
}
/**
* 删除缓存
* @param id /
*/
public void delCaches(Long id){
redisUtils.del(CacheKey.JOB_ID + id);
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\JobServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public PageData<AuditLog> getAuditLogs(
@Parameter(description = PAGE_SIZE_DESCRIPTION)
@RequestParam int pageSize,
@Parameter(description = PAGE_NUMBER_DESCRIPTION)
@RequestParam int page,
@Parameter(description = AUDIT_LOG_TEXT_SEARCH_DESCRIPTION)
@RequestParam(required = false) String textSearch,
@Parameter(description = AUDIT_LOG_SORT_PROPERTY_DESCRIPTION, schema = @Schema(allowableValues = {"createdTime", "entityType", "entityName", "userName", "actionType", "actionStatus"}))
@RequestParam(required = false) String sortProperty,
@Parameter(description = SORT_ORDER_DESCRIPTION, schema = @Schema(allowableValues = {"ASC", "DESC"}))
@RequestParam(required = false) String sortOrder,
@Parameter(description = AUDIT_LOG_QUERY_START_TIME_DESCRIPTION)
@RequestParam(required = false) Long startTime,
@Parameter(description = AUDIT_LOG_QUERY_END_TIME_DESCRIPTION)
@RequestParam(required = false) Long endTime,
@Parameter(description = AUDIT_LOG_QUERY_ACTION_TYPES_DESCRIPTION)
@RequestParam(name = "actionTypes", required = false) String actionTypesStr) throws ThingsboardException {
TenantId tenantId = getCurrentUser().getTenantId();
List<ActionType> actionTypes = parseActionTypesStr(actionTypesStr);
TimePageLink pageLink = createTimePageLink(pageSize, page, textSearch, sortProperty, sortOrder, getStartTime(startTime), getEndTime(endTime));
return checkNotNull(auditLogService.findAuditLogsByTenantId(tenantId, actionTypes, pageLink));
}
private List<ActionType> parseActionTypesStr(String actionTypesStr) {
List<ActionType> result = null;
if (StringUtils.isNoneBlank(actionTypesStr)) {
String[] tmp = actionTypesStr.split(",");
result = Arrays.stream(tmp).map(at -> ActionType.valueOf(at.toUpperCase())).collect(Collectors.toList());
}
return result; | }
private Long getStartTime(Long startTime) {
if (startTime == null) {
return 1L;
}
return startTime;
}
private Long getEndTime(Long endTime) {
if (endTime == null) {
return System.currentTimeMillis();
}
return endTime;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\AuditLogController.java | 2 |
请完成以下Java代码 | public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setWaitingTime (final int WaitingTime)
{
set_Value (COLUMNNAME_WaitingTime, WaitingTime);
}
@Override
public int getWaitingTime()
{
return get_ValueAsInt(COLUMNNAME_WaitingTime);
}
@Override
public void setWaitTime (final int WaitTime)
{
set_Value (COLUMNNAME_WaitTime, WaitTime);
}
@Override
public int getWaitTime()
{
return get_ValueAsInt(COLUMNNAME_WaitTime);
}
@Override
public void setWorkflow_ID (final int Workflow_ID)
{
if (Workflow_ID < 1)
set_Value (COLUMNNAME_Workflow_ID, null);
else
set_Value (COLUMNNAME_Workflow_ID, Workflow_ID);
}
@Override
public int getWorkflow_ID()
{
return get_ValueAsInt(COLUMNNAME_Workflow_ID);
}
@Override
public void setWorkingTime (final int WorkingTime)
{ | set_Value (COLUMNNAME_WorkingTime, WorkingTime);
}
@Override
public int getWorkingTime()
{
return get_ValueAsInt(COLUMNNAME_WorkingTime);
}
@Override
public void setXPosition (final int XPosition)
{
set_Value (COLUMNNAME_XPosition, XPosition);
}
@Override
public int getXPosition()
{
return get_ValueAsInt(COLUMNNAME_XPosition);
}
@Override
public void setYield (final int Yield)
{
set_Value (COLUMNNAME_Yield, Yield);
}
@Override
public int getYield()
{
return get_ValueAsInt(COLUMNNAME_Yield);
}
@Override
public void setYPosition (final int YPosition)
{
set_Value (COLUMNNAME_YPosition, YPosition);
}
@Override
public int getYPosition()
{
return get_ValueAsInt(COLUMNNAME_YPosition);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Node.java | 1 |
请完成以下Java代码 | public class UmsAdminRoleRelation implements Serializable {
private Long id;
private Long adminId;
private Long roleId;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getAdminId() {
return adminId;
}
public void setAdminId(Long adminId) {
this.adminId = adminId;
}
public Long getRoleId() {
return roleId;
} | public void setRoleId(Long roleId) {
this.roleId = roleId;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", adminId=").append(adminId);
sb.append(", roleId=").append(roleId);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsAdminRoleRelation.java | 1 |
请完成以下Java代码 | public String toString() {
PlanItem planItem = planItemInstanceEntity.getPlanItem();
StringBuilder stringBuilder = new StringBuilder();
String operationName = getOperationName();
stringBuilder.append(operationName != null ? operationName : "[Change plan item state]").append(" ");
if (planItem != null) {
stringBuilder.append(planItem);
}
stringBuilder.append(" (CaseInstance id: ");
stringBuilder.append(planItemInstanceEntity.getCaseInstanceId());
stringBuilder.append(", PlanItemInstance id: ");
stringBuilder.append(planItemInstanceEntity.getId());
stringBuilder.append("), ");
String currentState = planItemInstanceEntity.getState(); | String newState = getNewState();
if (!Objects.equals(currentState, newState)) {
stringBuilder.append("from [").append(currentState).append("] to new state: [").append(getNewState()).append("]");
stringBuilder.append(" with transition [");
stringBuilder.append(getLifeCycleTransition());
stringBuilder.append("]");
} else {
stringBuilder.append("will remain in state [").append(newState).append("]");
}
return stringBuilder.toString();
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\AbstractChangePlanItemInstanceStateOperation.java | 1 |
请完成以下Java代码 | public class CamundaErrorEventDefinitionImpl extends ErrorEventDefinitionImpl implements CamundaErrorEventDefinition {
protected static Attribute<String> camundaExpressionAttribute;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CamundaErrorEventDefinition.class, CAMUNDA_ELEMENT_ERROR_EVENT_DEFINITION)
.namespaceUri(CAMUNDA_NS)
.instanceProvider(new ModelTypeInstanceProvider<CamundaErrorEventDefinition>() {
public CamundaErrorEventDefinition newInstance(ModelTypeInstanceContext instanceContext) {
return new CamundaErrorEventDefinitionImpl(instanceContext);
}
});
camundaExpressionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_EXPRESSION)
.namespace(CAMUNDA_NS)
.build(); | typeBuilder.build();
}
public CamundaErrorEventDefinitionImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getCamundaExpression() {
return camundaExpressionAttribute.getValue(this);
}
public void setCamundaExpression(String camundaExpression) {
camundaExpressionAttribute.setValue(this, camundaExpression);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaErrorEventDefinitionImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public UserDetailsBuilder authorities(String... authorities) {
this.user.authorities(authorities);
return this;
}
/**
* Defines if the account is expired or not. Default is false.
* @param accountExpired true if the account is expired, false otherwise
* @return the {@link UserDetailsBuilder} for method chaining (i.e. to populate
* additional attributes for this user)
*/
public UserDetailsBuilder accountExpired(boolean accountExpired) {
this.user.accountExpired(accountExpired);
return this;
}
/**
* Defines if the account is locked or not. Default is false.
* @param accountLocked true if the account is locked, false otherwise
* @return the {@link UserDetailsBuilder} for method chaining (i.e. to populate
* additional attributes for this user)
*/
public UserDetailsBuilder accountLocked(boolean accountLocked) {
this.user.accountLocked(accountLocked);
return this;
}
/**
* Defines if the credentials are expired or not. Default is false.
* @param credentialsExpired true if the credentials are expired, false otherwise
* @return the {@link UserDetailsBuilder} for method chaining (i.e. to populate
* additional attributes for this user)
*/
public UserDetailsBuilder credentialsExpired(boolean credentialsExpired) {
this.user.credentialsExpired(credentialsExpired); | return this;
}
/**
* Defines if the account is disabled or not. Default is false.
* @param disabled true if the account is disabled, false otherwise
* @return the {@link UserDetailsBuilder} for method chaining (i.e. to populate
* additional attributes for this user)
*/
public UserDetailsBuilder disabled(boolean disabled) {
this.user.disabled(disabled);
return this;
}
UserDetails build() {
return this.user.build();
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\authentication\configurers\provisioning\UserDetailsManagerConfigurer.java | 2 |
请完成以下Java代码 | public class AstChoice extends AstRightValue {
private final AstNode question, yes, no;
public AstChoice(AstNode question, AstNode yes, AstNode no) {
this.question = question;
this.yes = yes;
this.no = no;
}
@Override
public Object eval(Bindings bindings, ELContext context) throws ELException {
Boolean value = bindings.convert(question.eval(bindings, context), Boolean.class);
return value.booleanValue() ? yes.eval(bindings, context) : no.eval(bindings, context);
}
@Override
public String toString() {
return "?";
}
@Override
public void appendStructure(StringBuilder b, Bindings bindings) { | question.appendStructure(b, bindings);
b.append(" ? ");
yes.appendStructure(b, bindings);
b.append(" : ");
no.appendStructure(b, bindings);
}
public int getCardinality() {
return 3;
}
public AstNode getChild(int i) {
return i == 0 ? question : i == 1 ? yes : i == 2 ? no : null;
}
} | repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstChoice.java | 1 |
请完成以下Java代码 | public static GS1Elements ofList(final List<GS1Element> list)
{
return new GS1Elements(list);
}
public List<GS1Element> toList() {return elements;}
public Optional<GTIN> getGTIN()
{
final GS1Element element = byApplicationIdentifier.get(GS1ApplicationIdentifier.GTIN);
if (element == null)
{
return Optional.empty();
}
return GTIN.optionalOfNullableString(element.getValueAsString());
}
public Optional<BigDecimal> getWeightInKg()
{
final GS1Element element = byApplicationIdentifier.get(GS1ApplicationIdentifier.ITEM_NET_WEIGHT_KG);
if (element == null)
{
return Optional.empty();
}
return Optional.of(element.getValueAsBigDecimal());
}
public Optional<LocalDate> getBestBeforeDate()
{ | final GS1Element element = byApplicationIdentifier.get(GS1ApplicationIdentifier.BEST_BEFORE_DATE);
if (element == null)
{
return Optional.empty();
}
return Optional.of(element.getValueAsLocalDate());
}
public Optional<String> getLotNumber()
{
final GS1Element element = byApplicationIdentifier.get(GS1ApplicationIdentifier.BATCH_OR_LOT_NUMBER);
if (element == null)
{
return Optional.empty();
}
return Optional.of(element.getValueAsString());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\gs1\GS1Elements.java | 1 |
请完成以下Java代码 | public Object getPersistentState() {
// membership is not updatable
return MembershipEntity.class;
}
public String getId() {
// For the sake of Entity caching the id is necessary
return id;
}
public void setId(String id) {
// For the sake of Entity caching the id is necessary
this.id = id;
}
public UserEntity getUser() {
return user;
}
public void setUser(UserEntity user) {
this.user = user;
}
public GroupEntity getGroup() {
return group;
}
public void setGroup(GroupEntity group) {
this.group = group;
}
// required for mybatis | public String getUserId(){
return user.getId();
}
// required for mybatis
public String getGroupId(){
return group.getId();
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[user=" + user
+ ", group=" + group
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\MembershipEntity.java | 1 |
请完成以下Java代码 | public void setM_ProductGroup(final de.metas.invoicecandidate.model.I_M_ProductGroup M_ProductGroup)
{
set_ValueFromPO(COLUMNNAME_M_ProductGroup_ID, de.metas.invoicecandidate.model.I_M_ProductGroup.class, M_ProductGroup);
}
@Override
public void setM_ProductGroup_ID (final int M_ProductGroup_ID)
{
if (M_ProductGroup_ID < 1)
set_Value (COLUMNNAME_M_ProductGroup_ID, null);
else
set_Value (COLUMNNAME_M_ProductGroup_ID, M_ProductGroup_ID);
}
@Override
public int getM_ProductGroup_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ProductGroup_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
} | @Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void 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.swat\de.metas.swat.base\src\main\java-gen\de\metas\invoicecandidate\model\X_C_Invoice_Candidate_Agg.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class MappingJackson2HttpMessageConverterConfiguration {
@Bean
@ConditionalOnMissingBean(org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.class)
Jackson2JsonMessageConvertersCustomizer jackson2HttpMessageConvertersCustomizer(ObjectMapper objectMapper) {
return new Jackson2JsonMessageConvertersCustomizer(objectMapper);
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(XmlMapper.class)
@ConditionalOnBean(org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.class)
protected static class MappingJackson2XmlHttpMessageConverterConfiguration {
@Bean
@ConditionalOnMissingBean(org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter.class)
Jackson2XmlMessageConvertersCustomizer mappingJackson2XmlHttpMessageConverter(
Jackson2ObjectMapperBuilder builder) {
return new Jackson2XmlMessageConvertersCustomizer(builder.createXmlMapper(true).build());
}
}
static class Jackson2JsonMessageConvertersCustomizer
implements ClientHttpMessageConvertersCustomizer, ServerHttpMessageConvertersCustomizer {
private final ObjectMapper objectMapper;
Jackson2JsonMessageConvertersCustomizer(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public void customize(ClientBuilder builder) {
builder.withJsonConverter(
new org.springframework.http.converter.json.MappingJackson2HttpMessageConverter(this.objectMapper));
}
@Override
public void customize(ServerBuilder builder) {
builder.withJsonConverter(
new org.springframework.http.converter.json.MappingJackson2HttpMessageConverter(this.objectMapper));
}
}
static class Jackson2XmlMessageConvertersCustomizer
implements ClientHttpMessageConvertersCustomizer, ServerHttpMessageConvertersCustomizer {
private final ObjectMapper objectMapper; | Jackson2XmlMessageConvertersCustomizer(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public void customize(ClientBuilder builder) {
builder.withXmlConverter(new org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter(
this.objectMapper));
}
@Override
public void customize(ServerBuilder builder) {
builder.withXmlConverter(new org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter(
this.objectMapper));
}
}
private static class PreferJackson2OrJacksonUnavailableCondition extends AnyNestedCondition {
PreferJackson2OrJacksonUnavailableCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY,
havingValue = "jackson2")
static class Jackson2Preferred {
}
@ConditionalOnMissingBean(JacksonJsonHttpMessageConvertersCustomizer.class)
static class JacksonUnavailable {
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-http-converter\src\main\java\org\springframework\boot\http\converter\autoconfigure\Jackson2HttpMessageConvertersConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Category implements Serializable {
@Id
@Column(unique = true, nullable = false)
private long id;
private String name;
@OneToMany
@JoinColumn(name = "category_id", foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
private List<Item> items = new ArrayList<>();
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
} | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
} | repos\tutorials-master\persistence-modules\hibernate-exceptions-2\src\main\java\com\baeldung\hibernate\entitynotfoundexception\Category.java | 2 |
请完成以下Java代码 | public class DependsOnType {
@XmlAttribute(name = "name", required = true)
protected String name;
@XmlAttribute(name = "copyright")
protected String copyright;
@XmlAttribute(name = "description")
protected String description;
@XmlAttribute(name = "version")
@XmlSchemaType(name = "unsignedInt")
protected Long version;
@XmlAttribute(name = "id")
@XmlSchemaType(name = "unsignedInt")
protected Long id;
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the copyright property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCopyright() {
return copyright;
}
/**
* Sets the value of the copyright property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCopyright(String value) {
this.copyright = value;
}
/**
* Gets the value of the description property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDescription(String value) {
this.description = value;
}
/**
* Gets the value of the version property.
*
* @return
* possible object is
* {@link Long } | *
*/
public Long getVersion() {
return version;
}
/**
* Sets the value of the version property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setVersion(Long value) {
this.version = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link Long }
*
*/
public long getId() {
if (id == null) {
return 0L;
} else {
return id;
}
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setId(Long value) {
this.id = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\DependsOnType.java | 1 |
请完成以下Java代码 | protected void executeSchemaOperations() {
commandExecutorSchemaOperations.execute(processEngineConfiguration.getSchemaOperationsCommand());
commandExecutorSchemaOperations.execute(processEngineConfiguration.getHistoryLevelCommand());
try {
commandExecutorSchemaOperations.execute(processEngineConfiguration.getProcessEngineBootstrapCommand());
} catch (OptimisticLockingException ole) {
// if an OLE occurred during the process engine bootstrap, we suppress it
// since all the data has already been persisted by a previous process engine bootstrap
LOG.historyCleanupJobReconfigurationFailure(ole);
}
}
@Override
public void close() {
ProcessEngines.unregister(this);
if(processEngineConfiguration.isMetricsEnabled()) {
processEngineConfiguration.getDbMetricsReporter().stop();
}
if ((jobExecutor != null)) {
// unregister process engine with Job Executor
jobExecutor.unregisterProcessEngine(this);
}
commandExecutorSchemaOperations.execute(new SchemaOperationProcessEngineClose());
processEngineConfiguration.close();
LOG.processEngineClosed(name);
}
@Override
public String getName() {
return name;
}
@Override
public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
}
@Override
public IdentityService getIdentityService() {
return identityService;
}
@Override
public ManagementService getManagementService() {
return managementService;
} | @Override
public TaskService getTaskService() {
return taskService;
}
@Override
public HistoryService getHistoryService() {
return historicDataService;
}
@Override
public RuntimeService getRuntimeService() {
return runtimeService;
}
@Override
public RepositoryService getRepositoryService() {
return repositoryService;
}
@Override
public FormService getFormService() {
return formService;
}
@Override
public AuthorizationService getAuthorizationService() {
return authorizationService;
}
@Override
public CaseService getCaseService() {
return caseService;
}
@Override
public FilterService getFilterService() {
return filterService;
}
@Override
public ExternalTaskService getExternalTaskService() {
return externalTaskService;
}
@Override
public DecisionService getDecisionService() {
return decisionService;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessEngineImpl.java | 1 |
请完成以下Java代码 | public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getSeqNo()));
}
/** Set X Position.
@param XPosition
Absolute X (horizontal) position in 1/72 of an inch
*/
public void setXPosition (int XPosition)
{
set_Value (COLUMNNAME_XPosition, Integer.valueOf(XPosition));
}
/** Get X Position.
@return Absolute X (horizontal) position in 1/72 of an inch | */
public int getXPosition ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_XPosition);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Y Position.
@param YPosition
Absolute Y (vertical) position in 1/72 of an inch
*/
public void setYPosition (int YPosition)
{
set_Value (COLUMNNAME_YPosition, Integer.valueOf(YPosition));
}
/** Get Y Position.
@return Absolute Y (vertical) position in 1/72 of an inch
*/
public int getYPosition ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_YPosition);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintLabelLine.java | 1 |
请完成以下Java代码 | public class FileSystemSingleton implements SingletonInterface{
private int filesWritten;
private FileSystemSingleton() {
}
private static class SingletonHolder {
public static final FileSystemSingleton instance = new FileSystemSingleton();
}
public static FileSystemSingleton getInstance() {
return SingletonHolder.instance;
}
@Override
public String describeMe() { | return "File System Responsibilities";
}
@Override
public String passOnLocks(MyLock lock) {
return lock.takeLock(2);
}
@Override
public void increment() {
this.filesWritten++;
}
public int getFilesWritten() {
return filesWritten;
}
} | repos\tutorials-master\core-java-modules\core-java-lang-oop-modifiers-2\src\main\java\com\baeldung\staticsingletondifference\FileSystemSingleton.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserDao {
@Autowired
private SessionFactory _sessionFactory;
private Session getSession() {
return _sessionFactory.getCurrentSession();
}
public void save(User user) {
getSession().save(user);
return;
}
public void delete(User user) {
getSession().delete(user);
return;
}
@SuppressWarnings("unchecked")
public List<User> getAll() {
return getSession().createQuery("from User").list();
} | public User getByEmail(String email) {
return (User) getSession().createQuery(
"from User where email = :email")
.setParameter("email", email)
.uniqueResult();
}
public User getById(long id) {
return (User) getSession().load(User.class, id);
}
public void update(User user) {
getSession().update(user);
return;
}
} // class UserDao | repos\spring-boot-samples-master\spring-boot-mysql-hibernate\src\main\java\netgloo\models\UserDao.java | 2 |
请完成以下Java代码 | public void setHospitalizationType(String value) {
this.hospitalizationType = value;
}
/**
* Gets the value of the hospitalizationMode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHospitalizationMode() {
if (hospitalizationMode == null) {
return "cantonal";
} else {
return hospitalizationMode;
}
}
/**
* Sets the value of the hospitalizationMode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHospitalizationMode(String value) {
this.hospitalizationMode = value;
}
/**
* Gets the value of the clazz property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getClazz() {
if (clazz == null) {
return "general";
} else {
return clazz;
}
}
/**
* Sets the value of the clazz property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClazz(String value) {
this.clazz = value;
}
/**
* Gets the value of the sectionMajor property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSectionMajor() {
return sectionMajor;
}
/**
* Sets the value of the sectionMajor property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSectionMajor(String value) {
this.sectionMajor = value;
}
/** | * Gets the value of the hasExpenseLoading property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public boolean isHasExpenseLoading() {
if (hasExpenseLoading == null) {
return true;
} else {
return hasExpenseLoading;
}
}
/**
* Sets the value of the hasExpenseLoading property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setHasExpenseLoading(Boolean value) {
this.hasExpenseLoading = value;
}
/**
* Gets the value of the doCostAssessment property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public boolean isDoCostAssessment() {
if (doCostAssessment == null) {
return false;
} else {
return doCostAssessment;
}
}
/**
* Sets the value of the doCostAssessment property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setDoCostAssessment(Boolean value) {
this.doCostAssessment = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\XtraStationaryType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserController {
private final UserRepository userRepository;
@Autowired
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@GetMapping("/signup")
public String showSignUpForm(User user) {
return "add-user";
}
@PostMapping("/adduser")
public String addUser(@Valid User user, BindingResult result, Model model) {
if (result.hasErrors()) {
return "add-user";
}
userRepository.save(user);
model.addAttribute("users", userRepository.findAll());
return "index";
}
@GetMapping("/edit/{id}")
public String showUpdateForm(@PathVariable("id") long id, Model model) {
User user = userRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id));
model.addAttribute("user", user);
return "update-user";
}
@PostMapping("/update/{id}")
public String updateUser(@PathVariable("id") long id, @Valid User user, BindingResult result, Model model) {
if (result.hasErrors()) { | user.setId(id);
return "update-user";
}
userRepository.save(user);
model.addAttribute("users", userRepository.findAll());
return "index";
}
@GetMapping("/delete/{id}")
public String deleteUser(@PathVariable("id") long id, Model model) {
User user = userRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id));
userRepository.delete(user);
model.addAttribute("users", userRepository.findAll());
return "index";
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence\src\main\java\com\baeldung\springbootcrudapp\application\controllers\UserController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getComment1() {
return comment1;
}
/**
* Sets the value of the comment1 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setComment1(String value) {
this.comment1 = value;
}
/**
* Gets the value of the comment2 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getComment2() {
return comment2;
}
/**
* Sets the value of the comment2 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setComment2(String value) {
this.comment2 = value;
}
/**
* Gets the value of the commercialInvoiceConsigneeVatNumber property.
*
* @return | * possible object is
* {@link String }
*
*/
public String getCommercialInvoiceConsigneeVatNumber() {
return commercialInvoiceConsigneeVatNumber;
}
/**
* Sets the value of the commercialInvoiceConsigneeVatNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCommercialInvoiceConsigneeVatNumber(String value) {
this.commercialInvoiceConsigneeVatNumber = value;
}
/**
* Gets the value of the commercialInvoiceConsignee property.
*
* @return
* possible object is
* {@link Address }
*
*/
public Address getCommercialInvoiceConsignee() {
return commercialInvoiceConsignee;
}
/**
* Sets the value of the commercialInvoiceConsignee property.
*
* @param value
* allowed object is
* {@link Address }
*
*/
public void setCommercialInvoiceConsignee(Address value) {
this.commercialInvoiceConsignee = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\International.java | 2 |
请完成以下Java代码 | public List<State> getAllPossibleStates() {
List<State> possibleStates = new ArrayList<>();
List<Position> availablePositions = this.board.getEmptyPositions();
availablePositions.forEach(p -> {
State newState = new State(this.board);
newState.setPlayerNo(3 - this.playerNo);
newState.getBoard().performMove(newState.getPlayerNo(), p);
possibleStates.add(newState);
});
return possibleStates;
}
void incrementVisit() {
this.visitCount++;
}
void addScore(double score) { | if (this.winScore != Integer.MIN_VALUE)
this.winScore += score;
}
void randomPlay() {
List<Position> availablePositions = this.board.getEmptyPositions();
int totalPossibilities = availablePositions.size();
int selectRandom = (int) (Math.random() * totalPossibilities);
this.board.performMove(this.playerNo, availablePositions.get(selectRandom));
}
void togglePlayer() {
this.playerNo = 3 - this.playerNo;
}
} | repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\mcts\montecarlo\State.java | 1 |
请完成以下Java代码 | public long iterateUsingIteratorAndEntrySet(Map<Integer, Integer> map) {
long sum = 0;
Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet()
.iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, Integer> pair = iterator.next();
sum += pair.getValue();
}
return sum;
}
public long iterateUsingIteratorAndKeySet(Map<Integer, Integer> map) {
long sum = 0;
Iterator<Integer> iterator = map.keySet()
.iterator();
while (iterator.hasNext()) {
Integer key = iterator.next();
sum += map.get(key);
}
return sum;
}
public long iterateUsingKeySetAndEnhanceForLoop(Map<Integer, Integer> map) {
long sum = 0;
for (Integer key : map.keySet()) {
sum += map.get(key);
}
return sum;
}
public long iterateUsingStreamAPIAndEntrySet(Map<Integer, Integer> map) {
return map.entrySet()
.stream()
.mapToLong(Map.Entry::getValue)
.sum();
}
public long iterateUsingStreamAPIAndKeySet(Map<Integer, Integer> map) {
return map.keySet()
.stream()
.mapToLong(map::get)
.sum();
}
public long iterateKeysUsingKeySetAndEnhanceForLoop(Map<Integer, Integer> map) {
long sum = 0;
for (Integer key : map.keySet()) {
sum += map.get(key);
}
return sum; | }
public long iterateValuesUsingValuesMethodAndEnhanceForLoop(Map<Integer, Integer> map) {
long sum = 0;
for (Integer value : map.values()) {
sum += value;
}
return sum;
}
public long iterateUsingMapIteratorApacheCollection(IterableMap<Integer, Integer> map) {
long sum = 0;
MapIterator<Integer, Integer> iterate = map.mapIterator();
while (iterate.hasNext()) {
iterate.next();
sum += iterate.getValue();
}
return sum;
}
public long iterateEclipseMap(MutableMap<Integer, Integer> mutableMap) throws IOException {
AtomicLong sum = new AtomicLong(0);
mutableMap.forEachKeyValue((key, value) -> {
sum.addAndGet(value);
});
return sum.get();
}
public long iterateMapUsingParallelStreamApi(Map<Integer, Integer> map) throws IOException {
return map.entrySet()
.parallelStream()
.mapToLong(Map.Entry::getValue)
.sum();
}
} | repos\tutorials-master\core-java-modules\core-java-collections-maps\src\main\java\com\baeldung\map\iteration\MapIteration.java | 1 |
请完成以下Java代码 | private static byte[] downloadImageData(String fileUrl) throws IOException {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(10000);
connection.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
connection.setRequestProperty("Accept", "image/*");
int responseCode = connection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
throw new IOException("HTTP请求失败,响应码: " + responseCode);
}
try (InputStream inputStream = connection.getInputStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
return outputStream.toByteArray();
} finally {
connection.disconnect();
}
}
/**
* byte转 MultipartFile
*
* @param data
* @param fileName
* @return
*/
private static MultipartFile convertByteToMultipartFile(byte[] data, String fileName) { | FileItemFactory factory = new DiskFileItemFactory();
FileItem item = factory.createItem(fileName, "application/octet-stream", true, fileName);
try (OutputStream os = item.getOutputStream();
ByteArrayInputStream bis = new ByteArrayInputStream(data)) {
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
throw new RuntimeException("字节数组转换失败", e);
}
try {
return new MyCommonsMultipartFile(item);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\util\HttpFileToMultipartFileUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class GLCategoryId implements RepoIdAware
{
public static final GLCategoryId NONE = new GLCategoryId(0);
int repoId;
@JsonCreator
public static GLCategoryId ofRepoId(final int repoId)
{
if (repoId == NONE.getRepoId())
{
return NONE;
}
return new GLCategoryId(repoId);
}
@NonNull
public static GLCategoryId ofRepoIdOrNone(final int repoId)
{
return repoId > 0 ? new GLCategoryId(repoId) : NONE;
}
public static int toRepoId(@Nullable final GLCategoryId glCategoryId)
{
return glCategoryId != null ? glCategoryId.getRepoId() : -1;
}
@Nullable
public static GLCategoryId ofRepoIdOrNull(final int repoId)
{
if (repoId < 0) | {
return null;
}
return ofRepoIdOrNone(repoId);
}
private GLCategoryId(final int repoId)
{
this.repoId = Check.assumeGreaterOrEqualToZero(repoId, "GL_Category_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\GLCategoryId.java | 2 |
请完成以下Java代码 | public void uncaughtException (Thread t, Throwable e)
{
log.info("uncaughtException = " + e.toString());
super.uncaughtException (t, e);
} // uncaughtException
/**
* String Representation
* @return name
*/
@Override
public String toString ()
{
return getName();
} // toString
/**
* Dump Info
*/ | public void dump()
{
if (!log.isDebugEnabled())
{
return;
}
log.debug(getName() + (isDestroyed() ? " (destroyed)" : ""));
log.debug("- Parent=" + getParent());
Thread[] list = new Thread[activeCount()];
log.debug("- Count=" + enumerate(list, true));
for (int i = 0; i < list.length; i++)
{
log.debug("-- " + list[i]);
}
} // dump
} // AdempiereServerGroup | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\compiere\server\AdempiereServerGroup.java | 1 |
请完成以下Java代码 | public class X_x_esr_import_in_c_bankstatement_v extends org.compiere.model.PO implements I_x_esr_import_in_c_bankstatement_v, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 767880106L;
/** Standard Constructor */
public X_x_esr_import_in_c_bankstatement_v (final Properties ctx, final int x_esr_import_in_c_bankstatement_v_ID, @Nullable final String trxName)
{
super (ctx, x_esr_import_in_c_bankstatement_v_ID, trxName);
}
/** Load Constructor */
public X_x_esr_import_in_c_bankstatement_v (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_BankStatement_ID (final int C_BankStatement_ID)
{
if (C_BankStatement_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BankStatement_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BankStatement_ID, C_BankStatement_ID);
}
@Override
public int getC_BankStatement_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BankStatement_ID);
}
@Override | public void setDateDoc (final @Nullable java.sql.Timestamp DateDoc)
{
set_ValueNoCheck (COLUMNNAME_DateDoc, DateDoc);
}
@Override
public java.sql.Timestamp getDateDoc()
{
return get_ValueAsTimestamp(COLUMNNAME_DateDoc);
}
@Override
public de.metas.payment.esr.model.I_ESR_Import getESR_Import()
{
return get_ValueAsPO(COLUMNNAME_ESR_Import_ID, de.metas.payment.esr.model.I_ESR_Import.class);
}
@Override
public void setESR_Import(final de.metas.payment.esr.model.I_ESR_Import ESR_Import)
{
set_ValueFromPO(COLUMNNAME_ESR_Import_ID, de.metas.payment.esr.model.I_ESR_Import.class, ESR_Import);
}
@Override
public void setESR_Import_ID (final int ESR_Import_ID)
{
if (ESR_Import_ID < 1)
set_ValueNoCheck (COLUMNNAME_ESR_Import_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ESR_Import_ID, ESR_Import_ID);
}
@Override
public int getESR_Import_ID()
{
return get_ValueAsInt(COLUMNNAME_ESR_Import_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_x_esr_import_in_c_bankstatement_v.java | 1 |
请完成以下Java代码 | public void setTextValue2(String textValue2) {}
@Override
public Long getLongValue() {
return null;
}
@Override
public void setLongValue(Long longValue) {}
@Override
public Double getDoubleValue() {
return null;
}
@Override
public void setDoubleValue(Double doubleValue) {}
@Override
public byte[] getBytes() {
return null;
}
@Override
public void setBytes(byte[] bytes) {}
@Override
public Object getCachedValue() {
return null;
}
@Override
public void setCachedValue(Object cachedValue) {}
@Override
public String getId() {
return null;
}
@Override
public void setId(String id) {}
@Override
public boolean isInserted() {
return false;
}
@Override
public void setInserted(boolean inserted) {}
@Override
public boolean isUpdated() {
return false;
}
@Override
public void setUpdated(boolean updated) {}
@Override
public boolean isDeleted() {
return false;
}
@Override
public void setDeleted(boolean deleted) {}
@Override
public Object getPersistentState() {
return null;
}
@Override
public void setRevision(int revision) {}
@Override
public int getRevision() {
return 0;
}
@Override
public int getRevisionNext() { | return 0;
}
@Override
public void setName(String name) {}
@Override
public void setProcessInstanceId(String processInstanceId) {}
@Override
public void setExecutionId(String executionId) {}
@Override
public Object getValue() {
return variableValue;
}
@Override
public void setValue(Object value) {
variableValue = value;
}
@Override
public String getTypeName() {
return TYPE_TRANSIENT;
}
@Override
public void setTypeName(String typeName) {}
@Override
public String getProcessInstanceId() {
return null;
}
@Override
public String getTaskId() {
return null;
}
@Override
public void setTaskId(String taskId) {}
@Override
public String getExecutionId() {
return null;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TransientVariableInstance.java | 1 |
请完成以下Java代码 | public String toString()
{
StringBuffer sb = new StringBuffer("[")
.append("Count=").append(m_count).append(",").append(m_totalCount)
.append(",Sum=").append(m_sum)
.append(",SumSquare=").append(m_sumSquare)
.append(",Min=").append(m_min)
.append(",Max=").append(m_max);
sb.append("]");
return sb.toString();
} // toString
/*************************************************************************/
/**
* Get Function Symbol of function
* @param function function
* @return function symbol
*/
static public String getFunctionSymbol (char function)
{
for (int i = 0; i < FUNCTIONS.length; i++)
{
if (FUNCTIONS[i] == function)
return FUNCTION_SYMBOLS[i];
}
return "UnknownFunction=" + function;
} // getFunctionSymbol
/**
* Get Function Name of function
* @param function function
* @return function name
*/
static public String getFunctionName (char function)
{
for (int i = 0; i < FUNCTIONS.length; i++)
{ | if (FUNCTIONS[i] == function)
return FUNCTION_NAMES[i];
}
return "UnknownFunction=" + function;
} // getFunctionName
/**
* Get DisplayType of function
* @param function function
* @param displayType columns display type
* @return function name
*/
static public int getFunctionDisplayType (char function, int displayType)
{
if (function == F_SUM || function == F_MIN || function == F_MAX)
return displayType;
if (function == F_COUNT)
return DisplayType.Integer;
// Mean, Variance, Std. Deviation
return DisplayType.Number;
}
} // PrintDataFunction | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\PrintDataFunction.java | 1 |
请完成以下Java代码 | public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
chain.doFilter(this.requestFactory.create((HttpServletRequest) req, (HttpServletResponse) res), res);
}
@Override
public void afterPropertiesSet() throws ServletException {
super.afterPropertiesSet();
updateFactory();
}
private void updateFactory() {
String rolePrefix = this.rolePrefix;
this.requestFactory = createServlet3Factory(rolePrefix);
}
/**
* Sets the {@link AuthenticationTrustResolver} to be used. The default is
* {@link AuthenticationTrustResolverImpl}.
* @param trustResolver the {@link AuthenticationTrustResolver} to use. Cannot be
* null. | */
public void setTrustResolver(AuthenticationTrustResolver trustResolver) {
Assert.notNull(trustResolver, "trustResolver cannot be null");
this.trustResolver = trustResolver;
updateFactory();
}
private HttpServletRequestFactory createServlet3Factory(String rolePrefix) {
HttpServlet3RequestFactory factory = new HttpServlet3RequestFactory(rolePrefix, this.securityContextRepository);
factory.setTrustResolver(this.trustResolver);
factory.setAuthenticationEntryPoint(this.authenticationEntryPoint);
factory.setAuthenticationManager(this.authenticationManager);
factory.setLogoutHandlers(this.logoutHandlers);
factory.setSecurityContextHolderStrategy(this.securityContextHolderStrategy);
return factory;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\servletapi\SecurityContextHolderAwareRequestFilter.java | 1 |
请完成以下Java代码 | public void setSel_Product_ID (final int Sel_Product_ID)
{
if (Sel_Product_ID < 1)
set_Value (COLUMNNAME_Sel_Product_ID, null);
else
set_Value (COLUMNNAME_Sel_Product_ID, Sel_Product_ID);
}
@Override
public int getSel_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_Sel_Product_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
} | @Override
public void setT_BOMLine_ID (final int T_BOMLine_ID)
{
if (T_BOMLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_T_BOMLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_T_BOMLine_ID, T_BOMLine_ID);
}
@Override
public int getT_BOMLine_ID()
{
return get_ValueAsInt(COLUMNNAME_T_BOMLine_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_T_BOMLine.java | 1 |
请完成以下Java代码 | public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public void addActivityInstanceReport(MigratingActivityInstanceValidationReport instanceReport) {
activityInstanceReports.add(instanceReport);
}
public void addTransitionInstanceReport(MigratingTransitionInstanceValidationReport instanceReport) {
transitionInstanceReports.add(instanceReport);
}
public List<MigratingActivityInstanceValidationReport> getActivityInstanceReports() {
return activityInstanceReports;
}
@Override
public List<MigratingTransitionInstanceValidationReport> getTransitionInstanceReports() {
return transitionInstanceReports;
}
public void addFailure(String failure) {
failures.add(failure);
}
public List<String> getFailures() {
return failures;
}
public boolean hasFailures() {
return !failures.isEmpty() || !activityInstanceReports.isEmpty() || !transitionInstanceReports.isEmpty();
}
public void writeTo(StringBuilder sb) {
sb.append("Cannot migrate process instance '")
.append(processInstanceId)
.append("':\n");
for (String failure : failures) {
sb.append("\t").append(failure).append("\n"); | }
for (MigratingActivityInstanceValidationReport report : activityInstanceReports) {
sb.append("\tCannot migrate activity instance '")
.append(report.getActivityInstanceId())
.append("':\n");
for (String failure : report.getFailures()) {
sb.append("\t\t").append(failure).append("\n");
}
}
for (MigratingTransitionInstanceValidationReport report : transitionInstanceReports) {
sb.append("\tCannot migrate transition instance '")
.append(report.getTransitionInstanceId())
.append("':\n");
for (String failure : report.getFailures()) {
sb.append("\t\t").append(failure).append("\n");
}
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\validation\instance\MigratingProcessInstanceValidationReportImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ExternalSystemServiceInstance create(@NonNull final CreateServiceInstanceRequest request)
{
final I_ExternalSystem_Service_Instance externalSysInstanceRecord = newInstance(I_ExternalSystem_Service_Instance.class);
externalSysInstanceRecord.setExternalSystem_Service_ID(request.getServiceId().getRepoId());
externalSysInstanceRecord.setExternalSystem_Config_ID(request.getConfigId().getRepoId());
externalSysInstanceRecord.setExpectedStatus(request.getExpectedStatus().getCode());
saveRecord(externalSysInstanceRecord);
return ofRecord(externalSysInstanceRecord);
}
@NonNull
public ExternalSystemServiceInstance update(@NonNull final ExternalSystemServiceInstance instance)
{
final I_ExternalSystem_Service_Instance externalSysInstanceRecord = InterfaceWrapperHelper.load(instance.getId(), I_ExternalSystem_Service_Instance.class);
externalSysInstanceRecord.setExternalSystem_Service_ID(instance.getService().getId().getRepoId());
externalSysInstanceRecord.setExternalSystem_Config_ID(instance.getConfigId().getRepoId());
externalSysInstanceRecord.setExpectedStatus(instance.getExpectedStatus().getCode());
saveRecord(externalSysInstanceRecord);
return ofRecord(externalSysInstanceRecord);
}
@NonNull
public Optional<ExternalSystemServiceInstance> getByConfigAndServiceId(@NonNull final ExternalSystemParentConfigId configId, @NonNull final ExternalSystemServiceId serviceId)
{
return queryBL.createQueryBuilder(I_ExternalSystem_Service_Instance.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_ExternalSystem_Service_Instance.COLUMN_ExternalSystem_Config_ID, configId)
.addEqualsFilter(I_ExternalSystem_Service_Instance.COLUMN_ExternalSystem_Service_ID, serviceId)
.create()
.firstOnlyOptional(I_ExternalSystem_Service_Instance.class) | .map(this::ofRecord);
}
@NonNull
public Stream<ExternalSystemServiceInstance> streamByConfigIds(@NonNull final Set<ExternalSystemParentConfigId> configIds)
{
return queryBL.createQueryBuilder(I_ExternalSystem_Service_Instance.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_ExternalSystem_Service_Instance.COLUMNNAME_ExternalSystem_Config_ID, configIds)
.create()
.stream()
.map(this::ofRecord);
}
@NonNull
private ExternalSystemServiceInstance ofRecord(@NonNull final I_ExternalSystem_Service_Instance record)
{
final ExternalSystemServiceModel service = serviceRepository.getById(ExternalSystemServiceId.ofRepoId(record.getExternalSystem_Service_ID()));
return ExternalSystemServiceInstance.builder()
.id(ExternalSystemServiceInstanceId.ofRepoId(record.getExternalSystem_Service_Instance_ID()))
.service(service)
.configId(ExternalSystemParentConfigId.ofRepoId(record.getExternalSystem_Config_ID()))
.expectedStatus(ExternalStatus.ofCode(record.getExpectedStatus()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\externalservice\externalserviceinstance\ExternalSystemServiceInstanceRepository.java | 2 |
请完成以下Spring Boot application配置 | server.port=8081
# \u6570\u636E\u6E90\u914D\u7F6E
#https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter
spring.datasource.druid.url=jdbc:h2:mem:ssb_test
spring.datasource.druid.driver-class-name=org.h2.Driver
spring.datasource.druid.username=root
spring.datasource.druid.password=root
spring.datasource.schema=classpath:db/schema.sql
spring.datasource.data=classpath:db/data.sql
# \u8FDB\u884C\u8BE5\u914D\u7F6E\u540E\uFF0Ch2 web consloe\u5C31\u53EF\u4EE5\u5728\u8FDC\u7A0B\u8BBF\u95EE\u4E86\u3002\u5426\u5219\u53EA\u80FD\u5728\u672C\u673A\u8BBF\u95EE\u3002
spring.h2.console.settings.web-allow-others=true
# \u8FDB\u884C\u8BE5\u914D\u7F6E\uFF0C\u4F60\u5C31\u53EF\u4EE5\u901A\u8FC7YOUR_URL/h2-console\u8BBF\u95EEh2 web consloe\u3002YOUR_URL\u662F\u4F60\u7A0B\u5E8F\u7684\u8BBF\u95EEURl\u3002
spring.h2.console.path=/h2-console
# \u521D\u59CB\u5316\u5927\u5C0F\uFF0C\u6700\u5C0F\uFF0C\u6700\u5927
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-active=20
# \u914D\u7F6E\u83B7\u53D6\u8FDE\u63A5\u7B49\u5F85\u8D85\u65F6\u7684\u65F6\u95F4
spring.datasource.druid.max-wait=60000
# \u914D\u7F6E\u95F4\u9694\u591A\u4E45\u624D\u8FDB\u884C\u4E00\u6B21\u68C0\u6D4B\uFF0C\u68C0\u6D4B\u9700\u8981\u5173\u95ED\u7684\u7A7A\u95F2\u8FDE\u63A5\uFF0C\u5355\u4F4D\u662F\u6BEB\u79D2
spring.datasource.druid.time-between-eviction-runs-millis=60000
# \u914D\u7F6E\u4E00\u4E2A\u8FDE\u63A5\u5728\u6C60\u4E2D\u6700\u5C0F\u751F\u5B58\u7684\u65F6\u95F4\uFF0C\u5355\u4F4D\u662F\u6BEB\u79D2
spring.datasource.druid.min-evictable-idle-time-millis=300000
#\u68C0\u6D4B\u8FDE\u63A5\u662F\u5426\u6709\u6548\u7684sql
spring.datasource.druid.validation-query=SELECT 'x'
spring.datasource.druid.validation-query-timeout=60000
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
# PSCache Mysql\u4E0B\u5EFA\u8BAE\u5173\u95ED
spring.datasource.druid.pool-prepared-statements=false
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=-1
#spring.datasource.druid.max-open-prepared-statements= #\u7B49\u4EF7\u4E8E\u4E0A\u9762\u7684max-pool-prepared-statement-per-connection-size
# \u914D\u7F6E\u76D1\u63A7\u7EDF\u8BA1\u62E6\u622A\u7684filters\uFF0C\u53BB\u6389\u540E\u76D1\u63A7\u754C\u9762sql\u65E0\u6CD5\u7EDF\u8BA1\uFF0C'wall'\u7528\u4E8E\u9632\u706B\u5899
spring.datasource.druid.filters=stat,wall,log4j
# WebStatFilter\u914D\u7F6E\uFF0C\u8BF4\u660E\u8BF7\u53C2\u8003Druid Wiki\uFF0C\u914D\u7F6E_\u914D\u7F6EWebStatFilter
#\u542F\u52A8\u9879\u76EE\u540E\u8BBF\u95EE http://127.0.0.1:8080/druid
#\u662F\u5426\u542F\u7528StatFilter\u9ED8\u8BA4\u503Ctrue
spring.datasource.druid.web-stat-filter.enabled=true
spring.datasource.druid.web-stat-filter.url-pattern=/*
spring.datasource.druid.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*
#\u7F3A\u7701sessionStatMaxCount\u662F1000\u4E2A
spring.datasource.druid.web-stat-filter.session-stat-max-count=1000
#\u5173\u95EDsession\u7EDF\u8BA1\u529F\u80FD
spring.datasource.druid.web-stat-filter.session-stat-enable=false
#\u914D\u7F6EprincipalSessionName\uFF0C\u4F7F\u5F97druid\u80FD\u591F\u77E5\u9053\u5F53\u524D\u7684session\u7684\u7528\u6237\u662F\u8C01
#\u5982\u679C\u4F60session\u4E2D\u4FDD\u5B58\u7684\u662F\u975Estring\u7C7B\u578B\u7684\u5BF9\u8C61\uFF0C\u9700\u8981\u91CD\u8F7DtoString\u65B9\u6CD5
spring.datasource.druid.web-stat-filter.principalSessionName=xxx.user
#\u5982\u679Cuser\u4FE1\u606F\u4FDD\u5B58\u5728cookie\u4E2D\uFF0C\u4F60\u53EF\u4EE5\u914D\u7F6EprincipalCookieName\uFF0C\u4F7F\u5F97druid\u77E5\u9053\u5F53\u524D\u7684user\u662F\u8C01
spring.datasource.druid.web-stat-filter.principalCookieName=xxx.user
#druid 0.2.7\u7248\u672C\u5F00\u59CB\u652F\u6301profile\uFF0C\u914D\u7F6EprofileEnable\u80FD\u591F\u76D1\u63A7\u5355\u4E2Aurl\u8C03\u7528\ | u7684sql\u5217\u8868\u3002
spring.datasource.druid.web-stat-filter.profile-enable=false
# StatViewServlet\u914D\u7F6E\uFF0C\u8BF4\u660E\u8BF7\u53C2\u8003Druid Wiki\uFF0C\u914D\u7F6E_StatViewServlet\u914D\u7F6E
#\u662F\u5426\u542F\u7528StatViewServlet\u9ED8\u8BA4\u503Ctrue
spring.datasource.druid.stat-view-servlet.enabled=true
spring.datasource.druid.stat-view-servlet.urlPattern=/druid/*
#\u7981\u7528HTML\u9875\u9762\u4E0A\u7684\u201CReset All\u201D\u529F\u80FD
spring.datasource.druid.stat-view-servlet.resetEnable=false
#\u7528\u6237\u540D
spring.datasource.druid.stat-view-servlet.loginUsername=admin
#\u5BC6\u7801
spring.datasource.druid.stat-view-servlet.loginPassword=admin
#IP\u767D\u540D\u5355(\u6CA1\u6709\u914D\u7F6E\u6216\u8005\u4E3A\u7A7A\uFF0C\u5219\u5141\u8BB8\u6240\u6709\u8BBF\u95EE)
spring.datasource.druid.stat-view-servlet.allow=127.0.0.1,192.168.163.1
#IP\u9ED1\u540D\u5355 (\u5B58\u5728\u5171\u540C\u65F6\uFF0Cdeny\u4F18\u5148\u4E8Eallow)
spring.datasource.druid.stat-view-servlet.deny=192.168.1.73
#mybatis
#entity\u626B\u63CF\u7684\u5305\u540D
mybatis.type-aliases-package=com.xiaolyuh.domain.model
#Mapper.xml\u6240\u5728\u7684\u4F4D\u7F6E
mybatis.mapper-locations=classpath*:/mybaits/*Mapper.xml
#\u5F00\u542FMyBatis\u7684\u4E8C\u7EA7\u7F13\u5B58
mybatis.configuration.cache-enabled=true
#pagehelper
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
#\u65E5\u5FD7\u914D\u7F6E
logging.level.com.xiaolyuh=debug
logging.level.org.springframework.web=debug
logging.level.org.springframework.transaction=debug
logging.level.org.mybatis=debug
debug=false | repos\spring-boot-student-master\spring-boot-student-mybatis-druid-2\src\main\resources\application.properties | 2 |
请完成以下Java代码 | private boolean isFullyAuthenticated(Authentication authentication) {
return this.authenticationTrustResolver.isFullyAuthenticated(authentication);
}
public void setAuthenticationTrustResolver(AuthenticationTrustResolver authenticationTrustResolver) {
Assert.notNull(authenticationTrustResolver, "AuthenticationTrustResolver cannot be set to null");
this.authenticationTrustResolver = authenticationTrustResolver;
}
@Override
public boolean supports(ConfigAttribute attribute) {
return (attribute.getAttribute() != null) && (IS_AUTHENTICATED_FULLY.equals(attribute.getAttribute())
|| IS_AUTHENTICATED_REMEMBERED.equals(attribute.getAttribute())
|| IS_AUTHENTICATED_ANONYMOUSLY.equals(attribute.getAttribute()));
}
/**
* This implementation supports any type of class, because it does not query the
* presented secure object.
* @param clazz the secure object type
* @return always {@code true}
*/
@Override
public boolean supports(Class<?> clazz) {
return true;
}
@Override
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) { | int result = ACCESS_ABSTAIN;
for (ConfigAttribute attribute : attributes) {
if (this.supports(attribute)) {
result = ACCESS_DENIED;
if (IS_AUTHENTICATED_FULLY.equals(attribute.getAttribute())) {
if (isFullyAuthenticated(authentication)) {
return ACCESS_GRANTED;
}
}
if (IS_AUTHENTICATED_REMEMBERED.equals(attribute.getAttribute())) {
if (this.authenticationTrustResolver.isRememberMe(authentication)
|| isFullyAuthenticated(authentication)) {
return ACCESS_GRANTED;
}
}
if (IS_AUTHENTICATED_ANONYMOUSLY.equals(attribute.getAttribute())) {
if (this.authenticationTrustResolver.isAnonymous(authentication)
|| isFullyAuthenticated(authentication)
|| this.authenticationTrustResolver.isRememberMe(authentication)) {
return ACCESS_GRANTED;
}
}
}
}
return result;
}
} | repos\spring-security-main\access\src\main\java\org\springframework\security\access\vote\AuthenticatedVoter.java | 1 |
请完成以下Java代码 | public boolean isValid() throws IOException, SAXException {
Validator validator = initValidator(xsdPath);
try {
validator.validate(new StreamSource(getFile(xmlPath)));
return true;
} catch (SAXException e) {
return false;
}
}
public List<SAXParseException> listParsingExceptions() throws IOException, SAXException {
XmlErrorHandler xsdErrorHandler = new XmlErrorHandler();
Validator validator = initValidator(xsdPath);
validator.setErrorHandler(xsdErrorHandler);
try {
validator.validate(new StreamSource(getFile(xmlPath))); | } catch (SAXParseException e) {}
xsdErrorHandler.getExceptions().forEach(e -> LOGGER.info(String.format("Line number: %s, Column number: %s. %s", e.getLineNumber(), e.getColumnNumber(), e.getMessage())));
return xsdErrorHandler.getExceptions();
}
private Validator initValidator(String xsdPath) throws SAXException {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source schemaFile = new StreamSource(getFile(xsdPath));
Schema schema = factory.newSchema(schemaFile);
return schema.newValidator();
}
private File getFile(String location) {
return new File(getClass().getClassLoader().getResource(location).getFile());
}
} | repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\xml\validation\XmlValidator.java | 1 |
请完成以下Java代码 | public List<PurchaseRow> getRows()
{
return rows.getAll();
}
@Override
public void notifyRecordsChanged(
@NonNull final TableRecordReferenceSet recordRefs,
final boolean watchedByFrontend)
{
}
@Override
public void patchViewRow(
@NonNull final RowEditingContext ctx,
@NonNull final List<JSONDocumentChangedEvent> fieldChangeRequests)
{
final PurchaseRowId idOfChangedRow = PurchaseRowId.fromDocumentId(ctx.getRowId());
final PurchaseRowChangeRequest rowChangeRequest = PurchaseRowChangeRequest.of(fieldChangeRequests);
patchViewRow(idOfChangedRow, rowChangeRequest);
}
public void patchViewRow(
@NonNull final PurchaseRowId idOfChangedRow, | @NonNull final PurchaseRowChangeRequest rowChangeRequest)
{
rows.patchRow(idOfChangedRow, rowChangeRequest);
// notify the frontend
final DocumentId groupRowDocumentId = idOfChangedRow.toGroupRowId().toDocumentId();
ViewChangesCollector
.getCurrentOrAutoflush()
.collectRowChanged(this, groupRowDocumentId);
}
@Override
public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors()
{
return additionalRelatedProcessDescriptors;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseView.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void updateIfValueChanged() {
if (tracedObject == variableInstanceEntity.getCachedValue()) {
if (type.updateValueIfChanged(tracedObject, tracedObjectOriginalValue, variableInstanceEntity)) {
VariableServiceConfiguration variableServiceConfiguration = getVariableServiceConfiguration();
variableServiceConfiguration.getInternalHistoryVariableManager().recordVariableUpdate(
variableInstanceEntity, variableServiceConfiguration.getClock().getCurrentTime());
}
}
}
protected VariableServiceConfiguration getVariableServiceConfiguration() {
String engineType = getEngineType(variableInstanceEntity.getScopeType());
Map<String, AbstractEngineConfiguration> engineConfigurationMap = Context.getCommandContext().getEngineConfigurations();
AbstractEngineConfiguration engineConfiguration = engineConfigurationMap.get(engineType);
if (engineConfiguration == null) {
for (AbstractEngineConfiguration possibleEngineConfiguration : engineConfigurationMap.values()) {
if (possibleEngineConfiguration instanceof HasVariableServiceConfiguration) {
engineConfiguration = possibleEngineConfiguration;
}
}
}
if (engineConfiguration == null) {
throw new FlowableException("Could not find engine configuration with variable service configuration"); | }
if (!(engineConfiguration instanceof HasVariableServiceConfiguration)) {
throw new FlowableException("Variable entity engine scope has no variable service configuration " + engineType);
}
return (VariableServiceConfiguration) engineConfiguration.getServiceConfigurations().get(EngineConfigurationConstants.KEY_VARIABLE_SERVICE_CONFIG);
}
protected String getEngineType(String scopeType) {
if (StringUtils.isNotEmpty(scopeType)) {
return scopeType;
} else {
return ScopeTypes.BPMN;
}
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\TraceableObject.java | 2 |
请完成以下Java代码 | protected List<DurationReportResult> executeDuration(CommandContext commandContext) {
return commandContext.getTaskReportManager()
.createHistoricTaskDurationReport(this);
}
public Date getCompletedAfter() {
return completedAfter;
}
public Date getCompletedBefore() {
return completedBefore;
}
@Override
public HistoricTaskInstanceReport completedAfter(Date completedAfter) {
ensureNotNull(NotValidException.class, "completedAfter", completedAfter);
this.completedAfter = completedAfter;
return this;
}
@Override
public HistoricTaskInstanceReport completedBefore(Date completedBefore) {
ensureNotNull(NotValidException.class, "completedBefore", completedBefore);
this.completedBefore = completedBefore;
return this;
}
public TenantCheck getTenantCheck() {
return tenantCheck;
}
public String getReportPeriodUnitName() {
return durationPeriodUnit.name();
} | protected class ExecuteDurationCmd implements Command<List<DurationReportResult>> {
@Override
public List<DurationReportResult> execute(CommandContext commandContext) {
return executeDuration(commandContext);
}
}
protected class HistoricTaskInstanceCountByNameCmd implements Command<List<HistoricTaskInstanceReportResult>> {
@Override
public List<HistoricTaskInstanceReportResult> execute(CommandContext commandContext) {
return executeCountByTaskName(commandContext);
}
}
protected class HistoricTaskInstanceCountByProcessDefinitionKey implements Command<List<HistoricTaskInstanceReportResult>> {
@Override
public List<HistoricTaskInstanceReportResult> execute(CommandContext commandContext) {
return executeCountByProcessDefinitionKey(commandContext);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricTaskInstanceReportImpl.java | 1 |
请完成以下Java代码 | public class X_C_Project_Acct extends org.compiere.model.PO implements I_C_Project_Acct, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 289389398L;
/** Standard Constructor */
public X_C_Project_Acct (final Properties ctx, final int C_Project_Acct_ID, @Nullable final String trxName)
{
super (ctx, C_Project_Acct_ID, trxName);
}
/** Load Constructor */
public X_C_Project_Acct (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public org.compiere.model.I_C_AcctSchema getC_AcctSchema()
{
return get_ValueAsPO(COLUMNNAME_C_AcctSchema_ID, org.compiere.model.I_C_AcctSchema.class);
}
@Override
public void setC_AcctSchema(final org.compiere.model.I_C_AcctSchema C_AcctSchema)
{
set_ValueFromPO(COLUMNNAME_C_AcctSchema_ID, org.compiere.model.I_C_AcctSchema.class, C_AcctSchema);
}
@Override
public void setC_AcctSchema_ID (final int C_AcctSchema_ID)
{
if (C_AcctSchema_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, C_AcctSchema_ID);
}
@Override
public int getC_AcctSchema_ID()
{
return get_ValueAsInt(COLUMNNAME_C_AcctSchema_ID);
}
@Override
public void setC_Project_ID (final int C_Project_ID)
{
if (C_Project_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Project_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Project_ID, C_Project_ID);
}
@Override
public int getC_Project_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Project_ID);
}
@Override
public org.compiere.model.I_C_ValidCombination getPJ_Asset_A()
{ | return get_ValueAsPO(COLUMNNAME_PJ_Asset_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setPJ_Asset_A(final org.compiere.model.I_C_ValidCombination PJ_Asset_A)
{
set_ValueFromPO(COLUMNNAME_PJ_Asset_Acct, org.compiere.model.I_C_ValidCombination.class, PJ_Asset_A);
}
@Override
public void setPJ_Asset_Acct (final int PJ_Asset_Acct)
{
set_Value (COLUMNNAME_PJ_Asset_Acct, PJ_Asset_Acct);
}
@Override
public int getPJ_Asset_Acct()
{
return get_ValueAsInt(COLUMNNAME_PJ_Asset_Acct);
}
@Override
public org.compiere.model.I_C_ValidCombination getPJ_WIP_A()
{
return get_ValueAsPO(COLUMNNAME_PJ_WIP_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setPJ_WIP_A(final org.compiere.model.I_C_ValidCombination PJ_WIP_A)
{
set_ValueFromPO(COLUMNNAME_PJ_WIP_Acct, org.compiere.model.I_C_ValidCombination.class, PJ_WIP_A);
}
@Override
public void setPJ_WIP_Acct (final int PJ_WIP_Acct)
{
set_Value (COLUMNNAME_PJ_WIP_Acct, PJ_WIP_Acct);
}
@Override
public int getPJ_WIP_Acct()
{
return get_ValueAsInt(COLUMNNAME_PJ_WIP_Acct);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_Acct.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal getPrice()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Price);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setProductName (final java.lang.String ProductName)
{
set_Value (COLUMNNAME_ProductName, ProductName);
}
@Override
public java.lang.String getProductName()
{
return get_ValueAsString(COLUMNNAME_ProductName);
}
@Override
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setScannedBarcode (final @Nullable java.lang.String ScannedBarcode) | {
set_Value (COLUMNNAME_ScannedBarcode, ScannedBarcode);
}
@Override
public java.lang.String getScannedBarcode()
{
return get_ValueAsString(COLUMNNAME_ScannedBarcode);
}
@Override
public void setTaxAmt (final BigDecimal TaxAmt)
{
set_Value (COLUMNNAME_TaxAmt, TaxAmt);
}
@Override
public BigDecimal getTaxAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_OrderLine.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static class SignatureVerification {
/**
* Maximum refresh rate for public keys in ms.
* We won't fetch new public keys any faster than that to avoid spamming UAA in case
* we receive a lot of "illegal" tokens.
*/
private long publicKeyRefreshRateLimit = 10 * 1000L;
/**
* Maximum TTL for the public key in ms.
* The public key will be fetched again from UAA if it gets older than that.
* That way, we make sure that we get the newest keys always in case they are updated there.
*/
private long ttl = 24 * 60 * 60 * 1000L;
/**
* Endpoint where to retrieve the public key used to verify token signatures.
*/
private String publicKeyEndpointUri = "http://uaa/oauth/token_key";
public long getPublicKeyRefreshRateLimit() {
return publicKeyRefreshRateLimit;
}
public void setPublicKeyRefreshRateLimit(long publicKeyRefreshRateLimit) {
this.publicKeyRefreshRateLimit = publicKeyRefreshRateLimit;
} | public long getTtl() {
return ttl;
}
public void setTtl(long ttl) {
this.ttl = ttl;
}
public String getPublicKeyEndpointUri() {
return publicKeyEndpointUri;
}
public void setPublicKeyEndpointUri(String publicKeyEndpointUri) {
this.publicKeyEndpointUri = publicKeyEndpointUri;
}
}
} | repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\config\oauth2\OAuth2Properties.java | 2 |
请完成以下Java代码 | public class ForecastLineHUDocumentHandler implements IHUDocumentHandler
{
@Override
public I_M_HU_PI_Item_Product getM_HU_PI_ItemProductFor(final Object document, final ProductId productId)
{
if (productId == null)
{
return null;
}
final I_M_ForecastLine forecastLine = getForecastLine(document);
final I_M_HU_PI_Item_Product piip;
if (InterfaceWrapperHelper.isNew(forecastLine)
&& forecastLine.getM_HU_PI_Item_Product_ID() > 0)
{
piip = forecastLine.getM_HU_PI_Item_Product();
}
else
{
final I_M_Forecast forecast = forecastLine.getM_Forecast();
final String huUnitType = X_M_HU_PI_Version.HU_UNITTYPE_TransportUnit;
piip = Services.get(IHUPIItemProductDAO.class).retrieveMaterialItemProduct(
productId, | BPartnerId.ofRepoIdOrNull(forecast.getC_BPartner_ID()),
TimeUtil.asZonedDateTime(forecast.getDatePromised()),
huUnitType,
false);
}
return piip;
}
@Override
public void applyChangesFor(final Object document)
{
final I_M_ForecastLine forecastLine = getForecastLine(document);
final ProductId productId = ProductId.ofRepoIdOrNull(forecastLine.getM_Product_ID());
final I_M_HU_PI_Item_Product piip = getM_HU_PI_ItemProductFor(forecastLine, productId);
forecastLine.setM_HU_PI_Item_Product(piip);
}
private I_M_ForecastLine getForecastLine(final Object document)
{
Check.assumeInstanceOf(document, I_M_ForecastLine.class, "document");
return InterfaceWrapperHelper.create(document, I_M_ForecastLine.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\hu_spis\ForecastLineHUDocumentHandler.java | 1 |
请完成以下Java代码 | public void setOrderedData(@NonNull final I_C_Invoice_Candidate ic)
{
final I_C_OLCand olc = getOLCand(ic);
setOrderedData(ic, olc);
}
private void setOrderedData(
@NonNull final I_C_Invoice_Candidate ic,
@NonNull final I_C_OLCand olc)
{
ic.setDateOrdered(olc.getDateCandidate());
final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class);
final Quantity olCandQuantity = Quantity.of(olCandEffectiveValuesBL.getEffectiveQtyEntered(olc), olCandEffectiveValuesBL.getC_UOM_Effective(olc));
ic.setQtyEntered(olCandQuantity.toBigDecimal());
ic.setC_UOM_ID(UomId.toRepoId(olCandQuantity.getUomId()));
final ProductId productId = olCandEffectiveValuesBL.getM_Product_Effective_ID(olc);
final Quantity qtyInProductUOM = uomConversionBL.convertToProductUOM(olCandQuantity, productId);
ic.setQtyOrdered(qtyInProductUOM.toBigDecimal());
}
private I_C_OLCand getOLCand(@NonNull final I_C_Invoice_Candidate ic)
{
return TableRecordCacheLocal.getReferencedValue(ic, I_C_OLCand.class);
}
/**
* <ul>
* <li>QtyDelivered := QtyOrdered
* <li>DeliveryDate := DateOrdered
* <li>M_InOut_ID: untouched
* </ul>
*
* @see IInvoiceCandidateHandler#setDeliveredData(I_C_Invoice_Candidate)
*/
@Override
public void setDeliveredData(@NonNull final I_C_Invoice_Candidate ic)
{
ic.setQtyDelivered(ic.getQtyOrdered()); // when changing this, make sure to threat ProductType.Service specially
ic.setQtyDeliveredInUOM(ic.getQtyEntered());
ic.setDeliveryDate(ic.getDateOrdered());
}
@Override
public PriceAndTax calculatePriceAndTax(@NonNull final I_C_Invoice_Candidate ic)
{
final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(ic.getAD_Org_ID()));
final I_C_OLCand olc = getOLCand(ic);
final IPricingResult pricingResult = Services.get(IOLCandBL.class).computePriceActual( | olc,
null,
PricingSystemId.NULL,
TimeUtil.asLocalDate(olCandEffectiveValuesBL.getDatePromised_Effective(olc), timeZone));
return PriceAndTax.builder()
.priceUOMId(pricingResult.getPriceUomId())
.priceActual(pricingResult.getPriceStd())
.taxIncluded(pricingResult.isTaxIncluded())
.invoicableQtyBasedOn(pricingResult.getInvoicableQtyBasedOn())
.build();
}
@Override
public void setBPartnerData(@NonNull final I_C_Invoice_Candidate ic)
{
final I_C_OLCand olc = getOLCand(ic);
InvoiceCandidateLocationAdapterFactory
.billLocationAdapter(ic)
.setFrom(olCandEffectiveValuesBL.getBuyerPartnerInfo(olc));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\invoicecandidate\spi\impl\C_OLCand_Handler.java | 1 |
请完成以下Java代码 | public static Date monthAdd(Date date, int months) throws ServiceException {
if (date == null) {
throw new ServiceException(ARG_ERROR_CODE, ARG_ERROR);
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, months);
return calendar.getTime();
}
/**
* 获取两个日期之间的差值。
*
* @param one
* @param two
* @return
* @throws ServiceException
*/
public static int dateDiff(Date one, Date two) throws ServiceException {
if (one == null || two == null) {
throw new ServiceException(ARG_ERROR_CODE, ARG_ERROR);
}
long diff = Math.abs((one.getTime() - two.getTime()) / (1000 * 3600 * 24));
return new Long(diff).intValue();
}
/**
* 计算几天前的时间
*
* @param date 当前时间
* @param day 几天前
* @return
*/
public static Date getDateBefore(Date date, int day) {
Calendar now = Calendar.getInstance();
now.setTime(date);
now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
return now.getTime();
}
/**
* 获取当前月第一天
*
* @return Date | * @throws ParseException
*/
public static Date getFirstAndLastOfMonth() {
LocalDate today = LocalDate.now();
LocalDate firstDay = LocalDate.of(today.getYear(),today.getMonth(),1);
ZoneId zone = ZoneId.systemDefault();
Instant instant = firstDay.atStartOfDay().atZone(zone).toInstant();
return Date.from(instant);
}
/**
* 获取当前周第一天
*
* @return Date
* @throws ParseException
*/
public static Date getWeekFirstDate(){
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date date = cal.getTime();
return date;
}
} | repos\springBoot-master\abel-util\src\main\java\cn\abel\utils\DateTimeUtils.java | 1 |
请完成以下Java代码 | public class CriteriaParser {
private static Map<String, Operator> ops;
private static Pattern SpecCriteraRegex = Pattern.compile("^(\\w+?)(" + Joiner.on("|")
.join(SearchOperation.SIMPLE_OPERATION_SET) + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?)$");
private enum Operator {
OR(1), AND(2);
final int precedence;
Operator(int p) {
precedence = p;
}
}
static {
Map<String, Operator> tempMap = new HashMap<>();
tempMap.put("AND", Operator.AND);
tempMap.put("OR", Operator.OR);
tempMap.put("or", Operator.OR);
tempMap.put("and", Operator.AND);
ops = Collections.unmodifiableMap(tempMap);
}
private static boolean isHigerPrecedenceOperator(String currOp, String prevOp) {
return (ops.containsKey(prevOp) && ops.get(prevOp).precedence >= ops.get(currOp).precedence);
}
public Deque<?> parse(String searchParam) {
Deque<Object> output = new LinkedList<>();
Deque<String> stack = new LinkedList<>();
Arrays.stream(searchParam.split("\\s+")).forEach(token -> {
if (ops.containsKey(token)) { | while (!stack.isEmpty() && isHigerPrecedenceOperator(token, stack.peek()))
output.push(stack.pop()
.equalsIgnoreCase(SearchOperation.OR_OPERATOR) ? SearchOperation.OR_OPERATOR : SearchOperation.AND_OPERATOR);
stack.push(token.equalsIgnoreCase(SearchOperation.OR_OPERATOR) ? SearchOperation.OR_OPERATOR : SearchOperation.AND_OPERATOR);
} else if (token.equals(SearchOperation.LEFT_PARANTHESIS)) {
stack.push(SearchOperation.LEFT_PARANTHESIS);
} else if (token.equals(SearchOperation.RIGHT_PARANTHESIS)) {
while (!stack.peek()
.equals(SearchOperation.LEFT_PARANTHESIS))
output.push(stack.pop());
stack.pop();
} else {
Matcher matcher = SpecCriteraRegex.matcher(token);
while (matcher.find()) {
output.push(new SpecSearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3), matcher.group(4), matcher.group(5)));
}
}
});
while (!stack.isEmpty())
output.push(stack.pop());
return output;
}
} | repos\tutorials-master\spring-web-modules\spring-rest-query-language\src\main\java\com\baeldung\web\util\CriteriaParser.java | 1 |
请完成以下Java代码 | public CostSegment toCostSegment()
{
return getCostSegment();
}
public AcctSchemaId getAcctSchemaId()
{
return getCostSegment().getAcctSchemaId();
}
public CostTypeId getCostTypeId()
{
return getCostSegment().getCostTypeId();
}
public CostingLevel getCostingLevel() {return getCostSegment().getCostingLevel();}
public ClientId getClientId()
{
return getCostSegment().getClientId(); | }
public OrgId getOrgId()
{
return getCostSegment().getOrgId();
}
public ProductId getProductId()
{
return getCostSegment().getProductId();
}
public AttributeSetInstanceId getAttributeSetInstanceId()
{
return getCostSegment().getAttributeSetInstanceId();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostSegmentAndElement.java | 1 |
请完成以下Java代码 | public void setNumberOfInsured(@Nullable final String numberOfInsured)
{
this.numberOfInsured = numberOfInsured;
this.numberOfInsuredSet = true;
}
public void setCopaymentFrom(@Nullable final LocalDate copaymentFrom)
{
this.copaymentFrom = copaymentFrom;
this.copaymentFromSet = true;
}
public void setCopaymentTo(@Nullable final LocalDate copaymentTo)
{
this.copaymentTo = copaymentTo;
this.copaymentToSet = true;
}
public void setIsTransferPatient(@Nullable final Boolean isTransferPatient)
{
this.isTransferPatient = isTransferPatient;
this.transferPatientSet = true;
}
public void setIVTherapy(@Nullable final Boolean IVTherapy)
{
this.isIVTherapy = IVTherapy;
this.ivTherapySet = true;
}
public void setFieldNurseIdentifier(@Nullable final String fieldNurseIdentifier)
{
this.fieldNurseIdentifier = fieldNurseIdentifier;
this.fieldNurseIdentifierSet = true;
}
public void setDeactivationReason(@Nullable final String deactivationReason)
{
this.deactivationReason = deactivationReason;
this.deactivationReasonSet = true;
}
public void setDeactivationDate(@Nullable final LocalDate deactivationDate)
{
this.deactivationDate = deactivationDate;
this.deactivationDateSet = true;
}
public void setDeactivationComment(@Nullable final String deactivationComment)
{
this.deactivationComment = deactivationComment;
this.deactivationCommentSet = true;
} | public void setClassification(@Nullable final String classification)
{
this.classification = classification;
this.classificationSet = true;
}
public void setCareDegree(@Nullable final BigDecimal careDegree)
{
this.careDegree = careDegree;
this.careDegreeSet = true;
}
public void setCreatedAt(@Nullable final Instant createdAt)
{
this.createdAt = createdAt;
this.createdAtSet = true;
}
public void setCreatedByIdentifier(@Nullable final String createdByIdentifier)
{
this.createdByIdentifier = createdByIdentifier;
this.createdByIdentifierSet = true;
}
public void setUpdatedAt(@Nullable final Instant updatedAt)
{
this.updatedAt = updatedAt;
this.updatedAtSet = true;
}
public void setUpdateByIdentifier(@Nullable final String updateByIdentifier)
{
this.updateByIdentifier = updateByIdentifier;
this.updateByIdentifierSet = true;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\request\alberta\JsonAlbertaPatient.java | 1 |
请完成以下Java代码 | public void addActionListener(ActionListener listener)
{
} // addActionListener
/**************************************************************************
* Key Listener Interface
* @param e event
*/
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {}
/**
* Key Released
* if Escape restore old Text.
* @param e event
*/
@Override
public void keyReleased(KeyEvent e)
{
// ESC
if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
setText(m_initialText);
m_setting = true;
try
{
fireVetoableChange(m_columnName, m_oldText, getText());
}
catch (PropertyVetoException pve) {}
m_setting = false;
} // keyReleased
/**
* Set Field/WindowNo for ValuePreference (NOP)
* @param mField field model
*/
@Override
public void setField (org.compiere.model.GridField mField)
{ | m_mField = mField;
EditorContextPopupMenu.onGridFieldSet(this);
} // setField
@Override
public GridField getField() {
return m_mField;
}
// metas: begin
@Override
public boolean isAutoCommit()
{
return true;
}
// metas: end
} // VText | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VText.java | 1 |
请完成以下Java代码 | public TypedValue getRootObject() {
return this.delegate.getRootObject();
}
@Override
public List<ConstructorResolver> getConstructorResolvers() {
return this.delegate.getConstructorResolvers();
}
@Override
public List<MethodResolver> getMethodResolvers() {
return this.delegate.getMethodResolvers();
}
@Override
public List<PropertyAccessor> getPropertyAccessors() {
return this.delegate.getPropertyAccessors();
}
@Override
public TypeLocator getTypeLocator() {
return this.delegate.getTypeLocator();
}
@Override
public TypeConverter getTypeConverter() {
return this.delegate.getTypeConverter();
}
@Override
public TypeComparator getTypeComparator() {
return this.delegate.getTypeComparator();
}
@Override
public OperatorOverloader getOperatorOverloader() {
return this.delegate.getOperatorOverloader();
} | @Override
public @Nullable BeanResolver getBeanResolver() {
return this.delegate.getBeanResolver();
}
@Override
public void setVariable(String name, @Nullable Object value) {
this.delegate.setVariable(name, value);
}
@Override
public Object lookupVariable(String name) {
Object result = this.delegate.lookupVariable(name);
if (result == null) {
result = JspAuthorizeTag.this.pageContext.findAttribute(name);
}
return result;
}
}
} | repos\spring-security-main\taglibs\src\main\java\org\springframework\security\taglibs\authz\JspAuthorizeTag.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Result<SysPermissionDataRule> deletePermissionRule(@RequestParam(name = "id", required = true) String id) {
Result<SysPermissionDataRule> result = new Result<SysPermissionDataRule>();
try {
sysPermissionDataRuleService.deletePermissionDataRule(id);
result.success("删除成功!");
} catch (Exception e) {
log.error(e.getMessage(), e);
result.error500("操作失败");
}
return result;
}
/**
* 查询菜单权限数据
*
* @param sysPermissionDataRule
* @return
*/
@RequestMapping(value = "/queryPermissionRule", method = RequestMethod.GET)
public Result<List<SysPermissionDataRule>> queryPermissionRule(SysPermissionDataRule sysPermissionDataRule) {
Result<List<SysPermissionDataRule>> result = new Result<>();
try {
List<SysPermissionDataRule> permRuleList = sysPermissionDataRuleService.queryPermissionRule(sysPermissionDataRule);
result.setResult(permRuleList);
} catch (Exception e) {
log.error(e.getMessage(), e);
result.error500("操作失败");
}
return result;
}
/**
* 部门权限表
* @param departId
* @return
*/
@RequestMapping(value = "/queryDepartPermission", method = RequestMethod.GET)
public Result<List<String>> queryDepartPermission(@RequestParam(name = "departId", required = true) String departId) {
Result<List<String>> result = new Result<>();
try {
List<SysDepartPermission> list = sysDepartPermissionService.list(new QueryWrapper<SysDepartPermission>().lambda().eq(SysDepartPermission::getDepartId, departId)); | result.setResult(list.stream().map(sysDepartPermission -> String.valueOf(sysDepartPermission.getPermissionId())).collect(Collectors.toList()));
result.setSuccess(true);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return result;
}
/**
* 保存部门授权
*
* @return
*/
@RequestMapping(value = "/saveDepartPermission", method = RequestMethod.POST)
@RequiresPermissions("system:permission:saveDepart")
public Result<String> saveDepartPermission(@RequestBody JSONObject json) {
long start = System.currentTimeMillis();
Result<String> result = new Result<>();
try {
String departId = json.getString("departId");
String permissionIds = json.getString("permissionIds");
String lastPermissionIds = json.getString("lastpermissionIds");
this.sysDepartPermissionService.saveDepartPermission(departId, permissionIds, lastPermissionIds);
result.success("保存成功!");
log.info("======部门授权成功=====耗时:" + (System.currentTimeMillis() - start) + "毫秒");
} catch (Exception e) {
result.error500("授权失败!");
log.error(e.getMessage(), e);
}
return result;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysPermissionController.java | 2 |
请完成以下Java代码 | public void close() {
ProcessEngines.unregister(this);
if (processEngineConfiguration.getProcessEngineLifecycleListener() != null) {
processEngineConfiguration.getProcessEngineLifecycleListener().onProcessEngineClosed(this);
}
processEngineConfiguration.getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createGlobalEvent(FlowableEngineEventType.ENGINE_CLOSED),
EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG);
}
// getters and setters //////////////////////////////////////////////////////
@Override
public String getName() {
return name;
}
@Override
public IdentityService getIdentityService() {
return identityService;
}
@Override
public ManagementService getManagementService() {
return managementService;
}
@Override
public TaskService getTaskService() {
return taskService;
}
@Override
public HistoryService getHistoryService() {
return historicDataService;
}
@Override
public RuntimeService getRuntimeService() {
return runtimeService;
} | @Override
public RepositoryService getRepositoryService() {
return repositoryService;
}
@Override
public FormService getFormService() {
return formService;
}
@Override
public DynamicBpmnService getDynamicBpmnService() {
return dynamicBpmnService;
}
@Override
public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\ProcessEngineImpl.java | 1 |
请完成以下Java代码 | public boolean isSOTrx ()
{
Object oo = get_Value(COLUMNNAME_IsSOTrx);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Referenz.
@param Reference
Bezug für diesen Eintrag | */
@Override
public void setReference (java.lang.String Reference)
{
set_Value (COLUMNNAME_Reference, Reference);
}
/** Get Referenz.
@return Bezug für diesen Eintrag
*/
@Override
public java.lang.String getReference ()
{
return (java.lang.String)get_Value(COLUMNNAME_Reference);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_C_Payment_Request.java | 1 |
请完成以下Java代码 | public I_AD_PrinterHW_Calibration retrieveCalibration(final I_AD_PrinterHW_MediaSize hwMediaSize, final I_AD_PrinterHW_MediaTray hwTray)
{
return lookupMap.getFirstOnly(I_AD_PrinterHW_Calibration.class, pojo -> Objects.equals(pojo.getAD_PrinterHW_MediaSize(), hwMediaSize) && Objects.equals(pojo.getAD_PrinterHW_MediaTray(), hwTray));
}
public I_C_Print_Job_Instructions retrievePrintJobInstructionsForPrintJob(final I_C_Print_Job printJob)
{
return lookupMap.getFirstOnly(I_C_Print_Job_Instructions.class, pojo -> pojo.getC_Print_Job_ID() == printJob.getC_Print_Job_ID());
}
@Override
public List<I_AD_Printer> retrievePrinters(final Properties ctx, final int adOrgId)
{
final List<I_AD_Printer> result = lookupMap.getRecords(I_AD_Printer.class, pojo -> {
if (!pojo.isActive())
{
return false; | }
return pojo.getAD_Org_ID() == 0 || pojo.getAD_Org_ID() == adOrgId;
});
final Comparator<I_AD_Printer> cmpOrg = (o1, o2) -> o1.getAD_Org_ID() - o2.getAD_Org_ID();
final Comparator<I_AD_Printer> cmpPrinterName = (o1, o2) -> o1.getPrinterName().compareTo(o2.getPrinterName());
Collections.sort(result, new ComparatorChain<I_AD_Printer>()
.addComparator(cmpOrg, true)
.addComparator(cmpPrinterName));
return result;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\PlainPrintingDAO.java | 1 |
请完成以下Java代码 | private void processAuthorizationResponse(HttpServletRequest request, HttpServletResponse response)
throws IOException {
OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository
.removeAuthorizationRequest(request, response);
String registrationId = authorizationRequest.getAttribute(OAuth2ParameterNames.REGISTRATION_ID);
ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId);
MultiValueMap<String, String> params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap());
String redirectUri = UrlUtils.buildFullRequestUrl(request);
OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponseUtils.convert(params,
redirectUri);
OAuth2AuthorizationCodeAuthenticationToken authenticationRequest = new OAuth2AuthorizationCodeAuthenticationToken(
clientRegistration, new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse));
authenticationRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
OAuth2AuthorizationCodeAuthenticationToken authenticationResult;
try {
authenticationResult = (OAuth2AuthorizationCodeAuthenticationToken) this.authenticationManager
.authenticate(authenticationRequest);
}
catch (OAuth2AuthorizationException ex) {
OAuth2Error error = ex.getError();
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(authorizationRequest.getRedirectUri())
.queryParam(OAuth2ParameterNames.ERROR, error.getErrorCode());
if (StringUtils.hasLength(error.getDescription())) {
uriBuilder.queryParam(OAuth2ParameterNames.ERROR_DESCRIPTION, error.getDescription()); | }
if (StringUtils.hasLength(error.getUri())) {
uriBuilder.queryParam(OAuth2ParameterNames.ERROR_URI, error.getUri());
}
this.redirectStrategy.sendRedirect(request, response, uriBuilder.build().encode().toString());
return;
}
Authentication currentAuthentication = this.securityContextHolderStrategy.getContext().getAuthentication();
String principalName = (currentAuthentication != null) ? currentAuthentication.getName() : "anonymousUser";
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(
authenticationResult.getClientRegistration(), principalName, authenticationResult.getAccessToken(),
authenticationResult.getRefreshToken());
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, currentAuthentication, request,
response);
String redirectUrl = authorizationRequest.getRedirectUri();
SavedRequest savedRequest = this.requestCache.getRequest(request, response);
if (savedRequest != null) {
redirectUrl = savedRequest.getRedirectUrl();
this.requestCache.removeRequest(request, response);
}
this.redirectStrategy.sendRedirect(request, response, redirectUrl);
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationCodeGrantFilter.java | 1 |
请完成以下Java代码 | public I_GL_JournalLine build()
{
glJournalLine.setGL_Journal(getGL_Journal());
InterfaceWrapperHelper.save(glJournalLine);
return glJournalLine;
}
public GL_Journal_Builder endLine()
{
return glJournalBuilder;
}
private I_GL_Journal getGL_Journal()
{
return glJournalBuilder.getGL_Journal();
}
public GL_JournalLine_Builder setAccountDR(final I_C_ElementValue accountDR)
{
final I_C_ValidCombination vc = createValidCombination(accountDR);
setAccountDR(vc);
return this;
}
public GL_JournalLine_Builder setAccountDR(final I_C_ValidCombination vc)
{
glJournalLine.setAccount_DR(vc);
return this;
}
public GL_JournalLine_Builder setAccountDR(final AccountId accountId)
{
glJournalLine.setAccount_DR_ID(accountId.getRepoId());
return this;
}
public GL_JournalLine_Builder setAccountCR(final I_C_ElementValue accountCR)
{
final I_C_ValidCombination vc = createValidCombination(accountCR);
setAccountCR(vc);
return this;
}
public GL_JournalLine_Builder setAccountCR(final I_C_ValidCombination vc)
{
glJournalLine.setAccount_CR(vc); | return this;
}
public GL_JournalLine_Builder setAccountCR(final AccountId accountId)
{
glJournalLine.setAccount_CR_ID(accountId.getRepoId());
return this;
}
public GL_JournalLine_Builder setAmount(final BigDecimal amount)
{
glJournalLine.setAmtSourceDr(amount);
glJournalLine.setAmtSourceCr(amount);
// NOTE: AmtAcctDr/Cr will be set on before save
return this;
}
private final I_C_ValidCombination createValidCombination(final I_C_ElementValue ev)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(ev);
final AcctSchemaId acctSchemaId = AcctSchemaId.ofRepoId(getGL_Journal().getC_AcctSchema_ID());
final AccountDimension dim = accountBL.createAccountDimension(ev, acctSchemaId);
return MAccount.get(ctx, dim);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal\GL_JournalLine_Builder.java | 1 |
请完成以下Java代码 | public String getMehrzweckfeld() {
return mehrzweckfeld;
}
public void setMehrzweckfeld(String mehrzweckfeld) {
this.mehrzweckfeld = mehrzweckfeld;
}
public BigInteger getGeschaeftsvorfallCode() {
return geschaeftsvorfallCode;
}
public void setGeschaeftsvorfallCode(BigInteger geschaeftsvorfallCode) {
this.geschaeftsvorfallCode = geschaeftsvorfallCode;
}
public String getBuchungstext() {
return buchungstext;
}
public void setBuchungstext(String buchungstext) {
this.buchungstext = buchungstext;
}
public String getPrimanotennummer() {
return primanotennummer;
}
public void setPrimanotennummer(String primanotennummer) {
this.primanotennummer = primanotennummer;
}
public String getVerwendungszweck() {
return verwendungszweck;
}
public void setVerwendungszweck(String verwendungszweck) {
this.verwendungszweck = verwendungszweck;
}
public String getPartnerBlz() {
return partnerBlz;
}
public void setPartnerBlz(String partnerBlz) {
this.partnerBlz = partnerBlz;
}
public String getPartnerKtoNr() {
return partnerKtoNr;
} | public void setPartnerKtoNr(String partnerKtoNr) {
this.partnerKtoNr = partnerKtoNr;
}
public String getPartnerName() {
return partnerName;
}
public void setPartnerName(String partnerName) {
this.partnerName = partnerName;
}
public String getTextschluessel() {
return textschluessel;
}
public void setTextschluessel(String textschluessel) {
this.textschluessel = textschluessel;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\schaeffer\compiere\mt940\BankstatementLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public EmailTwoFaAccountConfig generateNewAccountConfig(User user, EmailTwoFaProviderConfig providerConfig) {
EmailTwoFaAccountConfig config = new EmailTwoFaAccountConfig();
config.setEmail(user.getEmail());
return config;
}
@Override
public void check(TenantId tenantId) throws ThingsboardException {
try {
mailService.testConnection(tenantId);
} catch (Exception e) {
throw new ThingsboardException("Mail service is not set up", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
} | @Override
protected void sendVerificationCode(SecurityUser user, String verificationCode, EmailTwoFaProviderConfig providerConfig, EmailTwoFaAccountConfig accountConfig) throws ThingsboardException {
try {
mailService.sendTwoFaVerificationEmail(accountConfig.getEmail(), verificationCode, providerConfig.getVerificationCodeLifetime());
} catch (Exception e) {
throw new ThingsboardException("Couldn't send 2FA verification email", ThingsboardErrorCode.GENERAL);
}
}
@Override
public TwoFaProviderType getType() {
return TwoFaProviderType.EMAIL;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\mfa\provider\impl\EmailTwoFaProvider.java | 2 |
请完成以下Java代码 | public CurrencyId getCommonCurrency()
{
return Money.getCommonCurrencyIdOfAll(
profitSalesPriceActual.orElse(null),
profitPurchasePriceActual.orElse(null),
purchasePriceActual.orElse(null));
}
public int getCommonCurrencyRepoIdOr(final int defaultValue)
{
final CurrencyId currencyId = getCommonCurrency();
return currencyId != null ? currencyId.getRepoId() : defaultValue;
}
public Optional<Percent> getProfitPercent()
{
return calculateProfitPercent(
getProfitSalesPriceActual().orElse(null),
getProfitPurchasePriceActual().orElse(null));
}
private static Optional<Percent> calculateProfitPercent(
@Nullable final Money profitSalesPriceActual,
@Nullable final Money profitPurchasePriceActual)
{
if (profitSalesPriceActual == null || profitPurchasePriceActual == null)
{
return Optional.empty();
}
// If not the same currency then we cannot calculate the profit percentage
if (!Money.isSameCurrency(profitPurchasePriceActual, profitSalesPriceActual))
{
return Optional.empty();
}
final Percent profitPercent = Percent.ofDelta(profitPurchasePriceActual.toBigDecimal(), profitSalesPriceActual.toBigDecimal());
return Optional.of(profitPercent);
}
public BigDecimal getProfitSalesPriceActualAsBigDecimalOr(final BigDecimal defaultValue)
{
return profitSalesPriceActual.map(Money::toBigDecimal).orElse(defaultValue);
}
public BigDecimal getProfitPurchasePriceActualAsBigDecimalOr(@Nullable final BigDecimal defaultValue)
{
return profitPurchasePriceActual.map(Money::toBigDecimal).orElse(defaultValue);
}
public BigDecimal getPurchasePriceActualAsBigDecimalOr(@Nullable final BigDecimal defaultValue)
{
return purchasePriceActual.map(Money::toBigDecimal).orElse(defaultValue);
}
//
// | public static class PurchaseProfitInfoBuilder
{
public PurchaseProfitInfoBuilder profitSalesPriceActual(@Nullable final Money profitSalesPriceActual)
{
return profitSalesPriceActual(Optional.ofNullable(profitSalesPriceActual));
}
public PurchaseProfitInfoBuilder profitSalesPriceActual(@NonNull final Optional<Money> profitSalesPriceActual)
{
this.profitSalesPriceActual = profitSalesPriceActual;
return this;
}
public PurchaseProfitInfoBuilder profitPurchasePriceActual(@Nullable final Money profitPurchasePriceActual)
{
return profitPurchasePriceActual(Optional.ofNullable(profitPurchasePriceActual));
}
public PurchaseProfitInfoBuilder profitPurchasePriceActual(@NonNull final Optional<Money> profitPurchasePriceActual)
{
this.profitPurchasePriceActual = profitPurchasePriceActual;
return this;
}
public PurchaseProfitInfoBuilder purchasePriceActual(@Nullable final Money purchasePriceActual)
{
return purchasePriceActual(Optional.ofNullable(purchasePriceActual));
}
public PurchaseProfitInfoBuilder purchasePriceActual(@NonNull final Optional<Money> purchasePriceActual)
{
this.purchasePriceActual = purchasePriceActual;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\grossprofit\PurchaseProfitInfo.java | 1 |
请完成以下Java代码 | public static LocatorScannedCodeResolverResult notFound(@NonNull final LocatorGlobalQRCodeResolverKey resolver, @NonNull final String reason)
{
return new LocatorScannedCodeResolverResult(ImmutableList.of(LocatorNotResolvedReason.of(resolver, reason)));
}
public static LocatorScannedCodeResolverResult notFound(@NonNull final List<LocatorNotResolvedReason> notFoundReasons)
{
return new LocatorScannedCodeResolverResult(notFoundReasons);
}
public static LocatorScannedCodeResolverResult found(@NonNull final LocatorQRCode locatorQRCode)
{
return new LocatorScannedCodeResolverResult(locatorQRCode);
}
public boolean isFound() {return locatorQRCode != null;}
@NonNull
public LocatorId getLocatorId()
{ | return getLocatorQRCode().getLocatorId();
}
@NonNull
public LocatorQRCode getLocatorQRCode()
{
if (locatorQRCode == null)
{
throw AdempiereException.notFound()
.setParameter("notResolvedReasons", notResolvedReasons);
}
return locatorQRCode;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\qrcode\resolver\LocatorScannedCodeResolverResult.java | 1 |
请完成以下Java代码 | public void warmUpForShipmentScheduleIds(@NonNull final Collection<ShipmentScheduleId> shipmentScheduleIds)
{
CollectionUtils.getAllOrLoad(
shipmentSchedulesById,
shipmentScheduleIds,
shipmentScheduleBL::getByIds);
}
public void warmUpForShipperInternalNames(@NonNull final Collection<String> shipperInternalNameCollection)
{
CollectionUtils.getAllOrLoad(
shipperByInternalName,
shipperInternalNameCollection,
shipperDAO::getByInternalName);
}
private I_M_ShipmentSchedule getShipmentScheduleById(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
return shipmentSchedulesById.computeIfAbsent(shipmentScheduleId, shipmentScheduleBL::getById);
}
public OrgId getOrgId(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
final I_M_ShipmentSchedule shipmentSchedule = getShipmentScheduleById(shipmentScheduleId);
return OrgId.ofRepoId(shipmentSchedule.getAD_Org_ID());
}
public BPartnerId getBPartnerId(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
final I_M_ShipmentSchedule shipmentSchedule = getShipmentScheduleById(shipmentScheduleId);
return scheduleEffectiveBL.getBPartnerId(shipmentSchedule);
}
@Nullable
public ShipperId getShipperId(@Nullable final String shipperInternalName)
{
if (Check.isBlank(shipperInternalName))
{ | return null;
}
final I_M_Shipper shipper = shipperByInternalName.computeIfAbsent(shipperInternalName, this::loadShipper);
return shipper != null
? ShipperId.ofRepoId(shipper.getM_Shipper_ID())
: null;
}
@Nullable
public String getTrackingURL(@NonNull final String shipperInternalName)
{
final I_M_Shipper shipper = shipperByInternalName.computeIfAbsent(shipperInternalName, this::loadShipper);
return shipper != null
? shipper.getTrackingURL()
: null;
}
@Nullable
private I_M_Shipper loadShipper(@NonNull final String shipperInternalName)
{
return shipperDAO.getByInternalName(ImmutableSet.of(shipperInternalName)).get(shipperInternalName);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\shipping\ShipmentService.java | 1 |
请完成以下Java代码 | public class Person {
/**
* 主键
*/
@Id
private Long id;
/**
* 名字
*/
@Field(type = FieldType.Keyword)
private String name;
/**
* 国家
*/
@Field(type = FieldType.Keyword)
private String country;
/**
* 年龄
*/ | @Field(type = FieldType.Integer)
private Integer age;
/**
* 生日
*/
@Field(type = FieldType.Date)
private Date birthday;
/**
* 介绍
*/
@Field(type = FieldType.Text, analyzer = "ik_smart")
private String remark;
} | repos\spring-boot-demo-master\demo-elasticsearch\src\main\java\com\xkcoding\elasticsearch\model\Person.java | 1 |
请完成以下Java代码 | public static String preparePeopleTable(SparkSession spark) {
try {
String tablePath = Files.createTempDirectory("delta-table-").toAbsolutePath().toString();
Dataset<Row> data = spark.createDataFrame(
java.util.Arrays.asList(
new Person(1, "Alice"),
new Person(2, "Bob")
),
Person.class
);
data.write().format("delta").mode("overwrite").save(tablePath);
spark.sql("DROP TABLE IF EXISTS people");
spark.sql("CREATE TABLE IF NOT EXISTS people USING DELTA LOCATION '" + tablePath + "'");
return tablePath;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void cleanupPeopleTable(SparkSession spark) { | spark.sql("DROP TABLE IF EXISTS people");
}
public static void stopSession(SparkSession spark) {
if (spark != null) {
spark.stop();
}
}
public static class Person implements Serializable {
private int id;
private String name;
public Person() {}
public Person(int id, String name) { this.id = id; this.name = name; }
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
} | repos\tutorials-master\apache-spark-2\src\main\java\com\baeldung\delta\DeltaLake.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ShutdownOperation getShutdownOperation() {
return this.shutdownOperation;
}
public void setShutdownOperation(ShutdownOperation shutdownOperation) {
this.shutdownOperation = shutdownOperation;
}
public Scheme getScheme() {
return this.scheme;
}
public void setScheme(Scheme scheme) {
this.scheme = scheme;
}
public @Nullable String getToken() {
return this.token;
}
public void setToken(@Nullable String token) {
this.token = token;
}
public Format getFormat() {
return this.format;
}
public void setFormat(Format format) {
this.format = format;
}
public enum Format {
/**
* Push metrics in text format.
*/
TEXT,
/**
* Push metrics in protobuf format.
*/ | PROTOBUF
}
public enum Scheme {
/**
* Use HTTP to push metrics.
*/
HTTP,
/**
* Use HTTPS to push metrics.
*/
HTTPS
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\prometheus\PrometheusProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
public static ResultBody success() {
return success(null);
}
public static ResultBody success(Object data) {
ResultBody rb = new ResultBody();
rb.setCode(CommonEnum.SUCCESS.getResultCode());
rb.setMessage(CommonEnum.SUCCESS.getResultMsg());
rb.setResult(data);
return rb;
}
public static ResultBody error(BaseErrorInfoInterface errorInfo) {
ResultBody rb = new ResultBody();
rb.setCode(errorInfo.getResultCode());
rb.setMessage(errorInfo.getResultMsg());
rb.setResult(null);
return rb;
}
public static ResultBody error(String code, String message) { | ResultBody rb = new ResultBody();
rb.setCode(code);
rb.setMessage(message);
rb.setResult(null);
return rb;
}
public static ResultBody error( String message) {
ResultBody rb = new ResultBody();
rb.setCode("-1");
rb.setMessage(message);
rb.setResult(null);
return rb;
}
@Override
public String toString() {
return JSONObject.toJSONString(this);
}
} | repos\springboot-demo-master\Exception\src\main\java\com\et\exception\config\ResultBody.java | 2 |
请完成以下Java代码 | public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {}
/**
* Escape - Restore old Text.
* Indicate Change
* @param e
*/
@Override
public void keyReleased(KeyEvent e)
{
// ESC
if (e.getKeyCode() == KeyEvent.VK_ESCAPE && !getText().equals(m_oldText))
{
log.debug( "VMemo.keyReleased - ESC");
setText(m_oldText);
return;
}
// Indicate Change
if (m_firstChange && !m_oldText.equals(getText()))
{
log.debug( "VMemo.keyReleased - firstChange");
m_firstChange = false;
try
{
String text = getText();
// fireVetoableChange (m_columnName, text, null); // No data committed - done when focus lost !!!
// metas: Korrektur null fuehrt dazu, dass eine aenderung nicht erkannt wird.
fireVetoableChange(m_columnName, text, getText());
}
catch (PropertyVetoException pve) {}
} // firstChange
} // keyReleased
/**
* Focus Gained - Save for Escape
* @param e
*/
@Override
public void focusGained (FocusEvent e)
{
log.info(e.paramString());
if (e.getSource() instanceof VMemo)
requestFocus();
else
m_oldText = getText();
} // focusGained
/**
* Data Binding to MTable (via GridController)
* @param e
*/
@Override
public void focusLost (FocusEvent e)
{
//log.info( "VMemo.focusLost " + e.getSource(), e.paramString());
// something changed?
return; | } // focusLost
/*************************************************************************/
// Field for Value Preference
private GridField m_mField = null;
/**
* Set Field/WindowNo for ValuePreference (NOP)
* @param mField
*/
@Override
public void setField (org.compiere.model.GridField mField)
{
m_mField = mField;
EditorContextPopupMenu.onGridFieldSet(this);
} // setField
@Override
public GridField getField() {
return m_mField;
}
private class CInputVerifier extends InputVerifier {
@Override
public boolean verify(JComponent input) {
//NOTE: We return true no matter what since the InputVerifier is only introduced to fireVetoableChange in due time
if (getText() == null && m_oldText == null)
return true;
else if (getText().equals(m_oldText))
return true;
//
try
{
String text = getText();
fireVetoableChange(m_columnName, null, text);
m_oldText = text;
return true;
}
catch (PropertyVetoException pve) {}
return true;
} // verify
} // CInputVerifier
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
} // VMemo | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VMemo.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.