instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public Inventory unassign()
{
return responsibleId == null ? this : toBuilder().responsibleId(null).build();
}
public void assertHasAccess(@NonNull final UserId calledId)
{
if (!UserId.equals(responsibleId, calledId))
{
throw new AdempiereException("No access");
}
}
public Stream<InventoryLine> streamLines(@Nullable final InventoryLineId onlyLineId)
{
return onlyLineId != null
? Stream.of(getLineById(onlyLineId))
: lines.stream();
}
public Set<LocatorId> getLocatorIdsEligibleForCounting(@Nullable final InventoryLineId onlyLineId)
{
|
return streamLines(onlyLineId)
.filter(InventoryLine::isEligibleForCounting)
.map(InventoryLine::getLocatorId)
.collect(ImmutableSet.toImmutableSet());
}
public Inventory updatingLineById(@NonNull final InventoryLineId lineId, @NonNull UnaryOperator<InventoryLine> updater)
{
final ImmutableList<InventoryLine> newLines = CollectionUtils.map(
this.lines,
line -> InventoryLineId.equals(line.getId(), lineId) ? updater.apply(line) : line
);
return this.lines == newLines
? this
: toBuilder().lines(newLines).build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\Inventory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public IUserDAO userDAO()
{
return Services.get(IUserDAO.class);
}
@Bean
public ITrxManager trxManager()
{
return Services.get(ITrxManager.class);
}
@Bean
public IQueryBL queryBL()
{
return Services.get(IQueryBL.class);
}
@Bean
public ImportQueue<ImportTimeBookingInfo> timeBookingImportQueue()
{
return new ImportQueue<>(TIME_BOOKING_QUEUE_CAPACITY, IMPORT_TIME_BOOKINGS_LOG_MESSAGE_PREFIX);
}
@Bean
public ImportQueue<ImportIssueInfo> importIssuesQueue()
|
{
return new ImportQueue<>(ISSUE_QUEUE_CAPACITY, IMPORT_LOG_MESSAGE_PREFIX);
}
@Bean
public ObjectMapper objectMapper()
{
return JsonObjectMapperHolder.sharedJsonObjectMapper();
}
@Bean
public IMsgBL msgBL()
{
return Services.get(IMsgBL.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\configuration\ApplicationConfiguration.java
| 2
|
请完成以下Java代码
|
public void notifyRecordsChangedNow(@NonNull final TableRecordReferenceSet recordRefs)
{
if (recordRefs.isEmpty())
{
logger.trace("No changed records provided. Skip notifying views.");
return;
}
try (final IAutoCloseable ignored = ViewChangesCollector.currentOrNewThreadLocalCollector())
{
for (final IViewsIndexStorage viewsIndexStorage : viewsIndexStorages.values())
{
notifyRecordsChangedNow(recordRefs, viewsIndexStorage);
}
notifyRecordsChangedNow(recordRefs, defaultViewsIndexStorage);
}
}
private void notifyRecordsChangedNow(
@NonNull final TableRecordReferenceSet recordRefs,
@NonNull final IViewsIndexStorage viewsIndexStorage)
{
final ImmutableList<IView> views = viewsIndexStorage.getAllViews();
if (views.isEmpty())
{
return;
}
final MutableInt notifiedCount = MutableInt.zero();
for (final IView view : views)
{
try
{
final boolean watchedByFrontend = isWatchedByFrontend(view.getViewId());
|
view.notifyRecordsChanged(recordRefs, watchedByFrontend);
notifiedCount.incrementAndGet();
}
catch (final Exception ex)
{
logger.warn("Failed calling notifyRecordsChanged on view={} with recordRefs={}. Ignored.", view, recordRefs, ex);
}
}
logger.debug("Notified {} views in {} about changed records: {}", notifiedCount, viewsIndexStorage, recordRefs);
}
@lombok.Value(staticConstructor = "of")
private static class ViewFactoryKey
{
WindowId windowId;
JSONViewDataType viewType;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewsRepository.java
| 1
|
请完成以下Java代码
|
private ColumnSql getVirtualColumnSql()
{
return _virtualColumnSql;
}
public Builder setMandatory(final boolean mandatory)
{
this.mandatory = mandatory;
return this;
}
public Builder setHideGridColumnIfEmpty(final boolean hideGridColumnIfEmpty)
{
this.hideGridColumnIfEmpty = hideGridColumnIfEmpty;
return this;
}
public Builder setValueClass(final Class<?> valueClass)
{
this._valueClass = valueClass;
return this;
}
private Class<?> getValueClass()
{
if (_valueClass != null)
{
return _valueClass;
}
return getWidgetType().getValueClass();
}
public Builder setWidgetType(final DocumentFieldWidgetType widgetType)
{
this._widgetType = widgetType;
return this;
}
private DocumentFieldWidgetType getWidgetType()
{
Check.assumeNotNull(_widgetType, "Parameter widgetType is not null");
return _widgetType;
}
public Builder setMinPrecision(@NonNull final OptionalInt minPrecision)
{
this.minPrecision = minPrecision;
return this;
}
private OptionalInt getMinPrecision()
{
return minPrecision;
}
public Builder setSqlValueClass(final Class<?> sqlValueClass)
{
this._sqlValueClass = sqlValueClass;
return this;
}
private Class<?> getSqlValueClass()
|
{
if (_sqlValueClass != null)
{
return _sqlValueClass;
}
return getValueClass();
}
public Builder setLookupDescriptor(@Nullable final LookupDescriptor lookupDescriptor)
{
this._lookupDescriptor = lookupDescriptor;
return this;
}
public OptionalBoolean getNumericKey()
{
return _numericKey;
}
public Builder setKeyColumn(final boolean keyColumn)
{
this.keyColumn = keyColumn;
return this;
}
public Builder setEncrypted(final boolean encrypted)
{
this.encrypted = encrypted;
return this;
}
/**
* Sets ORDER BY priority and direction (ascending/descending)
*
* @param priority priority; if positive then direction will be ascending; if negative then direction will be descending
*/
public Builder setDefaultOrderBy(final int priority)
{
if (priority >= 0)
{
orderByPriority = priority;
orderByAscending = true;
}
else
{
orderByPriority = -priority;
orderByAscending = false;
}
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlDocumentFieldDataBindingDescriptor.java
| 1
|
请完成以下Java代码
|
public String toString()
{
final StringBuilder sb = new StringBuilder("M_Element[")
.append(get_ID())
.append("-")
.append(getColumnName())
.append("]");
return sb.toString();
}
@Override
protected boolean beforeSave(final boolean newRecord)
{
// Column AD_Element.ColumnName should be unique - teo_sarca [ 1613107 ]
final boolean columnNameChanged = newRecord || is_ValueChanged(COLUMNNAME_ColumnName);
if (columnNameChanged)
{
final String columnNameEffective = computeEffectiveColumnName(
getColumnName(),
AdElementId.ofRepoIdOrNull(getAD_Element_ID()));
setColumnName(columnNameEffective);
}
return true;
}
@Nullable
private static String computeEffectiveColumnName(@Nullable final String columnName, @Nullable final AdElementId adElementId)
{
if (columnName == null)
{
return null;
}
String columnNameNormalized = StringUtils.trimBlankToNull(columnName);
if (columnNameNormalized == null)
{
return null;
}
columnNameNormalized = StringUtils.ucFirst(columnNameNormalized);
assertColumnNameDoesNotExist(columnNameNormalized, adElementId);
return columnNameNormalized;
}
private static void assertColumnNameDoesNotExist(final String columnName, final AdElementId elementIdToExclude)
{
String sql = "select count(1) from AD_Element where UPPER(ColumnName)=UPPER(?)";
if (elementIdToExclude != null)
{
sql += " AND AD_Element_ID<>" + elementIdToExclude.getRepoId();
|
}
final int no = DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sql, columnName);
if (no > 0)
{
throw new AdempiereException("@SaveErrorNotUnique@ @ColumnName@: " + columnName);
}
}
@Override
protected boolean afterSave(final boolean newRecord, final boolean success)
{
if (!newRecord)
{
// update dependent entries only in case of existing element.
// new elements are not used yet.
updateDependentADEntries();
}
return success;
}
private void updateDependentADEntries()
{
final AdElementId adElementId = AdElementId.ofRepoId(getAD_Element_ID());
if (is_ValueChanged(COLUMNNAME_ColumnName))
{
final String columnName = getColumnName();
Services.get(IADTableDAO.class).updateColumnNameByAdElementId(adElementId, columnName);
Services.get(IADProcessDAO.class).updateColumnNameByAdElementId(adElementId, columnName);
}
final IElementTranslationBL elementTranslationBL = Services.get(IElementTranslationBL.class);
final ILanguageDAO languageDAO = Services.get(ILanguageDAO.class);
final String baseADLanguage = languageDAO.retrieveBaseLanguage();
elementTranslationBL.propagateElementTrls(adElementId, baseADLanguage);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\M_Element.java
| 1
|
请完成以下Java代码
|
public Instant getAuditEventDate() {
return auditEventDate;
}
public void setAuditEventDate(Instant auditEventDate) {
this.auditEventDate = auditEventDate;
}
public String getAuditEventType() {
return auditEventType;
}
public void setAuditEventType(String auditEventType) {
this.auditEventType = auditEventType;
}
public Map<String, String> getData() {
return data;
}
public void setData(Map<String, String> data) {
this.data = data;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
|
PersistentAuditEvent persistentAuditEvent = (PersistentAuditEvent) o;
return !(persistentAuditEvent.getId() == null || getId() == null) && Objects.equals(getId(), persistentAuditEvent.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "PersistentAuditEvent{" +
"principal='" + principal + '\'' +
", auditEventDate=" + auditEventDate +
", auditEventType='" + auditEventType + '\'' +
'}';
}
}
|
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\domain\PersistentAuditEvent.java
| 1
|
请完成以下Java代码
|
public String getDirectDeploy ()
{
return (String)get_Value(COLUMNNAME_DirectDeploy);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Summary Level.
@param IsSummary
This is a summary entity
*/
public void setIsSummary (boolean IsSummary)
{
set_Value (COLUMNNAME_IsSummary, Boolean.valueOf(IsSummary));
}
/** Get Summary Level.
@return This is a summary entity
*/
public boolean isSummary ()
{
Object oo = get_Value(COLUMNNAME_IsSummary);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** MediaType AD_Reference_ID=388 */
public static final int MEDIATYPE_AD_Reference_ID=388;
/** image/gif = GIF */
public static final String MEDIATYPE_ImageGif = "GIF";
/** image/jpeg = JPG */
public static final String MEDIATYPE_ImageJpeg = "JPG";
/** image/png = PNG */
public static final String MEDIATYPE_ImagePng = "PNG";
/** application/pdf = PDF */
public static final String MEDIATYPE_ApplicationPdf = "PDF";
/** text/css = CSS */
public static final String MEDIATYPE_TextCss = "CSS";
/** text/js = JS */
public static final String MEDIATYPE_TextJs = "JS";
/** Set Media Type.
@param MediaType
Defines the media type for the browser
*/
public void setMediaType (String MediaType)
{
set_Value (COLUMNNAME_MediaType, MediaType);
}
|
/** Get Media Type.
@return Defines the media type for the browser
*/
public String getMediaType ()
{
return (String)get_Value(COLUMNNAME_MediaType);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Media.java
| 1
|
请完成以下Java代码
|
public final boolean isDateOrTime()
{
return TYPES_ALL_DATES.contains(this);
}
public final boolean isDateWithTime()
{
return this == ZonedDateTime
|| this == Timestamp;
}
public final boolean isNumeric()
{
return TYPES_ALL_NUMERIC.contains(this);
}
public final boolean isBigDecimal()
{
return isNumeric() && BigDecimal.class.equals(getValueClassOrNull());
}
public final boolean isStrictText()
{
return this == Text || this == LongText;
}
public final boolean isText()
{
return isStrictText() || this == URL || this == Password;
}
public final boolean isButton()
{
return this == Button || this == ActionButton || this == ProcessButton || this == ZoomIntoButton;
}
public final boolean isLookup()
{
return this == Lookup || this == List;
|
}
public final boolean isSupportZoomInto()
{
return isLookup() || this == DocumentFieldWidgetType.ZoomIntoButton
// || this == DocumentFieldWidgetType.Labels // not implemented yet
;
}
public final boolean isBoolean()
{
return this == YesNo || this == Switch;
}
/**
* Same as {@link #getValueClassOrNull()} but it will throw exception in case there is no valueClass.
*
* @return value class
*/
public Class<?> getValueClass()
{
if (valueClass == null)
{
throw new IllegalStateException("valueClass is unknown for " + this);
}
return valueClass;
}
/**
* Gets the standard value class to be used for this widget.
* In case there are multiple value classes which can be used for this widget, the method will return null.
*
* @return value class or <code>null</code>
*/
public Class<?> getValueClassOrNull()
{
return valueClass;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentFieldWidgetType.java
| 1
|
请完成以下Java代码
|
public void disableExistingStartEventSubscriptions() {
timerManager.removeExistingTimerStartEventJobs();
eventSubscriptionManager.removeExistingSignalStartEventSubscriptions();
eventSubscriptionManager.removeExistingMessageStartEventSubscriptions();
}
protected enum ExpressionType {
USER,
GROUP,
}
/**
* @param processDefinition
*/
public void addAuthorizationsForNewProcessDefinition(Process process, ProcessDefinitionEntity processDefinition) {
CommandContext commandContext = Context.getCommandContext();
if (process != null) {
addAuthorizationsFromIterator(
commandContext,
process.getCandidateStarterUsers(),
processDefinition,
ExpressionType.USER
);
addAuthorizationsFromIterator(
commandContext,
process.getCandidateStarterGroups(),
processDefinition,
ExpressionType.GROUP
);
}
}
protected void addAuthorizationsFromIterator(
CommandContext commandContext,
List<String> expressions,
|
ProcessDefinitionEntity processDefinition,
ExpressionType expressionType
) {
if (expressions != null) {
Iterator<String> iterator = expressions.iterator();
while (iterator.hasNext()) {
@SuppressWarnings("cast")
String expression = iterator.next();
IdentityLinkEntity identityLink = commandContext.getIdentityLinkEntityManager().create();
identityLink.setProcessDef(processDefinition);
if (expressionType.equals(ExpressionType.USER)) {
identityLink.setUserId(expression);
} else if (expressionType.equals(ExpressionType.GROUP)) {
identityLink.setGroupId(expression);
}
identityLink.setType(IdentityLinkType.CANDIDATE);
commandContext.getIdentityLinkEntityManager().insert(identityLink);
}
}
}
public TimerManager getTimerManager() {
return timerManager;
}
public void setTimerManager(TimerManager timerManager) {
this.timerManager = timerManager;
}
public EventSubscriptionManager getEventSubscriptionManager() {
return eventSubscriptionManager;
}
public void setEventSubscriptionManager(EventSubscriptionManager eventSubscriptionManager) {
this.eventSubscriptionManager = eventSubscriptionManager;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\deployer\BpmnDeploymentHelper.java
| 1
|
请完成以下Java代码
|
public <T> void addRecordsByFilter(@NonNull final Class<T> modelClass, @NonNull final IQueryFilter<T> filters)
{
_records = null;
_selection_AD_Table_ID = null;
if (_filters == null)
{
_filters = new ArrayList<>();
}
_filters.add(LockRecordsByFilter.of(modelClass, filters));
}
public List<LockRecordsByFilter> getSelection_Filters()
{
return _filters;
}
public AdTableId getSelection_AD_Table_ID()
{
return _selection_AD_Table_ID;
}
|
public PInstanceId getSelection_PInstanceId()
{
return _selection_pinstanceId;
}
public Iterator<TableRecordReference> getRecordsIterator()
{
return _records == null ? null : _records.iterator();
}
public void addRecordByModel(final Object model)
{
final TableRecordReference record = TableRecordReference.of(model);
addRecords(Collections.singleton(record));
}
public void addRecordByModels(final Collection<?> models)
{
final Collection<TableRecordReference> records = convertModelsToRecords(models);
addRecords(records);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\LockRecords.java
| 1
|
请完成以下Java代码
|
public String toString() {
return "Book [isbn=" + isbn + ", title=" + title + ", author=" + author + ", publisher=" + publisher + ", cost=" + cost + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((author == null) ? 0 : author.hashCode());
long temp;
temp = Double.doubleToLongBits(cost);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((isbn == null) ? 0 : isbn.hashCode());
result = prime * result + ((publisher == null) ? 0 : publisher.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Book other = (Book) obj;
if (author == null) {
if (other.author != null)
return false;
|
} else if (!author.equals(other.author))
return false;
if (Double.doubleToLongBits(cost) != Double.doubleToLongBits(other.cost))
return false;
if (isbn == null) {
if (other.isbn != null)
return false;
} else if (!isbn.equals(other.isbn))
return false;
if (publisher == null) {
if (other.publisher != null)
return false;
} else if (!publisher.equals(other.publisher))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
}
|
repos\tutorials-master\persistence-modules\java-mongodb\src\main\java\com\baeldung\bsontojson\Book.java
| 1
|
请完成以下Java代码
|
public String getMsg(final Properties ctx, @NonNull final AdMessageKey adMessage)
{
return adMessage.toAD_Message();
}
@Override
public String getMsg(final Properties ctx, @NonNull final AdMessageKey adMessage, final boolean text)
{
return adMessage.toAD_Message() + "_" + (text ? "Text" : "Tooltip");
}
@Override
public String getMsg(final Properties ctx, @NonNull final AdMessageKey adMessage, final Object[] params)
{
if (params == null || params.length == 0)
{
return adMessage.toAD_Message();
}
return adMessage + "_" + Arrays.toString(params);
}
@Override
public String getMsg(@NonNull final AdMessageKey adMessage, final List<Object> params)
{
if (params == null || params.isEmpty())
{
return adMessage.toAD_Message();
}
return adMessage.toAD_Message() + "_" + params;
}
@Override
public Map<String, String> getMsgMap(final String adLanguage, final String prefix, final boolean removePrefix)
{
return ImmutableMap.of();
}
@Override
public String parseTranslation(final Properties ctx, final String message)
{
return message;
}
@Override
public String parseTranslation(final String adLanguage, final String message)
{
return message;
}
@Override
public String translate(final Properties ctx, final String text)
{
return text;
}
@Override
public String translate(final String adLanguage, final String text)
{
return text;
}
@Override
public String translate(final Properties ctx, final String text, final boolean isSOTrx)
{
return text;
}
@Override
public ITranslatableString translatable(final String text)
{
return TranslatableStrings.constant(text);
}
@Override
public ITranslatableString getTranslatableMsgText(@NonNull final AdMessageKey adMessage, final Object... msgParameters)
{
if (msgParameters == null || msgParameters.length == 0)
{
return TranslatableStrings.constant(adMessage.toAD_Message());
|
}
else
{
return TranslatableStrings.constant(adMessage.toAD_Message() + " - " + Joiner.on(", ").useForNull("-").join(msgParameters));
}
}
@Override
public void cacheReset()
{
// nothing
}
@Override
public String getBaseLanguageMsg(@NonNull final AdMessageKey adMessage, @Nullable final Object... msgParameters)
{
return TranslatableStrings.adMessage(adMessage, msgParameters)
.translate(Language.getBaseAD_Language());
}
@Override
public Optional<AdMessageId> getIdByAdMessage(@NonNull final AdMessageKey value)
{
return Optional.empty();
}
@Override
public boolean isMessageExists(final AdMessageKey adMessage)
{
return false;
}
@Override
public Optional<AdMessageKey> getAdMessageKeyById(final AdMessageId adMessageId)
{
return Optional.empty();
}
@Nullable
@Override
public String getErrorCode(final @NonNull AdMessageKey messageKey)
{
return null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\impl\PlainMsgBL.java
| 1
|
请完成以下Java代码
|
private final void loadQtysIfNeeded()
{
final IUOMDAO uomDAO = Services.get(IUOMDAO.class);
if (_loaded)
{
return;
}
final I_M_InOutLine firstInOutLine = inOutLines.get(0);
//
// Vendor Product
final int productId = _product.getM_Product_ID();
final UomId productUomId = UomId.ofRepoIdOrNull(_product.getC_UOM_ID());
Check.assumeNotNull(productUomId, "UomId of product={} may not be null", _product);
// Define the conversion context (in case we need it)
final UOMConversionContext uomConversionCtx = UOMConversionContext.of(ProductId.ofRepoId(_product.getM_Product_ID()));
//
// UOM
final UomId qtyReceivedTotalUomId = UomId.ofRepoId(firstInOutLine.getC_UOM_ID());
//
// Iterate Receipt Lines linked to this invoice candidate, extract & aggregate informations from them
BigDecimal qtyReceivedTotal = BigDecimal.ZERO;
IHandlingUnitsInfo handlingUnitsInfoTotal = null;
final ILoggable loggable = Loggables.withLogger(logger, Level.DEBUG);
for (final I_M_InOutLine inoutLine : inOutLines)
{
if (inoutLine.getM_Product_ID() != productId)
{
loggable.addLog("Not counting {} because its M_Product_ID={} is not the ID of product {}", new Object[] { inoutLine, inoutLine.getM_Product_ID(), _product });
continue;
}
final I_M_InOut inOutRecord = inoutLine.getM_InOut();
// task 09117: we only may count iol that are not reversed, in progress of otherwise "not relevant"
final I_M_InOut inout = inoutLine.getM_InOut();
final DocStatus inoutDocStatus = DocStatus.ofCode(inout.getDocStatus());
if (!inoutDocStatus.isCompletedOrClosed())
{
loggable.addLog("Not counting {} because its M_InOut has docstatus {}", inoutLine, inOutRecord.getDocStatus());
continue;
}
final BigDecimal qtyReceived = inoutBL.negateIfReturnMovmenType(inoutLine, inoutLine.getMovementQty());
logger.debug("M_InOut_ID={} has MovementType={}; -> proceeding with qtyReceived={}", inOutRecord.getM_InOut_ID(), inOutRecord.getMovementType(), qtyReceived);
|
final BigDecimal qtyReceivedConv = uomConversionBL.convertQty(uomConversionCtx, qtyReceived, productUomId, qtyReceivedTotalUomId);
qtyReceivedTotal = qtyReceivedTotal.add(qtyReceivedConv);
final IHandlingUnitsInfo handlingUnitsInfo = handlingUnitsInfoFactory.createFromModel(inoutLine);
if (handlingUnitsInfo == null)
{
// do nothing
}
if (handlingUnitsInfoTotal == null)
{
handlingUnitsInfoTotal = handlingUnitsInfo;
}
else
{
handlingUnitsInfoTotal = handlingUnitsInfoTotal.add(handlingUnitsInfo);
}
}
//
// Set loaded values
_qtyReceived = qtyReceivedTotal;
_qtyReceivedUOM = uomDAO.getById(qtyReceivedTotalUomId);
_handlingUnitsInfo = handlingUnitsInfoTotal;
_loaded = true;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\InOutLineAsVendorReceipt.java
| 1
|
请完成以下Java代码
|
private ImmutableList<PPOrderCandidateToAllocate> getSortedCandidates(@NonNull final Stream<I_PP_Order_Candidate> candidateStream)
{
final Map<String, PPOrderCandidatesGroup> headerAgg2PPOrderCandGroup = new HashMap<>();
candidateStream
.filter(orderCandidate -> !orderCandidate.isProcessed())
.sorted(Comparator.comparingInt(I_PP_Order_Candidate::getPP_Order_Candidate_ID))
.map(ppOrderCandidate -> PPOrderCandidateToAllocate.of(ppOrderCandidate, aggregationFactory.buildAggregationKey(ppOrderCandidate)))
.forEach(cand -> addPPOrderCandidateToGroup(headerAgg2PPOrderCandGroup, cand));
final ImmutableList.Builder<PPOrderCandidateToAllocate> sortedCandidates = new ImmutableList.Builder<>();
headerAgg2PPOrderCandGroup.values()
.stream()
.filter(Objects::nonNull)
.sorted(comparing(PPOrderCandidatesGroup::getGroupSeqNo, nullsLast(naturalOrder())))
.map(PPOrderCandidatesGroup::getPpOrderCandidateToAllocateList)
.forEach(sortedCandidates::addAll);
return sortedCandidates.build();
}
private static void addPPOrderCandidateToGroup(
@NonNull final Map<String, PPOrderCandidatesGroup> headerAgg2PPOrderCandGroup,
@NonNull final PPOrderCandidateToAllocate ppOrderCandidateToAllocate)
{
if (headerAgg2PPOrderCandGroup.get(ppOrderCandidateToAllocate.getHeaderAggregationKey()) == null)
{
headerAgg2PPOrderCandGroup.put(ppOrderCandidateToAllocate.getHeaderAggregationKey(), PPOrderCandidatesGroup.of(ppOrderCandidateToAllocate));
}
else
{
final PPOrderCandidatesGroup group = headerAgg2PPOrderCandGroup.get(ppOrderCandidateToAllocate.getHeaderAggregationKey());
group.addToGroup(ppOrderCandidateToAllocate);
}
}
@Getter
@EqualsAndHashCode
private static class PPOrderCandidatesGroup
{
@Nullable
private Integer groupSeqNo;
@NonNull
private final List<PPOrderCandidateToAllocate> ppOrderCandidateToAllocateList;
private PPOrderCandidatesGroup(@NonNull final PPOrderCandidateToAllocate ppOrderCandidateToAllocate)
{
this.ppOrderCandidateToAllocateList = new ArrayList<>();
this.ppOrderCandidateToAllocateList.add(ppOrderCandidateToAllocate);
this.groupSeqNo = ppOrderCandidateToAllocate.getPpOrderCandidate().getSeqNo() > 0
? ppOrderCandidateToAllocate.getPpOrderCandidate().getSeqNo()
: null;
}
|
@NonNull
public static PPOrderCandidatesGroup of(@NonNull final PPOrderCandidateToAllocate ppOrderCandidateToAllocate)
{
return new PPOrderCandidatesGroup(ppOrderCandidateToAllocate);
}
public void addToGroup(@NonNull final PPOrderCandidateToAllocate ppOrderCandidateToAllocate)
{
ppOrderCandidateToAllocateList.add(ppOrderCandidateToAllocate);
updateSeqNo(ppOrderCandidateToAllocate.getPpOrderCandidate().getSeqNo());
}
private void updateSeqNo(final int newSeqNo)
{
if (newSeqNo <= 0 || (groupSeqNo != null && groupSeqNo <= newSeqNo))
{
return;
}
this.groupSeqNo = newSeqNo;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\async\GeneratePPOrderFromPPOrderCandidate.java
| 1
|
请完成以下Java代码
|
public static long getSerialVersionUID() {
return serialVersionUID;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
|
this.age = age;
}
@Override
public String toString() {
return "Customer{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", age=" + age + '}';
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Customer customer = (Customer) o;
return Objects.equals(firstName, customer.firstName) && Objects.equals(lastName, customer.lastName) && Objects.equals(age, customer.age);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName, age);
}
}
|
repos\tutorials-master\apache-libraries-2\src\main\java\com\baeldung\apache\geode\Customer.java
| 1
|
请完成以下Java代码
|
public ListenerContainerFactoryResolver listenerContainerFactoryResolver(BeanFactory beanFactory) {
return new ListenerContainerFactoryResolver(beanFactory);
}
/**
* Create a {@link ListenerContainerFactoryConfigurer} that will be used to
* configure the {@link KafkaListenerContainerFactory} resolved by the
* {@link ListenerContainerFactoryResolver}.
* @param kafkaConsumerBackoffManager the {@link KafkaConsumerBackoffManager} used
* with the {@link KafkaBackoffAwareMessageListenerAdapter}.
* @param deadLetterPublishingRecovererFactory the factory that will provide the
* {@link DeadLetterPublishingRecoverer} instance to be used.
* @param clock the {@link Clock} instance to be used with the listener adapter.
* @return the instance.
*/
public ListenerContainerFactoryConfigurer listenerContainerFactoryConfigurer(KafkaConsumerBackoffManager kafkaConsumerBackoffManager,
DeadLetterPublishingRecovererFactory deadLetterPublishingRecovererFactory,
Clock clock) {
return new ListenerContainerFactoryConfigurer(kafkaConsumerBackoffManager, deadLetterPublishingRecovererFactory, clock);
}
/**
* Create the {@link RetryTopicNamesProviderFactory} instance that will be used
* to provide the property names for the retry topics' {@link KafkaListenerEndpoint}.
* @return the instance.
*/
public RetryTopicNamesProviderFactory retryTopicNamesProviderFactory() {
return new SuffixingRetryTopicNamesProviderFactory();
}
/**
* Create the {@link KafkaBackOffManagerFactory} that will be used to create the
* {@link KafkaConsumerBackoffManager} instance used to back off the partitions.
* @param registry the {@link ListenerContainerRegistry} used to fetch the
* {@link MessageListenerContainer}.
* @param applicationContext the application context.
* @return the instance.
*/
public KafkaBackOffManagerFactory kafkaBackOffManagerFactory(@Nullable ListenerContainerRegistry registry,
ApplicationContext applicationContext) {
return new ContainerPartitionPausingBackOffManagerFactory(registry, applicationContext);
}
|
/**
* Return the {@link Clock} instance that will be used for all
* time-related operations in the retry topic processes.
* @return the instance.
*/
public Clock internalRetryTopicClock() {
return this.internalRetryTopicClock;
}
/**
* Create a {@link Clock} instance that will be used for all time-related operations
* in the retry topic processes.
* @return the instance.
*/
protected Clock createInternalRetryTopicClock() {
return Clock.systemUTC();
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\RetryTopicComponentFactory.java
| 1
|
请完成以下Java代码
|
public String getDescription()
{
return Description;
} // getDescription
/**
* Return String representation
*
* @return Combination
*/
@Override
public String toString()
{
if (C_ValidCombination_ID == 0)
{
return "";
}
return Combination;
} // toString
/**
* Load C_ValidCombination with the given <code>ID</code> and (if the record exists and is active) sets this instance's members with the loaded record's <code>C_ValidCombination_ID</code>,
* <code>Combination</code> and <code>Description</code>.
*
* @param ID C_ValidCombination_ID
* @return true if found
*/
private boolean load(final int validcombinationID)
{
if (validcombinationID <= 0) // new
{
C_ValidCombination_ID = 0;
Combination = "";
Description = "";
return true;
}
if (validcombinationID == C_ValidCombination_ID) // already loaded
{
return true;
}
final I_C_ValidCombination account = InterfaceWrapperHelper.create(m_ctx, validcombinationID, I_C_ValidCombination.class, ITrx.TRXNAME_None);
if (account == null || !account.isActive())
{
return false;
}
C_ValidCombination_ID = account.getC_ValidCombination_ID();
Combination = account.getCombination();
Description = account.getDescription();
return true;
} // load
@Override
public String getTableName()
{
return I_C_ValidCombination.Table_Name;
}
/**
* Get underlying fully qualified Table.Column Name
*
* @return ""
*/
@Override
public String getColumnName()
|
{
return I_C_ValidCombination.Table_Name + "." + I_C_ValidCombination.COLUMNNAME_C_ValidCombination_ID;
} // getColumnName
@Override
public String getColumnNameNotFQ()
{
return I_C_ValidCombination.COLUMNNAME_C_ValidCombination_ID;
} // getColumnName
/**
* Return data as sorted Array. Used in Web Interface
*
* @param mandatory mandatory
* @param onlyValidated only valid
* @param onlyActive only active
* @param temporary force load for temporary display
* @return ArrayList with KeyNamePair
*/
@Override
public ArrayList<Object> getData(boolean mandatory, boolean onlyValidated, boolean onlyActive, boolean temporary)
{
ArrayList<Object> list = new ArrayList<>();
if (!mandatory)
list.add(KeyNamePair.EMPTY);
//
ArrayList<Object> params = new ArrayList<>();
String whereClause = "AD_Client_ID=?";
params.add(Env.getAD_Client_ID(m_ctx));
List<MAccount> accounts = new Query(m_ctx, MAccount.Table_Name, whereClause, ITrx.TRXNAME_None)
.setParameters(params)
.setOrderBy(MAccount.COLUMNNAME_Combination)
.setOnlyActiveRecords(onlyActive)
.list(MAccount.class);
for (final I_C_ValidCombination account : accounts)
{
list.add(new KeyNamePair(account.getC_ValidCombination_ID(), account.getCombination() + " - " + account.getDescription()));
}
// Sort & return
return list;
} // getData
public int getC_ValidCombination_ID()
{
return C_ValidCombination_ID;
}
} // MAccountLookup
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAccountLookup.java
| 1
|
请完成以下Java代码
|
public Long getMaxBackoff() {
return maxBackoff;
}
public void setMaxBackoff(Long maxBackoff) {
this.maxBackoff = maxBackoff;
}
public Integer getBackoffDecreaseThreshold() {
return backoffDecreaseThreshold;
}
public void setBackoffDecreaseThreshold(Integer backoffDecreaseThreshold) {
this.backoffDecreaseThreshold = backoffDecreaseThreshold;
}
public Float getWaitIncreaseFactor() {
return waitIncreaseFactor;
}
public void setWaitIncreaseFactor(Float waitIncreaseFactor) {
this.waitIncreaseFactor = waitIncreaseFactor;
}
@Override
public String toString() {
return joinOn(this.getClass())
.add("enabled=" + enabled)
|
.add("deploymentAware=" + deploymentAware)
.add("corePoolSize=" + corePoolSize)
.add("maxPoolSize=" + maxPoolSize)
.add("keepAliveSeconds=" + keepAliveSeconds)
.add("queueCapacity=" + queueCapacity)
.add("lockTimeInMillis=" + lockTimeInMillis)
.add("maxJobsPerAcquisition=" + maxJobsPerAcquisition)
.add("waitTimeInMillis=" + waitTimeInMillis)
.add("maxWait=" + maxWait)
.add("backoffTimeInMillis=" + backoffTimeInMillis)
.add("maxBackoff=" + maxBackoff)
.add("backoffDecreaseThreshold=" + backoffDecreaseThreshold)
.add("waitIncreaseFactor=" + waitIncreaseFactor)
.toString();
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\JobExecutionProperty.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class EmployeeRepository {
private static final Map<String, Employee> EMPLOYEE_DATA;
static {
EMPLOYEE_DATA = new HashMap<>();
EMPLOYEE_DATA.put("1", new Employee("1", "Employee 1"));
EMPLOYEE_DATA.put("2", new Employee("2", "Employee 2"));
EMPLOYEE_DATA.put("3", new Employee("3", "Employee 3"));
EMPLOYEE_DATA.put("4", new Employee("4", "Employee 4"));
EMPLOYEE_DATA.put("5", new Employee("5", "Employee 5"));
EMPLOYEE_DATA.put("6", new Employee("6", "Employee 6"));
EMPLOYEE_DATA.put("7", new Employee("7", "Employee 7"));
EMPLOYEE_DATA.put("8", new Employee("8", "Employee 8"));
EMPLOYEE_DATA.put("9", new Employee("9", "Employee 9"));
EMPLOYEE_DATA.put("10", new Employee("10", "Employee 10"));
}
public Mono<Employee> findEmployeeById(String id) {
|
return Mono.just(EMPLOYEE_DATA.get(id));
}
public Flux<Employee> findAllEmployees() {
return Flux.fromIterable(EMPLOYEE_DATA.values());
}
public Mono<Employee> updateEmployee(Employee employee) {
Employee existingEmployee = EMPLOYEE_DATA.get(employee.getId());
if (existingEmployee != null) {
existingEmployee.setName(employee.getName());
}
return Mono.just(existingEmployee);
}
}
|
repos\tutorials-master\spring-reactive-modules\spring-reactive\src\main\java\com\baeldung\reactive\webflux\EmployeeRepository.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class ImageRestController
{
public static final String ENDPOINT = MetasfreshRestAPIConstants.ENDPOINT_API_V2 + "/images";
private final AdImageRepository adImageRepository;
public ImageRestController(
@NonNull final AdImageRepository adImageRepository)
{
this.adImageRepository = adImageRepository;
}
@GetMapping("/byId/{imageId}")
@ResponseBody
public ResponseEntity<byte[]> getImageById(
@PathVariable("imageId") final int imageIdInt,
@RequestParam(name = "maxWidth", required = false, defaultValue = "-1") final int maxWidth,
@RequestParam(name = "maxHeight", required = false, defaultValue = "-1") final int maxHeight,
@NonNull final WebRequest request)
{
final AdImageId adImageId = AdImageId.ofRepoId(imageIdInt);
final AdImage adImage = adImageRepository.getById(adImageId);
final String etag = computeETag(adImage.getLastModified(), maxWidth, maxHeight);
if (request.checkNotModified(etag))
{
// Response: 304 Not Modified
return newResponse(HttpStatus.NOT_MODIFIED, etag).build();
}
return newResponse(HttpStatus.OK, etag)
.contentType(MediaType.parseMediaType(adImage.getContentType()))
|
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + adImage.getFilename() + "\"")
.body(adImage.getScaledImageData(maxWidth, maxHeight));
}
private static String computeETag(@NonNull final Instant lastModified, int maxWidth, int maxHeight)
{
return lastModified + "_" + Math.max(maxWidth, 0) + "_" + Math.max(maxHeight, 0);
}
private ResponseEntity.BodyBuilder newResponse(final HttpStatus status, final String etag)
{
return ResponseEntity.status(status)
.eTag(etag)
.cacheControl(CacheControl.maxAge(Duration.ofSeconds(10)));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\image\ImageRestController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public AuthenticationManager authenticationManager(UserDetailsService userDetailsService) {
// Before Spring Boot 4
// var authenticationProvider = new DaoAuthenticationProvider();
// authenticationProvider.setUserDetailsService(userDetailsService);
// After Spring Boot 4
var authenticationProvider = new DaoAuthenticationProvider(userDetailsService);
return new ProviderManager(authenticationProvider);
}
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.withUsername("in28minutes")
.password("{noop}dummy")
.authorities("read")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
@Bean
public JWKSource<SecurityContext> jwkSource() {
JWKSet jwkSet = new JWKSet(rsaKey());
return (((jwkSelector, securityContext)
-> jwkSelector.select(jwkSet)));
}
@Bean
JwtEncoder jwtEncoder(JWKSource<SecurityContext> jwkSource) {
return new NimbusJwtEncoder(jwkSource);
}
|
@Bean
JwtDecoder jwtDecoder() throws JOSEException {
return NimbusJwtDecoder
.withPublicKey(rsaKey().toRSAPublicKey())
.build();
}
@Bean
public RSAKey rsaKey() {
KeyPair keyPair = keyPair();
return new RSAKey
.Builder((RSAPublicKey) keyPair.getPublic())
.privateKey((RSAPrivateKey) keyPair.getPrivate())
.keyID(UUID.randomUUID().toString())
.build();
}
@Bean
public KeyPair keyPair() {
try {
var keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
return keyPairGenerator.generateKeyPair();
} catch (Exception e) {
throw new IllegalStateException(
"Unable to generate an RSA Key Pair", e);
}
}
}
|
repos\master-spring-and-spring-boot-main\13-full-stack\02-rest-api\src\main\java\com\in28minutes\rest\webservices\restfulwebservices\jwt\JwtSecurityConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Duration getLockPollRate() {
return lockPollRate;
}
public void setLockPollRate(Duration lockPollRate) {
this.lockPollRate = lockPollRate;
}
public Duration getSchemaLockWaitTime() {
return schemaLockWaitTime;
}
public void setSchemaLockWaitTime(Duration schemaLockWaitTime) {
this.schemaLockWaitTime = schemaLockWaitTime;
}
public boolean isEnableHistoryCleaning() {
return enableHistoryCleaning;
}
public void setEnableHistoryCleaning(boolean enableHistoryCleaning) {
this.enableHistoryCleaning = enableHistoryCleaning;
}
public String getHistoryCleaningCycle() {
return historyCleaningCycle;
}
public void setHistoryCleaningCycle(String historyCleaningCycle) {
this.historyCleaningCycle = historyCleaningCycle;
}
@Deprecated
@DeprecatedConfigurationProperty(replacement = "flowable.history-cleaning-after", reason = "Switched to using a Duration that allows more flexible configuration")
public void setHistoryCleaningAfterDays(int historyCleaningAfterDays) {
this.historyCleaningAfter = Duration.ofDays(historyCleaningAfterDays);
}
public Duration getHistoryCleaningAfter() {
return historyCleaningAfter;
|
}
public void setHistoryCleaningAfter(Duration historyCleaningAfter) {
this.historyCleaningAfter = historyCleaningAfter;
}
public int getHistoryCleaningBatchSize() {
return historyCleaningBatchSize;
}
public void setHistoryCleaningBatchSize(int historyCleaningBatchSize) {
this.historyCleaningBatchSize = historyCleaningBatchSize;
}
public String getVariableJsonMapper() {
return variableJsonMapper;
}
public void setVariableJsonMapper(String variableJsonMapper) {
this.variableJsonMapper = variableJsonMapper;
}
}
|
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\FlowableProperties.java
| 2
|
请完成以下Java代码
|
public String getRefTableName()
{
return refTableName;
}
/**
*
* @return AD_Ref_Table.AD_Key.AD_Reference_ID
*/
public int getRefDisplayType()
{
return refDisplayType;
}
/**
*
* @return AD_Ref_Table.AD_Table_ID.EntityType
*/
public String getEntityType()
{
return entityType;
}
|
/**
*
* @return AD_Ref_Table.AD_Key.IsKey
*/
public boolean isKey()
{
return isKey;
}
/**
*
* @return AD_Ref_Table.AD_Key.AD_Reference_Value_ID
*/
public int getKeyReferenceValueId()
{
return keyReferenceValueId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\modelgen\TableReferenceInfo.java
| 1
|
请完成以下Java代码
|
public Author as(String alias) {
return new Author(DSL.name(alias), this);
}
@Override
public Author as(Name alias) {
return new Author(alias, this);
}
/**
* Rename this table
*/
@Override
public Author rename(String name) {
return new Author(DSL.name(name), null);
}
|
/**
* Rename this table
*/
@Override
public Author rename(Name name) {
return new Author(name, null);
}
// -------------------------------------------------------------------------
// Row4 type methods
// -------------------------------------------------------------------------
@Override
public Row4<Integer, String, String, Integer> fieldsRow() {
return (Row4) super.fieldsRow();
}
}
|
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\model\tables\Author.java
| 1
|
请完成以下Java代码
|
public ReactorClientHttpRequestFactoryBuilder withReactorResourceFactory(
ReactorResourceFactory reactorResourceFactory) {
Assert.notNull(reactorResourceFactory, "'reactorResourceFactory' must not be null");
return new ReactorClientHttpRequestFactoryBuilder(getCustomizers(),
this.httpClientBuilder.withReactorResourceFactory(reactorResourceFactory));
}
/**
* Return a new {@link ReactorClientHttpRequestFactoryBuilder} that uses the given
* factory to create the underlying {@link HttpClient}.
* @param factory the factory to use
* @return a new {@link ReactorClientHttpRequestFactoryBuilder} instance
* @since 3.5.0
*/
public ReactorClientHttpRequestFactoryBuilder withHttpClientFactory(Supplier<HttpClient> factory) {
Assert.notNull(factory, "'factory' must not be null");
return new ReactorClientHttpRequestFactoryBuilder(getCustomizers(),
this.httpClientBuilder.withHttpClientFactory(factory));
}
/**
* Return a new {@link ReactorClientHttpRequestFactoryBuilder} that applies additional
* customization to the underlying {@link HttpClient}.
* @param httpClientCustomizer the customizer to apply
* @return a new {@link ReactorClientHttpRequestFactoryBuilder} instance
*/
public ReactorClientHttpRequestFactoryBuilder withHttpClientCustomizer(
UnaryOperator<HttpClient> httpClientCustomizer) {
Assert.notNull(httpClientCustomizer, "'httpClientCustomizer' must not be null");
return new ReactorClientHttpRequestFactoryBuilder(getCustomizers(),
this.httpClientBuilder.withHttpClientCustomizer(httpClientCustomizer));
}
/**
* Return a new {@link ReactorClientHttpRequestFactoryBuilder} that applies the given
* customizer. This can be useful for applying pre-packaged customizations.
* @param customizer the customizer to apply
* @return a new {@link ReactorClientHttpRequestFactoryBuilder}
* @since 4.0.0
*/
public ReactorClientHttpRequestFactoryBuilder with(
UnaryOperator<ReactorClientHttpRequestFactoryBuilder> customizer) {
return customizer.apply(this);
}
|
@Override
protected ReactorClientHttpRequestFactory createClientHttpRequestFactory(HttpClientSettings settings) {
HttpClient httpClient = this.httpClientBuilder.build(settings.withTimeouts(null, null));
ReactorClientHttpRequestFactory requestFactory = new ReactorClientHttpRequestFactory(httpClient);
PropertyMapper map = PropertyMapper.get();
map.from(settings::connectTimeout).asInt(Duration::toMillis).to(requestFactory::setConnectTimeout);
map.from(settings::readTimeout).asInt(Duration::toMillis).to(requestFactory::setReadTimeout);
return requestFactory;
}
static class Classes {
static final String HTTP_CLIENT = "reactor.netty.http.client.HttpClient";
static boolean present(@Nullable ClassLoader classLoader) {
return ClassUtils.isPresent(HTTP_CLIENT, classLoader);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\ReactorClientHttpRequestFactoryBuilder.java
| 1
|
请完成以下Java代码
|
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public List<Foo> getFooList() {
return fooList;
}
public void setFooList(final List<Foo> fooList) {
this.fooList = fooList;
}
//
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
|
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Bar other = (Bar) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Bar [name=").append(name).append("]");
return builder.toString();
}
}
|
repos\tutorials-master\persistence-modules\spring-hibernate-5\src\main\java\com\baeldung\hibernate\cache\model\Bar.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DerKurierClientFactory implements ShipperGatewayClientFactory
{
private final DerKurierShipperConfigRepository derKurierShipperConfigRepository;
private final DerKurierDeliveryOrderService derKurierDeliveryOrderService;
private final DerKurierDeliveryOrderRepository derKurierDeliveryOrderRepository;
private final Converters converters;
public DerKurierClientFactory(
@NonNull final DerKurierShipperConfigRepository derKurierShipperConfigRepository,
@NonNull final DerKurierDeliveryOrderService derKurierDeliveryOrderService,
@NonNull final DerKurierDeliveryOrderRepository derKurierDeliveryOrderRepository,
@NonNull final Converters converters)
{
this.derKurierShipperConfigRepository = derKurierShipperConfigRepository;
this.derKurierDeliveryOrderRepository = derKurierDeliveryOrderRepository;
this.derKurierDeliveryOrderService = derKurierDeliveryOrderService;
this.converters = converters;
}
@Override
public ShipperGatewayId getShipperGatewayId()
{
return DerKurierConstants.SHIPPER_GATEWAY_ID;
}
@Override
public ShipperGatewayClient newClientForShipperId(@NonNull final ShipperId shipperId)
{
final DerKurierShipperConfig shipperConfig = derKurierShipperConfigRepository.retrieveConfigForShipperId(shipperId.getRepoId());
return createClient(shipperConfig);
}
@VisibleForTesting
DerKurierClient createClient(@NonNull final DerKurierShipperConfig shipperConfig)
{
final RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder()
.rootUri(shipperConfig.getRestApiBaseUrl());
final RestTemplate restTemplate = restTemplateBuilder.build();
extractAndConfigureObjectMapperOfRestTemplate(restTemplate);
return new DerKurierClient(
restTemplate,
converters,
derKurierDeliveryOrderService,
derKurierDeliveryOrderRepository);
}
|
/**
* Put JavaTimeModule into the rest template's jackson object mapper.
* <b>
* Note 1: there have to be better ways to achieve this, but i don't know them.
* thx to https://stackoverflow.com/a/47176770/1012103
* <b>
* Note 2: visible because this is the object mapper we run with; we want our unit tests to use it as well.
*/
@VisibleForTesting
public static ObjectMapper extractAndConfigureObjectMapperOfRestTemplate(@NonNull final RestTemplate restTemplate)
{
final MappingJackson2HttpMessageConverter messageConverter = restTemplate
.getMessageConverters()
.stream()
.filter(MappingJackson2HttpMessageConverter.class::isInstance)
.map(MappingJackson2HttpMessageConverter.class::cast)
.findFirst().orElseThrow(() -> new RuntimeException("MappingJackson2HttpMessageConverter not found"));
final ObjectMapper objectMapper = messageConverter.getObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
return objectMapper;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java\de\metas\shipper\gateway\derkurier\DerKurierClientFactory.java
| 2
|
请完成以下Java代码
|
public final class ASIAvailableForSalesAttributesKeyFilter implements IQueryFilter<I_MD_Available_For_Sales>
{
public static ASIAvailableForSalesAttributesKeyFilter matchingAttributes(@NonNull final AttributesKeyPattern attributesKeyPattern)
{
return new ASIAvailableForSalesAttributesKeyFilter(attributesKeyPattern);
}
private final AttributesKeyPattern attributesKeyPattern;
private ASIAvailableForSalesAttributesKeyFilter(@NonNull final AttributesKeyPattern attributesKeyPattern)
{
this.attributesKeyPattern = attributesKeyPattern;
}
@Override
public String toString()
{
|
return MoreObjects.toStringHelper(this).addValue(attributesKeyPattern).toString();
}
@Override
public boolean accept(@Nullable final I_MD_Available_For_Sales availableForSales)
{
// Guard against null, shall not happen
if (availableForSales == null)
{
return false;
}
final AttributesKey expectedAttributesKey = AttributesKey.ofString(availableForSales.getStorageAttributesKey());
return attributesKeyPattern.matches(expectedAttributesKey);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\availableforsales\ASIAvailableForSalesAttributesKeyFilter.java
| 1
|
请完成以下Java代码
|
protected boolean afterSave(boolean newRecord, boolean success)
{
if (!success)
{
return success;
}
// Create Update
if (newRecord && getResult() != null)
{
final MRequestUpdate update = new MRequestUpdate(this);
update.save();
}
//
sendNotifications();
// ChangeRequest - created in Request Processor
if (getM_ChangeRequest_ID() != 0
&& is_ValueChanged(COLUMNNAME_R_Group_ID)) // different ECN assignment?
{
int oldID = get_ValueOldAsInt(COLUMNNAME_R_Group_ID);
if (getR_Group_ID() == 0)
{
setM_ChangeRequest_ID(0); // not effective as in afterSave
}
else
{
MGroup oldG = MGroup.get(getCtx(), oldID);
MGroup newG = MGroup.get(getCtx(), getR_Group_ID());
if (oldG.getPP_Product_BOM_ID() != newG.getPP_Product_BOM_ID()
|| oldG.getM_ChangeNotice_ID() != newG.getM_ChangeNotice_ID())
{
MChangeRequest ecr = new MChangeRequest(getCtx(), getM_ChangeRequest_ID(), get_TrxName());
if (!ecr.isProcessed()
|| ecr.getM_FixChangeNotice_ID() == 0)
{
ecr.setPP_Product_BOM_ID(newG.getPP_Product_BOM_ID());
ecr.setM_ChangeNotice_ID(newG.getM_ChangeNotice_ID());
ecr.save();
}
}
}
}
return success;
} // afterSave
private void sendNotifications()
{
final UserId oldSalesRepId = getOldSalesRepId();
final UserId newSalesRepId = getNewSalesRepId();
if (!UserId.equals(oldSalesRepId, newSalesRepId))
{
RequestNotificationsSender.newInstance()
.notifySalesRepChanged(RequestSalesRepChanged.builder()
.changedById(UserId.ofRepoIdOrNull(getUpdatedBy()))
.fromSalesRepId(oldSalesRepId)
.toSalesRepId(newSalesRepId)
.requestDocumentNo(getDocumentNo())
.requestId(RequestId.ofRepoId(getR_Request_ID()))
|
.build());
}
}
private UserId getOldSalesRepId()
{
final Object oldSalesRepIdObj = get_ValueOld(I_R_Request.COLUMNNAME_SalesRep_ID);
if (oldSalesRepIdObj instanceof Integer)
{
final int repoId = ((Integer)oldSalesRepIdObj).intValue();
return UserId.ofRepoId(repoId);
}
else
{
return null;
}
}
private UserId getNewSalesRepId()
{
final int repoId = getSalesRep_ID();
// NOTE: System(=0) is not a valid SalesRep anyways
return repoId > 0
? UserId.ofRepoId(repoId)
: null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MRequest.java
| 1
|
请完成以下Java代码
|
public Duration getCleanInstancesEndedAfter() {
return cleanInstancesEndedAfter;
}
public ProcessEngineConfiguration setCleanInstancesEndedAfter(Duration cleanInstancesEndedAfter) {
this.cleanInstancesEndedAfter = cleanInstancesEndedAfter;
return this;
}
public int getCleanInstancesBatchSize() {
return cleanInstancesBatchSize;
}
public ProcessEngineConfiguration setCleanInstancesBatchSize(int cleanInstancesBatchSize) {
this.cleanInstancesBatchSize = cleanInstancesBatchSize;
return this;
}
public HistoryCleaningManager getHistoryCleaningManager() {
return historyCleaningManager;
}
|
public ProcessEngineConfiguration setHistoryCleaningManager(HistoryCleaningManager historyCleaningManager) {
this.historyCleaningManager = historyCleaningManager;
return this;
}
public boolean isAlwaysUseArraysForDmnMultiHitPolicies() {
return alwaysUseArraysForDmnMultiHitPolicies;
}
public ProcessEngineConfiguration setAlwaysUseArraysForDmnMultiHitPolicies(boolean alwaysUseArraysForDmnMultiHitPolicies) {
this.alwaysUseArraysForDmnMultiHitPolicies = alwaysUseArraysForDmnMultiHitPolicies;
return this;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\ProcessEngineConfiguration.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class BaseValueInject {
@Value("normal")
private String normal; // Inject ordinary string
@Value("#{systemProperties['os.name']}")
private String systemPropertiesName; //Inject operating system properties
@Value("#{ T(java.lang.Math).random() * 100.0 }")
private double randomNumber; //Inject expression result
@Value("#{beanInject.another}")
private String fromAnotherBean; // Inject other Bean attributes: Inject the attribute another of the beanInject object. See the specific definition of the class below.
@Value("classpath:config.txt")
private Resource resourceFile; // Inject file resources
@Value("http://www.baidu.com")
|
private Resource testUrl; // Inject URL resources
@Override
public String toString() {
return "BaseValueInject{" +
"normal='" + normal + '\'' +
", systemPropertiesName='" + systemPropertiesName + '\'' +
", randomNumber=" + randomNumber +
", fromAnotherBean='" + fromAnotherBean + '\'' +
", resourceFile=" + resourceFile +
", testUrl=" + testUrl +
'}';
}
}
|
repos\springboot-demo-master\SpEL\src\main\java\com\et\spel\controller\BaseValueInject.java
| 2
|
请完成以下Java代码
|
public String getChatId() {
return chatId;
}
public void setChatId(@Nullable String chatId) {
this.chatId = chatId;
}
@Nullable
public String getAuthToken() {
return authToken;
}
public void setAuthToken(@Nullable String authToken) {
this.authToken = authToken;
}
public boolean isDisableNotify() {
return disableNotify;
|
}
public void setDisableNotify(boolean disableNotify) {
this.disableNotify = disableNotify;
}
public String getParseMode() {
return parseMode;
}
public void setParseMode(String parseMode) {
this.parseMode = parseMode;
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\TelegramNotifier.java
| 1
|
请完成以下Java代码
|
public boolean deposit(int funds) {
int[] stamps = new int[1];
int current = this.account.get(stamps);
int newStamp = this.stamp.incrementAndGet();
// Thread is paused here to allow other threads to update the stamp and amount (for testing only)
sleep();
return this.account.compareAndSet(current, current + funds, stamps[0], newStamp);
}
public boolean withdrawal(int funds) {
int[] stamps = new int[1];
int current = this.account.get(stamps);
int newStamp = this.stamp.incrementAndGet();
return this.account.compareAndSet(current, current - funds, stamps[0], newStamp);
|
}
public int getBalance() {
return account.getReference();
}
public int getStamp() {
return account.getStamp();
}
private static void sleep() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException ignored) {
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-3\src\main\java\com\baeldung\atomicstampedreference\StampedAccount.java
| 1
|
请完成以下Java代码
|
public void updateById(UserDO entity) {
// 生成 Update 条件
final Update update = new Update();
// 反射遍历 entity 对象,将非空字段设置到 Update 中
ReflectionUtils.doWithFields(entity.getClass(), new ReflectionUtils.FieldCallback() {
@Override
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
// 排除指定条件
if ("id".equals(field.getName()) // 排除 id 字段,因为作为查询主键
|| field.getAnnotation(Transient.class) != null // 排除 @Transient 注解的字段,因为非存储字段
|| Modifier.isStatic(field.getModifiers())) { // 排除静态字段
return;
}
// 设置字段可反射
if (!field.isAccessible()) {
field.setAccessible(true);
}
// 排除字段为空的情况
if (field.get(entity) == null) {
return;
}
// 设置更新条件
update.set(field.getName(), field.get(entity));
}
});
// 防御,避免有业务传递空的 Update 对象
if (update.getUpdateObject().isEmpty()) {
|
return;
}
// 执行更新
mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(entity.getId())), update, UserDO.class);
}
public void deleteById(Integer id) {
mongoTemplate.remove(new Query(Criteria.where("_id").is(id)), UserDO.class);
}
public UserDO findById(Integer id) {
return mongoTemplate.findOne(new Query(Criteria.where("_id").is(id)), UserDO.class);
}
public UserDO findByUsername(String username) {
return mongoTemplate.findOne(new Query(Criteria.where("username").is(username)), UserDO.class);
}
public List<UserDO> findAllById(List<Integer> ids) {
return mongoTemplate.find(new Query(Criteria.where("_id").in(ids)), UserDO.class);
}
}
|
repos\SpringBoot-Labs-master\lab-16-spring-data-mongo\lab-16-spring-data-mongodb\src\main\java\cn\iocoder\springboot\lab16\springdatamongodb\dao\UserDao.java
| 1
|
请完成以下Java代码
|
public class GroovyTypeDeclaration extends TypeDeclaration {
private int modifiers;
private final List<GroovyFieldDeclaration> fieldDeclarations = new ArrayList<>();
private final List<GroovyMethodDeclaration> methodDeclarations = new ArrayList<>();
GroovyTypeDeclaration(String name) {
super(name);
}
/**
* Sets the modifiers.
* @param modifiers the modifiers
*/
public void modifiers(int modifiers) {
this.modifiers = modifiers;
}
/**
* Returns the modifiers.
* @return the modifiers
*/
public int getModifiers() {
return this.modifiers;
}
/**
* Adds the given field declaration.
* @param fieldDeclaration the field declaration
*/
public void addFieldDeclaration(GroovyFieldDeclaration fieldDeclaration) {
this.fieldDeclarations.add(fieldDeclaration);
}
/**
* Return the field declarations.
* @return the field declarations
|
*/
public List<GroovyFieldDeclaration> getFieldDeclarations() {
return this.fieldDeclarations;
}
/**
* Adds the given method declaration.
* @param methodDeclaration the method declaration
*/
public void addMethodDeclaration(GroovyMethodDeclaration methodDeclaration) {
this.methodDeclarations.add(methodDeclaration);
}
/**
* Returns the method declarations.
* @return the method declarations
*/
public List<GroovyMethodDeclaration> getMethodDeclarations() {
return this.methodDeclarations;
}
}
|
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\groovy\GroovyTypeDeclaration.java
| 1
|
请完成以下Java代码
|
public class Person {
private String firstName;
private String lastName;
private int age;
public Person() {
}
public Person(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
|
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", age=" + age + '}';
}
}
|
repos\tutorials-master\spring-web-modules\spring-mvc-basics-3\src\main\java\com\baeldung\cachedrequest\Person.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void shipOrder(int orderId) {
Optional<ShippableOrder> order = this.orderRepository.findShippableOrder(orderId);
order.ifPresent(completedOrder -> {
Parcel parcel = new Parcel(completedOrder.getOrderId(), completedOrder.getAddress(), completedOrder.getPackageItems());
if (parcel.isTaxable()) {
// Calculate additional taxes
}
// Ship parcel
this.shippedParcels.put(completedOrder.getOrderId(), parcel);
});
}
@Override
public void listenToOrderEvents() {
this.eventBus.subscribe(EVENT_ORDER_READY_FOR_SHIPMENT, new EventSubscriber() {
@Override
public <E extends ApplicationEvent> void onEvent(E event) {
shipOrder(Integer.parseInt(event.getPayloadValue("order_id")));
}
});
}
|
@Override
public Optional<Parcel> getParcelByOrderId(int orderId) {
return Optional.ofNullable(this.shippedParcels.get(orderId));
}
public void setOrderRepository(ShippingOrderRepository orderRepository) {
this.orderRepository = orderRepository;
}
@Override
public EventBus getEventBus() {
return eventBus;
}
@Override
public void setEventBus(EventBus eventBus) {
this.eventBus = eventBus;
}
}
|
repos\tutorials-master\patterns-modules\ddd-contexts\ddd-contexts-shippingcontext\src\main\java\com\baeldung\dddcontexts\shippingcontext\service\ParcelShippingService.java
| 2
|
请完成以下Java代码
|
public void setDateFrom (Timestamp DateFrom)
{
set_Value (COLUMNNAME_DateFrom, DateFrom);
}
/** Get Date From.
@return Starting date for a range
*/
public Timestamp getDateFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_DateFrom);
}
/** Set Date To.
@param DateTo
End date of a date range
*/
public void setDateTo (Timestamp DateTo)
{
set_Value (COLUMNNAME_DateTo, DateTo);
}
/** Get Date To.
@return End date of a date range
*/
public Timestamp getDateTo ()
{
return (Timestamp)get_Value(COLUMNNAME_DateTo);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set GL Fund.
@param GL_Fund_ID
General Ledger Funds Control
*/
public void setGL_Fund_ID (int GL_Fund_ID)
{
if (GL_Fund_ID < 1)
set_ValueNoCheck (COLUMNNAME_GL_Fund_ID, null);
else
set_ValueNoCheck (COLUMNNAME_GL_Fund_ID, Integer.valueOf(GL_Fund_ID));
}
/** Get GL Fund.
@return General Ledger Funds Control
*/
public int getGL_Fund_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GL_Fund_ID);
if (ii == null)
return 0;
return ii.intValue();
}
|
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_Fund.java
| 1
|
请完成以下Java代码
|
public void setProjInvoiceRule (final java.lang.String ProjInvoiceRule)
{
set_Value (COLUMNNAME_ProjInvoiceRule, ProjInvoiceRule);
}
@Override
public java.lang.String getProjInvoiceRule()
{
return get_ValueAsString(COLUMNNAME_ProjInvoiceRule);
}
@Override
public org.compiere.model.I_R_Status getR_Project_Status()
{
return get_ValueAsPO(COLUMNNAME_R_Project_Status_ID, org.compiere.model.I_R_Status.class);
}
@Override
public void setR_Project_Status(final org.compiere.model.I_R_Status R_Project_Status)
{
set_ValueFromPO(COLUMNNAME_R_Project_Status_ID, org.compiere.model.I_R_Status.class, R_Project_Status);
}
@Override
public void setR_Project_Status_ID (final int R_Project_Status_ID)
{
if (R_Project_Status_ID < 1)
set_Value (COLUMNNAME_R_Project_Status_ID, null);
else
set_Value (COLUMNNAME_R_Project_Status_ID, R_Project_Status_ID);
}
@Override
public int getR_Project_Status_ID()
{
return get_ValueAsInt(COLUMNNAME_R_Project_Status_ID);
}
@Override
public void setSalesRep_ID (final int SalesRep_ID)
|
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, SalesRep_ID);
}
@Override
public int getSalesRep_ID()
{
return get_ValueAsInt(COLUMNNAME_SalesRep_ID);
}
@Override
public void setstartdatetime (final @Nullable java.sql.Timestamp startdatetime)
{
set_Value (COLUMNNAME_startdatetime, startdatetime);
}
@Override
public java.sql.Timestamp getstartdatetime()
{
return get_ValueAsTimestamp(COLUMNNAME_startdatetime);
}
@Override
public void setValue (final java.lang.String Value)
{
set_ValueNoCheck (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project.java
| 1
|
请完成以下Java代码
|
public boolean hasAttribute(String key)
{
return(this.containsKey(key));
}
/**
Perform the filtering operation.
*/
public String process(String to_process)
{
if ( to_process == null || to_process.length() == 0 )
return "";
StringBuffer bs = new StringBuffer(to_process.length() + 50);
StringCharacterIterator sci = new StringCharacterIterator(to_process);
String tmp = null;
|
for (char c = sci.first(); c != CharacterIterator.DONE; c = sci.next())
{
tmp = String.valueOf(c);
if (hasAttribute(tmp))
tmp = (String) this.get(tmp);
int ii = c;
if (ii > 255)
tmp = "&#" + ii + ";";
bs.append(tmp);
}
return(bs.toString());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\filter\CharacterFilter.java
| 1
|
请完成以下Java代码
|
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
// Spring runs CommandLineRunner bean when Spring Boot App starts
@Bean
public CommandLineRunner demo(BookRepository bookRepository) {
return (args) -> {
Book b1 = new Book("Book A", BigDecimal.valueOf(9.99), LocalDate.of(2023, 8, 31));
Book b2 = new Book("Book B", BigDecimal.valueOf(19.99), LocalDate.of(2023, 7, 31));
Book b3 = new Book("Book C", BigDecimal.valueOf(29.99), LocalDate.of(2023, 6, 10));
Book b4 = new Book("Book D", BigDecimal.valueOf(39.99), LocalDate.of(2023, 5, 5));
// save a few books, ID auto increase, expect 1, 2, 3, 4
bookRepository.save(b1);
bookRepository.save(b2);
bookRepository.save(b3);
bookRepository.save(b4);
// find all books
log.info("findAll(), expect 4 books");
log.info("-------------------------------");
for (Book book : bookRepository.findAll()) {
log.info(book.toString());
}
log.info("\n");
// find book by ID
Optional<Book> optionalBook = bookRepository.findById(1L);
optionalBook.ifPresent(obj -> {
log.info("Book found with findById(1L):");
log.info("--------------------------------");
log.info(obj.toString());
log.info("\n");
});
// find book by title
log.info("Book found with findByTitle('Book B')");
log.info("--------------------------------------------");
bookRepository.findByTitle("Book C").forEach(b -> {
log.info(b.toString());
|
log.info("\n");
});
// find book by published date after
log.info("Book found with findByPublishedDateAfter(), after 2023/7/1");
log.info("--------------------------------------------");
bookRepository.findByPublishedDateAfter(LocalDate.of(2023, 7, 1)).forEach(b -> {
log.info(b.toString());
log.info("\n");
});
// delete a book
bookRepository.deleteById(2L);
log.info("Book delete where ID = 2L");
log.info("--------------------------------------------");
// find all books
log.info("findAll() again, expect 3 books");
log.info("-------------------------------");
for (Book book : bookRepository.findAll()) {
log.info(book.toString());
}
log.info("\n");
};
}
}
|
repos\spring-boot-master\spring-data-jpa\src\main\java\com\mkyong\MainApplication.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class EmployeeService_Service
extends Service
{
private final static URL EMPLOYEESERVICE_WSDL_LOCATION;
private final static WebServiceException EMPLOYEESERVICE_EXCEPTION;
private final static QName EMPLOYEESERVICE_QNAME = new QName("http://bottomup.server.jaxws.baeldung.com/", "EmployeeService");
static {
URL url = null;
WebServiceException e = null;
try {
url = new URI("http://localhost:8080/employeeservice?wsdl").toURL();
} catch (MalformedURLException | URISyntaxException ex) {
e = new WebServiceException(ex);
}
EMPLOYEESERVICE_WSDL_LOCATION = url;
EMPLOYEESERVICE_EXCEPTION = e;
}
public EmployeeService_Service() {
super(__getWsdlLocation(), EMPLOYEESERVICE_QNAME);
}
public EmployeeService_Service(WebServiceFeature... features) {
super(__getWsdlLocation(), EMPLOYEESERVICE_QNAME, features);
}
public EmployeeService_Service(URL wsdlLocation) {
super(wsdlLocation, EMPLOYEESERVICE_QNAME);
}
public EmployeeService_Service(URL wsdlLocation, WebServiceFeature... features) {
super(wsdlLocation, EMPLOYEESERVICE_QNAME, features);
}
public EmployeeService_Service(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
public EmployeeService_Service(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
super(wsdlLocation, serviceName, features);
}
/**
*
* @return
* returns EmployeeService
|
*/
@WebEndpoint(name = "EmployeeServiceImplPort")
public EmployeeService getEmployeeServiceImplPort() {
return super.getPort(new QName("http://bottomup.server.jaxws.baeldung.com/", "EmployeeServiceImplPort"), EmployeeService.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns EmployeeService
*/
@WebEndpoint(name = "EmployeeServiceImplPort")
public EmployeeService getEmployeeServiceImplPort(WebServiceFeature... features) {
return super.getPort(new QName("http://bottomup.server.jaxws.baeldung.com/", "EmployeeServiceImplPort"), EmployeeService.class, features);
}
private static URL __getWsdlLocation() {
if (EMPLOYEESERVICE_EXCEPTION!= null) {
throw EMPLOYEESERVICE_EXCEPTION;
}
return EMPLOYEESERVICE_WSDL_LOCATION;
}
}
|
repos\tutorials-master\web-modules\jee-7\src\main\java\com\baeldung\jaxws\client\EmployeeService_Service.java
| 2
|
请完成以下Java代码
|
public static MenuResultItemSource forRootNode(final MTreeNode root)
{
final Enumeration<?> nodesEnum = root.preorderEnumeration();
final List<MenuResultItem> items = new ArrayList<>();
while (nodesEnum.hasMoreElements())
{
final MTreeNode node = (MTreeNode)nodesEnum.nextElement();
if (node == root)
{
continue;
}
if (node.isSummary())
{
continue;
}
final MenuResultItem item = new MenuResultItem(node);
items.add(item);
}
return new MenuResultItemSource(items);
}
private final ImmutableList<MenuResultItem> items;
private MenuResultItemSource(final List<MenuResultItem> items)
{
super();
this.items = ImmutableList.copyOf(items);
}
@Override
public List<MenuResultItem> query(final String searchText, final int limit)
{
return items;
}
}
/**
* {@link MenuResultItem} renderer.
*/
private static final class ResultItemRenderer implements ListCellRenderer<ResultItem>
{
private final DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
@Override
|
public Component getListCellRendererComponent(final JList<? extends ResultItem> list, final ResultItem value, final int index, final boolean isSelected, final boolean cellHasFocus)
{
final String valueAsText;
final Icon icon;
boolean enabled = true;
if (value == null)
{
// shall not happen
valueAsText = "";
icon = null;
}
else if (value == MORE_Marker)
{
valueAsText = "...";
icon = null;
enabled = false;
}
else if (value instanceof MenuResultItem)
{
final MenuResultItem menuItem = (MenuResultItem)value;
valueAsText = menuItem.getText();
icon = menuItem.getIcon();
}
else
{
valueAsText = value.toString();
icon = null;
}
defaultRenderer.getListCellRendererComponent(list, valueAsText, index, isSelected, cellHasFocus);
defaultRenderer.setIcon(icon);
defaultRenderer.setEnabled(enabled);
return defaultRenderer;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\tree\TreeSearchAutoCompleter.java
| 1
|
请完成以下Java代码
|
public void setM_Securpharm_Productdata_Result_ID (int M_Securpharm_Productdata_Result_ID)
{
if (M_Securpharm_Productdata_Result_ID < 1)
set_Value (COLUMNNAME_M_Securpharm_Productdata_Result_ID, null);
else
set_Value (COLUMNNAME_M_Securpharm_Productdata_Result_ID, Integer.valueOf(M_Securpharm_Productdata_Result_ID));
}
/** Get Securpharm Produktdaten Ergebnise.
@return Securpharm Produktdaten Ergebnise */
@Override
public int getM_Securpharm_Productdata_Result_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Securpharm_Productdata_Result_ID);
if (ii == null)
return 0;
return ii.intValue();
}
|
/** Set TransaktionsID Server.
@param TransactionIDServer TransaktionsID Server */
@Override
public void setTransactionIDServer (java.lang.String TransactionIDServer)
{
set_Value (COLUMNNAME_TransactionIDServer, TransactionIDServer);
}
/** Get TransaktionsID Server.
@return TransaktionsID Server */
@Override
public java.lang.String getTransactionIDServer ()
{
return (java.lang.String)get_Value(COLUMNNAME_TransactionIDServer);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java-gen\de\metas\vertical\pharma\securpharm\model\X_M_Securpharm_Action_Result.java
| 1
|
请完成以下Java代码
|
public Builder environment(String key, String value) {
this.environment.put(key, value);
return this;
}
public Builder environment(Map<String, String> environment) {
this.environment.putAll(environment);
return this;
}
public Builder ports(Collection<Integer> ports) {
this.ports.addAll(ports);
return this;
}
public Builder ports(int... ports) {
return ports(Arrays.stream(ports).boxed().toList());
}
public Builder command(String command) {
this.command = command;
return this;
}
public Builder label(String key, String value) {
this.labels.put(key, value);
return this;
}
|
public Builder labels(Map<String, String> label) {
this.labels.putAll(label);
return this;
}
/**
* Builds the {@link ComposeService} instance.
* @return the built instance
*/
public ComposeService build() {
return new ComposeService(this);
}
}
}
|
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\container\docker\compose\ComposeService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class FilterRegistrationConfig
{
private final ILanguageDAO languageDAO = Services.get(ILanguageDAO.class);
// NOTE: we are using standard spring CORS filter
// @Bean
// public FilterRegistrationBean<CORSFilter> corsFilter()
// {
// final FilterRegistrationBean<CORSFilter> registrationBean = new FilterRegistrationBean<>();
// registrationBean.setFilter(new CORSFilter());
// registrationBean.addUrlPatterns(MetasfreshRestAPIConstants.URL_PATTERN_API);
// registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
// return registrationBean;
// }
@Bean
public FilterRegistrationBean<UserAuthTokenFilter> authFilter(
@NonNull final UserAuthTokenService userAuthTokenService,
@NonNull final UserAuthTokenFilterConfiguration configuration)
{
|
final FilterRegistrationBean<UserAuthTokenFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new UserAuthTokenFilter(userAuthTokenService, configuration, languageDAO));
registrationBean.addUrlPatterns(MetasfreshRestAPIConstants.URL_PATTERN_API);
registrationBean.setOrder(2);
return registrationBean;
}
@Bean
public FilterRegistrationBean<ApiAuditFilter> apiAuditFilter(@NonNull final ApiAuditService apiAuditService)
{
final FilterRegistrationBean<ApiAuditFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new ApiAuditFilter(apiAuditService));
registrationBean.addUrlPatterns(MetasfreshRestAPIConstants.URL_PATTERN_API_V2);
registrationBean.setOrder(3);
return registrationBean;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\filter\FilterRegistrationConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public CommonResult<PmsProductCategory> getItem(@PathVariable Long id) {
PmsProductCategory productCategory = productCategoryService.getItem(id);
return CommonResult.success(productCategory);
}
@ApiOperation("删除商品分类")
@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult delete(@PathVariable Long id) {
int count = productCategoryService.delete(id);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
@ApiOperation("修改导航栏显示状态")
@RequestMapping(value = "/update/navStatus", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateNavStatus(@RequestParam("ids") List<Long> ids, @RequestParam("navStatus") Integer navStatus) {
int count = productCategoryService.updateNavStatus(ids, navStatus);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
|
}
}
@ApiOperation("修改显示状态")
@RequestMapping(value = "/update/showStatus", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateShowStatus(@RequestParam("ids") List<Long> ids, @RequestParam("showStatus") Integer showStatus) {
int count = productCategoryService.updateShowStatus(ids, showStatus);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
@ApiOperation("查询所有一级分类及子分类")
@RequestMapping(value = "/list/withChildren", method = RequestMethod.GET)
@ResponseBody
public CommonResult<List<PmsProductCategoryWithChildrenItem>> listWithChildren() {
List<PmsProductCategoryWithChildrenItem> list = productCategoryService.listWithChildren();
return CommonResult.success(list);
}
}
|
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\PmsProductCategoryController.java
| 2
|
请完成以下Java代码
|
private ProductId getProductIdToPack()
{
if (_productIdToPack == null)
{
final PackageableRow packageableRow = getSingleSelectedPackageableRow();
_productIdToPack = packageableRow.getProductId();
}
return _productIdToPack;
}
private void pickCUs()
{
final HuId splitCUId = Services.get(ITrxManager.class).callInNewTrx(this::performPickCU);
if (isAutoProcess)
{
autoProcessPicking(splitCUId);
}
}
private HuId performPickCU()
{
final HuId huIdToSplit = retrieveHUIdToSplit();
final ProductId productId = getProductId();
// validating the attributes here because it doesn't make sense to split the HU if it can't be used
huAttributesBL.validateMandatoryPickingAttributes(huIdToSplit, productId);
final List<I_M_HU> splitHUs = HUSplitBuilderCoreEngine.builder()
.huToSplit(handlingUnitsDAO.getById(huIdToSplit))
.requestProvider(this::createSplitAllocationRequest)
.destination(HUProducerDestination.ofVirtualPI())
.build()
.withPropagateHUValues()
.withAllowPartialUnloads(true) // we allow partial loads and unloads so if a user enters a very large number, then that will just account to "all of it" and there will be no error
.performSplit();
final I_M_HU splitCU = CollectionUtils.singleElement(splitHUs);
final HuId splitCUId = HuId.ofRepoId(splitCU.getM_HU_ID());
addHUIdToCurrentPickingSlot(splitCUId);
return splitCUId;
}
|
private IAllocationRequest createSplitAllocationRequest(final IHUContext huContext)
{
final ProductId productId = getProductId();
final I_C_UOM uom = productBL.getStockUOM(productId);
return AllocationUtils.builder()
.setHUContext(huContext)
.setProduct(productId)
.setQuantity(getQtyCUsPerTU(), uom)
.setDate(SystemTime.asZonedDateTime())
.setFromReferencedModel(null) // N/A
.setForceQtyAllocation(false)
.create();
}
private void autoProcessPicking(final HuId splitCUId)
{
final ShipmentScheduleId shipmentScheduleId = null;
pickingCandidateService.processForHUIds(ImmutableSet.of(splitCUId), shipmentScheduleId);
}
private HuId retrieveHUIdToSplit()
{
return retrieveEligibleHUEditorRows()
.map(HUEditorRow::getHuId)
.collect(GuavaCollectors.singleElementOrThrow(() -> new AdempiereException("Only one HU shall be selected")));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\husToPick\process\WEBUI_HUsToPick_PickCU.java
| 1
|
请完成以下Java代码
|
public JdkDto getJdk() {
return jdk;
}
public void setJdk(JdkDto jdk) {
this.jdk = jdk;
}
public Set<String> getCamundaIntegration() {
return camundaIntegration;
}
public void setCamundaIntegration(Set<String> camundaIntegration) {
this.camundaIntegration = camundaIntegration;
}
public LicenseKeyDataDto getLicenseKey() {
return licenseKey;
}
public void setLicenseKey(LicenseKeyDataDto licenseKey) {
this.licenseKey = licenseKey;
}
public Set<String> getWebapps() {
return webapps;
}
public void setWebapps(Set<String> webapps) {
this.webapps = webapps;
}
public Date getDataCollectionStartDate() {
return dataCollectionStartDate;
}
public void setDataCollectionStartDate(Date dataCollectionStartDate) {
this.dataCollectionStartDate = dataCollectionStartDate;
}
public static InternalsDto fromEngineDto(Internals other) {
LicenseKeyData licenseKey = other.getLicenseKey();
InternalsDto dto = new InternalsDto(
|
DatabaseDto.fromEngineDto(other.getDatabase()),
ApplicationServerDto.fromEngineDto(other.getApplicationServer()),
licenseKey != null ? LicenseKeyDataDto.fromEngineDto(licenseKey) : null,
JdkDto.fromEngineDto(other.getJdk()));
dto.dataCollectionStartDate = other.getDataCollectionStartDate();
dto.commands = new HashMap<>();
other.getCommands().forEach((name, command) -> dto.commands.put(name, new CommandDto(command.getCount())));
dto.metrics = new HashMap<>();
other.getMetrics().forEach((name, metric) -> dto.metrics.put(name, new MetricDto(metric.getCount())));
dto.setWebapps(other.getWebapps());
dto.setCamundaIntegration(other.getCamundaIntegration());
return dto;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\telemetry\InternalsDto.java
| 1
|
请完成以下Java代码
|
protected boolean isEnded(HistoricBatchEntity instance) {
return instance.getEndTime() != null;
}
protected boolean isStrategyStart(CommandContext commandContext) {
return HISTORY_REMOVAL_TIME_STRATEGY_START.equals(getHistoryRemovalTimeStrategy(commandContext));
}
protected boolean isStrategyEnd(CommandContext commandContext) {
return HISTORY_REMOVAL_TIME_STRATEGY_END.equals(getHistoryRemovalTimeStrategy(commandContext));
}
protected String getHistoryRemovalTimeStrategy(CommandContext commandContext) {
return commandContext.getProcessEngineConfiguration()
.getHistoryRemovalTimeStrategy();
}
protected boolean isDmnEnabled(CommandContext commandContext) {
return commandContext.getProcessEngineConfiguration().isDmnEnabled();
}
protected Date calculateRemovalTime(HistoricBatchEntity batch, CommandContext commandContext) {
return commandContext.getProcessEngineConfiguration()
.getHistoryRemovalTimeProvider()
.calculateRemovalTime(batch);
}
protected ByteArrayEntity findByteArrayById(String byteArrayId, CommandContext commandContext) {
return commandContext.getDbEntityManager()
.selectById(ByteArrayEntity.class, byteArrayId);
}
protected HistoricBatchEntity findBatchById(String instanceId, CommandContext commandContext) {
return commandContext.getHistoricBatchManager()
.findHistoricBatchById(instanceId);
|
}
public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() {
return JOB_DECLARATION;
}
protected SetRemovalTimeBatchConfiguration createJobConfiguration(SetRemovalTimeBatchConfiguration configuration, List<String> batchIds) {
return new SetRemovalTimeBatchConfiguration(batchIds)
.setRemovalTime(configuration.getRemovalTime())
.setHasRemovalTime(configuration.hasRemovalTime());
}
protected SetRemovalTimeJsonConverter getJsonConverterInstance() {
return SetRemovalTimeJsonConverter.INSTANCE;
}
public String getType() {
return Batch.TYPE_BATCH_SET_REMOVAL_TIME;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\removaltime\BatchSetRemovalTimeJobHandler.java
| 1
|
请完成以下Java代码
|
public class LinkThrowIconType extends IconType {
@Override
public Integer getWidth() {
return 17;
}
@Override
public Integer getHeight() {
return 15;
}
@Override
public String getAnchorValue() {
return null;
}
@Override
public String getFillValue() {
return "#585858";
}
@Override
public String getStyleValue() {
return "stroke-width:1.4;stroke-miterlimit:4;stroke-dasharray:none";
}
@Override
public String getDValue() {
return "m 3 3 l 0 0 m 8 8 l 8 0 l 0 -2 l 4 4 l -4 4 l 0 -2 l -8 0 l 0 -4 z";
}
@Override
public void drawIcon(int imageX, int imageY, int iconPadding, ProcessDiagramSVGGraphics2D svgGenerator) {
Element gTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_G_TAG);
gTag.setAttributeNS(null, "transform", "translate(" + (imageX - 7) + "," + (imageY - 7) + ")");
Element pathTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_PATH_TAG);
|
pathTag.setAttributeNS(null, "d", this.getDValue());
pathTag.setAttributeNS(null, "style", this.getStyleValue());
pathTag.setAttributeNS(null, "fill", this.getFillValue());
pathTag.setAttributeNS(null, "stroke", this.getStrokeValue());
gTag.appendChild(pathTag);
svgGenerator.getExtendDOMGroupManager().addElement(gTag);
}
@Override
public String getStrokeValue() {
return "#585858";
}
@Override
public String getStrokeWidth() {
return null;
}
}
|
repos\Activiti-develop\activiti-core\activiti-image-generator\src\main\java\org\activiti\image\impl\icon\LinkThrowIconType.java
| 1
|
请完成以下Java代码
|
public I_I_User retrieveImportRecord(final Properties ctx, final ResultSet rs) throws SQLException
{
final PO po = TableModelLoader.instance.getPO(ctx, I_I_User.Table_Name, rs, ITrx.TRXNAME_ThreadInherited);
return InterfaceWrapperHelper.create(po, I_I_User.class);
}
/*
* @param isInsertOnly ignored. This import is only for updates.
*/
@Override
protected ImportRecordResult importRecord(final @NonNull IMutable<Object> state,
final @NonNull I_I_User importRecord,
final boolean isInsertOnly) throws Exception
{
//
// Create a new user
final I_AD_User user = InterfaceWrapperHelper.newInstance(I_AD_User.class, importRecord);
user.setAD_Org_ID(importRecord.getAD_Org_ID());
//
// BPartner
{
int bpartnerId = importRecord.getC_BPartner_ID();
if (bpartnerId <= 0)
{
throw new AdempiereException("BPartner not found");
}
user.setC_BPartner_ID(bpartnerId);
}
//
// set data from the other fields
setUserFieldsAndSave(user, importRecord);
//
// Assign Role
final RoleId roleId = RoleId.ofRepoIdOrNull(importRecord.getAD_Role_ID());
if (roleId != null)
{
final UserId userId = UserId.ofRepoId(user.getAD_User_ID());
Services.get(IRoleDAO.class).createUserRoleAssignmentIfMissing(userId, roleId);
}
//
// Link back the request to current import record
importRecord.setAD_User_ID(user.getAD_User_ID());
//
return ImportRecordResult.Inserted;
}
private void setUserFieldsAndSave(@NonNull final I_AD_User user, @NonNull final I_I_User importRecord)
{
|
user.setFirstname(importRecord.getFirstname());
user.setLastname(importRecord.getLastname());
// set value after we set first name and last name
user.setValue(importRecord.getUserValue());
user.setEMail(importRecord.getEMail());
user.setIsNewsletter(importRecord.isNewsletter());
user.setPhone(importRecord.getPhone());
user.setFax(importRecord.getFax());
user.setMobilePhone(importRecord.getMobilePhone());
// user.gen
final I_AD_User loginUser = InterfaceWrapperHelper.create(user, I_AD_User.class);
loginUser.setLogin(importRecord.getLogin());
loginUser.setIsSystemUser(importRecord.isSystemUser());
final IUserBL userBL = Services.get(IUserBL.class);
userBL.changePasswordAndSave(loginUser, RandomStringUtils.randomAlphanumeric(8));
}
@Override
protected void markImported(final I_I_User importRecord)
{
importRecord.setI_IsImported(X_I_User.I_ISIMPORTED_Imported);
importRecord.setProcessed(true);
InterfaceWrapperHelper.save(importRecord);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\impexp\ADUserImportProcess.java
| 1
|
请完成以下Java代码
|
public class DynamicDatasourceInterceptor implements HandlerInterceptor {
/**
* 在请求处理之前进行调用(Controller方法调用之前)
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String requestURI = request.getRequestURI();
log.info("经过多数据源Interceptor,当前路径是{}", requestURI);
//获取动态数据源名称
String dsName = request.getParameter("dsName");
String dsKey = "master";
if (StringUtils.isNotEmpty(dsName)) {
dsKey = dsName;
}
DynamicDataSourceContextHolder.push(dsKey);
return true;
}
/**
|
* 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
}
/**
* 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
DynamicDataSourceContextHolder.clear();
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\mybatis\interceptor\DynamicDatasourceInterceptor.java
| 1
|
请完成以下Java代码
|
public class OrderItem {
private int productId;
private int quantity;
private float unitPrice;
private float unitWeight;
public OrderItem(int productId, int quantity, float unitPrice, float unitWeight) {
this.productId = productId;
this.quantity = quantity;
this.unitPrice = unitPrice;
this.unitWeight = unitWeight;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public float getTotalPrice() {
return this.quantity * this.unitPrice;
|
}
public void setUnitPrice(float unitPrice) {
this.unitPrice = unitPrice;
}
public float getUnitWeight() {
return unitWeight;
}
public float getUnitPrice() {
return unitPrice;
}
public void setUnitWeight(float unitWeight) {
this.unitWeight = unitWeight;
}
}
|
repos\tutorials-master\patterns-modules\ddd-contexts\ddd-contexts-ordercontext\src\main\java\com\baeldung\dddcontexts\ordercontext\model\OrderItem.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return getAsString();
}
@NonNull
@JsonValue
public String getAsString()
{
return attributesKeyString;
}
public boolean isNone()
{
return NONE.equals(this);
}
public boolean isAll()
{
return ALL.equals(this);
}
public boolean isOther()
{
return OTHER.equals(this);
}
public void assertNotAllOrOther()
{
Check.errorIf(isOther() || isAll(),
"AttributesKeys.OTHER or .ALL of the given attributesKey is not supported; attributesKey={}", this);
}
private static ImmutableSet<AttributesKeyPart> extractAttributeKeyParts(final String attributesKeyString)
{
if (attributesKeyString.trim().isEmpty())
{
return ImmutableSet.of();
}
try
{
return ATTRIBUTEVALUEIDS_SPLITTER.splitToList(attributesKeyString.trim())
.stream()
.map(AttributesKeyPart::parseString)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(ImmutableSet.toImmutableSet());
}
catch (final Exception ex)
{
throw AdempiereException.wrapIfNeeded(ex)
.appendParametersToMessage()
.setParameter("attributesKeyString", attributesKeyString);
}
}
|
public boolean contains(@NonNull final AttributesKey attributesKey)
{
return parts.containsAll(attributesKey.parts);
}
public AttributesKey getIntersection(@NonNull final AttributesKey attributesKey)
{
final HashSet<AttributesKeyPart> ownMutableParts = new HashSet<>(parts);
ownMutableParts.retainAll(attributesKey.parts);
return AttributesKey.ofParts(ownMutableParts);
}
/**
* @return {@code true} if ad least one attributeValueId from the given {@code attributesKey} is included in this instance.
*/
public boolean intersects(@NonNull final AttributesKey attributesKey)
{
return parts.stream().anyMatch(attributesKey.parts::contains);
}
public String getValueByAttributeId(@NonNull final AttributeId attributeId)
{
for (final AttributesKeyPart part : parts)
{
if (part.getType() == AttributeKeyPartType.AttributeIdAndValue
&& AttributeId.equals(part.getAttributeId(), attributeId))
{
return part.getValue();
}
}
throw new AdempiereException("Attribute `" + attributeId + "` was not found in `" + this + "`");
}
public static boolean equals(@Nullable final AttributesKey k1, @Nullable final AttributesKey k2)
{
return Objects.equals(k1, k2);
}
@Override
public int compareTo(@Nullable final AttributesKey o)
{
if (o == null)
{
return 1; // we assume that null is less than not-null
}
return this.getAsString().compareTo(o.getAsString());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\commons\AttributesKey.java
| 1
|
请完成以下Java代码
|
public String getPaymentRule ()
{
return (String)get_Value(COLUMNNAME_PaymentRule);
}
/** Set Processed.
@param Processed
The document has been processed
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
@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 Process Now.
@param Processing Process Now */
@Override
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
@Override
public boolean isProcessing ()
|
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
{
return ((Boolean)oo).booleanValue();
}
return "Y".equals(oo);
}
return false;
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
@Override
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Payroll.java
| 1
|
请完成以下Java代码
|
final class AvailableForSaleResultBuilder
{
public static AvailableForSaleResultBuilder createEmpty()
{
return new AvailableForSaleResultBuilder(ImmutableList.of(AvailableForSaleResultBucket.newAcceptingAny()));
}
@NonNull
public static AvailableForSaleResultBuilder createEmptyWithPredefinedBuckets(@NonNull final AvailableForSalesMultiQuery multiQuery)
{
final ImmutableList.Builder<AvailableForSaleResultBucket> buckets = ImmutableList.builder();
final List<AvailableForSalesQuery> availableForSalesQueries = multiQuery.getAvailableForSalesQueries();
for (final AvailableForSalesQuery query : availableForSalesQueries)
{
final List<AttributesKeyMatcher> storageAttributesKeyMatchers = AttributesKeyPatternsUtil.extractAttributesKeyMatchers(Collections.singletonList(query.getStorageAttributesKeyPattern()));
final ProductId productId = query.getProductId();
for (final AttributesKeyMatcher storageAttributesKeyMatcher : storageAttributesKeyMatchers)
{
final AvailableForSaleResultBucket bucket = AvailableForSaleResultBucket.builder()
.product(ProductClassifier.specific(productId.getRepoId()))
.storageAttributesKeyMatcher(storageAttributesKeyMatcher)
.warehouse(WarehouseClassifier.specificOrAny(query.getWarehouseId()))
.build();
bucket.addDefaultEmptyGroupIfPossible();
buckets.add(bucket);
}
}
return new AvailableForSaleResultBuilder(buckets.build());
}
private final ArrayList<AvailableForSaleResultBucket> buckets;
@VisibleForTesting
AvailableForSaleResultBuilder(final List<AvailableForSaleResultBucket> buckets)
{
this.buckets = new ArrayList<>(buckets);
}
|
public AvailableForSalesLookupResult build()
{
final ImmutableList<AvailableForSalesLookupBucketResult> groups = buckets.stream()
.flatMap(AvailableForSaleResultBucket::buildAndStreamGroups)
.collect(ImmutableList.toImmutableList());
return AvailableForSalesLookupResult.builder().availableForSalesResults(groups).build();
}
public void addQtyToAllMatchingGroups(@NonNull final AddToResultGroupRequest request)
{
// note that we might select more quantities than we actually wanted (bc of the way we match attributes in the query using LIKE)
// for that reason, we need to be lenient in case not all quantities can be added to a bucked
buckets.forEach(bucket -> bucket.addQtyToAllMatchingGroups(request));
}
@VisibleForTesting
ImmutableList<AvailableForSaleResultBucket> getBuckets()
{
return ImmutableList.copyOf(buckets);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\availableforsales\AvailableForSaleResultBuilder.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("count", currenciesById.size())
.toString();
}
@NonNull
public Currency getById(@NonNull final CurrencyId id)
{
final Currency currency = currenciesById.get(id);
if (currency == null)
{
throw new AdempiereException("@NotFound@ @C_Currency_ID@: " + id);
}
return currency;
}
|
public Currency getByCurrencyCode(@NonNull final CurrencyCode currencyCode)
{
final Currency currency = currenciesByCode.get(currencyCode);
if (currency == null)
{
throw new AdempiereException("@NotFound@ @ISO_Code@: " + currencyCode);
}
return currency;
}
public Optional<Currency> getByCurrencyCodeIfExists(@NonNull final CurrencyCode currencyCode)
{
return Optional.ofNullable(currenciesByCode.get(currencyCode));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\impl\CurrenciesMap.java
| 1
|
请完成以下Java代码
|
public String getTenantId() {
return tenantId;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", eventName=" + eventName
+ ", name=" + name
+ ", createTime=" + createTime
+ ", lastUpdated=" + lastUpdated
+ ", executionId=" + executionId
+ ", processDefinitionId=" + processDefinitionId
+ ", processInstanceId=" + processInstanceId
|
+ ", taskDefinitionKey=" + taskDefinitionKey
+ ", assignee=" + assignee
+ ", owner=" + owner
+ ", description=" + description
+ ", dueDate=" + dueDate
+ ", followUpDate=" + followUpDate
+ ", priority=" + priority
+ ", deleteReason=" + deleteReason
+ ", caseDefinitionId=" + caseDefinitionId
+ ", caseExecutionId=" + caseExecutionId
+ ", caseInstanceId=" + caseInstanceId
+ ", tenantId=" + tenantId
+ "]";
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\event\TaskEvent.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MobileUIPickingUserProfileService
{
@NonNull private final MobileUIPickingUserProfileRepository profileRepository;
@NonNull private final PickingConfigRepositoryV2 pickingConfigRepositoryV2;
@NonNull
public static MobileUIPickingUserProfileService newInstanceForUnitTesting()
{
Adempiere.assertUnitTestMode();
return new MobileUIPickingUserProfileService(new MobileUIPickingUserProfileRepository(), new PickingConfigRepositoryV2());
}
@NonNull
public MobileUIPickingUserProfile getProfile()
{
return profileRepository.getProfile();
}
@NonNull
public PickingJobOptions getPickingJobOptions(@Nullable final BPartnerId customerId)
{
|
return profileRepository.getPickingJobOptions(customerId);
}
@NonNull
public PickingJobAggregationType getAggregationType(@Nullable final BPartnerId customerId)
{
return profileRepository.getAggregationType(customerId);
}
public boolean isConsiderAttributes()
{
return pickingConfigRepositoryV2.getPickingConfig().isConsiderAttributes();
}
public void update(@NonNull UnaryOperator<MobileUIPickingUserProfile> updater)
{
profileRepository.update(updater);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\config\mobileui\MobileUIPickingUserProfileService.java
| 2
|
请完成以下Java代码
|
public List<HistoricEntityLink> getHistoricEntityLinkParentsForProcessInstance(String processInstanceId) {
return commandExecutor.execute(new GetHistoricEntityLinkParentsForProcessInstanceCmd(processInstanceId));
}
@Override
public List<HistoricEntityLink> getHistoricEntityLinkParentsForTask(String taskId) {
return commandExecutor.execute(new GetHistoricEntityLinkParentsForTaskCmd(taskId));
}
@Override
public ProcessInstanceHistoryLogQuery createProcessInstanceHistoryLogQuery(String processInstanceId) {
return new ProcessInstanceHistoryLogQueryImpl(commandExecutor, processInstanceId, configuration);
}
@Override
public void deleteHistoricTaskLogEntry(long logNumber) {
commandExecutor.execute(new DeleteHistoricTaskLogEntryByLogNumberCmd(logNumber));
}
@Override
public HistoricTaskLogEntryBuilder createHistoricTaskLogEntryBuilder(TaskInfo task) {
return new HistoricTaskLogEntryBuilderImpl(commandExecutor, task, configuration.getTaskServiceConfiguration());
}
@Override
|
public HistoricTaskLogEntryBuilder createHistoricTaskLogEntryBuilder() {
return new HistoricTaskLogEntryBuilderImpl(commandExecutor, configuration.getTaskServiceConfiguration());
}
@Override
public HistoricTaskLogEntryQuery createHistoricTaskLogEntryQuery() {
return new HistoricTaskLogEntryQueryImpl(commandExecutor, configuration.getTaskServiceConfiguration());
}
@Override
public NativeHistoricTaskLogEntryQuery createNativeHistoricTaskLogEntryQuery() {
return new NativeHistoricTaskLogEntryQueryImpl(commandExecutor, configuration.getTaskServiceConfiguration());
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\HistoryServiceImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Set<PPOrderAndCostCollectorId> retainExistingPPCostCollectorIds(
@NonNull final ProjectId projectId,
@NonNull final Set<PPOrderAndCostCollectorId> orderAndCostCollectorIds)
{
if (orderAndCostCollectorIds.isEmpty())
{
return ImmutableSet.of();
}
final Set<PPCostCollectorId> costCollectorIds = orderAndCostCollectorIds.stream().map(PPOrderAndCostCollectorId::getCostCollectorId).collect(Collectors.toSet());
return queryBL.createQueryBuilder(I_C_Project_Repair_CostCollector.class)
.addInArrayFilter(I_C_Project_Repair_CostCollector.COLUMNNAME_C_Project_ID, projectId)
.addInArrayFilter(I_C_Project_Repair_CostCollector.COLUMNNAME_From_Repair_Cost_Collector_ID, costCollectorIds)
.create()
.stream()
.map(record -> PPOrderAndCostCollectorId.ofRepoId(record.getFrom_Rapair_Order_ID(), record.getFrom_Repair_Cost_Collector_ID()))
.collect(ImmutableSet.toImmutableSet());
}
public boolean matchesByTaskAndProduct(
@NonNull final ServiceRepairProjectTaskId taskId,
@NonNull final ProductId productId)
{
return queryBL.createQueryBuilder(I_C_Project_Repair_CostCollector.class)
.addInArrayFilter(I_C_Project_Repair_CostCollector.COLUMNNAME_C_Project_ID, taskId.getProjectId())
.addInArrayFilter(I_C_Project_Repair_CostCollector.COLUMNNAME_C_Project_Repair_Task_ID, taskId)
|
.addInArrayFilter(I_C_Project_Repair_CostCollector.COLUMNNAME_M_Product_ID, productId)
.create()
.anyMatch();
}
public void deleteByIds(@NonNull final Collection<ServiceRepairProjectCostCollectorId> ids)
{
if (ids.isEmpty())
{
return;
}
queryBL.createQueryBuilder(I_C_Project_Repair_CostCollector.class)
.addInArrayFilter(I_C_Project_Repair_CostCollector.COLUMNNAME_C_Project_Repair_CostCollector_ID, ids)
.create()
.delete();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\repository\ServiceRepairProjectCostCollectorRepository.java
| 2
|
请完成以下Java代码
|
static EnvironmentPostProcessorsFactory fromSpringFactories(@Nullable ClassLoader classLoader) {
return new SpringFactoriesEnvironmentPostProcessorsFactory(
SpringFactoriesLoader.forDefaultResourceLocation(classLoader));
}
/**
* Return a {@link EnvironmentPostProcessorsFactory} that reflectively creates post
* processors from the given classes.
* @param classes the post processor classes
* @return an {@link EnvironmentPostProcessorsFactory} instance
*/
static EnvironmentPostProcessorsFactory of(Class<?>... classes) {
return new ReflectionEnvironmentPostProcessorsFactory(classes);
}
/**
* Return a {@link EnvironmentPostProcessorsFactory} that reflectively creates post
* processors from the given class names.
* @param classNames the post processor class names
* @return an {@link EnvironmentPostProcessorsFactory} instance
*/
static EnvironmentPostProcessorsFactory of(String... classNames) {
|
return of(null, classNames);
}
/**
* Return a {@link EnvironmentPostProcessorsFactory} that reflectively creates post
* processors from the given class names.
* @param classLoader the source class loader
* @param classNames the post processor class names
* @return an {@link EnvironmentPostProcessorsFactory} instance
*/
static EnvironmentPostProcessorsFactory of(@Nullable ClassLoader classLoader, String... classNames) {
return new ReflectionEnvironmentPostProcessorsFactory(classLoader, classNames);
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\support\EnvironmentPostProcessorsFactory.java
| 1
|
请完成以下Java代码
|
public static class KeyValuePair {
private String key;
private Object value;
public KeyValuePair() {
}
public KeyValuePair(String key, Object value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
|
}
public void setKey(String key) {
this.key = key;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
}
|
repos\tutorials-master\jackson-modules\jackson-conversions-3\src\main\java\com\baeldung\jackson\specifictype\dtos\PersonDTO.java
| 1
|
请完成以下Java代码
|
public Object fixedAmount(final FixedAmountCostCalculationMethodParams params)
{
record.setCostCalculation_FixedAmount(params.getFixedAmount().toBigDecimal());
return null;
}
@Override
public Object percentageOfAmount(final PercentageCostCalculationMethodParams params)
{
record.setCostCalculation_Percentage(params.getPercentage().toBigDecimal());
return null;
}
});
record.setCostDistributionMethod(from.getDistributionMethod().getCode());
record.setC_Currency_ID(from.getCostAmount().getCurrencyId().getRepoId());
record.setCostAmount(from.getCostAmount().toBigDecimal());
record.setCreated_OrderLine_ID(OrderLineId.toRepoId(from.getCreatedOrderLineId()));
}
private static void updateRecord(final I_C_Order_Cost_Detail record, final OrderCostDetail from)
{
record.setIsActive(true);
updateRecord(record, from.getOrderLineInfo());
record.setCostAmount(from.getCostAmount().toBigDecimal());
record.setQtyReceived(from.getInoutQty().toBigDecimal());
record.setCostAmountReceived(from.getInoutCostAmount().toBigDecimal());
}
private static void updateRecord(final I_C_Order_Cost_Detail record, final OrderCostDetailOrderLinePart from)
{
record.setC_OrderLine_ID(from.getOrderLineId().getRepoId());
record.setM_Product_ID(from.getProductId().getRepoId());
record.setC_UOM_ID(from.getUomId().getRepoId());
|
record.setQtyOrdered(from.getQtyOrdered().toBigDecimal());
record.setC_Currency_ID(from.getCurrencyId().getRepoId());
record.setLineNetAmt(from.getOrderLineNetAmt().toBigDecimal());
}
public void changeByOrderLineId(
@NonNull final OrderLineId orderLineId,
@NonNull Consumer<OrderCost> consumer)
{
final List<OrderCost> orderCosts = getByOrderLineIds(ImmutableSet.of(orderLineId));
orderCosts.forEach(orderCost -> {
consumer.accept(orderCost);
saveUsingCache(orderCost);
});
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\OrderCostRepositorySession.java
| 1
|
请完成以下Java代码
|
public String getTopic() {
return topic;
}
public String getMessage() {
return message;
}
public boolean isRetain() {
return retain;
}
public MqttQoS getQos() {
return qos;
}
public static MqttLastWill.Builder builder(){
return new MqttLastWill.Builder();
}
public static final class Builder {
private String topic;
private String message;
private boolean retain;
private MqttQoS qos;
public String getTopic() {
return topic;
}
public Builder setTopic(String topic) {
if(topic == null){
throw new NullPointerException("topic");
}
this.topic = topic;
return this;
}
public String getMessage() {
return message;
}
public Builder setMessage(String message) {
if(message == null){
throw new NullPointerException("message");
}
this.message = message;
return this;
}
public boolean isRetain() {
return retain;
}
public Builder setRetain(boolean retain) {
this.retain = retain;
return this;
}
public MqttQoS getQos() {
return qos;
}
public Builder setQos(MqttQoS qos) {
if(qos == null){
throw new NullPointerException("qos");
}
this.qos = qos;
return this;
}
public MqttLastWill build(){
|
return new MqttLastWill(topic, message, retain, qos);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MqttLastWill that = (MqttLastWill) o;
if (retain != that.retain) return false;
if (!topic.equals(that.topic)) return false;
if (!message.equals(that.message)) return false;
return qos == that.qos;
}
@Override
public int hashCode() {
int result = topic.hashCode();
result = 31 * result + message.hashCode();
result = 31 * result + (retain ? 1 : 0);
result = 31 * result + qos.hashCode();
return result;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("MqttLastWill{");
sb.append("topic='").append(topic).append('\'');
sb.append(", message='").append(message).append('\'');
sb.append(", retain=").append(retain);
sb.append(", qos=").append(qos.name());
sb.append('}');
return sb.toString();
}
}
|
repos\thingsboard-master\netty-mqtt\src\main\java\org\thingsboard\mqtt\MqttLastWill.java
| 1
|
请完成以下Java代码
|
public FinancialInstrumentQuantityChoice getQty() {
return qty;
}
/**
* Sets the value of the qty property.
*
* @param value
* allowed object is
* {@link FinancialInstrumentQuantityChoice }
*
*/
public void setQty(FinancialInstrumentQuantityChoice value) {
this.qty = value;
}
/**
* Gets the value of the orgnlAndCurFaceAmt property.
*
* @return
* possible object is
* {@link OriginalAndCurrentQuantities1 }
*
*/
public OriginalAndCurrentQuantities1 getOrgnlAndCurFaceAmt() {
return orgnlAndCurFaceAmt;
}
/**
* Sets the value of the orgnlAndCurFaceAmt property.
*
* @param value
* allowed object is
* {@link OriginalAndCurrentQuantities1 }
*
*/
|
public void setOrgnlAndCurFaceAmt(OriginalAndCurrentQuantities1 value) {
this.orgnlAndCurFaceAmt = value;
}
/**
* Gets the value of the prtry property.
*
* @return
* possible object is
* {@link ProprietaryQuantity1 }
*
*/
public ProprietaryQuantity1 getPrtry() {
return prtry;
}
/**
* Sets the value of the prtry property.
*
* @param value
* allowed object is
* {@link ProprietaryQuantity1 }
*
*/
public void setPrtry(ProprietaryQuantity1 value) {
this.prtry = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\TransactionQuantities2Choice.java
| 1
|
请完成以下Java代码
|
public Object generateSeedValue(final IAttributeSet attributeSet, final I_M_Attribute attribute, final Object valueInitialDefault)
{
// we don't support a value different from null
Check.assumeNull(valueInitialDefault, "valueInitialDefault null");
return BigDecimal.ZERO;
}
@Override
public String getAttributeValueType()
{
return X_M_Attribute.ATTRIBUTEVALUETYPE_Number;
}
@Override
public boolean canGenerateValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute)
{
return true;
}
@Override
|
public BigDecimal generateNumericValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute)
{
return BigDecimal.ZERO;
}
@Override
protected boolean isExecuteCallout(final IAttributeValueContext attributeValueContext,
final IAttributeSet attributeSet,
final I_M_Attribute attribute,
final Object valueOld,
final Object valueNew)
{
return !Objects.equals(valueOld, valueNew);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\WeightTareAdjustAttributeValueCallout.java
| 1
|
请完成以下Java代码
|
public void setIsUseBPartnerAddress (boolean IsUseBPartnerAddress)
{
set_Value (COLUMNNAME_IsUseBPartnerAddress, Boolean.valueOf(IsUseBPartnerAddress));
}
/** Get Benutze abw. Adresse.
@return Benutze abw. Adresse */
@Override
public boolean isUseBPartnerAddress ()
{
Object oo = get_Value(COLUMNNAME_IsUseBPartnerAddress);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Massenaustritt.
@param IsWriteOff Massenaustritt */
@Override
public void setIsWriteOff (boolean IsWriteOff)
{
throw new IllegalArgumentException ("IsWriteOff is virtual column"); }
/** Get Massenaustritt.
@return Massenaustritt */
@Override
public boolean isWriteOff ()
{
Object oo = get_Value(COLUMNNAME_IsWriteOff);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** 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 Process Now.
@param Processing Process Now */
@Override
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
@Override
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java-gen\de\metas\dunning\model\X_C_DunningDoc.java
| 1
|
请完成以下Java代码
|
protected void applySortBy(HistoricTaskInstanceQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_TASK_ID)) {
query.orderByTaskId();
} else if (sortBy.equals(SORT_BY_ACT_INSTANCE_ID)) {
query.orderByHistoricActivityInstanceId();
} else if (sortBy.equals(SORT_BY_PROC_DEF_ID)) {
query.orderByProcessDefinitionId();
} else if (sortBy.equals(SORT_BY_PROC_INST_ID)) {
query.orderByProcessInstanceId();
} else if (sortBy.equals(SORT_BY_EXEC_ID)) {
query.orderByExecutionId();
} else if (sortBy.equals(SORT_BY_TASK_DURATION)) {
query.orderByHistoricTaskInstanceDuration();
} else if (sortBy.equals(SORT_BY_END_TIME)) {
query.orderByHistoricTaskInstanceEndTime();
} else if (sortBy.equals(SORT_BY_START_TIME)) {
query.orderByHistoricActivityInstanceStartTime();
} else if (sortBy.equals(SORT_BY_TASK_NAME)) {
query.orderByTaskName();
} else if (sortBy.equals(SORT_BY_TASK_DESC)) {
query.orderByTaskDescription();
} else if (sortBy.equals(SORT_BY_ASSIGNEE)) {
query.orderByTaskAssignee();
} else if (sortBy.equals(SORT_BY_OWNER)) {
query.orderByTaskOwner();
} else if (sortBy.equals(SORT_BY_DUE_DATE)) {
query.orderByTaskDueDate();
} else if (sortBy.equals(SORT_BY_FOLLOW_UP_DATE)) {
query.orderByTaskFollowUpDate();
} else if (sortBy.equals(SORT_BY_DELETE_REASON)) {
query.orderByDeleteReason();
} else if (sortBy.equals(SORT_BY_TASK_DEF_KEY)) {
query.orderByTaskDefinitionKey();
|
} else if (sortBy.equals(SORT_BY_PRIORITY)) {
query.orderByTaskPriority();
} else if (sortBy.equals(SORT_BY_CASE_DEF_ID)) {
query.orderByCaseDefinitionId();
} else if (sortBy.equals(SORT_BY_CASE_INST_ID)) {
query.orderByCaseInstanceId();
} else if (sortBy.equals(SORT_BY_CASE_EXEC_ID)) {
query.orderByCaseExecutionId();
} else if (sortBy.equals(SORT_BY_TENANT_ID)) {
query.orderByTenantId();
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricTaskInstanceQueryDto.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SalesRegionRepository
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final CCache<Integer, SalesRegionsMap> cache = CCache.<Integer, SalesRegionsMap>builder()
.tableName(I_C_SalesRegion.Table_Name)
.build();
public SalesRegion getById(final SalesRegionId salesRegionId)
{
return getMap().getById(salesRegionId);
}
private SalesRegionsMap getMap() {return cache.getOrLoad(0, this::retrieveMap);}
private SalesRegionsMap retrieveMap()
{
final ImmutableList<SalesRegion> list = queryBL.createQueryBuilder(I_C_SalesRegion.class)
.create()
.stream()
.map(SalesRegionRepository::fromRecord)
.collect(ImmutableList.toImmutableList());
return new SalesRegionsMap(list);
}
private static SalesRegion fromRecord(final I_C_SalesRegion record)
{
return SalesRegion.builder()
.id(SalesRegionId.ofRepoId(record.getC_SalesRegion_ID()))
.value(record.getValue())
.name(record.getName())
.isActive(record.isActive())
.salesRepId(UserId.ofRepoIdOrNullIfSystem(record.getSalesRep_ID()))
.build();
}
public Optional<SalesRegion> getBySalesRepId(@NonNull final UserId salesRepId)
|
{
return getMap().stream()
.filter(salesRegion -> salesRegion.isActive()
&& UserId.equals(salesRegion.getSalesRepId(), salesRepId))
.max(Comparator.comparing(SalesRegion::getId));
}
//
//
//
private static class SalesRegionsMap
{
private final ImmutableMap<SalesRegionId, SalesRegion> byId;
public SalesRegionsMap(final List<SalesRegion> list)
{
this.byId = Maps.uniqueIndex(list, SalesRegion::getId);
}
public SalesRegion getById(final SalesRegionId salesRegionId)
{
final SalesRegion salesRegion = byId.get(salesRegionId);
if (salesRegion == null)
{
throw new AdempiereException("No sales region found for " + salesRegionId);
}
return salesRegion;
}
public Stream<SalesRegion> stream() {return byId.values().stream();}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\sales_region\SalesRegionRepository.java
| 2
|
请完成以下Java代码
|
public final class VATIdentifier
{
@NonNull private final String value;
private VATIdentifier(@NonNull final String value)
{
final String valueNorm = StringUtils.trimBlankToNull(value);
if (valueNorm == null)
{
throw new AdempiereException("Invalid VAT ID");
}
this.value = valueNorm;
}
@NonNull
public static VATIdentifier of(@NonNull final String value)
{
return new VATIdentifier(value);
}
@Nullable
public static VATIdentifier ofNullable(@Nullable final String value)
{
final String valueNorm = StringUtils.trimBlankToNull(value);
|
return valueNorm != null ? of(valueNorm) : null;
}
@Override
@Deprecated
public String toString() {return getAsString();}
@NonNull
public String getAsString() {return value;}
@Nullable
public static String toString(@Nullable final VATIdentifier vatId)
{
return vatId != null ? vatId.getAsString() : null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\tax\api\VATIdentifier.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
try {
Object obj = ctx.getBean(targetObject);
Method m = null;
try {
m = obj.getClass().getMethod(targetMethod);
//调用被代理对象的方法
m.invoke(obj);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
} catch (Exception e) {
throw new JobExecutionException(e);
|
}
}
public void setApplicationContext(ApplicationContext applicationContext) {
this.ctx = applicationContext;
}
public void setTargetObject(String targetObject) {
this.targetObject = targetObject;
}
public void setTargetMethod(String targetMethod) {
this.targetMethod = targetMethod;
}
}
|
repos\springBoot-master\springboot-Quartz\src\main\java\com\abel\quartz\config\InvokingJobDetailFactory.java
| 2
|
请完成以下Java代码
|
public int getC_OLCand_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OLCand_ID);
}
/**
* DocStatus AD_Reference_ID=131
* Reference name: _Document Status
*/
public static final int DOCSTATUS_AD_Reference_ID=131;
/** Drafted = DR */
public static final String DOCSTATUS_Drafted = "DR";
/** Completed = CO */
public static final String DOCSTATUS_Completed = "CO";
/** Approved = AP */
public static final String DOCSTATUS_Approved = "AP";
/** NotApproved = NA */
public static final String DOCSTATUS_NotApproved = "NA";
/** Voided = VO */
public static final String DOCSTATUS_Voided = "VO";
/** Invalid = IN */
public static final String DOCSTATUS_Invalid = "IN";
|
/** Reversed = RE */
public static final String DOCSTATUS_Reversed = "RE";
/** Closed = CL */
public static final String DOCSTATUS_Closed = "CL";
/** Unknown = ?? */
public static final String DOCSTATUS_Unknown = "??";
/** InProgress = IP */
public static final String DOCSTATUS_InProgress = "IP";
/** WaitingPayment = WP */
public static final String DOCSTATUS_WaitingPayment = "WP";
/** WaitingConfirmation = WC */
public static final String DOCSTATUS_WaitingConfirmation = "WC";
@Override
public void setDocStatus (final @Nullable java.lang.String DocStatus)
{
throw new IllegalArgumentException ("DocStatus is virtual column"); }
@Override
public java.lang.String getDocStatus()
{
return get_ValueAsString(COLUMNNAME_DocStatus);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Contract_Term_Alloc.java
| 1
|
请完成以下Java代码
|
public abstract class ComputerBuilder {
protected Map<String, String> computerParts = new HashMap<>();
protected List<String> motherboardSetupStatus = new ArrayList<>();
public final Computer buildComputer() {
addMotherboard();
setupMotherboard();
addProcessor();
return getComputer();
}
public abstract void addMotherboard();
public abstract void setupMotherboard();
|
public abstract void addProcessor();
public List<String> getMotherboardSetupStatus() {
return motherboardSetupStatus;
}
public Map<String, String> getComputerParts() {
return computerParts;
}
private Computer getComputer() {
return new Computer(computerParts);
}
}
|
repos\tutorials-master\patterns-modules\design-patterns-behavioral-2\src\main\java\com\baeldung\templatemethod\model\ComputerBuilder.java
| 1
|
请完成以下Java代码
|
public class SpringTransactionInterceptor extends AbstractCommandInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(SpringTransactionInterceptor.class);
protected PlatformTransactionManager transactionManager;
public SpringTransactionInterceptor(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
@Override
public <T> T execute(final CommandConfig config, final Command<T> command, CommandExecutor commandExecutor) {
LOGGER.debug("Running command with propagation {}", config.getTransactionPropagation());
// If the transaction is required (the other two options always need to go through the transactionTemplate),
// the transactionTemplate is not used when the transaction is already active.
// The reason for this is that the transactionTemplate try-catches exceptions and marks it as rollback.
// Which will break nested service calls that go through the same stack of interceptors.
int transactionPropagation = getPropagation(config);
if (transactionPropagation == TransactionTemplate.PROPAGATION_REQUIRED && TransactionSynchronizationManager.isActualTransactionActive()) {
return next.execute(config, command, commandExecutor);
|
} else {
TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
transactionTemplate.setPropagationBehavior(transactionPropagation);
return transactionTemplate.execute(status -> next.execute(config, command, commandExecutor));
}
}
private int getPropagation(CommandConfig config) {
switch (config.getTransactionPropagation()) {
case NOT_SUPPORTED:
return TransactionTemplate.PROPAGATION_NOT_SUPPORTED;
case REQUIRED:
return TransactionTemplate.PROPAGATION_REQUIRED;
case REQUIRES_NEW:
return TransactionTemplate.PROPAGATION_REQUIRES_NEW;
default:
throw new FlowableIllegalArgumentException("Unsupported transaction propagation: " + config.getTransactionPropagation());
}
}
}
|
repos\flowable-engine-main\modules\flowable-spring-common\src\main\java\org\flowable\common\spring\SpringTransactionInterceptor.java
| 1
|
请完成以下Java代码
|
public I_M_HU_PI_Item_Product getDefaultForProduct(@NonNull final ProductId productId, @NonNull final ZonedDateTime dateTime)
{
return huPIItemProductDAO.retrieveDefaultForProduct(productId, dateTime);
}
@NonNull
public I_M_HU_PI_Item_Product extractHUPIItemProduct(final I_C_Order order, final I_C_OrderLine orderLine)
{
final HUPIItemProductId hupiItemProductId = HUPIItemProductId.ofRepoIdOrNull(orderLine.getM_HU_PI_Item_Product_ID());
if (hupiItemProductId != null)
{
return huPIItemProductDAO.getRecordById(hupiItemProductId);
}
else
{
final ProductId productId = ProductId.ofRepoId(orderLine.getM_Product_ID());
final BPartnerId buyerBPartnerId = BPartnerId.ofRepoId(order.getC_BPartner_ID());
final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(order.getAD_Org_ID()));
return huPIItemProductDAO.retrieveMaterialItemProduct(
productId,
buyerBPartnerId,
TimeUtil.asZonedDateTime(order.getDateOrdered(), timeZone),
X_M_HU_PI_Version.HU_UNITTYPE_TransportUnit, true/* allowInfiniteCapacity */);
|
}
}
@Override
public int getRequiredLUCount(final @NonNull Quantity qty, final I_M_HU_LUTU_Configuration lutuConfigurationInStockUOM)
{
if (lutuConfigurationInStockUOM.isInfiniteQtyTU() || lutuConfigurationInStockUOM.isInfiniteQtyCU())
{
return 1;
}
else
{
// Note need to use the StockQty because lutuConfigurationInStockUOM is also in stock-UOM.
// And in the case of catchweight, it's very important to *not* make metasfresh convert quantites using the UOM-conversion
return lutuConfigurationFactory.calculateQtyLUForTotalQtyCUs(
lutuConfigurationInStockUOM,
qty);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUPIItemProductBL.java
| 1
|
请完成以下Java代码
|
public WebuiImageId uploadImage(@RequestParam("file") final MultipartFile file) throws IOException
{
userSession.assertLoggedIn();
return imageService.uploadImage(file);
}
@GetMapping("/{imageId}")
@ResponseBody
public ResponseEntity<byte[]> getImage(
@PathVariable("imageId") final int imageIdInt,
@RequestParam(name = "maxWidth", required = false, defaultValue = "-1") final int maxWidth,
@RequestParam(name = "maxHeight", required = false, defaultValue = "-1") final int maxHeight,
final WebRequest request)
{
userSession.assertLoggedIn();
final WebuiImageId imageId = WebuiImageId.ofRepoIdOrNull(imageIdInt);
return ETagResponseEntityBuilder.ofETagAware(request, getWebuiImage(imageId, maxWidth, maxHeight))
.includeLanguageInETag()
.cacheMaxAge(userSession.getHttpCacheMaxAge())
.jsonOptions(this::newJSONOptions)
.toResponseEntity((responseBuilder, webuiImage) -> webuiImage.toResponseEntity(responseBuilder));
}
|
private WebuiImage getWebuiImage(final WebuiImageId imageId, final int maxWidth, final int maxHeight)
{
final WebuiImage image = imageService.getWebuiImage(imageId, maxWidth, maxHeight);
assertUserHasAccess(image);
return image;
}
private void assertUserHasAccess(final WebuiImage image)
{
final BooleanWithReason hasAccess = userSession.getUserRolePermissions().checkCanView(image.getAdClientId(), image.getAdOrgId(), I_AD_Image.Table_ID, image.getAdImageId().getRepoId());
if (hasAccess.isFalse())
{
throw new EntityNotFoundException(hasAccess.getReason());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\upload\ImageRestController.java
| 1
|
请完成以下Java代码
|
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application;
}
@Profile("insecure")
@Configuration(proxyBeanMethods = false)
public static class SecurityPermitAllConfig {
private final AdminServerProperties adminServer;
public SecurityPermitAllConfig(AdminServerProperties adminServer) {
this.adminServer = adminServer;
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((authorizeRequests) -> authorizeRequests.anyRequest().permitAll())
.csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers(
PathPatternRequestMatcher.withDefaults().matcher(POST, this.adminServer.path("/instances")),
PathPatternRequestMatcher.withDefaults()
.matcher(DELETE, this.adminServer.path("/instances/*")),
PathPatternRequestMatcher.withDefaults().matcher(this.adminServer.path("/actuator/**"))));
return http.build();
}
}
@Profile("secure")
@Configuration(proxyBeanMethods = false)
public static class SecuritySecureConfig {
private final AdminServerProperties adminServer;
public SecuritySecureConfig(AdminServerProperties adminServer) {
this.adminServer = adminServer;
}
@Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(this.adminServer.path("/"));
|
http.authorizeHttpRequests((authorizeRequests) -> authorizeRequests
.requestMatchers(PathPatternRequestMatcher.withDefaults().matcher(this.adminServer.path("/assets/**")))
.permitAll()
.requestMatchers(PathPatternRequestMatcher.withDefaults().matcher(this.adminServer.path("/login")))
.permitAll()
.anyRequest()
.authenticated())
.formLogin((formLogin) -> formLogin.loginPage(this.adminServer.path("/login"))
.successHandler(successHandler))
.logout((logout) -> logout.logoutUrl(this.adminServer.path("/logout")))
.httpBasic(Customizer.withDefaults())
.csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers(
PathPatternRequestMatcher.withDefaults().matcher(POST, this.adminServer.path("/instances")),
PathPatternRequestMatcher.withDefaults()
.matcher(DELETE, this.adminServer.path("/instances/*")),
PathPatternRequestMatcher.withDefaults().matcher(this.adminServer.path("/actuator/**"))));
return http.build();
}
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-war\src\main\java\de\codecentric\boot\admin\sample\SpringBootAdminWarApplication.java
| 1
|
请完成以下Java代码
|
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (getClass() != obj.getClass()) {
|
return false;
}
return id != null && id.equals(((Book) obj).id);
}
@Override
public int hashCode() {
return 2021;
}
@Override
public String toString() {
return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}';
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootAudit\src\main\java\com\bookstore\entity\Book.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void updateUser(User user) {
logger.info("更新用户start...");
userMapper.updateById(user);
int userId = user.getId();
// 缓存存在,删除缓存
String key = "user_" + userId;
boolean hasKey = redisTemplate.hasKey(key);
if (hasKey) {
redisTemplate.delete(key);
logger.info("更新用户时候,从缓存中删除用户 >> " + userId);
}
}
/**
* 删除用户
|
* 如果缓存中存在,删除
*/
public void deleteById(int id) {
logger.info("删除用户start...");
userMapper.deleteById(id);
// 缓存存在,删除缓存
String key = "user_" + id;
boolean hasKey = redisTemplate.hasKey(key);
if (hasKey) {
redisTemplate.delete(key);
logger.info("更新用户时候,从缓存中删除用户 >> " + id);
}
}
}
|
repos\SpringBootBucket-master\springboot-redis\src\main\java\com\xncoding\pos\service\UserService.java
| 2
|
请完成以下Java代码
|
class PetOwner {
@Id Long Id;
String name;
List<Dog> dogs;
List<Cat> cats;
List<Fish> fish;
public PetOwner(String name, List<Cat> cats, List<Dog> dogs, List<Fish> fish) {
this.name = name;
this.cats = cats;
this.dogs = dogs;
this.fish = fish;
}
|
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
PetOwner petOwner = (PetOwner) o;
return Objects.equals(Id, petOwner.Id) && Objects.equals(name, petOwner.name) && Objects.equals(dogs, petOwner.dogs)
&& Objects.equals(cats, petOwner.cats) && Objects.equals(fish, petOwner.fish);
}
@Override
public int hashCode() {
return Objects.hash(Id, name, dogs, cats, fish);
}
}
|
repos\spring-data-examples-main\jdbc\singlequeryloading\src\main\java\example\springdata\jdbc\singlequeryloading\PetOwner.java
| 1
|
请完成以下Java代码
|
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setPOReference (final @Nullable java.lang.String POReference)
{
set_Value (COLUMNNAME_POReference, POReference);
}
@Override
public java.lang.String getPOReference()
{
return get_ValueAsString(COLUMNNAME_POReference);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
|
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setQM_Analysis_Report_ID (final int QM_Analysis_Report_ID)
{
if (QM_Analysis_Report_ID < 1)
set_ValueNoCheck (COLUMNNAME_QM_Analysis_Report_ID, null);
else
set_ValueNoCheck (COLUMNNAME_QM_Analysis_Report_ID, QM_Analysis_Report_ID);
}
@Override
public int getQM_Analysis_Report_ID()
{
return get_ValueAsInt(COLUMNNAME_QM_Analysis_Report_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_QM_Analysis_Report.java
| 1
|
请完成以下Java代码
|
public Incoterms getDefaultIncoterms(final @NotNull OrgId orgId)
{
return getIncotermsMap().getDefaultByOrgId(orgId);
}
@NotNull
public Incoterms getById(@NotNull final IncotermsId id)
{
return getIncotermsMap().getById(id);
}
@NotNull
public Incoterms getByValue(@NotNull final String value, @NotNull final OrgId orgId)
{
return getIncotermsMap().getByValue(value, orgId);
}
@NonNull
private IncotermsMap getIncotermsMap()
{
return cache.getOrLoadNonNull(0, this::retrieveIncotermsMap);
}
@NotNull
private IncotermsMap retrieveIncotermsMap()
{
final ImmutableList<Incoterms> incoterms = queryBL.createQueryBuilder(I_C_Incoterms.class)
.addOnlyActiveRecordsFilter()
.create()
.stream()
.map(IncotermsRepository::ofRecord)
.collect(ImmutableList.toImmutableList());
return new IncotermsRepository.IncotermsMap(incoterms);
}
private static Incoterms ofRecord(@NotNull final I_C_Incoterms record)
{
return Incoterms.builder()
.id(IncotermsId.ofRepoId(record.getC_Incoterms_ID()))
.name(record.getName())
.value(record.getValue())
.isDefault(record.isDefault())
.defaultLocation(record.getDefaultLocation())
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.build();
}
private static final class IncotermsMap
|
{
private final ImmutableMap<IncotermsId, Incoterms> byId;
private final ImmutableMap<OrgId, Incoterms> defaultByOrgId;
private final ImmutableMap<ValueAndOrgId, Incoterms> byValueAndOrgId;
IncotermsMap(final List<Incoterms> list)
{
this.byId = Maps.uniqueIndex(list, Incoterms::getId);
this.defaultByOrgId = list.stream().filter(Incoterms::isDefault)
.collect(ImmutableMap.toImmutableMap(Incoterms::getOrgId, incoterms->incoterms));
this.byValueAndOrgId = Maps.uniqueIndex(list, incoterm -> ValueAndOrgId.builder().value(incoterm.getValue()).orgId(incoterm.getOrgId()).build());
}
@NonNull
public Incoterms getById(@NonNull final IncotermsId id)
{
final Incoterms incoterms = byId.get(id);
if (incoterms == null)
{
throw new AdempiereException("Incoterms not found by ID: " + id);
}
return incoterms;
}
@Nullable
public Incoterms getDefaultByOrgId(@NonNull final OrgId orgId)
{
return CoalesceUtil.coalesce(defaultByOrgId.get(orgId), defaultByOrgId.get(OrgId.ANY));
}
@NonNull Incoterms getByValue(@NonNull final String value, @NonNull final OrgId orgId)
{
final Incoterms incoterms = CoalesceUtil.coalesce(byValueAndOrgId.get(ValueAndOrgId.builder().value(value).orgId(orgId).build()),
byValueAndOrgId.get(ValueAndOrgId.builder().value(value).orgId(OrgId.ANY).build()));
if (incoterms == null)
{
throw new AdempiereException("Incoterms not found by value: " + value + " and orgIds: " + orgId + " or " + OrgId.ANY);
}
return incoterms;
}
@Builder
@Value
private static class ValueAndOrgId
{
@NonNull String value;
@NonNull OrgId orgId;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\incoterms\IncotermsRepository.java
| 1
|
请完成以下Java代码
|
public PaymentRow build()
{
return new PaymentRow(this);
}
public Builder setOrgId(final OrgId orgId)
{
this.orgId = orgId;
return this;
}
public Builder setDocTypeName(final String docTypeName)
{
this.docTypeName = docTypeName;
return this;
}
public Builder setC_Payment_ID(final int C_Payment_ID)
{
this.C_Payment_ID = C_Payment_ID;
return this;
}
public Builder setDocumentNo(final String documentNo)
{
this.documentNo = documentNo;
return this;
}
public Builder setBPartnerName(final String bPartnerName)
{
BPartnerName = bPartnerName;
return this;
}
public Builder setPaymentDate(final Date paymentDate)
{
this.paymentDate = paymentDate;
return this;
}
/**
* task 09643: separate transaction date from the accounting date
*
* @param dateAcct
* @return
*/
public Builder setDateAcct(final Date dateAcct)
{
this.dateAcct = dateAcct;
return this;
|
}
public Builder setCurrencyISOCode(@Nullable final CurrencyCode currencyISOCode)
{
this.currencyISOCode = currencyISOCode;
return this;
}
public Builder setPayAmt(final BigDecimal payAmt)
{
this.payAmt = payAmt;
return this;
}
public Builder setPayAmtConv(final BigDecimal payAmtConv)
{
this.payAmtConv = payAmtConv;
return this;
}
public Builder setC_BPartner_ID(final int C_BPartner_ID)
{
this.C_BPartner_ID = C_BPartner_ID;
return this;
}
public Builder setOpenAmtConv(final BigDecimal openAmtConv)
{
this.openAmtConv = openAmtConv;
return this;
}
public Builder setMultiplierAP(final BigDecimal multiplierAP)
{
this.multiplierAP = multiplierAP;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\PaymentRow.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AlipayUtils {
/**
* 生成订单号
* @return String
*/
public String getOrderCode() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
int a = (int)(Math.random() * 9000.0D) + 1000;
System.out.println(a);
Date date = new Date();
String str = sdf.format(date);
String[] split = str.split("-");
String s = split[0] + split[1] + split[2];
String[] split1 = s.split(" ");
String s1 = split1[0] + split1[1];
String[] split2 = s1.split(":");
return split2[0] + split2[1] + split2[2] + a;
}
/**
* 校验签名
* @param request HttpServletRequest
* @param alipay 阿里云配置
* @return boolean
*/
public boolean rsaCheck(HttpServletRequest request, AlipayConfig alipay){
|
// 获取支付宝POST过来反馈信息
Map<String,String> params = new HashMap<>(1);
Map<String, String[]> requestParams = request.getParameterMap();
for (Object o : requestParams.keySet()) {
String name = (String) o;
String[] values = requestParams.get(name);
String valueStr = "";
for (int i = 0; i < values.length; i++) {
valueStr = (i == values.length - 1) ? valueStr + values[i]
: valueStr + values[i] + ",";
}
params.put(name, valueStr);
}
try {
return AlipaySignature.rsaCheckV1(params,
alipay.getPublicKey(),
alipay.getCharset(),
alipay.getSignType());
} catch (AlipayApiException e) {
return false;
}
}
}
|
repos\eladmin-master\eladmin-tools\src\main\java\me\zhengjie\utils\AlipayUtils.java
| 2
|
请完成以下Java代码
|
public String getValue(@NonNull final String attributeValue)
{
switch (attributeValue)
{
case DeliveryMappingConstants.ATTRIBUTE_VALUE_PICKUP_DATE_AND_TIME_START:
return getPickupDateAndTimeStart();
case DeliveryMappingConstants.ATTRIBUTE_VALUE_PICKUP_DATE_AND_TIME_END:
return getPickupDateAndTimeEnd();
case DeliveryMappingConstants.ATTRIBUTE_VALUE_DELIVERY_DATE:
return getDeliveryDate();
case DeliveryMappingConstants.ATTRIBUTE_VALUE_CUSTOMER_REFERENCE:
return getCustomerReference();
case DeliveryMappingConstants.ATTRIBUTE_VALUE_RECEIVER_COUNTRY_CODE:
return getDeliveryAddress().getCountry();
case DeliveryMappingConstants.ATTRIBUTE_VALUE_RECEIVER_CONTACT_LASTNAME_AND_FIRSTNAME:
return getDeliveryContact() != null ? getDeliveryContact().getName() : null;
case DeliveryMappingConstants.ATTRIBUTE_VALUE_RECEIVER_DEPARTMENT:
return getDeliveryAddress().getCompanyDepartment();
case DeliveryMappingConstants.ATTRIBUTE_VALUE_RECEIVER_COMPANY_NAME:
return getDeliveryAddress().getCompanyName1();
case DeliveryMappingConstants.ATTRIBUTE_VALUE_SENDER_COMPANY_NAME:
|
return getPickupAddress().getCompanyName1();
case DeliveryMappingConstants.ATTRIBUTE_VALUE_SENDER_COMPANY_NAME_2:
return getPickupAddress().getCompanyName2();
case DeliveryMappingConstants.ATTRIBUTE_VALUE_SENDER_DEPARTMENT:
return getPickupAddress().getCompanyDepartment();
case DeliveryMappingConstants.ATTRIBUTE_VALUE_SENDER_COUNTRY_CODE:
return getPickupAddress().getCountry();
case DeliveryMappingConstants.ATTRIBUTE_VALUE_SHIPPER_PRODUCT_EXTERNAL_ID:
return getShipperProduct() != null ? getShipperProduct().getCode() : null;
case DeliveryMappingConstants.ATTRIBUTE_VALUE_SHIPPER_EORI:
return getShipperEORI();
default:
throw new IllegalArgumentException("Unknown attributeValue: " + attributeValue);
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-delivery\src\main\java\de\metas\common\delivery\v1\json\request\JsonDeliveryRequest.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_ScannableCode_Format_ID (final int C_ScannableCode_Format_ID)
{
if (C_ScannableCode_Format_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_ScannableCode_Format_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_ScannableCode_Format_ID, C_ScannableCode_Format_ID);
}
@Override
public int getC_ScannableCode_Format_ID()
{
return get_ValueAsInt(COLUMNNAME_C_ScannableCode_Format_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
|
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@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);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ScannableCode_Format.java
| 1
|
请完成以下Java代码
|
public void createIfMissing(@NonNull final InputDataSourceCreateRequest request)
{
final I_AD_InputDataSource inputDataSource = retrieveInputDataSource(
Env.getCtx(),
request.getInternalName(),
false, // throwEx
ITrx.TRXNAME_None);
if (inputDataSource == null)
{
final I_AD_InputDataSource newInputDataSource = InterfaceWrapperHelper.create(Env.getCtx(), I_AD_InputDataSource.class, ITrx.TRXNAME_None);
newInputDataSource.setEntityType(request.getEntityType());
newInputDataSource.setValue(request.getInternalName());
newInputDataSource.setInternalName(request.getInternalName());
newInputDataSource.setIsDestination(request.isDestination());
newInputDataSource.setName(request.getName());
InterfaceWrapperHelper.save(newInputDataSource);
}
}
@Override
public Optional<InputDataSourceId> retrieveInputDataSourceIdBy(@NonNull final InputDataSourceQuery query)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final IQueryBuilder<I_AD_InputDataSource> queryBuilder = queryBL
.createQueryBuilder(I_AD_InputDataSource.class)
.addOnlyActiveRecordsFilter();
Check.assumeNotNull(query.getOrgId(), "Org Id is missing from InputDataSourceQuery ", query);
queryBuilder.addInArrayFilter(I_AD_InputDataSource.COLUMNNAME_AD_Org_ID, query.getOrgId(), OrgId.ANY);
if (Check.isNotBlank(query.getInternalName()))
{
queryBuilder.addEqualsFilter(I_AD_InputDataSource.COLUMNNAME_InternalName, query.getInternalName());
|
}
if (query.getExternalId() != null)
{
queryBuilder.addEqualsFilter(I_AD_InputDataSource.COLUMNNAME_ExternalId, query.getExternalId().getValue());
}
if (!isEmpty(query.getValue(), true))
{
queryBuilder.addEqualsFilter(I_AD_InputDataSource.COLUMNNAME_Value, query.getValue());
}
if (query.getInputDataSourceId() != null)
{
queryBuilder.addEqualsFilter(I_AD_InputDataSource.COLUMNNAME_AD_InputDataSource_ID, query.getInputDataSourceId());
}
try
{
final InputDataSourceId firstId = queryBuilder
.create()
.firstIdOnly(InputDataSourceId::ofRepoIdOrNull);
return Optional.ofNullable(firstId);
}
catch (final DBMoreThanOneRecordsFoundException e)
{
// augment and rethrow
throw e.appendParametersToMessage().setParameter("inputDataSourceQuery", query);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\impex\api\impl\InputDataSourceDAO.java
| 1
|
请完成以下Java代码
|
static Frame read(ConnectionInputStream inputStream) throws IOException {
int firstByte = inputStream.checkedRead();
Assert.state((firstByte & 0x80) != 0, "Fragmented frames are not supported");
int maskAndLength = inputStream.checkedRead();
boolean hasMask = (maskAndLength & 0x80) != 0;
int length = (maskAndLength & 0x7F);
Assert.state(length != 127, "Large frames are not supported");
if (length == 126) {
length = ((inputStream.checkedRead()) << 8 | inputStream.checkedRead());
}
byte[] mask = new byte[4];
if (hasMask) {
inputStream.readFully(mask, 0, mask.length);
}
byte[] payload = new byte[length];
inputStream.readFully(payload, 0, length);
if (hasMask) {
for (int i = 0; i < payload.length; i++) {
payload[i] ^= mask[i % 4];
}
}
return new Frame(Type.forCode(firstByte & 0x0F), payload);
}
/**
* Frame types.
*/
enum Type {
/**
* Continuation frame.
*/
CONTINUATION(0x00),
/**
* Text frame.
*/
TEXT(0x01),
/**
* Binary frame.
*/
BINARY(0x02),
/**
* Close frame.
*/
CLOSE(0x08),
/**
* Ping frame.
*/
PING(0x09),
|
/**
* Pong frame.
*/
PONG(0x0A);
private final int code;
Type(int code) {
this.code = code;
}
static Type forCode(int code) {
for (Type type : values()) {
if (type.code == code) {
return type;
}
}
throw new IllegalStateException("Unknown code " + code);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\livereload\Frame.java
| 1
|
请完成以下Java代码
|
static public MPrintTableFormat get(final Properties ctx, final int AD_PrintTableFormat_ID, final int AD_PrintFont_ID)
{
return get(ctx, AD_PrintTableFormat_ID, MPrintFont.get(AD_PrintFont_ID).getFont());
} // get
/**
* Get Default Table Format.
*
* @param ctx context
* @return Default Table Format (need to set standard font)
*/
static public MPrintTableFormat getDefault(final Properties ctx)
{
MPrintTableFormat tf = null;
String sql = "SELECT * FROM AD_PrintTableFormat "
+ "WHERE AD_Client_ID IN (0,?) AND IsActive='Y' "
+ "ORDER BY IsDefault DESC, AD_Client_ID DESC";
int AD_Client_ID = Env.getAD_Client_ID(ctx);
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, AD_Client_ID);
rs = pstmt.executeQuery();
if (rs.next())
tf = new MPrintTableFormat(ctx, rs, null);
}
catch (Exception e)
{
s_log.error(sql, e);
}
finally
{
DB.close(rs, pstmt);
rs = null;
pstmt = null;
}
return tf;
} // get
/**
* Get the Image
*
* @return image
*/
public Image getImage()
{
if (m_image != null)
{
return m_image;
}
//
if (isImageIsAttached())
{
final AttachmentEntryService attachmentEntryService = Adempiere.getBean(AttachmentEntryService.class);
final List<AttachmentEntry> entries = attachmentEntryService.getByReferencedRecord(TableRecordReference.of(Table_Name, getAD_PrintTableFormat_ID()));
if (entries.isEmpty())
{
log.warn("No Attachment entry - ID=" + get_ID());
return null;
}
final byte[] imageData = attachmentEntryService.retrieveData(entries.get(0).getId());
if (imageData != null)
{
m_image = Toolkit.getDefaultToolkit().createImage(imageData);
}
if (m_image != null)
{
log.debug(entries.get(0).getFilename() + " - Size=" + imageData.length);
}
else
{
log.warn(entries.get(0).getFilename() + " - not loaded (must be gif or jpg) - ID=" + get_ID());
}
}
else if (getImageURL() != null)
|
{
URL url;
try
{
url = new URL(getImageURL());
Toolkit tk = Toolkit.getDefaultToolkit();
m_image = tk.getImage(url);
}
catch (MalformedURLException e)
{
log.warn("Malformed URL - " + getImageURL(), e);
}
}
return m_image;
} // getImage
/**
* Get the Image
*
* @return image
*/
public Image getImageWaterMark()
{
if (m_image_water_mark != null)
{
return m_image_water_mark;
}
//
if (getAD_Image_ID() > 0)
{
m_image_water_mark = MImage.get(getCtx(), getAD_Image_ID()).getImage();
}
return m_image_water_mark;
} // getImage
} // MPrintTableFormat
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\MPrintTableFormat.java
| 1
|
请完成以下Java代码
|
public void setIsShowAllParams (boolean IsShowAllParams)
{
set_Value (COLUMNNAME_IsShowAllParams, Boolean.valueOf(IsShowAllParams));
}
/** Get Display All Parameters.
@return Display All Parameters */
@Override
public boolean isShowAllParams ()
{
Object oo = get_Value(COLUMNNAME_IsShowAllParams);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
|
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserQuery.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ArticleCommentsRestController {
private static final Logger log = LoggerFactory.getLogger(ArticleCommentsRestController.class);
private final KafkaTemplate<String, ArticleCommentAddedEvent> articleCommentsKafkaTemplate;
public ArticleCommentsRestController(
@Qualifier("articleCommentsKafkaTemplate") KafkaTemplate<String, ArticleCommentAddedEvent> articleCommentsKafkaTemplate) {
this.articleCommentsKafkaTemplate = articleCommentsKafkaTemplate;
}
@PostMapping("/articles/{articleSlug}/comments")
Response addArticleComment(
@PathVariable("articleSlug") String articleSlug,
@RequestBody ArticleCommentAddedDto dto
) {
log.info("HTTP Request received to save article comment: " + dto);
// some logic here (eg: save to DB)
|
var event = new ArticleCommentAddedEvent(articleSlug, dto.articleAuthor(), dto.comment(), dto.commentAuthor());
articleCommentsKafkaTemplate.send("baeldung.article-comment.added", articleSlug, event);
return new Response("Success", articleSlug);
}
record Response(String status, String articleSlug) {
}
record ArticleCommentAddedDto(String articleAuthor, String comment, String commentAuthor) {
}
}
|
repos\tutorials-master\spring-kafka-4\src\main\java\com\baeldung\kafka\monitoring\ArticleCommentsRestController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public JwtTokenStore jwtTokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter());
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager)
.tokenStore(jwtTokenStore())
.accessTokenConverter(jwtAccessTokenConverter());
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.checkTokenAccess("isAuthenticated()");
// oauthServer.tokenKeyAccess("isAuthenticated()")
|
// .checkTokenAccess("isAuthenticated()");
// oauthServer.tokenKeyAccess("permitAll()")
// .checkTokenAccess("permitAll()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("clientapp").secret("112233") // Client 账号、密码。
.authorizedGrantTypes("password", "refresh_token") // 密码模式
.scopes("read_userinfo", "read_contacts") // 可授权的 Scope
// .and().withClient() // 可以继续配置新的 Client
;
}
}
|
repos\SpringBoot-Labs-master\lab-68-spring-security-oauth\lab-68-demo11-authorization-server-by-jwt-store\src\main\java\cn\iocoder\springboot\lab68\authorizationserverdemo\config\OAuth2AuthorizationServerConfig.java
| 2
|
请完成以下Java代码
|
public static KPIDataContext ofUserSession(@NonNull final UserSession userSession)
{
return builderFromUserSession(userSession).build();
}
public static KPIDataContextBuilder builderFromUserSession(@NonNull final UserSession userSession)
{
return builder()
.userId(userSession.getLoggedUserId())
.roleId(userSession.getLoggedRoleId())
.clientId(userSession.getClientId())
.orgId(userSession.getOrgId());
}
public static KPIDataContext ofEnvProperties(@NonNull final Properties ctx)
{
return builder()
.userId(Env.getLoggedUserIdIfExists(ctx).orElse(null))
.roleId(Env.getLoggedRoleIdIfExists(ctx).orElse(null))
.clientId(Env.getClientId(ctx))
.orgId(Env.getOrgId(ctx))
.build();
}
public KPIDataContext retainOnlyRequiredParameters(@NonNull final Set<CtxName> requiredParameters)
{
UserId userId_new = null;
RoleId roleId_new = null;
ClientId clientId_new = null;
OrgId orgId_new = null;
for (final CtxName requiredParam : requiredParameters)
{
final String requiredParamName = requiredParam.getName();
if (CTXNAME_AD_User_ID.getName().equals(requiredParamName)
|
|| Env.CTXNAME_AD_User_ID.equals(requiredParamName))
{
userId_new = this.userId;
}
else if (CTXNAME_AD_Role_ID.getName().equals(requiredParamName)
|| Env.CTXNAME_AD_Role_ID.equals(requiredParamName))
{
roleId_new = this.roleId;
}
else if (CTXNAME_AD_Client_ID.getName().equals(requiredParamName)
|| Env.CTXNAME_AD_Client_ID.equals(requiredParamName))
{
clientId_new = this.clientId;
}
else if (CTXNAME_AD_Org_ID.getName().equals(requiredParamName)
|| Env.CTXNAME_AD_Org_ID.equals(requiredParamName))
{
orgId_new = this.orgId;
}
}
return toBuilder()
.userId(userId_new)
.roleId(roleId_new)
.clientId(clientId_new)
.orgId(orgId_new)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\KPIDataContext.java
| 1
|
请完成以下Java代码
|
public CredProtect getInput() {
return this.input;
}
public static class CredProtect implements Serializable {
@Serial
private static final long serialVersionUID = 109597301115842688L;
private final ProtectionPolicy credProtectionPolicy;
private final boolean enforceCredentialProtectionPolicy;
public CredProtect(ProtectionPolicy credProtectionPolicy, boolean enforceCredentialProtectionPolicy) {
this.enforceCredentialProtectionPolicy = enforceCredentialProtectionPolicy;
this.credProtectionPolicy = credProtectionPolicy;
}
public boolean isEnforceCredentialProtectionPolicy() {
|
return this.enforceCredentialProtectionPolicy;
}
public ProtectionPolicy getCredProtectionPolicy() {
return this.credProtectionPolicy;
}
public enum ProtectionPolicy {
USER_VERIFICATION_OPTIONAL, USER_VERIFICATION_OPTIONAL_WITH_CREDENTIAL_ID_LIST, USER_VERIFICATION_REQUIRED
}
}
}
|
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\CredProtectAuthenticationExtensionsClientInput.java
| 1
|
请完成以下Java代码
|
protected static ProcessPreconditionsResolution acceptIfEligibleOrder(final IProcessPreconditionsContext context)
{
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("one and only one order shall be selected");
}
// Only draft orders
final I_C_Order order = context.getSelectedModel(I_C_Order.class);
if (order.isProcessed())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("only draft orders are allowed");
}
// Only sales orders
if (!order.isSOTrx())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("only sales orders are allowed");
}
return ProcessPreconditionsResolution.accept();
}
protected final ProcessPreconditionsResolution acceptIfOrderLinesHaveSameGroupId(final IProcessPreconditionsContext context)
{
final Set<OrderLineId> orderLineIds = getSelectedOrderLineIds(context);
if (orderLineIds.isEmpty())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Select some order lines");
}
final Set<GroupId> groupIds = groupsRepo.extractGroupIdsFromOrderLineIds(orderLineIds);
if (groupIds.isEmpty())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Select a line which is part of a group");
}
else if (groupIds.size() > 1)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Selected lines shall be part of the same group");
}
return ProcessPreconditionsResolution.accept();
|
}
protected final ProcessPreconditionsResolution acceptIfOrderLinesNotInGroup(final IProcessPreconditionsContext context)
{
final Set<OrderLineId> orderLineIds = getSelectedOrderLineIds(context);
if (orderLineIds.isEmpty())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Select some order lines");
}
final Set<GroupId> groupIds = groupsRepo.extractGroupIdsFromOrderLineIds(orderLineIds);
if (!groupIds.isEmpty())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Select lines which are not already grouped");
}
return ProcessPreconditionsResolution.accept();
}
private static final Set<OrderLineId> getSelectedOrderLineIds(final IProcessPreconditionsContext context)
{
return context.getSelectedIncludedRecords()
.stream()
.filter(recordRef -> I_C_OrderLine.Table_Name.equals(recordRef.getTableName()))
.map(recordRef -> OrderLineId.ofRepoId(recordRef.getRecord_ID()))
.collect(ImmutableSet.toImmutableSet());
}
protected final Set<OrderLineId> getSelectedOrderLineIds()
{
return getSelectedIncludedRecordIds(I_C_OrderLine.class)
.stream()
.map(OrderLineId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
}
protected final List<I_C_OrderLine> getSelectedOrderLines()
{
return getSelectedIncludedRecords(I_C_OrderLine.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\process\OrderCompensationGroupProcess.java
| 1
|
请完成以下Java代码
|
class NestedUrlConnectionResources implements Runnable {
private final NestedLocation location;
private volatile ZipContent zipContent;
private volatile long size = -1;
private volatile InputStream inputStream;
NestedUrlConnectionResources(NestedLocation location) {
this.location = location;
}
NestedLocation getLocation() {
return this.location;
}
void connect() throws IOException {
synchronized (this) {
if (this.zipContent == null) {
this.zipContent = ZipContent.open(this.location.path(), this.location.nestedEntryName());
try {
connectData();
}
catch (IOException | RuntimeException ex) {
this.zipContent.close();
this.zipContent = null;
throw ex;
}
}
}
}
private void connectData() throws IOException {
CloseableDataBlock data = this.zipContent.openRawZipData();
try {
this.size = data.size();
this.inputStream = data.asInputStream();
}
catch (IOException | RuntimeException ex) {
data.close();
}
}
InputStream getInputStream() throws IOException {
synchronized (this) {
if (this.inputStream == null) {
throw new IOException("Nested location not found " + this.location);
}
return this.inputStream;
}
|
}
long getContentLength() {
return this.size;
}
@Override
public void run() {
releaseAll();
}
private void releaseAll() {
synchronized (this) {
if (this.zipContent != null) {
IOException exceptionChain = null;
try {
this.inputStream.close();
}
catch (IOException ex) {
exceptionChain = addToExceptionChain(exceptionChain, ex);
}
try {
this.zipContent.close();
}
catch (IOException ex) {
exceptionChain = addToExceptionChain(exceptionChain, ex);
}
this.size = -1;
if (exceptionChain != null) {
throw new UncheckedIOException(exceptionChain);
}
}
}
}
private IOException addToExceptionChain(IOException exceptionChain, IOException ex) {
if (exceptionChain != null) {
exceptionChain.addSuppressed(ex);
return exceptionChain;
}
return ex;
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\nested\NestedUrlConnectionResources.java
| 1
|
请完成以下Java代码
|
final class ProductInfoSupplier
{
private final IProductDAO productsRepo;
private final IUOMDAO uomsRepo;
private final Map<ProductId, ProductInfo> productInfos = new HashMap<>();
@Builder
private ProductInfoSupplier(final IProductDAO productsRepo, final IUOMDAO uomsRepo)
{
this.productsRepo = productsRepo;
this.uomsRepo = uomsRepo;
}
public ProductInfo getByProductId(@NonNull final ProductId productId)
{
return productInfos.computeIfAbsent(productId, this::retrieveProductInfo);
}
private ProductInfo retrieveProductInfo(@NonNull final ProductId productId)
{
final I_M_Product productRecord = productsRepo.getById(productId);
final UomId packageUOMId = UomId.ofRepoIdOrNull(productRecord.getPackage_UOM_ID());
final String packageSizeUOM;
if (packageUOMId != null)
{
final I_C_UOM packageUOM = uomsRepo.getById(packageUOMId);
packageSizeUOM = packageUOM.getUOMSymbol();
}
else
{
|
packageSizeUOM = null;
}
final String stockUOM = uomsRepo.getName(UomId.ofRepoId(productRecord.getC_UOM_ID())).translate(Env.getAD_Language());
final ITranslatableString productName = InterfaceWrapperHelper.getModelTranslationMap(productRecord)
.getColumnTrl(I_M_Product.COLUMNNAME_Name, productRecord.getName());
return ProductInfo.builder()
.productId(productId)
.code(productRecord.getValue())
.name(productName)
.packageSize(productRecord.getPackageSize())
.packageSizeUOM(packageSizeUOM)
.stockUOM(stockUOM)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\rows\factory\ProductInfoSupplier.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private <T extends DeliveryMethodNotificationTemplate> T processTemplate(T template, Map<String, String> additionalTemplateContext) {
Map<String, String> templateContext = new HashMap<>();
if (request.getInfo() != null) {
templateContext.putAll(request.getInfo().getTemplateData());
}
if (additionalTemplateContext != null) {
templateContext.putAll(additionalTemplateContext);
}
if (templateContext.isEmpty()) return template;
template = (T) template.copy();
template.getTemplatableValues().forEach(templatableValue -> {
String value = templatableValue.get();
if (StringUtils.isNotEmpty(value)) {
value = TemplateUtils.processTemplate(value, templateContext);
templatableValue.set(value);
|
}
});
return template;
}
private Map<String, String> createTemplateContextForRecipient(NotificationRecipient recipient) {
return Map.of(
"recipientTitle", recipient.getTitle(),
"recipientEmail", Strings.nullToEmpty(recipient.getEmail()),
"recipientFirstName", Strings.nullToEmpty(recipient.getFirstName()),
"recipientLastName", Strings.nullToEmpty(recipient.getLastName())
);
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\NotificationProcessingContext.java
| 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.