instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | protected boolean removeEldestEntry(Map.Entry<String, T> eldest) {
boolean removeEldest = size() > limit;
if (removeEldest && logger.isTraceEnabled()) {
logger.trace("Cache limit {} is reached, {} will be evicted", limit, eldest.getKey());
}
return removeEldest;
}
}
);
}
public T get(String id) {
return cache.get(id);
}
public void add(String id, T obj) {
cache.put(id, obj);
} | public void remove(String id) {
cache.remove(id);
}
@Override
public boolean contains(String id) {
return cache.containsKey(id);
}
public void clear() {
cache.clear();
}
// For testing purposes only
public int size() {
return cache.size();
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\deploy\DefaultDeploymentCache.java | 1 |
请完成以下Java代码 | class NamePattern
{
public static NamePattern ofStringOrAny(@Nullable final String pattern)
{
final String patternNorm = normalizeString(pattern);
if (patternNorm == null)
{
return ANY;
}
else
{
return new NamePattern(patternNorm);
}
}
public static NamePattern any()
{
return ANY;
}
private static final NamePattern ANY = new NamePattern();
@Getter
private final boolean any;
private final String pattern;
private NamePattern(@NonNull final String patternNormalized)
{
this.any = false;
this.pattern = patternNormalized;
}
private static final String normalizeString(final String str)
{
if (str == null)
{
return null;
}
final String strNorm = str.trim();
if (strNorm.isEmpty())
{
return null;
}
return strNorm;
}
private NamePattern()
{
this.any = true;
this.pattern = null;
}
@Override
public String toString()
{
if (any)
{
return MoreObjects.toStringHelper(this).addValue("ANY").toString();
}
else
{
return MoreObjects.toStringHelper(this).add("pattern", pattern).toString();
}
}
public boolean isMatching(@NonNull final DataEntryTab tab)
{
return isMatching(tab.getInternalName())
|| isMatching(tab.getCaption());
}
public boolean isMatching(@NonNull final DataEntrySubTab subTab)
{
return isMatching(subTab.getInternalName())
|| isMatching(subTab.getCaption());
}
public boolean isMatching(@NonNull final DataEntrySection section)
{
return isMatching(section.getInternalName())
|| isMatching(section.getCaption());
}
public boolean isMatching(@NonNull final DataEntryLine line) | {
return isMatching(String.valueOf(line.getSeqNo()));
}
public boolean isMatching(@NonNull final DataEntryField field)
{
return isAny()
|| isMatching(field.getCaption());
}
private boolean isMatching(final ITranslatableString trl)
{
if (isAny())
{
return true;
}
if (isMatching(trl.getDefaultValue()))
{
return true;
}
for (final String adLanguage : trl.getAD_Languages())
{
if (isMatching(trl.translate(adLanguage)))
{
return true;
}
}
return false;
}
@VisibleForTesting
boolean isMatching(final String name)
{
if (isAny())
{
return true;
}
final String nameNorm = normalizeString(name);
if (nameNorm == null)
{
return false;
}
return pattern.equalsIgnoreCase(nameNorm);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\data\impexp\NamePattern.java | 1 |
请完成以下Java代码 | public void afterModelLinked(final MTLinkRequest request)
{
final I_M_InOutLine receiptLine = InterfaceWrapperHelper.create(request.getModel(), I_M_InOutLine.class);
final I_M_Material_Tracking materialTracking = request.getMaterialTrackingRecord();
if (!isEligible(receiptLine, materialTracking))
{
return;
}
final BigDecimal qtyReceivedToAdd = receiptLine.getMovementQty();
final BigDecimal qtyReceived = materialTracking.getQtyReceived();
final BigDecimal qtyReceivedNew = qtyReceived.add(qtyReceivedToAdd);
materialTracking.setQtyReceived(qtyReceivedNew);
InterfaceWrapperHelper.save(materialTracking);
// task 08021
final IQualityBasedInvoicingDAO qualityBasedInvoicingDAO = Services.get(IQualityBasedInvoicingDAO.class);
final IMaterialTrackingDocuments materialTrackingDocuments = qualityBasedInvoicingDAO.retrieveMaterialTrackingDocuments(materialTracking);
final PPOrderQualityCalculator calculator = new PPOrderQualityCalculator();
calculator.update(materialTrackingDocuments);
// end task 08021
}
/**
* Decrease {@link I_M_Material_Tracking#COLUMNNAME_QtyReceived}
*/
@Override
public void afterModelUnlinked(final Object model, final I_M_Material_Tracking materialTrackingOld)
{
final I_M_InOutLine receiptLine = InterfaceWrapperHelper.create(model, I_M_InOutLine.class);
if (!isEligible(receiptLine, materialTrackingOld)) | {
return;
}
final BigDecimal qtyReceivedToRemove = receiptLine.getMovementQty();
final BigDecimal qtyReceived = materialTrackingOld.getQtyReceived();
final BigDecimal qtyReceivedNew = qtyReceived.subtract(qtyReceivedToRemove);
materialTrackingOld.setQtyReceived(qtyReceivedNew);
InterfaceWrapperHelper.save(materialTrackingOld);
}
private final boolean isEligible(final I_M_InOutLine inoutLine, final I_M_Material_Tracking materialTracking)
{
// check if the inoutLine's product is our tracked product.
if (materialTracking.getM_Product_ID() != inoutLine.getM_Product_ID())
{
return false;
}
final I_M_InOut inout = inoutLine.getM_InOut();
// Shipments are not eligible (just in case)
if (inout.isSOTrx())
{
return false;
}
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\spi\impl\listeners\InOutLineMaterialTrackingListener.java | 1 |
请完成以下Java代码 | protected Long getProcessDefinedPriority(ProcessDefinitionImpl processDefinition, String propertyKey, ExecutionEntity execution, String errorMsgHead) {
if (processDefinition != null) {
ParameterValueProvider priorityProvider = (ParameterValueProvider) processDefinition.getProperty(propertyKey);
if (priorityProvider != null) {
return evaluateValueProvider(priorityProvider, execution, errorMsgHead);
}
}
return null;
}
/**
* Logs the exception which was thrown if the priority can not be determined.
*
* @param execution the current execution entity
* @param value the current value
* @param e the exception which was catched
*/
protected abstract void logNotDeterminingPriority(ExecutionEntity execution, Object value, ProcessEngineException e);
protected boolean isSymptomOfContextSwitchFailure(Throwable t, ExecutionEntity contextExecution) {
// a context switch failure can occur, if the current engine has no PA registration for the deployment
// subclasses may assert the actual throwable to narrow down the diagnose | return ProcessApplicationContextUtil.getTargetProcessApplication(contextExecution) == null;
}
/**
* Checks if the given number is a valid long value.
* @param value the number which should be checked
* @return true if is a valid long value, false otherwise
*/
protected boolean isValidLongValue(Number value) {
return
value instanceof Short ||
value instanceof Integer ||
value instanceof Long;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\DefaultPriorityProvider.java | 1 |
请完成以下Java代码 | public int getC_LicenseFeeSettingsLine_ID()
{
return get_ValueAsInt(COLUMNNAME_C_LicenseFeeSettingsLine_ID);
}
@Override
public void setPercentOfBasePoints (final BigDecimal PercentOfBasePoints)
{
set_Value (COLUMNNAME_PercentOfBasePoints, PercentOfBasePoints);
}
@Override
public BigDecimal getPercentOfBasePoints()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PercentOfBasePoints); | return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_LicenseFeeSettingsLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void recurseBackwards(@NonNull final Result resultIn, int depth)
{
for (final HuId vhuSourceId : resultIn.getVhuSourceIds())
{
load(
HUTraceEventQuery.builder().vhuId(vhuSourceId).recursionMode(RecursionMode.BACKWARD).build(),
depth
);
}
}
private void recurseForwards(@NonNull final Result resultIn, final int depth)
{
for (final HuId vhuId : resultIn.getVhuIds())
{
recurseForwardViaVhuLink(vhuId, depth);
recurseForwardViaSourceVhuLink(vhuId, depth);
}
}
private void recurseForwardViaVhuLink(final HuId vhuId, int depth)
{
load(
HUTraceEventQuery.builder().vhuId(vhuId).recursionMode(RecursionMode.NONE).build(),
depth
);
}
/**
* Get the records where our vhuId is the vhuSourceId.
*/
private void recurseForwardViaSourceVhuLink(@NonNull final HuId vhuId, final int depth)
{
final IQueryBuilder<I_M_HU_Trace> sqlQueryBuilder = createQueryBuilderOrNull(HUTraceEventQuery.builder().vhuSourceId(vhuId).recursionMode(RecursionMode.NONE).build());
if (sqlQueryBuilder == null)
{
return;
}
final Collection<HuId> directFollowupVhuIds = sqlQueryBuilder.create().listDistinct(I_M_HU_Trace.COLUMNNAME_VHU_ID, HuId.class);
for (final HuId directFollowupVhuId : directFollowupVhuIds)
{
load(HUTraceEventQuery.builder().vhuId(directFollowupVhuId).recursionMode(RecursionMode.FORWARD).build(), depth); | }
}
}
/**
* Return all records; this makes absolutely no sense in production; Intended to be used only use for testing.
*/
@VisibleForTesting
public List<HUTraceEvent> queryAll()
{
Adempiere.assertUnitTestMode();
final IQueryBL queryBL = Services.get(IQueryBL.class);
final IQueryBuilder<I_M_HU_Trace> queryBuilder = queryBL.createQueryBuilder(I_M_HU_Trace.class)
.orderBy().addColumn(I_M_HU_Trace.COLUMN_M_HU_Trace_ID).endOrderBy();
return queryBuilder.create()
.stream()
.map(HuTraceEventToDbRecordUtil::fromDbRecord)
.collect(Collectors.toList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\trace\repository\RetrieveDbRecordsUtil.java | 2 |
请完成以下Java代码 | public String getCouponCode() {
return couponCode;
}
public void setCouponCode(String couponCode) {
this.couponCode = couponCode;
}
public String getMemberNickname() {
return memberNickname;
}
public void setMemberNickname(String memberNickname) {
this.memberNickname = memberNickname;
}
public Integer getGetType() {
return getType;
}
public void setGetType(Integer getType) {
this.getType = getType;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getUseStatus() {
return useStatus;
}
public void setUseStatus(Integer useStatus) {
this.useStatus = useStatus;
}
public Date getUseTime() {
return useTime;
} | public void setUseTime(Date useTime) {
this.useTime = useTime;
}
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
public String getOrderSn() {
return orderSn;
}
public void setOrderSn(String orderSn) {
this.orderSn = orderSn;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", couponId=").append(couponId);
sb.append(", memberId=").append(memberId);
sb.append(", couponCode=").append(couponCode);
sb.append(", memberNickname=").append(memberNickname);
sb.append(", getType=").append(getType);
sb.append(", createTime=").append(createTime);
sb.append(", useStatus=").append(useStatus);
sb.append(", useTime=").append(useTime);
sb.append(", orderId=").append(orderId);
sb.append(", orderSn=").append(orderSn);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsCouponHistory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class M_Inventory
{
private final SecurPharmService securPharmService;
public M_Inventory(@NonNull final SecurPharmService securPharmService)
{
this.securPharmService = securPharmService;
}
@DocValidate(timings = ModelValidator.TIMING_AFTER_COMPLETE)
public void beforeComplete(final I_M_Inventory inventory)
{
if (securPharmService.hasConfig())
{
final InventoryId inventoryId = InventoryId.ofRepoId(inventory.getM_Inventory_ID());
securPharmService.scheduleAction(SecurPharmaActionRequest.builder()
.action(SecurPharmAction.DECOMMISSION)
.inventoryId(inventoryId)
.build());
}
} | @DocValidate(timings = ModelValidator.TIMING_BEFORE_REVERSECORRECT)
public void beforeReverse(final I_M_Inventory inventory)
{
if (securPharmService.hasConfig())
{
final InventoryId inventoryId = InventoryId.ofRepoId(inventory.getM_Inventory_ID());
securPharmService.scheduleAction(SecurPharmaActionRequest.builder()
.action(SecurPharmAction.UNDO_DECOMMISSION)
.inventoryId(inventoryId)
.build());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\inventory\interceptor\M_Inventory.java | 2 |
请完成以下Java代码 | public static IssuingToleranceSpec ofPercent(@NonNull final Percent percent)
{
return builder().valueType(IssuingToleranceValueType.PERCENTAGE).percent(percent).build();
}
public static IssuingToleranceSpec ofQuantity(@NonNull final Quantity qty)
{
return builder().valueType(IssuingToleranceValueType.QUANTITY).qty(qty).build();
}
public @NonNull IssuingToleranceValueType getValueType() {return valueType;}
private void assertValueType(@NonNull IssuingToleranceValueType expectedValueType)
{
if (this.valueType != expectedValueType)
{
throw new AdempiereException("Expected " + this + " to be of type: " + expectedValueType);
}
}
@NonNull
public Percent getPercent()
{
assertValueType(IssuingToleranceValueType.PERCENTAGE);
return Check.assumeNotNull(percent, "percent not null");
}
@NonNull
public Quantity getQty()
{
assertValueType(IssuingToleranceValueType.QUANTITY);
return Check.assumeNotNull(qty, "qty not null");
}
public ITranslatableString toTranslatableString()
{
if (valueType == IssuingToleranceValueType.PERCENTAGE)
{
final Percent percent = getPercent();
return TranslatableStrings.builder().appendPercent(percent).build();
}
else if (valueType == IssuingToleranceValueType.QUANTITY)
{
final Quantity qty = getQty();
return TranslatableStrings.builder().appendQty(qty.toBigDecimal(), qty.getUOMSymbol()).build();
}
else
{
// shall not happen
return TranslatableStrings.empty();
}
}
public Quantity addTo(@NonNull final Quantity qtyBase)
{
if (valueType == IssuingToleranceValueType.PERCENTAGE)
{
final Percent percent = getPercent();
return qtyBase.add(percent);
}
else if (valueType == IssuingToleranceValueType.QUANTITY)
{
final Quantity qty = getQty();
return qtyBase.add(qty);
}
else
{
// shall not happen
throw new AdempiereException("Unknown valueType: " + valueType);
}
}
public Quantity subtractFrom(@NonNull final Quantity qtyBase)
{
if (valueType == IssuingToleranceValueType.PERCENTAGE) | {
final Percent percent = getPercent();
return qtyBase.subtract(percent);
}
else if (valueType == IssuingToleranceValueType.QUANTITY)
{
final Quantity qty = getQty();
return qtyBase.subtract(qty);
}
else
{
// shall not happen
throw new AdempiereException("Unknown valueType: " + valueType);
}
}
public IssuingToleranceSpec convertQty(@NonNull final UnaryOperator<Quantity> qtyConverter)
{
if (valueType == IssuingToleranceValueType.QUANTITY)
{
final Quantity qtyConv = qtyConverter.apply(qty);
if (qtyConv.equals(qty))
{
return this;
}
return toBuilder().qty(qtyConv).build();
}
else
{
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\IssuingToleranceSpec.java | 1 |
请完成以下Java代码 | default String getFormatedExpressionString()
{
return getExpressionString();
}
/**
* Gets the list of parameter names.<br>
* In most implementations this can be the result of a {@link #getParameters()} that was "dumbed down" via {@link CtxNames#toNames(java.util.Collection)}.<br>
* However, if your implementation wraps around and delegates to an internal {@link IExpression} instance, then I recommend to explicitly delegate also this method.
*
* @return list of parameter names or empty list; never return {@code null}
*/
default Set<String> getParameterNames()
{
return CtxNames.toNames(getParameters());
}
/**
* Return the parameters as {@link CtxName}s.<br>
* If you really, really have only strings in your implementation, you can use {@link CtxNames#parseAll(java.util.Collection)} to implement the method.
*/
Set<CtxName> getParameters();
/**
* Consider using {@link #evaluate(Evaluatee, OnVariableNotFound)}. This method will be deprecated in future.
*/
@Deprecated
default V evaluate(final Evaluatee ctx, final boolean ignoreUnparsable)
{
// backward compatibility
final OnVariableNotFound onVariableNotFound = ignoreUnparsable ? OnVariableNotFound.Empty : OnVariableNotFound.ReturnNoResult;
return evaluate(ctx, onVariableNotFound);
} | /**
* Evaluates expression in given context.
*
* @return evaluation result
* @throws ExpressionEvaluationException if evaluation fails and we were advised to throw exception
*/
V evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException;
/**
* @return true if the given <code>result</code> shall be considered as "NO RESULT"
*/
default boolean isNoResult(final Object result)
{
return result == null;
}
/**
* @return true if this expression is constant and always evaluated "NO RESULT"
* @see #isNoResult(Object)
*/
default boolean isNullExpression()
{
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\IExpression.java | 1 |
请完成以下Java代码 | public Mono<AuthorizationResult> authorize(Mono<Authentication> authentication, ServerWebExchange exchange) {
return Flux.fromIterable(this.mappings)
.concatMap((mapping) -> mapping.getMatcher()
.matches(exchange)
.filter(MatchResult::isMatch)
.map(MatchResult::getVariables)
.flatMap((variables) -> {
logger.debug(LogMessage.of(() -> "Checking authorization on '"
+ exchange.getRequest().getPath().pathWithinApplication() + "' using "
+ mapping.getEntry()));
return mapping.getEntry().authorize(authentication, new AuthorizationContext(exchange, variables));
}))
.next()
.switchIfEmpty(Mono.fromCallable(() -> new AuthorizationDecision(false)));
}
public static DelegatingReactiveAuthorizationManager.Builder builder() {
return new DelegatingReactiveAuthorizationManager.Builder();
}
public static final class Builder {
private final List<ServerWebExchangeMatcherEntry<ReactiveAuthorizationManager<AuthorizationContext>>> mappings = new ArrayList<>(); | private Builder() {
}
public DelegatingReactiveAuthorizationManager.Builder add(
ServerWebExchangeMatcherEntry<ReactiveAuthorizationManager<AuthorizationContext>> entry) {
this.mappings.add(entry);
return this;
}
public DelegatingReactiveAuthorizationManager build() {
return new DelegatingReactiveAuthorizationManager(this.mappings);
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\authorization\DelegatingReactiveAuthorizationManager.java | 1 |
请完成以下Java代码 | public List<T> poll(long durationInMillis) {
if (subscribed) {
@SuppressWarnings("unchecked")
List<T> messages = partitions
.stream()
.map(tpi -> {
try {
return storage.get(tpi.getFullTopicName());
} catch (InterruptedException e) {
if (!stopped) {
log.error("Queue was interrupted.", e);
}
return Collections.emptyList();
}
})
.flatMap(List::stream)
.map(msg -> (T) msg).collect(Collectors.toList());
if (messages.size() > 0) {
return messages;
}
try {
Thread.sleep(durationInMillis);
} catch (InterruptedException e) {
if (!stopped) {
log.error("Failed to sleep.", e);
}
}
}
return Collections.emptyList();
} | @Override
public void commit() {
}
@Override
public boolean isStopped() {
return stopped;
}
@Override
public Set<TopicPartitionInfo> getPartitions() {
return partitions;
}
@Override
public List<String> getFullTopicNames() {
return partitions.stream().map(TopicPartitionInfo::getFullTopicName).collect(Collectors.toList());
}
} | repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\memory\InMemoryTbQueueConsumer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BatchConfiguration {
protected List<String> ids;
protected DeploymentMappings idMappings;
protected boolean failIfNotExists;
protected String batchId;
public BatchConfiguration(List<String> ids) {
this(ids, true);
}
public BatchConfiguration(List<String> ids, boolean failIfNotExists) {
this(ids, null, failIfNotExists);
}
public BatchConfiguration(List<String> ids, DeploymentMappings mappings) {
this(ids, mappings, true);
}
public BatchConfiguration(List<String> ids, DeploymentMappings mappings, boolean failIfNotExists) {
this.ids = ids;
this.idMappings = mappings;
this.failIfNotExists = failIfNotExists;
}
public BatchConfiguration(List<String> ids, DeploymentMappings mappings, String batchId) {
this.ids = ids;
this.idMappings = mappings;
this.batchId = batchId;
}
public List<String> getIds() {
return ids;
}
public void setIds(List<String> ids) {
this.ids = ids;
}
public DeploymentMappings getIdMappings() {
return idMappings; | }
public void setIdMappings(DeploymentMappings idMappings) {
this.idMappings = idMappings;
}
public boolean isFailIfNotExists() {
return failIfNotExists;
}
public void setFailIfNotExists(boolean failIfNotExists) {
this.failIfNotExists = failIfNotExists;
}
public String getBatchId() {
return batchId;
}
public void setBatchId(String batchId) {
this.batchId = batchId;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\BatchConfiguration.java | 2 |
请完成以下Java代码 | public void setCopy(Boolean value) {
this.copy = value;
}
/**
* Gets the value of the creditAdvice property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public boolean isCreditAdvice() {
if (creditAdvice == null) {
return false;
} else {
return creditAdvice;
}
}
/**
* Sets the value of the creditAdvice property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setCreditAdvice(Boolean value) {
this.creditAdvice = value; | }
/**
* Gets the value of the responseTimestamp property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getResponseTimestamp() {
return responseTimestamp;
}
/**
* Sets the value of the responseTimestamp property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setResponseTimestamp(BigInteger value) {
this.responseTimestamp = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\PayloadType.java | 1 |
请完成以下Java代码 | private static LocalTime fromObjectToLocalTime(final Object valueObj)
{
return fromObjectTo(valueObj,
LocalTime.class,
de.metas.util.converter.DateTimeConverters::fromJsonToLocalTime,
TimeUtil::asLocalTime);
}
public static ZonedDateTime fromObjectToZonedDateTime(final Object valueObj)
{
return fromObjectTo(valueObj,
ZonedDateTime.class,
de.metas.util.converter.DateTimeConverters::fromJsonToZonedDateTime,
TimeUtil::asZonedDateTime);
}
public static Instant fromObjectToInstant(final Object valueObj)
{
return fromObjectTo(valueObj,
Instant.class,
de.metas.util.converter.DateTimeConverters::fromJsonToInstant,
TimeUtil::asInstant);
}
@Nullable
private static <T> T fromObjectTo(
final Object valueObj,
@NonNull final Class<T> type,
@NonNull final Function<String, T> fromJsonConverer,
@NonNull final Function<Object, T> fromObjectConverter)
{
if (valueObj == null
|| JSONNullValue.isNull(valueObj))
{
return null;
}
else if (type.isInstance(valueObj))
{
return type.cast(valueObj);
}
else if (valueObj instanceof CharSequence)
{
final String json = valueObj.toString().trim();
if (json.isEmpty())
{
return null;
}
if (isPossibleJdbcTimestamp(json))
{
try
{
final Timestamp timestamp = fromPossibleJdbcTimestamp(json);
return fromObjectConverter.apply(timestamp);
}
catch (final Exception e)
{ | logger.warn("Error while converting possible JDBC Timestamp `{}` to java.sql.Timestamp", json, e);
return fromJsonConverer.apply(json);
}
}
else
{
return fromJsonConverer.apply(json);
}
}
else if (valueObj instanceof StringLookupValue)
{
final String key = ((StringLookupValue)valueObj).getIdAsString();
if (Check.isEmpty(key))
{
return null;
}
else
{
return fromJsonConverer.apply(key);
}
}
else
{
return fromObjectConverter.apply(valueObj);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\DateTimeConverters.java | 1 |
请完成以下Java代码 | public String getFilename() {
return filename;
}
@Override
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public void setValue(byte[] bytes) {
this.value = bytes;
}
@Override
public InputStream getValue() {
if (value == null) {
return null;
}
return new ByteArrayInputStream(value);
}
@Override
public ValueType getType() {
return type;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public void setEncoding(Charset encoding) {
this.encoding = encoding.name();
}
@Override
public Charset getEncodingAsCharset() {
if (encoding == null) {
return null;
}
return Charset.forName(encoding);
}
@Override | public String getEncoding() {
return encoding;
}
/**
* Get the byte array directly without wrapping it inside a stream to evade
* not needed wrapping. This method is intended for the internal API, which
* needs the byte array anyways.
*/
public byte[] getByteArray() {
return value;
}
@Override
public String toString() {
return "FileValueImpl [mimeType=" + mimeType + ", filename=" + filename + ", type=" + type + ", isTransient=" + isTransient + "]";
}
@Override
public boolean isTransient() {
return isTransient;
}
public void setTransient(boolean isTransient) {
this.isTransient = isTransient;
}
} | repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\value\FileValueImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ArticleCommentService {
private final ArticleCommentRepository articleCommentRepository;
/**
* Get comment by id.
*
* @param commentId comment id
* @return Returns comment
*/
public ArticleComment getComment(int commentId) {
return articleCommentRepository
.findById(commentId)
.orElseThrow(() -> new NoSuchElementException("invalid comment id."));
}
/**
* Get all comments by article.
*
* @param article article
* @return Returns all comments
*/
public List<ArticleComment> getComments(Article article) {
return articleCommentRepository.findByArticle(article);
}
/**
* Write a comment.
*
* @param articleComment comment
* @return Returns the written comment
*/
public ArticleComment write(ArticleComment articleComment) {
return articleCommentRepository.save(articleComment);
} | /**
* Delete comment.
*
* @param requester user who requested
* @param articleComment comment
*/
public void delete(User requester, ArticleComment articleComment) {
if (articleComment.isNotAuthor(requester)) {
throw new IllegalArgumentException("you can't delete comments written by others.");
}
articleCommentRepository.delete(articleComment);
}
} | repos\realworld-java21-springboot3-main\module\core\src\main\java\io\zhc1\realworld\service\ArticleCommentService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ProdImageEntity implements Serializable{
/** 主键 */
private String id;
/** 图片的URL */
private String imageURL;
/** 图片所属产品的ID */
private String productId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public String getProductId() { | return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
@Override
public String toString() {
return "ProdImageEntity{" +
"id='" + id + '\'' +
", imageURL='" + imageURL + '\'' +
", productId='" + productId + '\'' +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\product\ProdImageEntity.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getCURRENCYQUAL() {
return currencyqual;
}
/**
* Sets the value of the currencyqual property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCURRENCYQUAL(String value) {
this.currencyqual = value;
}
/**
* Gets the value of the currencycode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCURRENCYCODE() {
return currencycode;
}
/**
* Sets the value of the currencycode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCURRENCYCODE(String value) {
this.currencycode = value;
}
/**
* Gets the value of the currencyexrate property.
* | * @return
* possible object is
* {@link String }
*
*/
public String getCURRENCYEXRATE() {
return currencyexrate;
}
/**
* Sets the value of the currencyexrate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCURRENCYEXRATE(String value) {
this.currencyexrate = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\HCURR1.java | 2 |
请完成以下Java代码 | public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Target URL.
@param TargetURL
URL for the Target
*/
public void setTargetURL (String TargetURL)
{
set_Value (COLUMNNAME_TargetURL, TargetURL);
}
/** Get Target URL.
@return URL for the Target
*/
public String getTargetURL ()
{
return (String)get_Value(COLUMNNAME_TargetURL);
}
/** Set Click Count.
@param W_ClickCount_ID
Web Click Management
*/
public void setW_ClickCount_ID (int W_ClickCount_ID)
{
if (W_ClickCount_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_ClickCount_ID, null); | else
set_ValueNoCheck (COLUMNNAME_W_ClickCount_ID, Integer.valueOf(W_ClickCount_ID));
}
/** Get Click Count.
@return Web Click Management
*/
public int getW_ClickCount_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_ClickCount_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_ClickCount.java | 1 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable()
{
final ImmutableSet<InvoiceId> invoiceIds = getSelectedInvoiceIds();
if (invoiceIds.isEmpty())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
// technical detail: all records must have the same Export Status
EDIExportStatus sameExportStatus = null;
for (final InvoiceId invoiceId : invoiceIds)
{
final de.metas.edi.model.I_C_Invoice invoice = ediDocOutBoundLogService.retreiveById(invoiceId);
final EDIExportStatus fromExportStatus = EDIExportStatus.ofNullableCode(invoice.getEDI_ExportStatus());
if (fromExportStatus == null)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Selected record is not an EDI Invoice: " + invoice);
}
if (ChangeEDI_ExportStatusHelper.getAvailableTargetExportStatuses(fromExportStatus).isEmpty())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Cannot change ExportStatus from the current one: " + fromExportStatus);
}
if (sameExportStatus == null)
{
sameExportStatus = fromExportStatus;
}
if (!sameExportStatus.equals(fromExportStatus))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("All records must have the same EDI ExportStatus");
}
}
return ProcessPreconditionsResolution.accept();
}
@ProcessParamLookupValuesProvider(parameterName = PARAM_TargetExportStatus, numericKey = false, lookupSource = LookupSource.list) | private LookupValuesList getTargetExportStatusLookupValues(final LookupDataSourceContext context)
{
final de.metas.edi.model.I_C_Invoice invoice = ediDocOutBoundLogService.retreiveById(getSelectedInvoiceIds().iterator().next());
final EDIExportStatus fromExportStatus = EDIExportStatus.ofCode(invoice.getEDI_ExportStatus());
return ChangeEDI_ExportStatusHelper.computeTargetExportStatusLookupValues(fromExportStatus);
}
@Override
@Nullable
public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
final de.metas.edi.model.I_C_Invoice invoice = ediDocOutBoundLogService.retreiveById(getSelectedInvoiceIds().iterator().next());
final EDIExportStatus fromExportStatus = EDIExportStatus.ofCode(invoice.getEDI_ExportStatus());
return ChangeEDI_ExportStatusHelper.computeParameterDefaultValue(fromExportStatus);
}
@Override
protected String doIt() throws Exception
{
final EDIExportStatus targetExportStatus = EDIExportStatus.ofCode(p_TargetExportStatus);
for (final InvoiceId invoiceId : getSelectedInvoiceIds())
{
ChangeEDI_ExportStatusHelper.C_InvoiceDoIt(invoiceId, targetExportStatus);
}
return MSG_OK;
}
private ImmutableSet<InvoiceId> getSelectedInvoiceIds()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
return selectedRowIds.toIds(InvoiceId::ofRepoId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\edi_desadv\ChangeEDI_ExportStatus_C_Invoice_GridView.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Menu {
private String name;
private String path;
private String title;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
} | public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return "Menu{" +
"name='" + name + '\'' +
", path='" + path + '\'' +
", title='" + title + '\'' +
'}';
}
} | repos\spring-boot-master\yaml-simple\src\main\java\com\mkyong\config\model\Menu.java | 2 |
请完成以下Java代码 | public class AddressType implements CompositeUserType<Address> {
@Override
public Object getPropertyValue(Address component, int property) throws HibernateException {
switch (property) {
case 0:
return component.getAddressLine1();
case 1:
return component.getAddressLine2();
case 2:
return component.getCity();
case 3:
return component.getCountry();
case 4:
return component.getZipCode();
default:
throw new IllegalArgumentException(property + " is an invalid property index for class type " + component.getClass()
.getName());
}
}
@Override
public Address instantiate(ValueAccess values) {
return new Address(values.getValue(0, String.class), values.getValue(1, String.class), values.getValue(2, String.class),
values.getValue(3, String.class), values.getValue(4, Integer.class));
}
@Override
public Class<?> embeddable() {
return Address.class;
}
@Override
public Class<Address> returnedClass() {
return Address.class;
}
@Override
public boolean equals(Address x, Address y) {
if (x == y) {
return true;
}
if (Objects.isNull(x) || Objects.isNull(y)) {
return false;
}
return x.equals(y);
}
@Override
public int hashCode(Address x) {
return x.hashCode();
}
@Override
public Address deepCopy(Address value) {
if (Objects.isNull(value)) {
return null;
} | Address newEmpAdd = new Address();
newEmpAdd.setAddressLine1(value.getAddressLine1());
newEmpAdd.setAddressLine2(value.getAddressLine2());
newEmpAdd.setCity(value.getCity());
newEmpAdd.setCountry(value.getCountry());
newEmpAdd.setZipCode(value.getZipCode());
return newEmpAdd;
}
@Override
public boolean isMutable() {
return true;
}
@Override
public Serializable disassemble(Address value) {
return (Serializable) deepCopy(value);
}
@Override
public Address assemble(Serializable cached, Object owner) {
return deepCopy((Address) cached);
}
@Override
public Address replace(Address detached, Address managed, Object owner) {
return detached;
}
@Override
public boolean isInstance(Object object) {
return CompositeUserType.super.isInstance(object);
}
@Override
public boolean isSameClass(Object object) {
return CompositeUserType.super.isSameClass(object);
}
} | repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\customtypes\AddressType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void addToCache(@NonNull final I_DD_Order ddOrder)
{
addToCache(ImmutableList.of(ddOrder));
}
private void addToCache(@NonNull final List<I_DD_Order> ddOrders)
{
ddOrders.forEach(ddOrder -> ddOrdersCache.put(DDOrderId.ofRepoId(ddOrder.getDD_Order_ID()), ddOrder));
CollectionUtils.getAllOrLoad(ddOrderLinesCache, ddOrdersCache.keySet(), loadingSupportServices::getLinesByDDOrderIds);
final ImmutableSet<DDOrderLineId> ddOrderLineIds = ddOrderLinesCache.values()
.stream()
.flatMap(Collection::stream)
.map(ddOrderLine -> DDOrderLineId.ofRepoId(ddOrderLine.getDD_OrderLine_ID()))
.collect(ImmutableSet.toImmutableSet());
CollectionUtils.getAllOrLoad(schedulesCache, ddOrderLineIds, loadingSupportServices::getSchedulesByDDOrderLineIds);
} | I_DD_Order getDDOrder(final DDOrderId ddOrderId)
{
return ddOrdersCache.computeIfAbsent(ddOrderId, loadingSupportServices::getDDOrderById);
}
private List<I_DD_OrderLine> getDDOrderLines(final DDOrderId ddOrderId)
{
return CollectionUtils.getOrLoad(ddOrderLinesCache, ddOrderId, loadingSupportServices::getLinesByDDOrderIds);
}
private List<DDOrderMoveSchedule> getSchedules(final DDOrderLineId ddOrderLineId)
{
return CollectionUtils.getOrLoad(schedulesCache, ddOrderLineId, loadingSupportServices::getSchedulesByDDOrderLineIds);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\service\DistributionJobLoader.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class JWTCsrfTokenRepository implements CsrfTokenRepository {
private static final String DEFAULT_CSRF_TOKEN_ATTR_NAME = CSRFConfig.class.getName()
.concat(".CSRF_TOKEN");
private static final Logger log = LoggerFactory.getLogger(JWTCsrfTokenRepository.class);
private byte[] secret;
public JWTCsrfTokenRepository(byte[] secret) {
this.secret = secret;
}
@Override
public CsrfToken generateToken(HttpServletRequest request) {
String id = UUID.randomUUID()
.toString()
.replace("-", "");
Date now = new Date();
Date exp = new Date(System.currentTimeMillis() + (1000 * 30)); // 30 seconds
String token = Jwts.builder()
.setId(id)
.setIssuedAt(now)
.setNotBefore(now)
.setExpiration(exp)
.signWith(SignatureAlgorithm.HS256, secret)
.compact();
return new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", token);
}
@Override
public void saveToken(CsrfToken token, HttpServletRequest request, HttpServletResponse response) {
if (token == null) {
HttpSession session = request.getSession(false); | if (session != null) {
session.removeAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME);
}
} else {
HttpSession session = request.getSession();
session.setAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME, token);
}
}
@Override
public CsrfToken loadToken(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null || "GET".equals(request.getMethod())) {
return null;
}
return (CsrfToken) session.getAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME);
}
} | repos\tutorials-master\security-modules\jjwt\src\main\java\io\jsonwebtoken\jjwtfun\config\JWTCsrfTokenRepository.java | 2 |
请完成以下Java代码 | public int getC_TaxCategory_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_TaxCategory_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Same Currency.
@param IsSameCurrency Same Currency */
public void setIsSameCurrency (boolean IsSameCurrency)
{
set_Value (COLUMNNAME_IsSameCurrency, Boolean.valueOf(IsSameCurrency));
}
/** Get Same Currency.
@return Same Currency */
public boolean isSameCurrency ()
{
Object oo = get_Value(COLUMNNAME_IsSameCurrency);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Same Tax.
@param IsSameTax
Use the same tax as the main transaction
*/
public void setIsSameTax (boolean IsSameTax)
{
set_Value (COLUMNNAME_IsSameTax, Boolean.valueOf(IsSameTax));
}
/** Get Same Tax.
@return Use the same tax as the main transaction
*/
public boolean isSameTax ()
{
Object oo = get_Value(COLUMNNAME_IsSameTax);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
} | /** Set Price includes Tax.
@param IsTaxIncluded
Tax is included in the price
*/
public void setIsTaxIncluded (boolean IsTaxIncluded)
{
set_Value (COLUMNNAME_IsTaxIncluded, Boolean.valueOf(IsTaxIncluded));
}
/** Get Price includes Tax.
@return Tax is included in the price
*/
public boolean isTaxIncluded ()
{
Object oo = get_Value(COLUMNNAME_IsTaxIncluded);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Charge.java | 1 |
请完成以下Java代码 | private void notify(
final boolean ok,
final String subject,
final String summary,
final String logInfo,
final int adTableId,
final int recordId)
{
final Properties ctx = getCtx();
// notify supervisor if error
final INotificationBL notificationBL = Services.get(INotificationBL.class);
final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
final int adClientId = Env.getAD_Client_ID(ctx);
final int adOrgId = Env.getAD_Org_ID(ctx);
if (!ok)
{
if (sysConfigBL.getBooleanValue(SYSCONFIG_NOTIFY_ON_NOT_OK, false, adClientId, adOrgId))
{
final UserId supervisorId = m_model.getSupervisor_ID() > 0 ? UserId.ofRepoId(m_model.getSupervisor_ID()) : null;
if (supervisorId != null)
{
notificationBL.send(UserNotificationRequest.builder()
.recipientUserId(supervisorId)
.subjectADMessage(MSG_PROCESS_RUN_ERROR)
.contentPlain(summary + " " + logInfo)
.targetAction(TargetRecordAction.of(TableRecordReference.of(adTableId, recordId)))
.build());
}
}
}
else if (sysConfigBL.getBooleanValue(SYSCONFIG_NOTIFY_ON_OK, false, adClientId, adOrgId))
{
for (final UserId userId : m_model.getRecipientAD_User_IDs())
{
notificationBL.send(UserNotificationRequest.builder()
.recipientUserId(userId)
.subjectADMessage(MSG_PROCESS_OK)
.contentPlain(summary + " " + logInfo)
.targetAction(TargetRecordAction.of(TableRecordReference.of(adTableId, recordId)))
.build());
}
}
}
/**
* This implementation evaluated a cron pattern to do the scheduling. If the model's scheduling type is not "cron",
* then the super classe's scheduling is used instead.
*/
@Override
public void run()
{ | if (!X_AD_Scheduler.SCHEDULETYPE_CronSchedulingPattern.equals(m_model.getScheduleType()))
{
super.run();
return;
}
final String cronPattern = m_model.getCronPattern();
if (Check.isNotBlank(cronPattern) && SchedulingPattern.validate(cronPattern))
{
cronScheduler = new it.sauronsoftware.cron4j.Scheduler();
cronScheduler.schedule(cronPattern, () -> {
runNow();
final long next = predictor.nextMatchingTime();
setDateNextRun(new Timestamp(next));
});
predictor = new Predictor(cronPattern);
final long next = predictor.nextMatchingTime();
setDateNextRun(new Timestamp(next));
cronScheduler.start();
while (true)
{
if (!sleep())
{
cronScheduler.stop();
break;
}
else if (!cronScheduler.isStarted())
{
break;
}
}
}
else
{
super.run();
}
}
} // Scheduler | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\compiere\server\Scheduler.java | 1 |
请完成以下Java代码 | public void setM_CostType_ID (int M_CostType_ID)
{
if (M_CostType_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_CostType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_CostType_ID, Integer.valueOf(M_CostType_ID));
}
/** Get Kostenkategorie.
@return Type of Cost (e.g. Current, Plan, Future)
*/
@Override
public int getM_CostType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_CostType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** 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_M_CostType.java | 1 |
请完成以下Java代码 | protected TaskEntity getEntity() {
ensureNotNull("taskId", entityId);
TaskEntity task = commandContext
.getTaskManager()
.findTaskById(entityId);
ensureNotNull("task " + entityId + " doesn't exist", "task", task);
checkSetTaskVariables(task);
task.addCustomLifecycleListener(this);
return task;
}
@Override
protected void onSuccess(AbstractVariableScope scope) {
TaskEntity task = (TaskEntity) scope;
if (taskLocalVariablesUpdated) {
task.triggerUpdateEvent();
}
task.removeCustomLifecycleListener(this);
super.onSuccess(scope);
}
@Override
protected ExecutionEntity getContextExecution() {
return getEntity().getExecution();
}
protected void logVariableOperation(AbstractVariableScope scope) {
TaskEntity task = (TaskEntity) scope; | commandContext.getOperationLogManager().logVariableOperation(getLogEntryOperation(), null, task.getId(),
PropertyChange.EMPTY_CHANGE);
}
protected void checkSetTaskVariables(TaskEntity task) {
for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkUpdateTaskVariable(task);
}
}
protected void onLocalVariableChanged() {
taskLocalVariablesUpdated = true;
}
@Override
public void onCreate(VariableInstanceEntity variableInstance, AbstractVariableScope sourceScope) {
onLocalVariableChanged();
}
@Override
public void onDelete(VariableInstanceEntity variableInstance, AbstractVariableScope sourceScope) {
onLocalVariableChanged();
}
@Override
public void onUpdate(VariableInstanceEntity variableInstance, AbstractVariableScope sourceScope) {
onLocalVariableChanged();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SetTaskVariablesCmd.java | 1 |
请完成以下Java代码 | public ICompositeQueryUpdater<T> addAddValueToColumn(final String columnName, final BigDecimal valueToAdd, final IQueryFilter<T> onlyWhenFilter)
{
final IQueryUpdater<T> updater = new AddToColumnQueryUpdater<>(columnName, valueToAdd, onlyWhenFilter);
return addQueryUpdater(updater);
}
@Override
public boolean update(final T model)
{
boolean updated = false;
for (final IQueryUpdater<T> updater : queryUpdaters)
{
if (updater.update(model))
{
updated = true;
}
}
return updated;
}
@Override
public String getSql(final Properties ctx, final List<Object> params)
{
buildSql(ctx);
params.addAll(sqlParams);
return sql;
}
private void buildSql(final Properties ctx)
{
if (sqlBuilt)
{
return; | }
if (queryUpdaters.isEmpty())
{
throw new AdempiereException("Cannot build sql update query for an empty " + CompositeQueryUpdater.class);
}
final StringBuilder sql = new StringBuilder();
final List<Object> params = new ArrayList<>();
for (final IQueryUpdater<T> updater : queryUpdaters)
{
final ISqlQueryUpdater<T> sqlUpdater = (ISqlQueryUpdater<T>)updater;
final String sqlChunk = sqlUpdater.getSql(ctx, params);
if (Check.isEmpty(sqlChunk))
{
continue;
}
if (sql.length() > 0)
{
sql.append(", ");
}
sql.append(sqlChunk);
}
this.sql = sql.toString();
this.sqlParams = params;
this.sqlBuilt = true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\CompositeQueryUpdater.java | 1 |
请完成以下Java代码 | final class CompositeRfQResponsePublisher implements IRfQResponsePublisher
{
private static final Logger logger = LogManager.getLogger(CompositeRfQResponsePublisher.class);
private final CopyOnWriteArrayList<IRfQResponsePublisher> publishers = new CopyOnWriteArrayList<>();
private String _displayName; // lazy
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.addValue(publishers)
.toString();
}
@Override
public String getDisplayName()
{
if (_displayName == null)
{
final List<String> publisherNames = new ArrayList<>(publishers.size());
for (final IRfQResponsePublisher publisher : publishers)
{
publisherNames.add(publisher.getDisplayName());
}
_displayName = "composite["
+ Joiner.on(", ").skipNulls().join(publisherNames)
+ "]";
}
return _displayName;
}
@Override
public void publish(final RfQResponsePublisherRequest request)
{
Check.assumeNotNull(request, "request not null");
for (final IRfQResponsePublisher publisher : publishers)
{
try
{
publisher.publish(request);
onSuccess(publisher, request);
}
catch (final Exception ex)
{
onException(publisher, request, ex);
}
}
}
private void onSuccess(final IRfQResponsePublisher publisher, final RfQResponsePublisherRequest request)
{ | final ILoggable loggable = Loggables.get();
loggable.addLog("OK - " + publisher.getDisplayName() + ": " + request.getSummary());
}
private void onException(final IRfQResponsePublisher publisher, final RfQResponsePublisherRequest request, final Exception ex)
{
final ILoggable loggable = Loggables.get();
loggable.addLog("@Error@ - " + publisher.getDisplayName() + ": " + ex.getMessage());
logger.warn("Publishing failed: publisher={}, request={}", publisher, request, ex);
}
public void addRfQResponsePublisher(final IRfQResponsePublisher publisher)
{
Check.assumeNotNull(publisher, "publisher not null");
final boolean added = publishers.addIfAbsent(publisher);
if (!added)
{
logger.warn("Publisher {} was already added to {}", publisher, publishers);
return;
}
_displayName = null; // reset
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\impl\CompositeRfQResponsePublisher.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RedisServiceImpl implements RedisService {
@Autowired
private RedisTemplate redisTemplate;
/**
* 批量删除对应的value
*
* @param keys
*/
@Override
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量删除key
*
* @param pattern
*/
@Override
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0) {
redisTemplate.delete(keys);
}
}
/**
* 删除对应的value
*
* @param key
*/
@Override
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
@Override
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
*
* @param key
* @return
*/
@Override
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
@Override | public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
@Override
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Redis\src\main\java\com\gaoxi\redis\service\RedisServiceImpl.java | 2 |
请完成以下Java代码 | protected int hashCode(URL url) {
String protocol = url.getProtocol();
int hash = (protocol != null) ? protocol.hashCode() : 0;
String file = url.getFile();
int indexOfSeparator = file.indexOf(SEPARATOR);
if (indexOfSeparator == -1) {
return hash + file.hashCode();
}
String fileWithoutEntry = file.substring(0, indexOfSeparator);
try {
hash += new URL(fileWithoutEntry).hashCode();
}
catch (MalformedURLException ex) {
hash += fileWithoutEntry.hashCode();
}
String entry = file.substring(indexOfSeparator + 2);
return hash + entry.hashCode();
}
@Override
protected boolean sameFile(URL url1, URL url2) {
if (!url1.getProtocol().equals(PROTOCOL) || !url2.getProtocol().equals(PROTOCOL)) {
return false;
}
String file1 = url1.getFile();
String file2 = url2.getFile();
int indexOfSeparator1 = file1.indexOf(SEPARATOR);
int indexOfSeparator2 = file2.indexOf(SEPARATOR);
if (indexOfSeparator1 == -1 || indexOfSeparator2 == -1) {
return super.sameFile(url1, url2);
}
String entry1 = file1.substring(indexOfSeparator1 + 2);
String entry2 = file2.substring(indexOfSeparator2 + 2);
if (!entry1.equals(entry2)) {
return false;
}
try {
URL innerUrl1 = new URL(file1.substring(0, indexOfSeparator1));
URL innerUrl2 = new URL(file2.substring(0, indexOfSeparator2));
if (!super.sameFile(innerUrl1, innerUrl2)) {
return false;
}
}
catch (MalformedURLException unused) {
return super.sameFile(url1, url2);
}
return true; | }
static int indexOfSeparator(String spec) {
return indexOfSeparator(spec, 0, spec.length());
}
static int indexOfSeparator(String spec, int start, int limit) {
for (int i = limit - 1; i >= start; i--) {
if (spec.charAt(i) == '!' && (i + 1) < limit && spec.charAt(i + 1) == '/') {
return i;
}
}
return -1;
}
/**
* Clear any internal caches.
*/
public static void clearCache() {
JarUrlConnection.clearCache();
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\jar\Handler.java | 1 |
请完成以下Java代码 | default Comparable<?> getFieldValueAsComparable(@NonNull final String fieldName, final JSONOptions jsonOpts)
{
return getFieldNameAndJsonValues().getAsComparable(fieldName, jsonOpts);
}
default boolean isFieldEmpty(@NonNull final String fieldName) {return getFieldNameAndJsonValues().isEmpty(fieldName);}
default Map<String, DocumentFieldWidgetType> getWidgetTypesByFieldName()
{
return ImmutableMap.of();
}
default Map<String, ViewEditorRenderMode> getViewEditorRenderModeByFieldName()
{
return ImmutableMap.of();
}
//
// Included documents (children)
// @formatter:off
default Collection<? extends IViewRow> getIncludedRows() { return ImmutableList.of(); }
// @formatter:on
//
// Attributes
// @formatter:off
default boolean hasAttributes() { return false; }
default IViewRowAttributes getAttributes() { throw new EntityNotFoundException("Row does not support attributes"); }
// @formatter:on
//
// IncludedView
// @formatter:off
default ViewId getIncludedViewId() { return null; } | // @formatter:on
//
// Single column row
// @formatter:off
/** @return true if frontend shall display one single column */
default boolean isSingleColumn() { return false; }
/** @return text to be displayed if {@link #isSingleColumn()} */
default ITranslatableString getSingleColumnCaption() { return TranslatableStrings.empty(); }
// @formatter:on
/**
* @return a stream of given row and all it's included rows recursively
*/
default Stream<IViewRow> streamRecursive()
{
return this.getIncludedRows()
.stream()
.map(IViewRow::streamRecursive)
.reduce(Stream.of(this), Stream::concat);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\IViewRow.java | 1 |
请完成以下Java代码 | public Map<String, String> createEmptyMapUsingMapsObject() {
Map<String, String> emptyMap = Maps.newHashMap();
return emptyMap;
}
public Map createGenericEmptyMapUsingGuavaMapsObject() {
Map genericEmptyMap = Maps.<String, Integer>newHashMap();
return genericEmptyMap;
}
public static Map<String, String> createMapUsingGuava() {
Map<String, String> emptyMapUsingGuava =
Maps.newHashMap(ImmutableMap.of());
return emptyMapUsingGuava;
}
public static Map<String, String> createImmutableMapUsingGuava() { | Map<String, String> emptyImmutableMapUsingGuava = ImmutableMap.of();
return emptyImmutableMapUsingGuava;
}
public SortedMap<String, String> createEmptySortedMap() {
SortedMap<String, String> sortedMap = Collections.emptySortedMap();
return sortedMap;
}
public NavigableMap<String, String> createEmptyNavigableMap() {
NavigableMap<String, String> navigableMap = Collections.emptyNavigableMap();
return navigableMap;
}
} | repos\tutorials-master\core-java-modules\core-java-collections-maps-3\src\main\java\com\baeldung\map\emptymap\EmptyMapInitializer.java | 1 |
请完成以下Java代码 | public int getC_Cycle_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Cycle_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Cycle Step.
@param C_CycleStep_ID
The step for this Cycle
*/
public void setC_CycleStep_ID (int C_CycleStep_ID)
{
if (C_CycleStep_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_CycleStep_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_CycleStep_ID, Integer.valueOf(C_CycleStep_ID));
}
/** Get Cycle Step.
@return The step for this Cycle
*/
public int getC_CycleStep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_CycleStep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Relative Weight.
@param RelativeWeight
Relative weight of this step (0 = ignored)
*/
public void setRelativeWeight (BigDecimal RelativeWeight)
{
set_Value (COLUMNNAME_RelativeWeight, RelativeWeight);
} | /** Get Relative Weight.
@return Relative weight of this step (0 = ignored)
*/
public BigDecimal getRelativeWeight ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RelativeWeight);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CycleStep.java | 1 |
请完成以下Java代码 | public void setJitter(@Nullable Duration jitter) {
this.jitter = jitter;
}
/**
* Return the value to multiply the current interval by for each attempt. The default
* value, {@code 1.0}, effectively results in a fixed delay.
* @return the value to multiply the current interval by for each attempt
* @see #DEFAULT_MULTIPLIER
*/
public Double getMultiplier() {
return this.multiplier;
}
/**
* Specify a multiplier for a delay for the next retry attempt.
* @param multiplier value to multiply the current interval by for each attempt (must
* be greater than or equal to 1)
*/
public void setMultiplier(Double multiplier) {
this.multiplier = multiplier;
}
/**
* Return the maximum delay for any retry attempt.
* @return the maximum delay
*/
public Duration getMaxDelay() {
return this.maxDelay;
}
/**
* Specify the maximum delay for any retry attempt, limiting how far
* {@linkplain #getJitter() jitter} and the {@linkplain #getMultiplier() multiplier}
* can increase the {@linkplain #getDelay() delay}. | * <p>
* The default is unlimited.
* @param maxDelay the maximum delay (must be positive)
* @see #DEFAULT_MAX_DELAY
*/
public void setMaxDelay(Duration maxDelay) {
this.maxDelay = maxDelay;
}
/**
* Set the factory to use to create the {@link RetryPolicy}, or {@code null} to use
* the default. The function takes a {@link Builder RetryPolicy.Builder} initialized
* with the state of this instance that can be further configured, or ignored to
* restart from scratch.
* @param factory a factory to customize the retry policy.
*/
public void setFactory(@Nullable Function<RetryPolicy.Builder, RetryPolicy> factory) {
this.factory = factory;
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\retry\RetryPolicySettings.java | 1 |
请完成以下Java代码 | public class HttpResponseImpl extends AbstractCloseableConnectorResponse implements HttpResponse {
private static final HttpConnectorLogger LOG = HttpLogger.HTTP_LOGGER;
protected ClassicHttpResponse httpResponse;
public HttpResponseImpl(ClassicHttpResponse httpResponse) {
this.httpResponse = httpResponse;
}
public Integer getStatusCode() {
return getResponseParameter(PARAM_NAME_STATUS_CODE);
}
public String getResponse() {
return getResponseParameter(PARAM_NAME_RESPONSE);
}
public Map<String, String> getHeaders() {
return getResponseParameter(PARAM_NAME_RESPONSE_HEADERS);
}
public String getHeader(String field) {
Map<String, String> headers = getHeaders();
if (headers != null) {
return headers.get(field);
} else {
return null;
}
} | protected void collectResponseParameters(Map<String, Object> responseParameters) {
responseParameters.put(PARAM_NAME_STATUS_CODE, httpResponse.getCode());
collectResponseHeaders();
if (httpResponse.getEntity() != null) {
try {
String response = IoUtil.inputStreamAsString(httpResponse.getEntity().getContent());
responseParameters.put(PARAM_NAME_RESPONSE, response);
} catch (IOException e) {
throw LOG.unableToReadResponse(e);
} finally {
IoUtil.closeSilently(httpResponse);
}
}
}
protected void collectResponseHeaders() {
Map<String, String> headers = new HashMap<>();
for (Header header : httpResponse.getHeaders()) {
headers.put(header.getName(), header.getValue());
}
responseParameters.put(PARAM_NAME_RESPONSE_HEADERS, headers);
}
protected Closeable getClosable() {
return httpResponse;
}
} | repos\camunda-bpm-platform-master\connect\http-client\src\main\java\org\camunda\connect\httpclient\impl\HttpResponseImpl.java | 1 |
请完成以下Java代码 | public double score(int[] featureVector, int currentTag)
{
double score = 0;
for (int index : featureVector)
{
if (index == -1)
{
continue;
}
else if (index < -1 || index >= featureMap.size())
{
throw new IllegalArgumentException("在打分时传入了非法的下标");
}
else
{
index = index * featureMap.tagSet.size() + currentTag;
score += parameter[index]; // 其实就是特征权重的累加
}
}
return score;
}
/**
* 加载模型
*
* @param modelFile
* @throws IOException
*/
public void load(String modelFile) throws IOException
{
if (HanLP.Config.DEBUG)
ConsoleLogger.logger.start("加载 %s ... ", modelFile);
ByteArrayStream byteArray = ByteArrayStream.createByteArrayStream(modelFile);
if (!load(byteArray))
{
throw new IOException(String.format("%s 加载失败", modelFile));
}
if (HanLP.Config.DEBUG)
ConsoleLogger.logger.finish(" 加载完毕\n");
}
public TagSet tagSet()
{
return featureMap.tagSet;
}
@Override
public void save(DataOutputStream out) throws IOException
{
if (!(featureMap instanceof ImmutableFeatureMDatMap)) | {
featureMap = new ImmutableFeatureMDatMap(featureMap.entrySet(), tagSet());
}
featureMap.save(out);
for (float aParameter : this.parameter)
{
out.writeFloat(aParameter);
}
}
@Override
public boolean load(ByteArray byteArray)
{
if (byteArray == null)
return false;
featureMap = new ImmutableFeatureMDatMap();
featureMap.load(byteArray);
int size = featureMap.size();
TagSet tagSet = featureMap.tagSet;
if (tagSet.type == TaskType.CLASSIFICATION)
{
parameter = new float[size];
for (int i = 0; i < size; i++)
{
parameter[i] = byteArray.nextFloat();
}
}
else
{
parameter = new float[size * tagSet.size()];
for (int i = 0; i < size; i++)
{
for (int j = 0; j < tagSet.size(); ++j)
{
parameter[i * tagSet.size() + j] = byteArray.nextFloat();
}
}
}
// assert !byteArray.hasMore();
// byteArray.close();
if (!byteArray.hasMore())
byteArray.close();
return true;
}
public TaskType taskType()
{
return featureMap.tagSet.type;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\model\LinearModel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class User {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private Integer age;
public User(){}
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) { | this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
} | repos\SpringBoot-Learning-master\1.x\Chapter3-2-2\src\main\java\com\didispace\domain\User.java | 2 |
请完成以下Java代码 | public Object intercept(Invocation invocation) throws Throwable {
final List<Object> results = (List<Object>) invocation.proceed();
if (results.isEmpty()) {
return results;
}
final ResultSetHandler statementHandler = PluginUtils.realTarget(invocation.getTarget());
final MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
final MappedStatement mappedStatement = (MappedStatement) metaObject.getValue(MAPPED_STATEMENT);
final ResultMap resultMap = mappedStatement.getResultMaps().isEmpty() ? null : mappedStatement.getResultMaps().get(0);
Object result = results.get(0);
CryptEntity cryptEntity = result.getClass().getAnnotation(CryptEntity.class);
if (cryptEntity == null || resultMap == null) {
return results;
}
List<String> cryptFieldList = getCryptField(resultMap);
log.info("CryptReadInterceptor cryptFieldList: {}", cryptFieldList);
cryptFieldList.forEach(item -> {
results.forEach(x -> {
MetaObject objMetaObject = SystemMetaObject.forObject(x);
Object value = objMetaObject.getValue(item);
if (Objects.nonNull(value)) {
objMetaObject.setValue(item, encrypt.decrypt(value.toString()));
}
});
});
return results;
}
/**
* 获取需要加密的属性
*
* @param resultMap
* @return
*/
private List<String> getCryptField(ResultMap resultMap) {
Class<?> clazz = resultMap.getType();
log.info("clazz: {}", clazz); | List<String> fieldList = ENTITY_FILED_ANN_MAP.get(clazz.getName());
if (Objects.isNull(fieldList)) {
fieldList = new ArrayList<>();
for (Field declaredField : clazz.getDeclaredFields()) {
CryptField cryptField = declaredField.getAnnotation(CryptField.class);
if (cryptField != null) {
fieldList.add(declaredField.getName());
}
}
ENTITY_FILED_ANN_MAP.put(clazz.getName(), fieldList);
}
return fieldList;
}
@Override
public Object plugin(Object target) {
if (target instanceof ResultSetHandler) {
return Plugin.wrap(target, this);
}
return target;
}
@Override
public void setProperties(Properties properties) {
}
} | repos\spring-boot-quick-master\mybatis-crypt-plugin\src\main\java\com\quick\db\crypt\intercept\CryptReadInterceptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class EmbeddedDatabaseCondition extends SpringBootCondition {
private static final String DATASOURCE_URL_PROPERTY = "spring.datasource.url";
private static final String EMBEDDED_DATABASE_TYPE = "org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType";
private final SpringBootCondition pooledCondition = new PooledDataSourceCondition();
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConditionMessage.Builder message = ConditionMessage.forCondition("EmbeddedDataSource");
if (hasDataSourceUrlProperty(context)) {
return ConditionOutcome.noMatch(message.because(DATASOURCE_URL_PROPERTY + " is set"));
}
if (anyMatches(context, metadata, this.pooledCondition)) {
return ConditionOutcome.noMatch(message.foundExactly("supported pooled data source"));
}
if (!ClassUtils.isPresent(EMBEDDED_DATABASE_TYPE, context.getClassLoader())) {
return ConditionOutcome
.noMatch(message.didNotFind("required class").items(Style.QUOTE, EMBEDDED_DATABASE_TYPE));
}
EmbeddedDatabaseType type = EmbeddedDatabaseConnection.get(context.getClassLoader()).getType();
if (type == null) { | return ConditionOutcome.noMatch(message.didNotFind("embedded database").atAll());
}
return ConditionOutcome.match(message.found("embedded database").items(type));
}
private boolean hasDataSourceUrlProperty(ConditionContext context) {
Environment environment = context.getEnvironment();
if (environment.containsProperty(DATASOURCE_URL_PROPERTY)) {
try {
return StringUtils.hasText(environment.getProperty(DATASOURCE_URL_PROPERTY));
}
catch (IllegalArgumentException ex) {
// NOTE: This should be PlaceholderResolutionException
// Ignore unresolvable placeholder errors
}
}
return false;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\DataSourceAutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setBankAccountOwner(String value) {
this.bankAccountOwner = value;
}
/**
*
* The creditor ID of the SEPA direct debit.
*
*
* @return
* possible object is
* {@link String }
*
*/
public String getCreditorID() {
return creditorID;
}
/**
* Sets the value of the creditorID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCreditorID(String value) {
this.creditorID = value;
}
/**
*
* The mandate reference of the SEPA direct debit.
*
*
* @return
* possible object is
* {@link String }
*
*/
public String getMandateReference() {
return mandateReference;
}
/**
* Sets the value of the mandateReference property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMandateReference(String value) {
this.mandateReference = value;
}
/** | *
* The debit collection date.
*
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getDebitCollectionDate() {
return debitCollectionDate;
}
/**
* Sets the value of the debitCollectionDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setDebitCollectionDate(XMLGregorianCalendar value) {
this.debitCollectionDate = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\SEPADirectDebitType.java | 2 |
请完成以下Java代码 | public final void closeOnCompletion() throws SQLException
{
getStatementImpl().closeOnCompletion();
}
@Override
public final boolean isCloseOnCompletion() throws SQLException
{
return getStatementImpl().isCloseOnCompletion();
}
@Override
public final String getSql()
{
return this.vo.getSql();
}
protected final String convertSqlAndSet(final String sql)
{
final String sqlConverted = DB.getDatabase().convertStatement(sql);
vo.setSql(sqlConverted);
MigrationScriptFileLoggerHolder.logMigrationScript(sql);
return sqlConverted;
}
@Override
public final void commit() throws SQLException
{
if (this.ownedConnection != null && !this.ownedConnection.getAutoCommit())
{
this.ownedConnection.commit();
}
}
@Nullable | private static Trx getTrx(@NonNull final CStatementVO vo)
{
final ITrxManager trxManager = Services.get(ITrxManager.class);
final String trxName = vo.getTrxName();
if (trxManager.isNull(trxName))
{
return (Trx)ITrx.TRX_None;
}
else
{
final ITrx trx = trxManager.get(trxName, false); // createNew=false
// NOTE: we assume trx if of type Trx because we need to invoke getConnection()
return (Trx)trx;
}
}
@Override
public String toString()
{
return "AbstractCStatementProxy [ownedConnection=" + this.ownedConnection + ", closed=" + closed + ", p_vo=" + vo + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\sql\impl\AbstractCStatementProxy.java | 1 |
请完成以下Java代码 | public static byte[] readBytes(@NonNull final Resource resource)
{
try
{
return readBytes(resource.getInputStream());
}
catch (IOException e)
{
throw new AdempiereException("Error reading stream", e);
}
}
// metas: 03749
public static String encodeBase64(final byte[] b)
{
return BaseEncoding.base64().encode(b);
}
// metas: 03749
public static byte[] decodeBase64(final String str)
{
return BaseEncoding.base64().decode(str);
}
// 03743
public static void writeBytes(final File file, final byte[] data)
{
FileOutputStream out = null;
try
{
out = new FileOutputStream(file, false);
out.write(data);
}
catch (final IOException e)
{
throw new AdempiereException("Cannot write file " + file + "."
+ "\n " + e.getLocalizedMessage() // also append the original error message because it could be helpful for user.
, e);
}
finally
{
if (out != null)
{
close(out);
out = null;
}
}
}
public static final void close(Closeable c)
{
try
{
c.close();
}
catch (final IOException e)
{
// e.printStackTrace();
}
}
/**
* Writes the given {@link Throwable}s stack trace into a string.
*
* @param e
* @return
*/
public static String dumpStackTraceToString(Throwable e)
{
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return sw.toString();
} | /**
* Smart converting given exception to string
*
* @param e
* @return
*/
public static String getErrorMsg(Throwable e)
{
// save the exception for displaying to user
String msg = e.getLocalizedMessage();
if (Check.isEmpty(msg, true))
{
msg = e.getMessage();
}
if (Check.isEmpty(msg, true))
{
// note that e.g. a NullPointerException doesn't have a nice message
msg = dumpStackTraceToString(e);
}
return msg;
}
public static String replaceNonDigitCharsWithZero(String stringToModify)
{
final int size = stringToModify.length();
final StringBuilder stringWithZeros = new StringBuilder();
for (int i = 0; i < size; i++)
{
final char currentChar = stringToModify.charAt(i);
if (!Character.isDigit(currentChar))
{
stringWithZeros.append('0');
}
else
{
stringWithZeros.append(currentChar);
}
}
return stringWithZeros.toString();
}
public static int getMinimumOfThree(final int no1, final int no2, final int no3)
{
return no1 < no2 ? (no1 < no3 ? no1 : no3) : (no2 < no3 ? no2 : no3);
}
} // Util | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Util.java | 1 |
请完成以下Java代码 | private static ImmutableSet<AdUISectionId> extractUISectionIds(final Collection<I_AD_UI_Section> uiSections)
{
return uiSections.stream().map(DAOWindowUIElementsProvider::extractUISectionId).distinct().collect(ImmutableSet.toImmutableSet());
}
private static AdUISectionId extractUISectionId(final I_AD_UI_Section from) {return AdUISectionId.ofRepoId(from.getAD_UI_Section_ID());}
private ImmutableSet<AdUIColumnId> extractUIColumnIds(final Collection<I_AD_UI_Column> uiColumns)
{
return uiColumns.stream().map(DAOWindowUIElementsProvider::extractUIColumnId).distinct().collect(ImmutableSet.toImmutableSet());
}
private static AdUIColumnId extractUIColumnId(final I_AD_UI_Column from) {return AdUIColumnId.ofRepoId(from.getAD_UI_Column_ID());}
private static AdUISectionId extractUISectionId(final I_AD_UI_Column from) {return AdUISectionId.ofRepoId(from.getAD_UI_Section_ID());}
private static AdUIColumnId extractUIColumnId(final I_AD_UI_ElementGroup from) {return AdUIColumnId.ofRepoId(from.getAD_UI_Column_ID());}
private ImmutableSet<AdUIElementGroupId> extractUIElementGroupIds(final Collection<I_AD_UI_ElementGroup> froms) | {
return froms.stream().map(DAOWindowUIElementsProvider::extractUIElementGroupId).distinct().collect(ImmutableSet.toImmutableSet());
}
private static AdUIElementGroupId extractUIElementGroupId(final I_AD_UI_ElementGroup from) {return AdUIElementGroupId.ofRepoId(from.getAD_UI_ElementGroup_ID());}
private static AdUIElementGroupId extractUIElementGroupId(final I_AD_UI_Element from) {return AdUIElementGroupId.ofRepoId(from.getAD_UI_ElementGroup_ID());}
private static AdTabId extractTabId(final I_AD_UI_Element from) {return AdTabId.ofRepoId(from.getAD_Tab_ID());}
private ImmutableSet<AdUIElementId> extractUIElementIds(final Collection<I_AD_UI_Element> froms)
{
return froms.stream().map(DAOWindowUIElementsProvider::extractUIElementId).distinct().collect(ImmutableSet.toImmutableSet());
}
private static AdUIElementId extractUIElementId(final I_AD_UI_Element from) {return AdUIElementId.ofRepoId(from.getAD_UI_Element_ID());}
private static AdUIElementId extractUIElementId(final I_AD_UI_ElementField from) {return AdUIElementId.ofRepoId(from.getAD_UI_Element_ID());}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\standard\DAOWindowUIElementsProvider.java | 1 |
请完成以下Java代码 | public final class RtState implements State {
private List<Transition> transitions;
private boolean isFinal;
public RtState() {
this(false);
}
public RtState(final boolean isFinal) {
this.transitions = new ArrayList<>();
this.isFinal = isFinal;
}
public State transit(final CharSequence c) {
return transitions
.stream()
.filter(t -> t.isPossible(c)) | .map(Transition::state)
.findAny()
.orElseThrow(() -> new IllegalArgumentException("Input not accepted: " + c));
}
public boolean isFinal() {
return this.isFinal;
}
@Override
public State with(Transition tr) {
this.transitions.add(tr);
return this;
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-3\src\main\java\com\baeldung\algorithms\automata\RtState.java | 1 |
请完成以下Java代码 | public class SendMessage implements Serializable {
private static final long serialVersionUID = -4731326195678504565L;
/**
* ID
*/
private long id;
/**
* 名称
*/
private String name;
/**
* 年龄
*/
private int age;
public long getId() {
return id;
} | public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
} | repos\spring-boot-student-master\spring-boot-student-rabbitmq\src\main\java\com\xiaolyuh\mq\message\SendMessage.java | 1 |
请完成以下Java代码 | public class RedissonConfiguration {
@Value("${spring.redis.host}")
private String redisHost;
@Value("${spring.redis.port}")
private int redisPort;
@Value("${spring.redis.database}")
private int redisDatabase;
@Value("${spring.redis.password:}")
private String redisPassword;
@Value("${spring.redis.timeout:5000}")
private int timeout;
@Value("${spring.redis.lettuce.pool.max-active:64}")
private int connectionPoolSize;
@Value("${spring.redis.lettuce.pool.min-idle:16}")
private int connectionMinimumIdleSize; | @Bean
public RedissonClient redissonClient() {
Config config = new Config();
config.useSingleServer()
.setAddress("redis://" + redisHost + ":" + redisPort)
.setDatabase(redisDatabase)
.setTimeout(timeout)
.setConnectionPoolSize(connectionPoolSize)
.setConnectionMinimumIdleSize(connectionMinimumIdleSize);
if(StrUtil.isNotBlank(redisPassword)){
config.useSingleServer().setPassword(redisPassword);
}
return Redisson.create(config);
}
} | repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\config\RedissonConfiguration.java | 1 |
请完成以下Java代码 | public Optional<Money> getProfitBasePrice(@NonNull final OrderAndLineId orderLineId)
{
return getProfitMinBasePrice(ImmutableList.of(orderLineId));
}
/**
* Gets the minimum {@link I_C_OrderLine#getPriceGrossProfit()}, more or less
*/
public Optional<Money> getProfitMinBasePrice(@NonNull final Collection<OrderAndLineId> orderAndLineIds)
{
if (orderAndLineIds.isEmpty())
{
return Optional.empty();
}
final ImmutableSet<Money> profitBasePrices = ordersRepo.getOrderLinesByIds(orderAndLineIds, I_C_OrderLine.class)
.stream()
.map(this::getProfitBasePrice)
.collect(ImmutableSet.toImmutableSet());
if (profitBasePrices.isEmpty())
{
return Optional.empty(); | }
else if (profitBasePrices.size() == 1)
{
return Optional.of(profitBasePrices.iterator().next());
}
else if (!Money.isSameCurrency(profitBasePrices))
{
return Optional.empty();
}
else
{
return profitBasePrices.stream().reduce(Money::min);
}
}
private Money getProfitBasePrice(@NonNull final I_C_OrderLine orderLineRecord)
{
final CurrencyId currencyId = CurrencyId.ofRepoId(orderLineRecord.getC_Currency_ID());
return Money.of(orderLineRecord.getProfitPriceActual(), currencyId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\grossprofit\OrderLineWithGrossProfitPriceRepository.java | 1 |
请完成以下Java代码 | public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getDatePublished() { | return datePublished;
}
public void setDatePublished(String datePublished) {
this.datePublished = datePublished;
}
public int getWordCount() {
return wordCount;
}
public void setWordCount(int wordCount) {
this.wordCount = wordCount;
}
} | repos\tutorials-master\vertx-modules\vertx\src\main\java\com\baeldung\model\Article.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MultiMethodKafkaListenerEndpoint<K, V> extends MethodKafkaListenerEndpoint<K, V> {
private List<Method> methods;
private @Nullable Method defaultMethod;
private @Nullable Validator validator;
/**
* Construct an instance for the provided methods, default method and bean.
* @param methods the methods.
* @param defaultMethod the default method.
* @param bean the bean.
* @since 2.1.3
*/
@SuppressWarnings("this-escape")
public MultiMethodKafkaListenerEndpoint(List<Method> methods, @Nullable Method defaultMethod, Object bean) {
this.methods = methods;
this.defaultMethod = defaultMethod;
setBean(bean);
}
/**
* Get a method list.
* @return the method list.
* @since 3.2
*/
public List<Method> getMethods() {
return this.methods;
}
/**
* Set a method list.
* @param methods the methods.
* @since 3.2
*/
public void setMethods(List<Method> methods) {
this.methods = methods;
}
/**
* Get a default method.
* @return the default method.
* @since 3.2
*/
public @Nullable Method getDefaultMethod() {
return this.defaultMethod;
}
/**
* Set a default method.
* @param defaultMethod the default method.
* @since 3.2
*/
public void setDefaultMethod(@Nullable Method defaultMethod) {
this.defaultMethod = defaultMethod;
}
/**
* Set a payload validator. | * @param validator the validator.
* @since 2.5.11
*/
public void setValidator(Validator validator) {
this.validator = validator;
}
@Override
protected HandlerAdapter configureListenerAdapter(MessagingMessageListenerAdapter<K, V> messageListener) {
List<InvocableHandlerMethod> invocableHandlerMethods = new ArrayList<>();
InvocableHandlerMethod defaultHandler = null;
for (Method method : this.methods) {
MessageHandlerMethodFactory messageHandlerMethodFactory = getMessageHandlerMethodFactory();
if (messageHandlerMethodFactory != null) {
InvocableHandlerMethod handler = messageHandlerMethodFactory
.createInvocableHandlerMethod(getBean(), method);
invocableHandlerMethods.add(handler);
if (method.equals(this.defaultMethod)) {
defaultHandler = handler;
}
}
}
DelegatingInvocableHandler delegatingHandler = new DelegatingInvocableHandler(invocableHandlerMethods,
defaultHandler, getBean(), getResolver(), getBeanExpressionContext(), getBeanFactory(), this.validator);
return new HandlerAdapter(delegatingHandler);
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\config\MultiMethodKafkaListenerEndpoint.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setName(final String name)
{
this.name = name;
}
public String getName(final Locale locale)
{
final ProductTrl productTrl = TranslationHelper.getTranslation(translations, locale);
if (productTrl != null)
{
return productTrl.getName();
}
return name;
}
public void setPackingInfo(@Nullable final String packingInfo)
{
this.packingInfo = packingInfo; | }
@Nullable
public String getPackingInfo(final Locale locale)
{
return packingInfo;
}
public void setShared(final boolean shared)
{
this.shared = shared;
}
public boolean isShared()
{
return shared;
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\Product.java | 2 |
请完成以下Java代码 | public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address; | }
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Customer{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", address=" + address +
'}';
}
} | repos\tutorials-master\spring-web-modules\spring-rest-http-3\src\main\java\com\baeldung\bulkandbatchapi\request\Customer.java | 1 |
请完成以下Java代码 | public void closeIt(final DocumentTableFields docFields)
{
final I_C_RfQ rfq = extractRfQ(docFields);
//
rfqEventDispacher.fireBeforeClose(rfq);
//
// Mark as closed
rfq.setDocStatus(X_C_RfQ.DOCSTATUS_Closed);
rfq.setDocAction(X_C_RfQ.DOCACTION_None);
rfq.setProcessed(true);
rfq.setIsRfQResponseAccepted(false);
InterfaceWrapperHelper.save(rfq);
//
// Close RfQ Responses
for (final I_C_RfQResponse rfqResponse : rfqDAO.retrieveAllResponses(rfq))
{
if (!rfqBL.isDraft(rfqResponse))
{
continue;
}
rfqBL.complete(rfqResponse);
}
//
rfqEventDispacher.fireAfterClose(rfq);
// Make sure it's saved
InterfaceWrapperHelper.save(rfq);
}
@Override
public void unCloseIt(final DocumentTableFields docFields)
{
final I_C_RfQ rfq = extractRfQ(docFields);
//
rfqEventDispacher.fireBeforeUnClose(rfq);
//
// Mark as completed
rfq.setDocStatus(X_C_RfQ.DOCSTATUS_Completed);
rfq.setDocAction(X_C_RfQ.DOCACTION_Close);
InterfaceWrapperHelper.save(rfq);
//
// UnClose RfQ Responses
for (final I_C_RfQResponse rfqResponse : rfqDAO.retrieveAllResponses(rfq))
{
if (!rfqBL.isClosed(rfqResponse))
{
continue;
}
rfqBL.unclose(rfqResponse);
}
//
rfqEventDispacher.fireAfterUnClose(rfq);
// Make sure it's saved
InterfaceWrapperHelper.save(rfq);
}
@Override
public void reverseCorrectIt(final DocumentTableFields docFields) | {
throw new UnsupportedOperationException();
}
@Override
public void reverseAccrualIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
@Override
public void reactivateIt(final DocumentTableFields docFields)
{
final I_C_RfQ rfq = extractRfQ(docFields);
//
// Void and delete all responses
for (final I_C_RfQResponse rfqResponse : rfqDAO.retrieveAllResponses(rfq))
{
voidAndDelete(rfqResponse);
}
rfq.setIsRfQResponseAccepted(false);
rfq.setDocAction(IDocument.ACTION_Complete);
rfq.setProcessed(false);
}
private void voidAndDelete(final I_C_RfQResponse rfqResponse)
{
// Prevent deleting/voiding an already closed RfQ response
if (rfqBL.isClosed(rfqResponse))
{
throw new RfQDocumentClosedException(rfqBL.getSummary(rfqResponse));
}
// TODO: FRESH-402 shall we throw exception if the rfqResponse was published?
rfqResponse.setProcessed(false);
InterfaceWrapperHelper.delete(rfqResponse);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\RfQDocumentHandler.java | 1 |
请完成以下Java代码 | private boolean checkShippingCompleted() {
return shipping.status() == ShippingStatus.DELIVERED || shipping.status() == ShippingStatus.RETURNED;
}
@Override
public void paymentAuthorized(String transactionId, String authorizationId) {
log.info("[I116] Payment authorized: transactionId={}, authorizationId={}", transactionId, authorizationId);
Workflow.await(() -> payment != null);
payment = new PaymentAuthorization(
payment.info(),
PaymentStatus.APPROVED,
payment.orderId(),
transactionId,
authorizationId,
null
);
}
@Override
public void paymentDeclined(String transactionId, String cause) {
log.info("[I116] Payment declined: transactionId={}, cause={}", transactionId, cause);
Workflow.await(() -> payment != null);
payment = new PaymentAuthorization(
payment.info(),
PaymentStatus.DECLINED,
payment.orderId(),
transactionId,
null,
cause
);
}
@Override
public void packagePickup(Instant pickupTime) {
Workflow.await(() -> shipping != null);
shipping = shipping.toStatus(ShippingStatus.SHIPPED, pickupTime, "Package picked up");
}
@Override
public void packageDelivered(Instant pickupTime) {
Workflow.await(() -> shipping != null);
shipping = shipping.toStatus(ShippingStatus.DELIVERED, pickupTime, "Package delivered");
}
@Override
public void packageReturned(Instant pickupTime) {
shipping = shipping.toStatus(ShippingStatus.RETURNED, pickupTime, "Package returned"); | }
@Override
public Order getOrder() {
return order;
}
@Override
public Shipping getShipping() {
return shipping;
}
@Override
public PaymentAuthorization getPayment() {
return payment;
}
@Override
public RefundRequest getRefund() {
return refund;
}
} | repos\tutorials-master\saas-modules\temporal\src\main\java\com\baeldung\temporal\workflows\sboot\order\workflow\OrderWorkflowImpl.java | 1 |
请完成以下Java代码 | public void setQuery(String query) {
this.query = query;
}
/**
* Return the validation query or {@code null}.
* @return the query
*/
public @Nullable String getQuery() {
return this.query;
}
/**
* {@link RowMapper} that expects and returns results from a single column.
*/
private static final class SingleColumnRowMapper implements RowMapper<Object> { | @Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
if (columns != 1) {
throw new IncorrectResultSetColumnCountException(1, columns);
}
Object result = JdbcUtils.getResultSetValue(rs, 1);
Assert.state(result != null, "'result' must not be null");
return result;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\health\DataSourceHealthIndicator.java | 1 |
请完成以下Java代码 | protected InputStream applyResourceOverrides(String file, InputStream assetStream) {
// use a copy of the list cause it could be modified during iteration
List<PluginResourceOverride> resourceOverrides = new ArrayList<PluginResourceOverride>(runtimeDelegate.getResourceOverrides());
for (PluginResourceOverride pluginResourceOverride : resourceOverrides) {
assetStream = pluginResourceOverride.filterResource(assetStream, new RequestInfo(headers, servletContext, uriInfo));
}
return assetStream;
}
protected String getContentType(String file) {
if (file.endsWith(".js")) {
return MIME_TYPE_TEXT_JAVASCRIPT;
} else
if (file.endsWith(".html")) {
return MIME_TYPE_TEXT_HTML;
} else
if (file.endsWith(".css")) {
return MIME_TYPE_TEXT_CSS;
} else {
return MIME_TYPE_TEXT_PLAIN;
}
}
/**
* Returns an input stream for a given resource
*
* @param resourceName
* @return
*/
protected InputStream getPluginAssetAsStream(AppPlugin plugin, String fileName) {
String assetDirectory = plugin.getAssetDirectory();
if (assetDirectory == null) {
return null; | }
InputStream result = getWebResourceAsStream(assetDirectory, fileName);
if (result == null) {
result = getClasspathResourceAsStream(plugin, assetDirectory, fileName);
}
return result;
}
protected InputStream getWebResourceAsStream(String assetDirectory, String fileName) {
String resourceName = String.format("/%s/%s", assetDirectory, fileName);
return servletContext.getResourceAsStream(resourceName);
}
protected InputStream getClasspathResourceAsStream(AppPlugin plugin, String assetDirectory, String fileName) {
String resourceName = String.format("%s/%s", assetDirectory, fileName);
return plugin.getClass().getClassLoader().getResourceAsStream(resourceName);
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\plugin\resource\AbstractAppPluginRootResource.java | 1 |
请完成以下Java代码 | protected String getSerializedStringValue(byte[] serializedByteValue) {
if(serializedByteValue != null) {
if(!isSerializationTextBased()) {
serializedByteValue = Base64.encodeBase64(serializedByteValue);
}
return StringUtil.fromBytes(serializedByteValue);
}
else {
return null;
}
}
protected byte[] getSerializedBytesValue(String serializedStringValue) {
if(serializedStringValue != null) {
byte[] serializedByteValue = StringUtil.toByteArray(serializedStringValue);
if (!isSerializationTextBased()) {
serializedByteValue = Base64.decodeBase64(serializedByteValue);
}
return serializedByteValue;
}
else {
return null;
}
}
protected boolean canWriteValue(TypedValue typedValue) {
if (!(typedValue instanceof SerializableValue) && !(typedValue instanceof UntypedValueImpl)) {
return false;
}
if (typedValue instanceof SerializableValue) {
SerializableValue serializableValue = (SerializableValue) typedValue;
String requestedDataFormat = serializableValue.getSerializationDataFormat();
if (!serializableValue.isDeserialized()) {
// serialized object => dataformat must match
return serializationDataFormat.equals(requestedDataFormat);
} else {
final boolean canSerialize = typedValue.getValue() == null || canSerializeValue(typedValue.getValue());
return canSerialize && (requestedDataFormat == null || serializationDataFormat.equals(requestedDataFormat));
}
} else {
return typedValue.getValue() == null || canSerializeValue(typedValue.getValue());
}
}
/** | * return true if this serializer is able to serialize the provided object.
*
* @param value the object to test (guaranteed to be a non-null value)
* @return true if the serializer can handle the object.
*/
protected abstract boolean canSerializeValue(Object value);
// methods to be implemented by subclasses ////////////
/**
* Implementations must return a byte[] representation of the provided object.
* The object is guaranteed not to be null.
*
* @param deserializedObject the object to serialize
* @return the byte array value of the object
* @throws exception in case the object cannot be serialized
*/
protected abstract byte[] serializeToByteArray(Object deserializedObject) throws Exception;
/**
* Deserialize the object from a byte array.
*
* @param object the object to deserialize
* @param valueFields the value fields
* @return the deserialized object
* @throws exception in case the object cannot be deserialized
*/
protected abstract Object deserializeFromByteArray(byte[] object, ValueFields valueFields) throws Exception;
/**
* Return true if the serialization is text based. Return false otherwise
*
*/
protected abstract boolean isSerializationTextBased();
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\serializer\AbstractSerializableValueSerializer.java | 1 |
请完成以下Java代码 | protected void scheduleTimers(ProcessDefinitionEntity processDefinition, Process process) {
JobManager jobManager = Context.getCommandContext().getJobManager();
List<TimerJobEntity> timers = getTimerDeclarations(processDefinition, process);
for (TimerJobEntity timer : timers) {
jobManager.scheduleTimerJob(timer);
}
}
protected List<TimerJobEntity> getTimerDeclarations(ProcessDefinitionEntity processDefinition, Process process) {
JobManager jobManager = Context.getCommandContext().getJobManager();
List<TimerJobEntity> timers = new ArrayList<TimerJobEntity>();
if (process != null && CollectionUtil.isNotEmpty(process.getFlowElements())) {
for (FlowElement element : process.getFlowElements()) {
if (element instanceof StartEvent) {
StartEvent startEvent = (StartEvent) element;
if (CollectionUtil.isNotEmpty(startEvent.getEventDefinitions())) {
EventDefinition eventDefinition = startEvent.getEventDefinitions().get(0);
if (eventDefinition instanceof TimerEventDefinition) {
TimerEventDefinition timerEventDefinition = (TimerEventDefinition) eventDefinition;
TimerJobEntity timerJob = jobManager.createTimerJob(
timerEventDefinition,
false,
null,
TimerStartEventJobHandler.TYPE,
TimerEventHandler.createConfiguration( | startEvent.getId(),
timerEventDefinition.getEndDate(),
timerEventDefinition.getCalendarName()
)
);
if (timerJob != null) {
timerJob.setProcessDefinitionId(processDefinition.getId());
if (processDefinition.getTenantId() != null) {
timerJob.setTenantId(processDefinition.getTenantId());
}
timers.add(timerJob);
}
}
}
}
}
}
return timers;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\deployer\TimerManager.java | 1 |
请完成以下Java代码 | protected void configureExpressionManager() {
if (processEngineConfiguration.getExpressionManager() == null && applicationContext != null) {
SpringExpressionManager expressionManager = new SpringExpressionManager(
applicationContext,
processEngineConfiguration.getBeans()
);
List<CustomFunctionProvider> customFunctionProviders =
processEngineConfiguration.getCustomFunctionProviders();
List<ELResolver> customELResolvers = processEngineConfiguration.getCustomELResolvers();
if (customFunctionProviders != null) {
expressionManager.setCustomFunctionProviders(customFunctionProviders);
}
if (customELResolvers != null) {
expressionManager.setCustomELResolvers(customELResolvers);
}
processEngineConfiguration.setExpressionManager(expressionManager);
}
}
protected void configureExternallyManagedTransactions() {
if (processEngineConfiguration instanceof SpringProcessEngineConfiguration) {
// remark: any config can be injected, so we cannot have SpringConfiguration as member
SpringProcessEngineConfiguration engineConfiguration =
(SpringProcessEngineConfiguration) processEngineConfiguration;
if (engineConfiguration.getTransactionManager() != null) {
processEngineConfiguration.setTransactionsExternallyManaged(true);
} | }
}
public Class<ProcessEngine> getObjectType() {
return ProcessEngine.class;
}
public boolean isSingleton() {
return true;
}
public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
}
public void setProcessEngineConfiguration(ProcessEngineConfigurationImpl processEngineConfiguration) {
this.processEngineConfiguration = processEngineConfiguration;
}
} | repos\Activiti-develop\activiti-core\activiti-spring\src\main\java\org\activiti\spring\ProcessEngineFactoryBean.java | 1 |
请完成以下Java代码 | public I_M_HU_PI_Item getDefaultM_LU_PI_ItemOrNull()
{
final List<I_M_HU_PI_Item> luPIItems = getAvailableLUPIItems();
final Optional<I_M_HU_PI_Item> defaultHUPIItem = luPIItems.stream()
.filter(luPIItem -> luPIItem.getM_HU_PI_Version().isCurrent() && luPIItem.getM_HU_PI_Version().isActive() && luPIItem.getM_HU_PI_Version().getM_HU_PI().isActive())
.sorted(Comparator.comparing(I_M_HU_PI_Item::getM_HU_PI_Item_ID)) // TODO what to order by ?
.findFirst();
return defaultHUPIItem.orElse(null);
}
private List<I_M_HU_PI_Item> getAvailableLUPIItems()
{
final HUEditorRow tuRow = getSelectedRow();
final I_M_HU tuHU = tuRow.getM_HU();
final I_M_HU_PI_Version effectivePIVersion = handlingUnitsBL.getEffectivePIVersion(tuHU);
Check.errorIf(effectivePIVersion == null, "tuHU is inconsistent; hu={}", tuHU);
return handlingUnitsDAO.retrieveParentPIItemsForParentPI(
effectivePIVersion.getM_HU_PI(),
null,
IHandlingUnitsBL.extractBPartnerIdOrNull(tuHU));
}
public boolean getShowWarehouseFlag()
{
final ActionType currentActionType = getActionType();
if (currentActionType == null)
{
return false;
}
final boolean isMoveToWarehouseAllowed = _isMoveToDifferentWarehouseEnabled && statusBL.isStatusActive(getSelectedRow().getM_HU());
if (!isMoveToWarehouseAllowed) | {
return false;
}
final boolean showWarehouse;
switch (currentActionType)
{
case CU_To_NewCU:
case CU_To_NewTUs:
case TU_To_NewLUs:
case TU_To_NewTUs:
showWarehouse = true;
break;
default:
showWarehouse = false;
}
return showWarehouse;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WebuiHUTransformParametersFiller.java | 1 |
请完成以下Java代码 | public static final class AuthenticatorSelectionCriteriaBuilder {
private @Nullable AuthenticatorAttachment authenticatorAttachment;
private @Nullable ResidentKeyRequirement residentKey;
private @Nullable UserVerificationRequirement userVerification;
private AuthenticatorSelectionCriteriaBuilder() {
}
/**
* Sets the {@link #getAuthenticatorAttachment()} property.
* @param authenticatorAttachment the authenticator attachment
* @return the {@link AuthenticatorSelectionCriteriaBuilder}
*/
public AuthenticatorSelectionCriteriaBuilder authenticatorAttachment(
AuthenticatorAttachment authenticatorAttachment) {
this.authenticatorAttachment = authenticatorAttachment;
return this;
}
/**
* Sets the {@link #getResidentKey()} property.
* @param residentKey the resident key
* @return the {@link AuthenticatorSelectionCriteriaBuilder}
*/
public AuthenticatorSelectionCriteriaBuilder residentKey(ResidentKeyRequirement residentKey) { | this.residentKey = residentKey;
return this;
}
/**
* Sets the {@link #getUserVerification()} property.
* @param userVerification the user verification requirement
* @return the {@link AuthenticatorSelectionCriteriaBuilder}
*/
public AuthenticatorSelectionCriteriaBuilder userVerification(UserVerificationRequirement userVerification) {
this.userVerification = userVerification;
return this;
}
/**
* Builds a {@link AuthenticatorSelectionCriteria}
* @return a new {@link AuthenticatorSelectionCriteria}
*/
public AuthenticatorSelectionCriteria build() {
return new AuthenticatorSelectionCriteria(this.authenticatorAttachment, this.residentKey,
this.userVerification);
}
}
} | repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\AuthenticatorSelectionCriteria.java | 1 |
请完成以下Java代码 | public void setC_Year_ID (int C_Year_ID)
{
if (C_Year_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Year_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Year_ID, Integer.valueOf(C_Year_ID));
}
/** Get Year.
@return Calendar Year
*/
public int getC_Year_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Year_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Year.
@param FiscalYear
The Fiscal Year
*/
public void setFiscalYear (String FiscalYear)
{
set_Value (COLUMNNAME_FiscalYear, FiscalYear);
}
/** Get Year.
@return The Fiscal Year | */
public String getFiscalYear ()
{
return (String)get_Value(COLUMNNAME_FiscalYear);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getFiscalYear());
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Year.java | 1 |
请完成以下Java代码 | protected MaterialPlanningContext createContextOrNull(@NonNull final SupplyRequiredDescriptor supplyRequiredDescriptor)
{
final OrgId orgId = supplyRequiredDescriptor.getOrgId();
final WarehouseId warehouseId = supplyRequiredDescriptor.getWarehouseId();
final I_M_Warehouse warehouse = warehouseDAO.getById(warehouseId);
final ProductId productId = ProductId.ofRepoId(supplyRequiredDescriptor.getProductId());
final AttributeSetInstanceId attributeSetInstanceId = AttributeSetInstanceId.ofRepoIdOrNone(supplyRequiredDescriptor.getAttributeSetInstanceId());
final ResourceId plantId = productPlanningDAO.findPlantIfExists(orgId, warehouse, productId, attributeSetInstanceId).orElse(null);
if (plantId == null)
{
Loggables.withLogger(logger, Level.DEBUG).addLog("No plant found for {}, {}, {}, {}", orgId, warehouse, productId, attributeSetInstanceId);
return null;
}
final ProductPlanningQuery productPlanningQuery = ProductPlanningQuery.builder()
.orgId(orgId)
.warehouseId(warehouseId)
.plantId(plantId)
.productId(productId)
.includeWithNullProductId(false)
.attributeSetInstanceId(attributeSetInstanceId)
.build();
final ProductPlanning productPlanning = productPlanningDAO.find(productPlanningQuery).orElse(null);
if (productPlanning == null) | {
Loggables.withLogger(logger, Level.DEBUG).addLog("No PP_Product_Planning record found => nothing to do; query={}", productPlanningQuery);
return null;
}
final I_AD_Org org = orgDAO.getById(orgId);
return MaterialPlanningContext.builder()
.productId(productId)
.attributeSetInstanceId(attributeSetInstanceId)
.warehouseId(warehouseId)
.productPlanning(productPlanning)
.plantId(plantId)
.clientAndOrgId(ClientAndOrgId.ofClientAndOrg(org.getAD_Client_ID(), org.getAD_Org_ID()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\event\SupplyRequiredHandlerHelper.java | 1 |
请完成以下Java代码 | 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;
}
public List<AddressDetails> getAddressDetails() {
return addressDetails;
}
public void setAddressDetails(List<AddressDetails> addressDetails) {
this.addressDetails = addressDetails;
}
} | repos\tutorials-master\xml-modules\xstream\src\main\java\com\baeldung\pojo\CustomerAddressDetails.java | 1 |
请完成以下Java代码 | public class RsaClassLoader extends ClassLoader {
private static final int MAGIC = 0xcafebabe;
Logger logger = LoggerFactory.getLogger(RsaClassLoader.class);
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
try {
// 先使用父加载器加载
return getParent().loadClass(name);
} catch (Throwable t) {
return findClass(name);
}
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException { | String fileName = name.replace('.', File.separatorChar) + ".class";
try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName)) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
logger.warn("请输入解密私钥,否则无法启动服务");
System.out.print("请输入解密私钥::");
String privateKey = br.readLine();
logger.info("解密[{}] 文件 开始", name);
byte[] bytes = RSAUtil.decryptByPrivateKey(RSAUtil.toByteArray(inputStream), privateKey);
logger.info("解密[{}] 文件 结束", name);
return this.defineClass(name, bytes, 0, bytes.length);
} catch (Exception e) {
logger.info("解密 [{}] 文件异常: {}", name, e.getMessage(), e);
throw new ClassNotFoundException(String.format("解密 [%s] 文件异常: %s", name, e.getCause()));
}
}
} | repos\spring-boot-student-master\spring-boot-student-jvm\src\main\java\com\xiaolyuh\RsaClassLoader.java | 1 |
请完成以下Java代码 | public int hashCode() {
return Objects.hash(super.hashCode(), additionalInfoBytes);
}
public static JsonNode getJson(Supplier<JsonNode> jsonData, Supplier<byte[]> binaryData) {
JsonNode json = jsonData.get();
if (json != null) {
return json;
} else {
byte[] data = binaryData.get();
if (data != null) {
try {
return mapper.readTree(new ByteArrayInputStream(data));
} catch (IOException e) {
log.warn("Can't deserialize json data: ", e);
return null; | }
} else {
return null;
}
}
}
public static void setJson(JsonNode json, Consumer<JsonNode> jsonConsumer, Consumer<byte[]> bytesConsumer) {
jsonConsumer.accept(json);
try {
bytesConsumer.accept(mapper.writeValueAsBytes(json));
} catch (JsonProcessingException e) {
log.warn("Can't serialize json data: ", e);
}
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\BaseDataWithAdditionalInfo.java | 1 |
请完成以下Java代码 | public void deleteByTenantId(TenantId tenantId) {
deleteCustomersByTenantId(tenantId);
}
private final PaginatedRemover<TenantId, Customer> customersByTenantRemover =
new PaginatedRemover<>() {
@Override
protected PageData<Customer> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) {
return customerDao.findCustomersByTenantId(id.getId(), pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, Customer entity) {
deleteCustomer(tenantId, new CustomerId(entity.getUuidId()));
}
};
@Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findCustomerById(tenantId, new CustomerId(entityId.getId())));
} | @Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(findCustomerByIdAsync(tenantId, new CustomerId(entityId.getId())))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public long countByTenantId(TenantId tenantId) {
return customerDao.countByTenantId(tenantId);
}
@Override
public EntityType getEntityType() {
return EntityType.CUSTOMER;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\customer\CustomerServiceImpl.java | 1 |
请完成以下Java代码 | public String getTargetRef() {
return targetRef;
}
public void setTargetRef(String targetRef) {
this.targetRef = targetRef;
}
public String getTransformation() {
return transformation;
}
public void setTransformation(String transformation) {
this.transformation = transformation;
}
public List<Assignment> getAssignments() {
return assignments;
}
public void setAssignments(List<Assignment> assignments) {
this.assignments = assignments;
}
@Override
public DataAssociation clone() {
DataAssociation clone = new DataAssociation();
clone.setValues(this); | return clone;
}
public void setValues(DataAssociation otherAssociation) {
super.setValues(otherAssociation);
setSourceRef(otherAssociation.getSourceRef());
setTargetRef(otherAssociation.getTargetRef());
setTransformation(otherAssociation.getTransformation());
assignments = new ArrayList<>();
if (otherAssociation.getAssignments() != null && !otherAssociation.getAssignments().isEmpty()) {
for (Assignment assignment : otherAssociation.getAssignments()) {
assignments.add(assignment.clone());
}
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\DataAssociation.java | 1 |
请完成以下Java代码 | public static <T> List<T> copyAndReverse(final List<T> list)
{
if (list == null)
{
return null;
}
if (list.isEmpty())
{
return Collections.emptyList();
}
final List<T> listCopy = new ArrayList<>(list);
Collections.reverse(listCopy);
return listCopy;
}
/**
* @param list | * @param predicate
* @return a filtered copy of given list
*/
public static final <E> List<E> copyAndFilter(final List<? extends E> list, final Predicate<? super E> predicate)
{
final List<E> copy = new ArrayList<>();
for (final E element : list)
{
if (predicate.apply(element))
{
copy.add(element);
}
}
return copy;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\ListUtils.java | 1 |
请完成以下Java代码 | public void configureGroups(Groups<WebClient.Builder> groups) {
// @formatter:off
groups.forEachClient((group, client) ->
client.filter(this.filter)
);
groups.forEachProxyFactory((group, factory) ->
factory.httpRequestValuesProcessor(this.processor)
);
// @formatter:on
}
/**
* Create an instance for Reactive web applications from the provided
* {@link ReactiveOAuth2AuthorizedClientManager}.
*
* It will add {@link ServerOAuth2AuthorizedClientExchangeFilterFunction} to the
* {@link WebClient} and {@link ClientRegistrationIdProcessor} to the
* {@link org.springframework.web.service.invoker.HttpServiceProxyFactory}.
* @param authorizedClientManager the manager to use.
* @return the {@link OAuth2WebClientHttpServiceGroupConfigurer}.
*/
public static OAuth2WebClientHttpServiceGroupConfigurer from(
ReactiveOAuth2AuthorizedClientManager authorizedClientManager) {
ServerOAuth2AuthorizedClientExchangeFilterFunction filter = new ServerOAuth2AuthorizedClientExchangeFilterFunction(
authorizedClientManager);
return new OAuth2WebClientHttpServiceGroupConfigurer(filter);
}
/**
* Create an instance for Servlet based environments from the provided
* {@link OAuth2AuthorizedClientManager}. | *
* It will add {@link ServletOAuth2AuthorizedClientExchangeFilterFunction} to the
* {@link WebClient} and {@link ClientRegistrationIdProcessor} to the
* {@link org.springframework.web.service.invoker.HttpServiceProxyFactory}.
* @param authorizedClientManager the manager to use.
* @return the {@link OAuth2WebClientHttpServiceGroupConfigurer}.
*/
public static OAuth2WebClientHttpServiceGroupConfigurer from(
OAuth2AuthorizedClientManager authorizedClientManager) {
ServletOAuth2AuthorizedClientExchangeFilterFunction filter = new ServletOAuth2AuthorizedClientExchangeFilterFunction(
authorizedClientManager);
return new OAuth2WebClientHttpServiceGroupConfigurer(filter);
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\reactive\function\client\support\OAuth2WebClientHttpServiceGroupConfigurer.java | 1 |
请完成以下Java代码 | public int getDoc_User_ID(DocumentTableFields docFields)
{
return extractCustomsInvoice(docFields).getCreatedBy();
}
@Override
public String completeIt(DocumentTableFields docFields)
{
final I_C_Customs_Invoice shipmentDeclaration = extractCustomsInvoice(docFields);
shipmentDeclaration.setProcessed(true);
shipmentDeclaration.setDocAction(IDocument.ACTION_ReActivate);
return IDocument.STATUS_Completed;
}
@Override
public void reactivateIt(DocumentTableFields docFields) | {
final I_C_Customs_Invoice customsInvoice = extractCustomsInvoice(docFields);
customsInvoice.setProcessed(false);
customsInvoice.setDocAction(IDocument.ACTION_Complete);
}
private static I_C_Customs_Invoice extractCustomsInvoice(final DocumentTableFields docFields)
{
return InterfaceWrapperHelper.create(docFields, I_C_Customs_Invoice.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\customs\document\CustomsInvoiceDocumentHandler.java | 1 |
请完成以下Java代码 | public ConditionEvaluationBuilder processInstanceBusinessKey(String businessKey) {
ensureNotNull("businessKey", businessKey);
this.businessKey = businessKey;
return this;
}
@Override
public ConditionEvaluationBuilder processDefinitionId(String processDefinitionId) {
ensureNotNull("processDefinitionId", processDefinitionId);
this.processDefinitionId = processDefinitionId;
return this;
}
@Override
public ConditionEvaluationBuilder setVariable(String variableName, Object variableValue) {
ensureNotNull("variableName", variableName);
this.variables.put(variableName, variableValue);
return this;
}
@Override
public ConditionEvaluationBuilder setVariables(Map<String, Object> variables) {
ensureNotNull("variables", variables);
if (variables != null) {
this.variables.putAll(variables);
}
return this;
} | @Override
public ConditionEvaluationBuilder tenantId(String tenantId) {
ensureNotNull(
"The tenant-id cannot be null. Use 'withoutTenantId()' if you want to evaluate conditional start event with a process definition which has no tenant-id.",
"tenantId", tenantId);
isTenantIdSet = true;
this.tenantId = tenantId;
return this;
}
@Override
public ConditionEvaluationBuilder withoutTenantId() {
isTenantIdSet = true;
tenantId = null;
return this;
}
@Override
public List<ProcessInstance> evaluateStartConditions() {
return execute(new EvaluateStartConditionCmd(this));
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ConditionEvaluationBuilderImpl.java | 1 |
请完成以下Java代码 | public class User {
@Getter
@EqualsAndHashCode.Include
private final String id;
private final List<String> followingIds;
private final List<String> favoriteArticleIds;
@Getter
@Setter
private String username;
@Getter
@Setter
private String encodedPassword;
@Getter
@Setter
private String email;
@Getter
@Setter
@Nullable
private String bio;
@Getter
@Setter
@Nullable
private String image;
@Builder
public User(String id,
@Nullable List<String> followingIds,
@Nullable List<String> favoriteArticleIds,
String username,
String encodedPassword,
String email,
@Nullable String bio,
@Nullable String image
) {
this.id = id;
this.followingIds = ofNullable(followingIds).orElse(new ArrayList<>());
this.favoriteArticleIds = ofNullable(favoriteArticleIds).orElse(new ArrayList<>());
this.username = username;
this.encodedPassword = encodedPassword;
this.email = email;
this.bio = bio;
this.image = image;
}
public List<String> getFollowingIds() {
return Collections.unmodifiableList(followingIds);
} | public List<String> getFavoriteArticleIds() {
return Collections.unmodifiableList(favoriteArticleIds);
}
public void follow(String userId) {
followingIds.add(userId);
}
public void unfollow(String userId) {
followingIds.remove(userId);
}
public void follow(User user) {
follow(user.getId());
}
public void unfollow(User user) {
unfollow(user.getId());
}
public void favorite(Article article) {
article.incrementFavoritesCount();
favoriteArticleIds.add(article.getId());
}
public void unfavorite(Article article) {
article.decrementFavoritesCount();
favoriteArticleIds.remove(article.getId());
}
public boolean isFavoriteArticle(Article article) {
return favoriteArticleIds.contains(article.getId());
}
public boolean isFollowing(User user) {
return followingIds.contains(user.getId());
}
public boolean isFollower(User user) {
return user.isFollowing(this);
}
} | repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\user\User.java | 1 |
请完成以下Java代码 | public boolean isUserUpdateable ()
{
Object oo = get_Value(COLUMNNAME_IsUserUpdateable);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name. | @return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserDef_Win.java | 1 |
请完成以下Java代码 | public int getAD_Sequence_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Sequence_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_AD_Table getAD_Table() throws RuntimeException
{
return (I_AD_Table)MTable.get(getCtx(), I_AD_Table.Table_Name)
.getPO(getAD_Table_ID(), get_TrxName()); }
/** Set Table.
@param AD_Table_ID
Database Table information
*/
public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get Table.
@return Database Table information
*/
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Document No.
@param DocumentNo
Document sequence number of the document
*/
public void setDocumentNo (String DocumentNo)
{
set_ValueNoCheck (COLUMNNAME_DocumentNo, DocumentNo); | }
/** Get Document No.
@return Document sequence number of the document
*/
public String getDocumentNo ()
{
return (String)get_Value(COLUMNNAME_DocumentNo);
}
/** Set Record ID.
@param Record_ID
Direct internal record ID
*/
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Record ID.
@return Direct internal record ID
*/
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Sequence_Audit.java | 1 |
请完成以下Java代码 | public Object getUserOject()
{
return m_userObject;
}
protected String convertUserObjectForTextField(final Object userObject)
{
return userObject == null ? "" : userObject.toString();
}
protected boolean isMatching(final Object userObject, final String search)
{
if (userObject == null)
{
return false;
}
final String s1 = StringUtils
.stripDiacritics(convertUserObjectForTextField(userObject));
final String s2 = StringUtils.stripDiacritics(search);
return s1.equalsIgnoreCase(s2);
}
/**
*
* @param search
* @param caretPosition
* @param params empty list. Needs to be filled by the implementing method.
* @return full SELECT SQL or null on error
*/
protected abstract String getSelectSQL(String search, int caretPosition, List<Object> params);
/**
* @return loaded object or null if object at current result set possition was not valid
*/
protected abstract Object fetchUserObject(ResultSet rs) throws SQLException;
@Override
public void mouseEntered(final MouseEvent e)
{
// nothing to do
}
@Override
public void mouseExited(final MouseEvent e)
{
// nothing to do
}
@Override
public void mousePressed(final MouseEvent e)
{
// nothing to do
}
@Override
public void mouseReleased(final MouseEvent e)
{
// nothing to do
}
@Override
public void mouseClicked(final MouseEvent e)
{
if (e == null || listBox.getSelectedValue().equals(ITEM_More)) | {
setUserObject(null);
return;
}
popup.setVisible(false); // 02027: tsa: hide popup when an item is selected
final Object selected = listBox.getSelectedValue();
setUserObject(selected);
textBox.setText(convertUserObjectForTextField(selected));
}
public void addPropertyChangeListener(final PropertyChangeListener listener)
{
listBox.addPropertyChangeListener(listener);
}
public void setMaxItems(final int maxItems)
{
m_maxItems = maxItems;
listBox.setVisibleRowCount(m_maxItems + 1);
}
public int getMaxItems()
{
return m_maxItems;
}
public final String getText()
{
return textBox.getText();
}
protected final int getTextCaretPosition()
{
return textBox.getCaretPosition();
}
protected final void setTextCaretPosition(final int caretPosition)
{
textBox.setCaretPosition(caretPosition);
}
protected final void setText(final String text)
{
textBox.setText(text);
}
public final boolean isEnabled()
{
final boolean textBoxHasFocus = textBox.isFocusOwner();
return textBoxHasFocus;
}
public void setPopupMinimumChars(final int popupMinimumChars)
{
m_popupMinimumChars = popupMinimumChars;
}
public int getPopupMinimumChars()
{
return m_popupMinimumChars;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\FieldAutoCompleter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class InsuranceContractMaxPermanentPrescriptionPeriod {
@SerializedName("amount")
private BigDecimal amount = null;
@SerializedName("timePeriod")
private BigDecimal timePeriod = null;
public InsuranceContractMaxPermanentPrescriptionPeriod amount(BigDecimal amount) {
this.amount = amount;
return this;
}
/**
* Anzahl der Tage, Wochen, Monate
* @return amount
**/
@Schema(example = "1", description = "Anzahl der Tage, Wochen, Monate")
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public InsuranceContractMaxPermanentPrescriptionPeriod timePeriod(BigDecimal timePeriod) {
this.timePeriod = timePeriod;
return this;
}
/**
* Zeitintervall (Unbekannt = 0, Minute = 1, Stunde = 2, Tag = 3, Woche = 4, Monat = 5, Quartal = 6, Halbjahr = 7, Jahr = 8)
* @return timePeriod
**/
@Schema(example = "6", description = "Zeitintervall (Unbekannt = 0, Minute = 1, Stunde = 2, Tag = 3, Woche = 4, Monat = 5, Quartal = 6, Halbjahr = 7, Jahr = 8)")
public BigDecimal getTimePeriod() {
return timePeriod;
}
public void setTimePeriod(BigDecimal timePeriod) {
this.timePeriod = timePeriod;
} | @Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InsuranceContractMaxPermanentPrescriptionPeriod insuranceContractMaxPermanentPrescriptionPeriod = (InsuranceContractMaxPermanentPrescriptionPeriod) o;
return Objects.equals(this.amount, insuranceContractMaxPermanentPrescriptionPeriod.amount) &&
Objects.equals(this.timePeriod, insuranceContractMaxPermanentPrescriptionPeriod.timePeriod);
}
@Override
public int hashCode() {
return Objects.hash(amount, timePeriod);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class InsuranceContractMaxPermanentPrescriptionPeriod {\n");
sb.append(" amount: ").append(toIndentedString(amount)).append("\n");
sb.append(" timePeriod: ").append(toIndentedString(timePeriod)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\InsuranceContractMaxPermanentPrescriptionPeriod.java | 2 |
请完成以下Java代码 | public static SCryptPasswordEncoder defaultsForSpringSecurity_v4_1() {
return new SCryptPasswordEncoder(16384, 8, 1, 32, 64);
}
/**
* Constructs a SCrypt password encoder with cpu cost of 65,536, memory cost of 8,
* parallelization of 1, a key length of 32 and a salt length of 16 bytes.
* @return the {@link SCryptPasswordEncoder}
* @since 5.8
*/
public static SCryptPasswordEncoder defaultsForSpringSecurity_v5_8() {
return new SCryptPasswordEncoder(DEFAULT_CPU_COST, DEFAULT_MEMORY_COST, DEFAULT_PARALLELISM, DEFAULT_KEY_LENGTH,
DEFAULT_SALT_LENGTH);
}
@Override
protected String encodeNonNullPassword(String rawPassword) {
return digest(rawPassword, this.saltGenerator.generateKey());
}
@Override
protected boolean matchesNonNull(String rawPassword, String encodedPassword) {
return decodeAndCheckMatches(rawPassword, encodedPassword);
}
@Override
protected boolean upgradeEncodingNonNull(String encodedPassword) {
String[] parts = encodedPassword.split("\\$");
if (parts.length != 4) {
throw new IllegalArgumentException("Encoded password does not look like SCrypt: " + encodedPassword);
}
long params = Long.parseLong(parts[1], 16);
int cpuCost = (int) Math.pow(2, params >> 16 & 0xffff);
int memoryCost = (int) params >> 8 & 0xff;
int parallelization = (int) params & 0xff;
return cpuCost < this.cpuCost || memoryCost < this.memoryCost || parallelization < this.parallelization;
}
private boolean decodeAndCheckMatches(CharSequence rawPassword, String encodedPassword) {
String[] parts = encodedPassword.split("\\$");
if (parts.length != 4) {
return false;
}
long params = Long.parseLong(parts[1], 16);
byte[] salt = decodePart(parts[2]);
byte[] derived = decodePart(parts[3]);
int cpuCost = (int) Math.pow(2, params >> 16 & 0xffff);
int memoryCost = (int) params >> 8 & 0xff;
int parallelization = (int) params & 0xff;
byte[] generated = SCrypt.generate(Utf8.encode(rawPassword), salt, cpuCost, memoryCost, parallelization,
this.keyLength);
return MessageDigest.isEqual(derived, generated); | }
private String digest(CharSequence rawPassword, byte[] salt) {
byte[] derived = SCrypt.generate(Utf8.encode(rawPassword), salt, this.cpuCost, this.memoryCost,
this.parallelization, this.keyLength);
String params = Long.toString(
((int) (Math.log(this.cpuCost) / Math.log(2)) << 16L) | this.memoryCost << 8 | this.parallelization,
16);
StringBuilder sb = new StringBuilder((salt.length + derived.length) * 2);
sb.append("$").append(params).append('$');
sb.append(encodePart(salt)).append('$');
sb.append(encodePart(derived));
return sb.toString();
}
private byte[] decodePart(String part) {
return Base64.getDecoder().decode(Utf8.encode(part));
}
private String encodePart(byte[] part) {
return Utf8.decode(Base64.getEncoder().encode(part));
}
} | repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\scrypt\SCryptPasswordEncoder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ManualOauthRequestController {
private static Logger logger = LoggerFactory.getLogger(ManualOauthRequestController.class);
private static final String RESOURCE_ENDPOINT = "localhost:8082/spring-security-oauth-resource/foos/1";
@Value("${the.authorization.client-id}")
private String clientId;
@Value("${the.authorization.client-secret}")
private String clientSecret;
@Value("${the.authorization.token-uri}")
private String tokenUri;
@Autowired
WebClient client;
@GetMapping("/manual-request-oauth")
public Mono<String> obtainSecuredResource() {
logger.info("Creating web client...");
Mono<String> resource = client.post()
.uri(tokenUri)
.header(HttpHeaders.AUTHORIZATION, "Basic " + Base64.getEncoder()
.encodeToString((clientId + ":" + clientSecret).getBytes()))
.body(BodyInserters.fromFormData(OAuth2ParameterNames.GRANT_TYPE, GrantType.CLIENT_CREDENTIALS.getValue())) | .retrieve()
.bodyToMono(JsonNode.class)
.flatMap(tokenResponse -> {
String accessTokenValue = tokenResponse.get("access_token")
.textValue();
logger.info("Retrieved the following access token: {}", accessTokenValue);
return client.get()
.uri(RESOURCE_ENDPOINT)
.headers(h -> h.setBearerAuth(accessTokenValue))
.retrieve()
.bodyToMono(String.class);
});
logger.info("non-blocking Oauth calls registered...");
return resource.map(res -> "Retrieved the resource using a manual approach: " + res);
}
} | repos\tutorials-master\spring-reactive-modules\spring-reactive-oauth\src\main\java\com\baeldung\webclient\manualrequest\web\ManualOauthRequestController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Set<String> getPostLogoutRedirectUris() {
return this.postLogoutRedirectUris;
}
public void setPostLogoutRedirectUris(Set<String> postLogoutRedirectUris) {
this.postLogoutRedirectUris = postLogoutRedirectUris;
}
public Set<String> getScopes() {
return this.scopes;
}
public void setScopes(Set<String> scopes) {
this.scopes = scopes;
}
}
/**
* Token settings of the registered client.
*/
public static class Token {
/**
* Time-to-live for an authorization code.
*/
private Duration authorizationCodeTimeToLive = Duration.ofMinutes(5);
/**
* Time-to-live for an access token.
*/
private Duration accessTokenTimeToLive = Duration.ofMinutes(5);
/**
* Token format for an access token.
*/
private String accessTokenFormat = "self-contained";
/**
* Time-to-live for a device code.
*/
private Duration deviceCodeTimeToLive = Duration.ofMinutes(5);
/**
* Whether refresh tokens are reused or a new refresh token is issued when
* returning the access token response.
*/
private boolean reuseRefreshTokens = true;
/**
* Time-to-live for a refresh token.
*/
private Duration refreshTokenTimeToLive = Duration.ofMinutes(60);
/**
* JWS algorithm for signing the ID Token.
*/
private String idTokenSignatureAlgorithm = "RS256";
public Duration getAuthorizationCodeTimeToLive() {
return this.authorizationCodeTimeToLive;
} | public void setAuthorizationCodeTimeToLive(Duration authorizationCodeTimeToLive) {
this.authorizationCodeTimeToLive = authorizationCodeTimeToLive;
}
public Duration getAccessTokenTimeToLive() {
return this.accessTokenTimeToLive;
}
public void setAccessTokenTimeToLive(Duration accessTokenTimeToLive) {
this.accessTokenTimeToLive = accessTokenTimeToLive;
}
public String getAccessTokenFormat() {
return this.accessTokenFormat;
}
public void setAccessTokenFormat(String accessTokenFormat) {
this.accessTokenFormat = accessTokenFormat;
}
public Duration getDeviceCodeTimeToLive() {
return this.deviceCodeTimeToLive;
}
public void setDeviceCodeTimeToLive(Duration deviceCodeTimeToLive) {
this.deviceCodeTimeToLive = deviceCodeTimeToLive;
}
public boolean isReuseRefreshTokens() {
return this.reuseRefreshTokens;
}
public void setReuseRefreshTokens(boolean reuseRefreshTokens) {
this.reuseRefreshTokens = reuseRefreshTokens;
}
public Duration getRefreshTokenTimeToLive() {
return this.refreshTokenTimeToLive;
}
public void setRefreshTokenTimeToLive(Duration refreshTokenTimeToLive) {
this.refreshTokenTimeToLive = refreshTokenTimeToLive;
}
public String getIdTokenSignatureAlgorithm() {
return this.idTokenSignatureAlgorithm;
}
public void setIdTokenSignatureAlgorithm(String idTokenSignatureAlgorithm) {
this.idTokenSignatureAlgorithm = idTokenSignatureAlgorithm;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-security-oauth2-authorization-server\src\main\java\org\springframework\boot\security\oauth2\server\authorization\autoconfigure\servlet\OAuth2AuthorizationServerProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | GrpcChannelFactory shadedNettyGrpcChannelFactory(
final GrpcChannelsProperties properties,
final GlobalClientInterceptorRegistry globalClientInterceptorRegistry,
final List<GrpcChannelConfigurer> channelConfigurers) {
log.info("Detected grpc-netty-shaded: Creating ShadedNettyChannelFactory");
return new ShadedNettyChannelFactory(properties, globalClientInterceptorRegistry, channelConfigurers);
}
// Then try the normal netty channel factory
@ConditionalOnMissingBean(GrpcChannelFactory.class)
@ConditionalOnClass(name = {"io.netty.channel.Channel", "io.grpc.netty.NettyChannelBuilder"})
@Bean
@Lazy
GrpcChannelFactory nettyGrpcChannelFactory(
final GrpcChannelsProperties properties,
final GlobalClientInterceptorRegistry globalClientInterceptorRegistry,
final List<GrpcChannelConfigurer> channelConfigurers) {
log.info("Detected grpc-netty: Creating NettyChannelFactory");
return new NettyChannelFactory(properties, globalClientInterceptorRegistry, channelConfigurers); | }
// Finally try the in process channel factory
@ConditionalOnMissingBean(GrpcChannelFactory.class)
@ConditionalOnClass(name = {"io.grpc.inprocess.InProcessChannelBuilder"})
@Bean
@Lazy
GrpcChannelFactory inProcessGrpcChannelFactory(
final GrpcChannelsProperties properties,
final GlobalClientInterceptorRegistry globalClientInterceptorRegistry,
final List<GrpcChannelConfigurer> channelConfigurers) {
log.warn("Could not find a GrpcChannelFactory on the classpath: Creating InProcessChannelFactory as fallback");
return new InProcessChannelFactory(properties, globalClientInterceptorRegistry, channelConfigurers);
}
} | repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\autoconfigure\GrpcClientAutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public JsonPluFileAudit getJsonPluFileAuditNonNull()
{
if (this.jsonPluFileAudit == null)
{
throw new RuntimeCamelException("JsonPluFileAudit cannot be null!");
}
return this.jsonPluFileAudit;
}
@NonNull
public String getUpdatedPLUFileContent()
{
if (this.pluFileXmlContent == null)
{
throw new RuntimeCamelException("pluFileXmlContent cannot be null!");
}
return this.pluFileXmlContent;
}
@NonNull
public String getPLUTemplateFilename()
{ | if (this.pluTemplateFilename == null)
{
throw new RuntimeCamelException("filename cannot be null!");
}
return this.pluTemplateFilename;
}
@NonNull
public List<String> getPluFileConfigKeys()
{
return this.pluFileConfigs.getPluFileConfigs()
.stream()
.map(JsonExternalSystemLeichMehlPluFileConfig::getTargetFieldName)
.collect(ImmutableList.toImmutableList());
}
@Nullable
public Integer getAdPInstance()
{
return JsonMetasfreshId.toValue(this.jsonExternalSystemRequest.getAdPInstanceId());
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-leichundmehl\src\main\java\de\metas\camel\externalsystems\leichundmehl\to_leichundmehl\pporder\ExportPPOrderRouteContext.java | 2 |
请完成以下Java代码 | public <T> T decodeBytes(final byte[] data, final Class<T> clazz)
{
try
{
return mapper.readValue(data, clazz);
}
catch (final Exception e)
{
throw new RuntimeException("Cannot parse bytes: " + data, e);
}
}
@Override
public <T> byte[] encode(final T object)
{
try | {
return mapper.writeValueAsBytes(object);
}
catch (final Exception e)
{
throw new RuntimeException(e);
}
}
@Override
public String getContentType()
{
return "application/json";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\org\adempiere\util\beans\JsonBeanEncoder.java | 1 |
请完成以下Java代码 | public void setProductName (final @Nullable java.lang.String ProductName)
{
throw new IllegalArgumentException ("ProductName is virtual column"); }
@Override
public java.lang.String getProductName()
{
return get_ValueAsString(COLUMNNAME_ProductName);
}
@Override
public void setQtyCount (final BigDecimal QtyCount)
{
set_Value (COLUMNNAME_QtyCount, QtyCount);
}
@Override
public BigDecimal getQtyCount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCount); | return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_Fresh_QtyOnHand_Line.java | 1 |
请完成以下Java代码 | public HUQueryBuilder addHUIdsToExclude(final Collection<HuId> huIdsToExclude)
{
if (huIdsToExclude == null || huIdsToExclude.isEmpty())
{
return this;
}
this._huIdsToExclude.addAll(huIdsToExclude);
this._huIdsToAlwaysInclude.removeAll(huIdsToExclude);
return this;
}
@Override
public HUQueryBuilder addHUIdsToAlwaysInclude(final Collection<HuId> huIdsToAlwaysInclude)
{
if (huIdsToAlwaysInclude == null || huIdsToAlwaysInclude.isEmpty())
{
return this;
}
this._huIdsToAlwaysInclude.addAll(huIdsToAlwaysInclude);
this._huIdsToExclude.removeAll(huIdsToAlwaysInclude);
return this;
}
@Override
public HUQueryBuilder addPIVersionToInclude(@NonNull final HuPackingInstructionsVersionId huPIVersionId)
{
_huPIVersionIdsToInclude.add(huPIVersionId);
return this;
}
private Set<HuPackingInstructionsVersionId> getPIVersionIdsToInclude()
{
return _huPIVersionIdsToInclude;
}
@Override
public HUQueryBuilder setExcludeAfterPickingLocator(final boolean excludeAfterPickingLocator)
{
locators.setExcludeAfterPickingLocator(excludeAfterPickingLocator);
return this;
}
@Override
public HUQueryBuilder setIncludeAfterPickingLocator(final boolean includeAfterPickingLocator)
{
locators.setIncludeAfterPickingLocator(includeAfterPickingLocator);
return this;
}
@Override
public HUQueryBuilder setExcludeHUsOnPickingSlot(final boolean excludeHUsOnPickingSlot)
{ | _excludeHUsOnPickingSlot = excludeHUsOnPickingSlot;
return this;
}
@Override
public IHUQueryBuilder setExcludeReservedToOtherThan(@Nullable final HUReservationDocRef documentRef)
{
_excludeReservedToOtherThanRef = documentRef;
return this;
}
@Override
public IHUQueryBuilder setExcludeReserved()
{
_excludeReserved = true;
return this;
}
@Override
public IHUQueryBuilder setIgnoreHUsScheduledInDDOrder(final boolean ignoreHUsScheduledInDDOrder)
{
this.ignoreHUsScheduledInDDOrder = ignoreHUsScheduledInDDOrder;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUQueryBuilder.java | 1 |
请完成以下Java代码 | public void setQtyBatch (final BigDecimal QtyBatch)
{
set_Value (COLUMNNAME_QtyBatch, QtyBatch);
}
@Override
public BigDecimal getQtyBatch()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyBatch);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyBOM (final @Nullable BigDecimal QtyBOM)
{
set_Value (COLUMNNAME_QtyBOM, QtyBOM);
}
@Override
public BigDecimal getQtyBOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyBOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setScrap (final @Nullable BigDecimal Scrap)
{
set_Value (COLUMNNAME_Scrap, Scrap);
}
@Override
public BigDecimal getScrap()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Scrap);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
} | @Override
public void setTM_Product_ID (final int TM_Product_ID)
{
if (TM_Product_ID < 1)
set_Value (COLUMNNAME_TM_Product_ID, null);
else
set_Value (COLUMNNAME_TM_Product_ID, TM_Product_ID);
}
@Override
public int getTM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_TM_Product_ID);
}
@Override
public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_RV_PP_Product_BOMLine.java | 1 |
请完成以下Java代码 | public boolean toBoolean()
{
return isSales();
}
public static boolean toBoolean(final SOTrx soTrx)
{
if (soTrx == null)
{
return false;
}
return soTrx.toBoolean();
}
public boolean isSales()
{
return this == SALES; | }
public boolean isPurchase()
{
return this == PURCHASE;
}
/**
* @return true if AP (Account Payable), aka Purchase
*/
public boolean isAP() {return isPurchase();}
public SOTrx invert()
{
return isSales() ? PURCHASE : SALES;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\lang\SOTrx.java | 1 |
请完成以下Java代码 | public void addInitializers(ServletContextInitializer... initializers) {
Assert.notNull(initializers, "'initializers' must not be null");
this.initializers.addAll(Arrays.asList(initializers));
}
public void setLocaleCharsetMappings(Map<Locale, Charset> localeCharsetMappings) {
Assert.notNull(localeCharsetMappings, "'localeCharsetMappings' must not be null");
this.localeCharsetMappings = localeCharsetMappings;
}
public void setInitParameters(Map<String, String> initParameters) {
this.initParameters = initParameters;
}
public void setCookieSameSiteSuppliers(List<? extends CookieSameSiteSupplier> cookieSameSiteSuppliers) {
Assert.notNull(cookieSameSiteSuppliers, "'cookieSameSiteSuppliers' must not be null");
this.cookieSameSiteSuppliers = new ArrayList<>(cookieSameSiteSuppliers);
} | public void addCookieSameSiteSuppliers(CookieSameSiteSupplier... cookieSameSiteSuppliers) {
Assert.notNull(cookieSameSiteSuppliers, "'cookieSameSiteSuppliers' must not be null");
this.cookieSameSiteSuppliers.addAll(Arrays.asList(cookieSameSiteSuppliers));
}
public void addWebListenerClassNames(String... webListenerClassNames) {
this.webListenerClassNames.addAll(Arrays.asList(webListenerClassNames));
}
public Set<String> getWebListenerClassNames() {
return this.webListenerClassNames;
}
public List<URL> getStaticResourceUrls() {
return this.staticResourceJars.getUrls();
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\ServletWebServerSettings.java | 1 |
请完成以下Java代码 | public I_M_Tour_Instance retrieveTourInstance(final Object contextProvider, final ITourInstanceQueryParams params)
{
Check.assumeNotNull(contextProvider, "contextProvider not null");
final IQueryBuilder<I_M_Tour_Instance> queryBuilder = Services.get(IQueryBL.class)
.createQueryBuilder(I_M_Tour_Instance.class, contextProvider)
// Only active tour instances are relevant for us
.addOnlyActiveRecordsFilter()
// Matching our params
.filter(createTourInstanceMatcher(params));
queryBuilder.orderBy()
.addColumn(I_M_Tour_Instance.COLUMNNAME_M_ShipperTransportation_ID, Direction.Descending, Nulls.Last);
if (isOnlyOneTourInstanceExpected(params))
{
return queryBuilder
.create()
.firstOnly(I_M_Tour_Instance.class);
}
else
{
return queryBuilder
.create()
.first(I_M_Tour_Instance.class);
}
}
@Override
public boolean isTourInstanceMatches(final I_M_Tour_Instance tourInstance, final ITourInstanceQueryParams params)
{
if (tourInstance == null)
{
return false;
}
return createTourInstanceMatcher(params)
.accept(tourInstance);
}
@Override | public boolean hasDeliveryDays(final I_M_Tour_Instance tourInstance)
{
Check.assumeNotNull(tourInstance, "tourInstance not null");
final int tourInstanceId = tourInstance.getM_Tour_Instance_ID();
Check.assume(tourInstanceId > 0, "tourInstance shall not be a new/not saved one");
return Services.get(IQueryBL.class)
.createQueryBuilder(I_M_DeliveryDay.class, tourInstance)
// .addOnlyActiveRecordsFilter() // check all records
// Delivery days for our tour instance
.addEqualsFilter(I_M_DeliveryDay.COLUMN_M_Tour_Instance_ID, tourInstanceId)
.create()
.anyMatch();
}
public I_M_Tour_Instance retrieveTourInstanceForShipperTransportation(final I_M_ShipperTransportation shipperTransportation)
{
Check.assumeNotNull(shipperTransportation, "shipperTransportation not null");
return Services.get(IQueryBL.class)
.createQueryBuilder(I_M_Tour_Instance.class, shipperTransportation)
// .addOnlyActiveRecordsFilter()
// Delivery days for our tour instance
.addEqualsFilter(I_M_Tour_Instance.COLUMN_M_ShipperTransportation_ID, shipperTransportation.getM_ShipperTransportation_ID())
.create()
.firstOnly(I_M_Tour_Instance.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\api\impl\TourInstanceDAO.java | 1 |
请完成以下Java代码 | public static class CreateAndOpenIncludedViewAction implements ResultAction
{
@NonNull
CreateViewRequest createViewRequest;
}
public static final class CloseViewAction implements ResultAction
{
public static final CloseViewAction instance = new CloseViewAction();
private CloseViewAction() {}
}
@lombok.Value
@lombok.Builder
public static class OpenSingleDocument implements ResultAction
{
@NonNull
DocumentPath documentPath;
@Builder.Default
ProcessExecutionResult.RecordsToOpen.TargetTab targetTab = ProcessExecutionResult.RecordsToOpen.TargetTab.NEW_TAB;
}
@lombok.Value
@lombok.Builder
public static class SelectViewRowsAction implements ResultAction
{
@NonNull ViewId viewId;
@NonNull DocumentIdsSelection rowIds;
} | @lombok.Value
@lombok.Builder
public static class DisplayQRCodeAction implements ResultAction
{
@NonNull String code;
}
@lombok.Value
@lombok.Builder
public static class NewRecordAction implements ResultAction
{
@NonNull String windowId;
@NonNull @Singular Map<String, String> fieldValues;
@NonNull @Builder.Default ProcessExecutionResult.WebuiNewRecord.TargetTab targetTab = ProcessExecutionResult.WebuiNewRecord.TargetTab.SAME_TAB;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\ProcessInstanceResult.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ExtendedDateType {
@XmlValue
protected String value;
@XmlAttribute(name = "DateFunctionCodeQualifier", namespace = "http://erpel.at/schemas/1p0/documents/extensions/edifact")
@XmlSchemaType(name = "anySimpleType")
protected String dateFunctionCodeQualifier;
@XmlAttribute(name = "DateFormatCode", namespace = "http://erpel.at/schemas/1p0/documents/extensions/edifact")
@XmlSchemaType(name = "anySimpleType")
protected String dateFormatCode;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
/**
* Gets the value of the dateFunctionCodeQualifier property.
*
* @return
* possible object is
* {@link String }
* | */
public String getDateFunctionCodeQualifier() {
return dateFunctionCodeQualifier;
}
/**
* Sets the value of the dateFunctionCodeQualifier property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDateFunctionCodeQualifier(String value) {
this.dateFunctionCodeQualifier = value;
}
/**
* Gets the value of the dateFormatCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDateFormatCode() {
return dateFormatCode;
}
/**
* Sets the value of the dateFormatCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDateFormatCode(String value) {
this.dateFormatCode = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ExtendedDateType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | ReactiveMongoTemplate reactiveMongoTemplate(ReactiveMongoDatabaseFactory reactiveMongoDatabaseFactory,
MongoConverter converter) {
return new ReactiveMongoTemplate(reactiveMongoDatabaseFactory, converter);
}
@Bean
@ConditionalOnMissingBean(DataBufferFactory.class)
DefaultDataBufferFactory dataBufferFactory() {
return new DefaultDataBufferFactory();
}
@Bean
@ConditionalOnMissingBean(ReactiveGridFsOperations.class)
ReactiveGridFsTemplate reactiveGridFsTemplate(DataMongoProperties dataProperties,
ReactiveMongoDatabaseFactory reactiveMongoDatabaseFactory, MappingMongoConverter mappingMongoConverter,
DataBufferFactory dataBufferFactory) {
return new ReactiveGridFsTemplate(dataBufferFactory,
new GridFsReactiveMongoDatabaseFactory(reactiveMongoDatabaseFactory, dataProperties),
mappingMongoConverter, dataProperties.getGridfs().getBucket());
}
/**
* {@link ReactiveMongoDatabaseFactory} decorator to use {@link Gridfs#getDatabase()}
* from the {@link MongoProperties} when set.
*/
static class GridFsReactiveMongoDatabaseFactory implements ReactiveMongoDatabaseFactory {
private final ReactiveMongoDatabaseFactory delegate;
private final DataMongoProperties properties;
GridFsReactiveMongoDatabaseFactory(ReactiveMongoDatabaseFactory delegate, DataMongoProperties properties) {
this.delegate = delegate;
this.properties = properties;
}
@Override
public boolean hasCodecFor(Class<?> type) {
return this.delegate.hasCodecFor(type);
}
@Override
public Mono<MongoDatabase> getMongoDatabase() throws DataAccessException {
String gridFsDatabase = getGridFsDatabase();
if (StringUtils.hasText(gridFsDatabase)) {
return this.delegate.getMongoDatabase(gridFsDatabase);
}
return this.delegate.getMongoDatabase();
}
private @Nullable String getGridFsDatabase() {
return this.properties.getGridfs().getDatabase();
}
@Override
public Mono<MongoDatabase> getMongoDatabase(String dbName) throws DataAccessException {
return this.delegate.getMongoDatabase(dbName);
}
@Override
public <T> Optional<Codec<T>> getCodecFor(Class<T> type) {
return this.delegate.getCodecFor(type); | }
@Override
public PersistenceExceptionTranslator getExceptionTranslator() {
return this.delegate.getExceptionTranslator();
}
@Override
public CodecRegistry getCodecRegistry() {
return this.delegate.getCodecRegistry();
}
@Override
public Mono<ClientSession> getSession(ClientSessionOptions options) {
return this.delegate.getSession(options);
}
@Override
public ReactiveMongoDatabaseFactory withSession(ClientSession session) {
return this.delegate.withSession(session);
}
@Override
public boolean isTransactionActive() {
return this.delegate.isTransactionActive();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-data-mongodb\src\main\java\org\springframework\boot\data\mongodb\autoconfigure\DataMongoReactiveAutoConfiguration.java | 2 |
请完成以下Java代码 | private static HuUnitType extractHUType(final I_M_HU hu)
{
final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class);
if (handlingUnitsBL.isLoadingUnit(hu))
{
return HuUnitType.LU;
}
else if (handlingUnitsBL.isTransportUnitOrAggregate(hu))
{
return HuUnitType.TU;
}
else if (handlingUnitsBL.isVirtual(hu))
{
return HuUnitType.VHU;
}
else
{
throw new HUException("Unknown HU type: " + hu); // shall hot happen
}
}
@Override
public HuId getHUId()
{
return huId;
}
@Override
public BPartnerId getBPartnerId()
{
return bpartnerId;
}
@Override
public HuUnitType getHUUnitType()
{
return huUnitType;
} | @Override
public boolean isTopLevel()
{
return Services.get(IHandlingUnitsBL.class).isTopLevel(hu);
}
@Override
public List<HUToReport> getIncludedHUs()
{
if (_includedHUs == null)
{
final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class);
this._includedHUs = handlingUnitsDAO.retrieveIncludedHUs(hu)
.stream()
.map(HUToReportWrapper::of)
.collect(ImmutableList.toImmutableList());
}
return _includedHUs;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\report\HUToReportWrapper.java | 1 |
请完成以下Java代码 | public boolean isDetached() {
return eventSubscriptionEntity.getExecutionId() == null;
}
public void detachState() {
eventSubscriptionEntity.setExecution(null);
}
public void attachState(MigratingScopeInstance newOwningInstance) {
eventSubscriptionEntity.setExecution(newOwningInstance.resolveRepresentativeExecution());
}
@Override
public void attachState(MigratingTransitionInstance targetTransitionInstance) {
throw MIGRATION_LOGGER.cannotAttachToTransitionInstance(this);
}
public void migrateState() {
if (updateEvent) {
targetDeclaration.updateSubscription(eventSubscriptionEntity); | }
eventSubscriptionEntity.setActivity((ActivityImpl) targetScope);
}
public void migrateDependentEntities() {
// do nothing
}
public void create(ExecutionEntity scopeExecution) {
eventSubscriptionDeclaration.createSubscriptionForExecution(scopeExecution);
}
public void remove() {
eventSubscriptionEntity.delete();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingEventSubscriptionInstance.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
public String getNote() { | return note;
}
public void setNote(String note) {
this.note = note;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public boolean isMarried() {
return married;
}
public void setMarried(boolean married) {
this.married = married;
}
public long getIncome() {
return income;
}
public void setIncome(long income) {
this.income = income;
}
@Override
public String toString() {
return "User [name=" + name + ", email=" + email + ", gender=" + gender + ", password=" + password
+ ", profession=" + profession + ", note=" + note + ", birthday=" + birthday + ", married=" + married
+ ", income=" + income + "]";
}
} | repos\SpringBoot-Projects-FullStack-master\Part-5 Spring Boot Web Application\SpringBootFormValidationJSP\src\main\java\spring\validation\model\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<HADRE1> getHADRE1() {
if (hadre1 == null) {
hadre1 = new ArrayList<HADRE1>();
}
return this.hadre1;
}
/**
* Gets the value of the htrsd1 property.
*
* @return
* possible object is
* {@link HTRSD1 }
*
*/
public HTRSD1 getHTRSD1() {
return htrsd1;
}
/**
* Sets the value of the htrsd1 property.
*
* @param value
* allowed object is
* {@link HTRSD1 }
*
*/
public void setHTRSD1(HTRSD1 value) {
this.htrsd1 = value;
}
/**
* Gets the value of the packin property.
*
* @return
* possible object is
* {@link PACKINXlief }
* | */
public PACKINXlief getPACKIN() {
return packin;
}
/**
* Sets the value of the packin property.
*
* @param value
* allowed object is
* {@link PACKINXlief }
*
*/
public void setPACKIN(PACKINXlief value) {
this.packin = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\HEADERXlief.java | 2 |
请完成以下Java代码 | public int getDLM_Referencing_Table_ID()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Referencing_Table_ID);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
/**
* Set DLM aktiviert.
*
* @param IsDLM
* Die Datensätze einer Tabelle mit aktiviertem DLM können vom System unterschiedlichen DLM-Levels zugeordnet werden
*/
@Override
public void setIsDLM(final boolean IsDLM)
{
throw new IllegalArgumentException("IsDLM is virtual column");
}
/**
* Get DLM aktiviert.
* | * @return Die Datensätze einer Tabelle mit aktiviertem DLM können vom System unterschiedlichen DLM-Levels zugeordnet werden
*/
@Override
public boolean isDLM()
{
final Object oo = get_Value(COLUMNNAME_IsDLM);
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.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition_Config_Line.java | 1 |
请完成以下Java代码 | public class DelegatingLogoutSuccessHandler implements LogoutSuccessHandler {
private final LinkedHashMap<RequestMatcher, LogoutSuccessHandler> matcherToHandler;
private @Nullable LogoutSuccessHandler defaultLogoutSuccessHandler;
public DelegatingLogoutSuccessHandler(LinkedHashMap<RequestMatcher, LogoutSuccessHandler> matcherToHandler) {
Assert.notEmpty(matcherToHandler, "matcherToHandler cannot be null");
this.matcherToHandler = matcherToHandler;
}
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
@Nullable Authentication authentication) throws IOException, ServletException {
for (Map.Entry<RequestMatcher, LogoutSuccessHandler> entry : this.matcherToHandler.entrySet()) {
RequestMatcher matcher = entry.getKey();
if (matcher.matches(request)) {
LogoutSuccessHandler handler = entry.getValue();
handler.onLogoutSuccess(request, response, authentication);
return; | }
}
if (this.defaultLogoutSuccessHandler != null) {
this.defaultLogoutSuccessHandler.onLogoutSuccess(request, response, authentication);
}
}
/**
* Sets the default {@link LogoutSuccessHandler} if no other handlers available
* @param defaultLogoutSuccessHandler the defaultLogoutSuccessHandler to set
*/
public void setDefaultLogoutSuccessHandler(LogoutSuccessHandler defaultLogoutSuccessHandler) {
this.defaultLogoutSuccessHandler = defaultLogoutSuccessHandler;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\logout\DelegatingLogoutSuccessHandler.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.