instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public class SpringsteenProblem implements Problem<ISeq<SpringsteenRecord>, BitGene, Double> {
private ISeq<SpringsteenRecord> records;
private double maxPricePerUniqueSong;
public SpringsteenProblem(ISeq<SpringsteenRecord> records, double maxPricePerUniqueSong) {
this.records = requireNonNull(records);
this.maxPricePerUniqueSong = maxPricePerUniqueSong;
}
@Override
public Function<ISeq<SpringsteenRecord>, Double> fitness() {
return SpringsteenRecords -> {
double cost = SpringsteenRecords.stream()
.mapToDouble(r -> r.price)
.sum();
int uniqueSongCount = SpringsteenRecords.stream()
.flatMap(r -> r.songs.stream())
.collect(Collectors.toSet())
.size();
double pricePerUniqueSong = cost / uniqueSongCount;
return pricePerUniqueSong <= maxPricePerUniqueSong ? uniqueSongCount : 0.0;
};
}
@Override
public Codec<ISeq<SpringsteenRecord>, BitGene> codec() {
return codecs.ofSubSet(records);
}
public static void main(String[] args) {
double maxPricePerUniqueSong = 2.5;
SpringsteenProblem springsteen = new SpringsteenProblem(
ISeq.of(new SpringsteenRecord("SpringsteenRecord1", 25, ISeq.of("Song1", "Song2", "Song3", "Song4", "Song5", "Song6")), new SpringsteenRecord("SpringsteenRecord2", 15, ISeq.of("Song2", "Song3", "Song4", "Song5", "Song6", "Song7")),
new SpringsteenRecord("SpringsteenRecord3", 35, ISeq.of("Song5", "Song6", "Song7", "Song8", "Song9", "Song10")), new SpringsteenRecord("SpringsteenRecord4", 17, ISeq.of("Song9", "Song10", "Song12", "Song4", "Song13", "Song14")),
new SpringsteenRecord("SpringsteenRecord5", 29, ISeq.of("Song1", "Song2", "Song13", "Song14", "Song15", "Song16")), new SpringsteenRecord("SpringsteenRecord6", 5, ISeq.of("Song18", "Song20", "Song30", "Song40"))),
maxPricePerUniqueSong);
Engine<BitGene, Double> engine = Engine.builder(springsteen)
.build();
|
ISeq<SpringsteenRecord> result = springsteen.codec()
.decoder()
.apply(engine.stream()
.limit(10)
.collect(EvolutionResult.toBestGenotype()));
double cost = result.stream()
.mapToDouble(r -> r.price)
.sum();
int uniqueSongCount = result.stream()
.flatMap(r -> r.songs.stream())
.collect(Collectors.toSet())
.size();
double pricePerUniqueSong = cost / uniqueSongCount;
System.out.println("Overall cost: " + cost);
System.out.println("Unique songs: " + uniqueSongCount);
System.out.println("Cost per song: " + pricePerUniqueSong);
System.out.println("Records: " + result.map(r -> r.name)
.toString(", "));
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-genetic\src\main\java\com\baeldung\algorithms\ga\jenetics\SpringsteenProblem.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ExpressionManager getExpressionManager() {
return expressionManager;
}
public VariableServiceConfiguration setExpressionManager(ExpressionManager expressionManager) {
this.expressionManager = expressionManager;
return this;
}
public int getMaxLengthString() {
return maxLengthString;
}
public VariableServiceConfiguration setMaxLengthString(int maxLengthString) {
this.maxLengthString = maxLengthString;
return this;
}
public boolean isLoggingSessionEnabled() {
return loggingSessionEnabled;
}
public VariableServiceConfiguration setLoggingSessionEnabled(boolean loggingSessionEnabled) {
this.loggingSessionEnabled = loggingSessionEnabled;
return this;
}
public boolean isSerializableVariableTypeTrackDeserializedObjects() {
|
return serializableVariableTypeTrackDeserializedObjects;
}
public void setSerializableVariableTypeTrackDeserializedObjects(boolean serializableVariableTypeTrackDeserializedObjects) {
this.serializableVariableTypeTrackDeserializedObjects = serializableVariableTypeTrackDeserializedObjects;
}
public VariableJsonMapper getVariableJsonMapper() {
return variableJsonMapper;
}
public void setVariableJsonMapper(VariableJsonMapper variableJsonMapper) {
this.variableJsonMapper = variableJsonMapper;
}
public VariableInstanceValueModifier getVariableInstanceValueModifier() {
return variableInstanceValueModifier;
}
public void setVariableInstanceValueModifier(VariableInstanceValueModifier variableInstanceValueModifier) {
this.variableInstanceValueModifier = variableInstanceValueModifier;
}
}
|
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\VariableServiceConfiguration.java
| 2
|
请完成以下Java代码
|
private IInfoColumnController getInfoColumnControllerOrNull(final I_AD_InfoColumn infoColumn)
{
final IInfoQueryCriteria criteria = getInfoQueryCriteria(infoColumn, false); // don't retrieve the default
if (criteria == null)
{
return null;
}
if (criteria instanceof IInfoColumnController)
{
final IInfoColumnController columnController = (IInfoColumnController)criteria;
return columnController;
}
return null;
}
@Override
protected void prepareTable(final Info_Column[] layout, final String from, final String staticWhere, final String orderBy)
{
super.prepareTable(layout, from, staticWhere, orderBy);
setupInfoColumnControllerBindings();
}
private void setupInfoColumnControllerBindings()
{
for (int i = 0; i < p_layout.length; i++)
{
final int columnIndexModel = i;
final Info_Column infoColumn = p_layout[columnIndexModel];
final IInfoColumnController columnController = infoColumn.getColumnController();
final List<Info_Column> dependentColumns = infoColumn.getDependentColumns();
if (columnController == null
&& (dependentColumns == null || dependentColumns.isEmpty()))
{
// if there is no controller on this column and there are no dependent columns
// then there is no point for adding a binder
continue;
}
final TableModel tableModel = getTableModel();
|
final InfoColumnControllerBinder binder = new InfoColumnControllerBinder(this, infoColumn, columnIndexModel);
tableModel.addTableModelListener(binder);
}
}
@Override
public void setValue(final Info_Column infoColumn, final int rowIndexModel, final Object value)
{
final int colIndexModel = getColumnIndex(infoColumn);
if (colIndexModel < 0)
{
return;
}
p_table.setValueAt(value, rowIndexModel, colIndexModel);
}
@Override
public void setValueByColumnName(final String columnName, final int rowIndexModel, final Object value)
{
final int colIndexModel = getColumnIndex(columnName);
if (colIndexModel < 0)
{
return;
}
p_table.setValueAt(value, rowIndexModel, colIndexModel);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\InfoSimple.java
| 1
|
请完成以下Java代码
|
public boolean isValueChanged(final Object model, final String columnName)
{
return POWrapper.isValueChanged(model, columnName);
}
@Override
public boolean isValueChanged(final Object model, final Set<String> columnNames)
{
return POWrapper.isValueChanged(model, columnNames);
}
@Override
public boolean isNull(final Object model, final String columnName)
{
return POWrapper.isNull(model, columnName);
}
@Nullable
@Override
public <T> T getDynAttribute(final @NonNull Object model, final String attributeName)
{
return POWrapper.getDynAttribute(model, attributeName);
}
@Override
public Object setDynAttribute(final Object model, final String attributeName, final Object value)
{
return POWrapper.setDynAttribute(model, attributeName, value);
}
public <T> T computeDynAttributeIfAbsent(@NonNull final Object model, @NonNull final String attributeName, @NonNull final Supplier<T> supplier)
{
return POWrapper.computeDynAttributeIfAbsent(model, attributeName, supplier);
}
@Override
|
public <T extends PO> T getPO(final Object model, final boolean strict)
{
// always strict, else other wrapper helpers will handle it!
return POWrapper.getStrictPO(model);
}
@Override
public Evaluatee getEvaluatee(final Object model)
{
return POWrapper.getStrictPO(model);
}
@Override
public boolean isCopy(final Object model) {return POWrapper.getStrictPO(model).isCopiedFromOtherRecord();}
@Override
public boolean isCopying(final Object model) {return POWrapper.getStrictPO(model).isCopying();}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POInterfaceWrapperHelper.java
| 1
|
请完成以下Java代码
|
public int countNumberOfRequestsWithFunction(ToIntFunction<List<S>> function) {
return function.applyAsInt(repository.findAll());
}
public Optional<S> getUserById(Long id) {
return repository.findById(id);
}
public void deleteAll() {
repository.deleteAll();
}
public List<S> saveAll(Iterable<S> entities) {
return repository.saveAll(entities);
}
public List<S> findAll() {
return repository.findAll();
}
public Optional<S> getUserByIdWithPredicate(long id, Predicate<S> predicate) {
Optional<S> user = repository.findById(id);
user.ifPresent(predicate::test);
return user;
|
}
public int getUserByIdWithFunction(Long id, ToIntFunction<S> function) {
Optional<S> optionalUser = repository.findById(id);
if (optionalUser.isPresent()) {
return function.applyAsInt(optionalUser.get());
} else {
return 0;
}
}
public void save(S entity) {
repository.save(entity);
}
}
|
repos\tutorials-master\persistence-modules\spring-boot-persistence-2\src\main\java\com\baeldung\listvsset\Service.java
| 1
|
请完成以下Java代码
|
public static HttpHeaders sanitize(HttpHeaders request, List<String> ignoredHeders,
List<String> requestOnlyHeaders) {
HttpHeaders result = new HttpHeaders();
for (String name : request.headerNames()) {
List<String> value = request.get(name);
name = name.toLowerCase(Locale.ROOT);
if (!IGNORED.containsHeader(name) && !REQUEST_ONLY.containsHeader(name) && !ignoredHeders.contains(name)
&& !requestOnlyHeaders.contains(name) && value != null) {
result.put(name, value);
}
}
return result;
}
@SuppressWarnings("unchecked")
public static HttpHeaders sanitize(HttpHeaders request) {
return sanitize(request, Collections.EMPTY_LIST, Collections.EMPTY_LIST);
}
public static MessageHeaders fromHttp(HttpHeaders headers) {
Map<String, Object> map = new LinkedHashMap<>();
for (String name : headers.headerNames()) {
Collection<?> values = multi(headers.get(name));
name = name.toLowerCase(Locale.ROOT);
Object value = values == null ? null : (values.size() == 1 ? values.iterator().next() : values);
if (name.toLowerCase(Locale.ROOT).equals(HttpHeaders.CONTENT_TYPE.toLowerCase(Locale.ROOT))) {
|
name = MessageHeaders.CONTENT_TYPE;
}
map.put(name, value);
}
return new MessageHeaders(map);
}
private static Collection<?> multi(@Nullable Object value) {
if (value == null) {
return Collections.emptyList();
}
return value instanceof Collection ? (Collection<?>) value : List.of(value);
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\FunctionHandlerHeaderUtils.java
| 1
|
请完成以下Java代码
|
private static ZonedDateTime fromObjectToZonedDateTime(final Object valueObj, final ZoneId zoneId)
{
return fromObjectTo(valueObj,
ZonedDateTime.class,
DateTimeConverters::fromJsonToZonedDateTime,
(object) -> TimeUtil.asZonedDateTime(object, zoneId));
}
@Nullable
private static Instant fromObjectToInstant(final Object valueObj, final ZoneId zoneId)
{
return fromObjectTo(valueObj,
Instant.class,
DateTimeConverters::fromJsonToInstant,
(object) -> TimeUtil.asInstant(object, zoneId));
}
@Nullable
private static <T> T fromObjectTo(
@NonNull final Object valueObj,
@NonNull final Class<T> type,
@NonNull final Function<String, T> fromJsonConverter,
@NonNull final Function<Object, T> fromObjectConverter)
{
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 (json.length() == 21 && json.charAt(10) == ' ') // json string - possible in JDBC format (`2016-06-11 00:00:00.0`)
{
final Timestamp timestamp = Timestamp.valueOf(json);
return fromObjectConverter.apply(timestamp);
}
else
{
return fromJsonConverter.apply(json);
}
}
else
{
return fromObjectConverter.apply(valueObj);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\util\converter\DateTimeConverters.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static final class CacheKey
{
int mainRecordId;
DataEntrySubTabId subTabId;
}
@ToString
@VisibleForTesting
static final class DataEntryRecordIdIndex implements CacheIndexDataAdapter<DataEntryRecordId, CacheKey, DataEntryRecord>
{
@Override
public DataEntryRecordId extractDataItemId(final DataEntryRecord dataItem)
{
return dataItem.getId().get();
}
@Override
public ImmutableSet<TableRecordReference> extractRecordRefs(final DataEntryRecord dataItem)
|
{
final DataEntryRecordId id = dataItem.getId().orElse(null);
return id != null
? ImmutableSet.of(TableRecordReference.of(I_DataEntry_Record.Table_Name, id))
: ImmutableSet.of();
}
@Override
public List<CacheKey> extractCacheKeys(final DataEntryRecord dataItem)
{
final CacheKey singleCacheKey = CacheKey.of(dataItem.getMainRecord().getRecord_ID(), dataItem.getDataEntrySubTabId());
return ImmutableList.of(singleCacheKey);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\dataentry\impl\DataEntryRecordCache.java
| 2
|
请完成以下Java代码
|
public java.lang.String getEntityType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** Set Request handler type.
@param IMP_RequestHandlerType_ID Request handler type */
@Override
public void setIMP_RequestHandlerType_ID (int IMP_RequestHandlerType_ID)
{
if (IMP_RequestHandlerType_ID < 1)
set_ValueNoCheck (COLUMNNAME_IMP_RequestHandlerType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_IMP_RequestHandlerType_ID, Integer.valueOf(IMP_RequestHandlerType_ID));
}
/** Get Request handler type.
@return Request handler type */
@Override
public int getIMP_RequestHandlerType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_IMP_RequestHandlerType_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\adempiere\process\rpl\requesthandler\model\X_IMP_RequestHandlerType.java
| 1
|
请完成以下Java代码
|
protected String doIt()
{
final IDunningBL dunningBL = Services.get(IDunningBL.class);
final IDunningContext context = dunningBL.createDunningContext(getCtx(),
null, // DunningDate, not needed
null, // C_DunningLevel, not needed
get_TrxName());
context.setProperty(IDunningProducer.CONTEXT_ProcessDunningDoc, p_isAutoProcess);
//
// Create Async Batch for tracking
// retrieve async batch type
final I_C_Async_Batch_Type asyncBatchType;
asyncBatchType = asyncBatchDAO.retrieveAsyncBatchType(getCtx(), m_asyncBatchType);
Check.assumeNotNull(asyncBatchType, "Defined Async Batch type should not be null for internal name ", m_asyncBatchType);
// Create Async Batch for tracking
final AsyncBatchId asyncBatchId = asyncBatchBL.newAsyncBatch()
.setContext(getCtx())
.setC_Async_Batch_Type(asyncBatchType.getInternalName())
.setAD_PInstance_Creator_ID(getPinstanceId())
.setName(m_AsyncBatchName)
.setDescription(m_AsyncBatchDesc)
.buildAndEnqueue();
context.setProperty(IDunningProducer.CONTEXT_AsyncBatchIdDunningDoc, asyncBatchId);
final SelectedDunningCandidatesSource source = new SelectedDunningCandidatesSource(getProcessInfo().getWhereClause());
source.setDunningContext(context);
dunningBL.processCandidates(context, source);
return MSG_OK;
}
/**
* This dunning candidate source returns only those candidates that have been selected by the user.
|
*/
private static final class SelectedDunningCandidatesSource extends AbstractDunningCandidateSource
{
private final String whereClause;
public SelectedDunningCandidatesSource(final String whereClause)
{
this.whereClause = whereClause;
}
@Override
public Iterator<I_C_Dunning_Candidate> iterator()
{
final IDunningDAO dunningDAO = Services.get(IDunningDAO.class);
final Iterator<I_C_Dunning_Candidate> it = dunningDAO.retrieveNotProcessedCandidatesIteratorRW(getDunningContext(), whereClause);
return it;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\process\C_Dunning_Candidate_Process.java
| 1
|
请完成以下Java代码
|
private void checkIdempotency(OrderStateEnum curOrderState, List<OrderStateEnum> allowStateList) {
// allowStateList为空
if (CollectionUtils.isEmpty(allowStateList)) {
throw new CommonSysException(ExpCodeEnum.AllowStateList_NULL);
}
for (OrderStateEnum orderStateEnum : allowStateList) {
if (orderStateEnum == curOrderState) {
// 幂等性检查通过
return;
}
}
// 幂等性检查不通过
throw new CommonBizException(ExpCodeEnum.NO_REPEAT);
}
/**
* 获取当前订单的状态
* @param orderProcessContext 订单受理上下文
* @return 订单状态
*/
private OrderStateEnum getOrderState(OrderProcessContext orderProcessContext) {
// 获取订单ID
String orderId = orderProcessContext.getOrderProcessReq().getOrderId();
if (StringUtils.isEmpty(orderId)) {
throw new CommonBizException(ExpCodeEnum.PROCESSREQ_ORDERID_NULL);
}
// 查询订单
OrderQueryReq orderQueryReq = new OrderQueryReq();
orderQueryReq.setId(orderId);
List<OrdersEntity> ordersEntityList = orderDAO.findOrders(orderQueryReq);
// 订单不存在
if (CollectionUtils.isEmpty(ordersEntityList)) {
throw new CommonBizException(ExpCodeEnum.ORDER_NULL);
}
|
// 获取订单状态
// TODO 更新订单状态时,要连带更新order表中的状态
OrderStateEnum orderStateEnum = ordersEntityList.get(0).getOrderStateEnum();
// 订单存在 & 订单状态不存在
if (orderStateEnum == null) {
throw new CommonBizException(ExpCodeEnum.ORDER_STATE_NULL);
}
// 返回订单状态
return orderStateEnum;
}
/**
* 设置订单允许的状态(子类必须重写这个函数)
*/
protected abstract void setAllowStateList();
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\component\idempotent\BaseIdempotencyComponent.java
| 1
|
请完成以下Java代码
|
private static void updateReservationRecord(
@NonNull final I_C_Payment_Reservation record,
@NonNull final PaymentReservation from)
{
InterfaceWrapperHelper.setValue(record, "AD_Client_ID", from.getClientId().getRepoId());
record.setAD_Org_ID(from.getOrgId().getRepoId());
record.setAmount(from.getAmount().toBigDecimal());
record.setBill_BPartner_ID(from.getPayerContactId().getBpartnerId().getRepoId());
record.setBill_User_ID(from.getPayerContactId().getUserId().getRepoId());
record.setBill_EMail(from.getPayerEmail().getAsString());
record.setC_Currency_ID(from.getAmount().getCurrencyId().getRepoId());
record.setC_Order_ID(from.getSalesOrderId().getRepoId());
record.setDateTrx(TimeUtil.asTimestamp(from.getDateTrx()));
record.setPaymentRule(from.getPaymentRule().getCode());
record.setStatus(from.getStatus().getCode());
}
private static PaymentReservation toPaymentReservation(@NonNull final I_C_Payment_Reservation record)
|
{
final CurrencyId currencyId = CurrencyId.ofRepoId(record.getC_Currency_ID());
return PaymentReservation.builder()
.id(PaymentReservationId.ofRepoId(record.getC_Payment_Reservation_ID()))
.clientId(ClientId.ofRepoId(record.getAD_Client_ID()))
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.amount(Money.of(record.getAmount(), currencyId))
.payerContactId(BPartnerContactId.ofRepoId(record.getBill_BPartner_ID(), record.getBill_User_ID()))
.payerEmail(EMailAddress.ofString(record.getBill_EMail()))
.salesOrderId(OrderId.ofRepoId(record.getC_Order_ID()))
.dateTrx(TimeUtil.asLocalDate(record.getDateTrx()))
.paymentRule(PaymentRule.ofCode(record.getPaymentRule()))
.status(PaymentReservationStatus.ofCode(record.getStatus()))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\reservation\PaymentReservationRepository.java
| 1
|
请完成以下Java代码
|
public void setAD_Process_Para_ID (final int AD_Process_Para_ID)
{
if (AD_Process_Para_ID < 1)
set_Value (COLUMNNAME_AD_Process_Para_ID, null);
else
set_Value (COLUMNNAME_AD_Process_Para_ID, AD_Process_Para_ID);
}
@Override
public int getAD_Process_Para_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Process_Para_ID);
}
@Override
public void setAD_WF_Node_ID (final int AD_WF_Node_ID)
{
if (AD_WF_Node_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_WF_Node_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_WF_Node_ID, AD_WF_Node_ID);
}
@Override
public int getAD_WF_Node_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_WF_Node_ID);
}
@Override
public void setAD_WF_Node_Para_ID (final int AD_WF_Node_Para_ID)
{
if (AD_WF_Node_Para_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_WF_Node_Para_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_WF_Node_Para_ID, AD_WF_Node_Para_ID);
}
@Override
public int getAD_WF_Node_Para_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_WF_Node_Para_ID);
}
@Override
public void setAttributeName (final java.lang.String AttributeName)
{
set_Value (COLUMNNAME_AttributeName, AttributeName);
}
@Override
public java.lang.String getAttributeName()
{
return get_ValueAsString(COLUMNNAME_AttributeName);
}
@Override
public void setAttributeValue (final java.lang.String AttributeValue)
{
set_Value (COLUMNNAME_AttributeValue, AttributeValue);
}
|
@Override
public java.lang.String getAttributeValue()
{
return get_ValueAsString(COLUMNNAME_AttributeValue);
}
@Override
public void setDescription (final java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
@Override
public void setEntityType (final java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
@Override
public java.lang.String getEntityType()
{
return get_ValueAsString(COLUMNNAME_EntityType);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Node_Para.java
| 1
|
请完成以下Java代码
|
public void setC_TaxGroup_ID (int C_TaxGroup_ID)
{
if (C_TaxGroup_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_TaxGroup_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_TaxGroup_ID, Integer.valueOf(C_TaxGroup_ID));
}
/** Get Tax Group.
@return Tax Group */
public int getC_TaxGroup_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_TaxGroup_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 Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
|
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_C_TaxGroup.java
| 1
|
请完成以下Java代码
|
public void objectInserted(ObjectInsertedEvent event) {
System.out.println("Object inserted \n "
+ event.getObject().toString());
}
@Override
public void objectUpdated(ObjectUpdatedEvent event) {
System.out.println("Object was updated \n"
+ "New Content \n"
+ event.getObject().toString());
}
@Override
public void objectDeleted(ObjectDeletedEvent event) {
System.out.println("Object retracted \n"
+ event.getOldObject().toString());
}
});
return kieSession;
}
@Bean
public KieContainer getKieContainer() throws IOException {
LOGGER.info("Container created...");
getKieRepository();
KieBuilder kb = kieServices.newKieBuilder(getKieFileSystem());
|
kb.buildAll();
KieModule kieModule = kb.getKieModule();
return kieServices.newKieContainer(kieModule.getReleaseId());
}
private void getKieRepository() {
final KieRepository kieRepository = kieServices.getRepository();
kieRepository.addKieModule(new KieModule() {
@Override
public ReleaseId getReleaseId() {
return kieRepository.getDefaultReleaseId();
}
});
}
private KieFileSystem getKieFileSystem() throws IOException {
KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
kieFileSystem.write(ResourceFactory.newClassPathResource("order.drl"));
return kieFileSystem;
}
}
|
repos\springboot-demo-master\drools\src\main\java\com\et\drools\DroolsConfig.java
| 1
|
请完成以下Java代码
|
public final HttpHeaders headers() {
return this.headers;
}
@Override
public MultiValueMap<String, Cookie> cookies() {
return this.cookies;
}
@Override
public @Nullable ModelAndView writeTo(HttpServletRequest request, HttpServletResponse response, Context context)
throws ServletException, IOException {
try {
writeStatusAndHeaders(response);
long lastModified = headers().getLastModified();
ServletWebRequest servletWebRequest = new ServletWebRequest(request, response);
HttpMethod httpMethod = HttpMethod.valueOf(request.getMethod());
if (SAFE_METHODS.contains(httpMethod)
&& servletWebRequest.checkNotModified(headers().getETag(), lastModified)) {
return null;
}
else {
return writeToInternal(request, response, context);
}
}
catch (Throwable throwable) {
return handleError(throwable, request, response, context);
}
}
private void writeStatusAndHeaders(HttpServletResponse response) {
response.setStatus(this.statusCode.value());
writeHeaders(response);
writeCookies(response);
}
private void writeHeaders(HttpServletResponse servletResponse) {
|
this.headers.forEach((headerName, headerValues) -> {
for (String headerValue : headerValues) {
servletResponse.addHeader(headerName, headerValue);
}
});
// HttpServletResponse exposes some headers as properties: we should include those
// if not already present
if (servletResponse.getContentType() == null && this.headers.getContentType() != null) {
servletResponse.setContentType(this.headers.getContentType().toString());
}
if (servletResponse.getCharacterEncoding() == null && this.headers.getContentType() != null
&& this.headers.getContentType().getCharset() != null) {
servletResponse.setCharacterEncoding(this.headers.getContentType().getCharset().name());
}
}
private void writeCookies(HttpServletResponse servletResponse) {
this.cookies.values().stream().flatMap(Collection::stream).forEach(servletResponse::addCookie);
}
protected abstract @Nullable ModelAndView writeToInternal(HttpServletRequest request, HttpServletResponse response,
Context context) throws Exception;
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\AbstractGatewayServerResponse.java
| 1
|
请完成以下Spring Boot application配置
|
auth-server: http://localhost:8085/uac
server:
port: 8086
security:
oauth2:
client:
client-id: sheep1
client-secret: 123456
user-authorization-uri: ${auth-server}/oauth/authorize
access-token-uri:
|
${auth-server}/oauth/token
resource:
jwt:
key-uri: ${auth-server}/oauth/token_key
|
repos\Spring-Boot-In-Action-master\springbt_sso_jwt\codesheep-client1\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
protected String doIt() throws Exception
{
final IQueryFilter<I_M_ShipmentSchedule> queryFilters = createShipmentSchedulesQueryFilters();
Check.assumeNotNull(queryFilters, "Shipment Schedule queryFilters shall not be null");
final ShipmentScheduleWorkPackageParameters workPackageParameters = ShipmentScheduleWorkPackageParameters.builder()
.adPInstanceId(getPinstanceId())
.queryFilters(queryFilters)
.quantityType(quantityType)
.completeShipments(isCompleteShipments)
.isShipmentDateToday(isShipToday)
.build();
final Result result = ShipmentScheduleEnqueuer.newInstance(getCtx(), getTrxName())
.createWorkpackages(workPackageParameters);
return "@Created@: " + result.getEnqueuedPackagesCount() + " @" + I_C_Queue_WorkPackage.COLUMNNAME_C_Queue_WorkPackage_ID + "@; @Skip@ " + result.getSkippedPackagesCount();
}
@NonNull
private IQueryFilter<I_M_ShipmentSchedule> createShipmentSchedulesQueryFilters()
{
final ICompositeQueryFilter<I_M_ShipmentSchedule> filters = queryBL.createCompositeQueryFilter(I_M_ShipmentSchedule.class);
filters.addOnlyActiveRecordsFilter();
//
|
// Filter only selected shipment schedules
if (Ini.isSwingClient())
{
final IQueryFilter<I_M_ShipmentSchedule> selectionFilter = getProcessInfo().getQueryFilterOrElseTrue();
filters.addFilter(selectionFilter);
}
else
{
final IQueryFilter<I_M_ShipmentSchedule> selectionFilter = getProcessInfo().getQueryFilterOrElse(null);
if (selectionFilter == null)
{
throw new AdempiereException("@NoSelection@");
}
filters.addFilter(selectionFilter);
}
return shipmentService.createShipmentScheduleEnqueuerQueryFilters(filters, nowInstant);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\process\M_ShipmentSchedule_EnqueueSelection.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ShipperExtensionType {
@XmlElement(name = "TypeOfTransportDocument")
protected String typeOfTransportDocument;
@XmlElement(name = "TransportDocumentNumber")
protected String transportDocumentNumber;
@XmlElement(name = "TransportDocumentDate")
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar transportDocumentDate;
@XmlElement(name = "SCAC")
protected String scac;
/**
* Gets the value of the typeOfTransportDocument property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTypeOfTransportDocument() {
return typeOfTransportDocument;
}
/**
* Sets the value of the typeOfTransportDocument property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTypeOfTransportDocument(String value) {
this.typeOfTransportDocument = value;
}
/**
* Gets the value of the transportDocumentNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTransportDocumentNumber() {
return transportDocumentNumber;
}
/**
* Sets the value of the transportDocumentNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTransportDocumentNumber(String value) {
this.transportDocumentNumber = value;
}
/**
* Gets the value of the transportDocumentDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
|
public XMLGregorianCalendar getTransportDocumentDate() {
return transportDocumentDate;
}
/**
* Sets the value of the transportDocumentDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setTransportDocumentDate(XMLGregorianCalendar value) {
this.transportDocumentDate = value;
}
/**
* Gets the value of the scac property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSCAC() {
return scac;
}
/**
* Sets the value of the scac property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSCAC(String value) {
this.scac = 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\ShipperExtensionType.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void setPaidAmt (final BigDecimal PaidAmt)
{
set_Value (COLUMNNAME_PaidAmt, PaidAmt);
}
@Override
public BigDecimal getPaidAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PaidAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
/**
* Status AD_Reference_ID=541890
* Reference name: C_POS_Order_Status
*/
public static final int STATUS_AD_Reference_ID=541890;
/** Drafted = DR */
public static final String STATUS_Drafted = "DR";
/** WaitingPayment = WP */
public static final String STATUS_WaitingPayment = "WP";
/** Completed = CO */
public static final String STATUS_Completed = "CO";
/** Voided = VO */
public static final String STATUS_Voided = "VO";
|
/** Closed = CL */
public static final String STATUS_Closed = "CL";
@Override
public void setStatus (final java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return get_ValueAsString(COLUMNNAME_Status);
}
@Override
public void setTaxAmt (final BigDecimal TaxAmt)
{
set_Value (COLUMNNAME_TaxAmt, TaxAmt);
}
@Override
public BigDecimal getTaxAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_Order.java
| 2
|
请完成以下Java代码
|
public int getC_OLCand_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OLCand_ID);
}
@Override
public void setC_OLCand_Paypal_ID (final int C_OLCand_Paypal_ID)
{
if (C_OLCand_Paypal_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_OLCand_Paypal_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_OLCand_Paypal_ID, C_OLCand_Paypal_ID);
}
@Override
public int getC_OLCand_Paypal_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OLCand_Paypal_ID);
}
@Override
public void setPayPal_Token (final @Nullable java.lang.String PayPal_Token)
{
set_Value (COLUMNNAME_PayPal_Token, PayPal_Token);
}
|
@Override
public java.lang.String getPayPal_Token()
{
return get_ValueAsString(COLUMNNAME_PayPal_Token);
}
@Override
public void setPayPal_Transaction_ID (final @Nullable java.lang.String PayPal_Transaction_ID)
{
set_Value (COLUMNNAME_PayPal_Transaction_ID, PayPal_Transaction_ID);
}
@Override
public java.lang.String getPayPal_Transaction_ID()
{
return get_ValueAsString(COLUMNNAME_PayPal_Transaction_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java-gen\de\metas\payment\paypal\model\X_C_OLCand_Paypal.java
| 1
|
请完成以下Java代码
|
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Notiz.
@param Note
Optional additional user defined information
*/
@Override
public void setNote (java.lang.String Note)
{
set_Value (COLUMNNAME_Note, Note);
}
/** Get Notiz.
@return Optional additional user defined information
*/
@Override
public java.lang.String getNote ()
{
return (java.lang.String)get_Value(COLUMNNAME_Note);
}
/** Set Notiz Header.
@param NoteHeader
Optional weitere Information für ein Dokument
*/
@Override
public void setNoteHeader (java.lang.String NoteHeader)
{
set_Value (COLUMNNAME_NoteHeader, NoteHeader);
}
|
/** Get Notiz Header.
@return Optional weitere Information für ein Dokument
*/
@Override
public java.lang.String getNoteHeader ()
{
return (java.lang.String)get_Value(COLUMNNAME_NoteHeader);
}
/** Set Drucktext.
@param PrintName
The label text to be printed on a document or correspondence.
*/
@Override
public void setPrintName (java.lang.String PrintName)
{
set_Value (COLUMNNAME_PrintName, PrintName);
}
/** Get Drucktext.
@return The label text to be printed on a document or correspondence.
*/
@Override
public java.lang.String getPrintName ()
{
return (java.lang.String)get_Value(COLUMNNAME_PrintName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DunningLevel.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void insert(DeadLetterJobEntity jobEntity) {
insert(jobEntity, true);
}
@Override
public void delete(DeadLetterJobEntity jobEntity) {
super.delete(jobEntity);
deleteByteArrayRef(jobEntity.getExceptionByteArrayRef());
deleteByteArrayRef(jobEntity.getCustomValuesByteArrayRef());
// If the job used to be a history job, the configuration contains the id of the byte array containing the history json
// (because deadletter jobs don't have an advanced configuration column)
if (HistoryJobEntity.HISTORY_JOB_TYPE.equals(jobEntity.getJobType()) && jobEntity.getJobHandlerConfiguration() != null) {
// To avoid duplicating the byteArrayEntityManager lookup, a (fake) ByteArrayRef is created.
new ByteArrayRef(jobEntity.getJobHandlerConfiguration(), serviceConfiguration.getCommandExecutor()).delete(serviceConfiguration.getEngineName());
}
if (getServiceConfiguration().getInternalJobManager() != null) {
getServiceConfiguration().getInternalJobManager().handleJobDelete(jobEntity);
}
// Send event
if (getEventDispatcher() != null && getEventDispatcher().isEnabled()) {
getEventDispatcher().dispatchEvent(FlowableJobEventBuilder.createEntityEvent(
FlowableEngineEventType.ENTITY_DELETED, jobEntity), engineType);
}
}
|
protected DeadLetterJobEntity createDeadLetterJob(AbstractRuntimeJobEntity job) {
DeadLetterJobEntity newJobEntity = create();
newJobEntity.setJobHandlerConfiguration(job.getJobHandlerConfiguration());
newJobEntity.setCustomValues(job.getCustomValues());
newJobEntity.setJobHandlerType(job.getJobHandlerType());
newJobEntity.setExclusive(job.isExclusive());
newJobEntity.setRepeat(job.getRepeat());
newJobEntity.setRetries(job.getRetries());
newJobEntity.setEndDate(job.getEndDate());
newJobEntity.setExecutionId(job.getExecutionId());
newJobEntity.setProcessInstanceId(job.getProcessInstanceId());
newJobEntity.setProcessDefinitionId(job.getProcessDefinitionId());
newJobEntity.setScopeId(job.getScopeId());
newJobEntity.setSubScopeId(job.getSubScopeId());
newJobEntity.setScopeType(job.getScopeType());
newJobEntity.setScopeDefinitionId(job.getScopeDefinitionId());
// Inherit tenant
newJobEntity.setTenantId(job.getTenantId());
newJobEntity.setJobType(job.getJobType());
return newJobEntity;
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\DeadLetterJobEntityManagerImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public final class TransactionManagerCustomizers {
private final List<? extends TransactionManagerCustomizer<?>> customizers;
private TransactionManagerCustomizers(List<? extends TransactionManagerCustomizer<?>> customizers) {
this.customizers = customizers;
}
/**
* Customize the given {@code transactionManager}.
* @param transactionManager the transaction manager to customize
*/
@SuppressWarnings("unchecked")
public void customize(TransactionManager transactionManager) {
LambdaSafe.callbacks(TransactionManagerCustomizer.class, this.customizers, transactionManager)
.withLogger(TransactionManagerCustomizers.class)
.invoke((customizer) -> customizer.customize(transactionManager));
|
}
/**
* Returns a new {@code TransactionManagerCustomizers} instance containing the given
* {@code customizers}.
* @param customizers the customizers
* @return the new instance
*/
public static TransactionManagerCustomizers of(
@Nullable Collection<? extends TransactionManagerCustomizer<?>> customizers) {
return new TransactionManagerCustomizers(
(customizers != null) ? new ArrayList<>(customizers) : Collections.emptyList());
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-transaction\src\main\java\org\springframework\boot\transaction\autoconfigure\TransactionManagerCustomizers.java
| 2
|
请完成以下Java代码
|
public Duration getTimeout() {
return this.timeout;
}
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
public Tcp getTcp() {
return this.tcp;
}
/**
* Readiness wait strategies.
*/
public enum Wait {
/**
* Always perform readiness checks.
*/
ALWAYS,
/**
* Never perform readiness checks.
*/
NEVER,
/**
* Only perform readiness checks if docker was started with lifecycle
* management.
*/
ONLY_IF_STARTED
}
/**
* TCP properties.
*/
public static class Tcp {
/**
* Timeout for connections.
*/
private Duration connectTimeout = Duration.ofMillis(200);
|
/**
* Timeout for reads.
*/
private Duration readTimeout = Duration.ofMillis(200);
public Duration getConnectTimeout() {
return this.connectTimeout;
}
public void setConnectTimeout(Duration connectTimeout) {
this.connectTimeout = connectTimeout;
}
public Duration getReadTimeout() {
return this.readTimeout;
}
public void setReadTimeout(Duration readTimeout) {
this.readTimeout = readTimeout;
}
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\lifecycle\DockerComposeProperties.java
| 1
|
请完成以下Java代码
|
protected void prepareTable(final Info_Column[] layout, final String from, final String staticWhere, final String orderBy)
{
super.prepareTable(layout, from, staticWhere, orderBy);
setupInfoColumnControllerBindings();
}
private void setupInfoColumnControllerBindings()
{
for (int i = 0; i < p_layout.length; i++)
{
final int columnIndexModel = i;
final Info_Column infoColumn = p_layout[columnIndexModel];
final IInfoColumnController columnController = infoColumn.getColumnController();
final List<Info_Column> dependentColumns = infoColumn.getDependentColumns();
if (columnController == null
&& (dependentColumns == null || dependentColumns.isEmpty()))
{
// if there is no controller on this column and there are no dependent columns
// then there is no point for adding a binder
continue;
}
final TableModel tableModel = getTableModel();
final InfoColumnControllerBinder binder = new InfoColumnControllerBinder(this, infoColumn, columnIndexModel);
tableModel.addTableModelListener(binder);
}
}
@Override
public void setValue(final Info_Column infoColumn, final int rowIndexModel, final Object value)
{
|
final int colIndexModel = getColumnIndex(infoColumn);
if (colIndexModel < 0)
{
return;
}
p_table.setValueAt(value, rowIndexModel, colIndexModel);
}
@Override
public void setValueByColumnName(final String columnName, final int rowIndexModel, final Object value)
{
final int colIndexModel = getColumnIndex(columnName);
if (colIndexModel < 0)
{
return;
}
p_table.setValueAt(value, rowIndexModel, colIndexModel);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\InfoSimple.java
| 1
|
请完成以下Java代码
|
protected void filterOnOptimisticLockingFailure(CommandContext commandContext, final List<LockedExternalTask> tasks) {
commandContext.getDbEntityManager().registerOptimisticLockingListener(new OptimisticLockingListener() {
@Override
public Class<? extends DbEntity> getEntityType() {
return ExternalTaskEntity.class;
}
@Override
public OptimisticLockingResult failedOperation(DbOperation operation) {
if (operation instanceof DbEntityOperation) {
DbEntityOperation dbEntityOperation = (DbEntityOperation) operation;
DbEntity dbEntity = dbEntityOperation.getEntity();
boolean failedOperationEntityInList = false;
Iterator<LockedExternalTask> it = tasks.iterator();
while (it.hasNext()) {
LockedExternalTask resultTask = it.next();
if (resultTask.getId().equals(dbEntity.getId())) {
it.remove();
failedOperationEntityInList = true;
break;
}
}
// If the entity that failed with an OLE is not in the list,
// we rethrow the OLE to the caller.
if (!failedOperationEntityInList) {
return OptimisticLockingResult.THROW;
}
// If the entity that failed with an OLE has been removed
// from the list, we suppress the OLE.
return OptimisticLockingResult.IGNORE;
}
// If none of the conditions are satisfied, this might indicate a bug,
|
// so we throw the OLE.
return OptimisticLockingResult.THROW;
}
});
}
protected void validateInput() {
EnsureUtil.ensureNotNull("workerId", workerId);
EnsureUtil.ensureGreaterThanOrEqual("maxResults", maxResults, 0);
for (TopicFetchInstruction instruction : fetchInstructions.values()) {
EnsureUtil.ensureNotNull("topicName", instruction.getTopicName());
EnsureUtil.ensurePositive("lockTime", instruction.getLockDuration());
}
}
protected List<QueryOrderingProperty> orderingPropertiesWithPriority(boolean usePriority,
List<QueryOrderingProperty> queryOrderingProperties) {
List<QueryOrderingProperty> results = new ArrayList<>();
// Priority needs to be the first item in the list because it takes precedence over other sorting options
// Multi level ordering works by going through the list of ordering properties from first to last item
if (usePriority) {
results.add(new QueryOrderingProperty(PRIORITY, DESCENDING));
}
results.addAll(queryOrderingProperties);
return results;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\FetchExternalTasksCmd.java
| 1
|
请完成以下Spring Boot application配置
|
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=12345678
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create
#logging.level.net.sf.ehcache=debug
# 不同实例的配置
#spring.cache.ehcache.config=classpath:ehcache-1.xml
#spring.cache.ehcache.config=classpath:ehcache
|
-2.xml
# 用不同命令启动不同实例
#-Dserver.port=8001 -Dspring.cache.ehcache.config=classpath:ehcache-1.xml
#-Dserver.port=8002 -Dspring.cache.ehcache.config=classpath:ehcache-2.xml
|
repos\SpringBoot-Learning-master\2.x\chapter5-3\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public Void call() throws Exception {
performNext();
return null;
}
}, targetProcessApplication, new InvocationContext(nextInvocation.execution));
}
else {
if(!nextInvocation.operation.isAsyncCapable()) {
// if operation is not async capable, perform right away.
invokeNext();
}
else {
try {
isExecuting = true;
while (! queuedInvocations.isEmpty()) {
// assumption: all operations are executed within the same process application...
invokeNext();
}
}
finally {
isExecuting = false;
}
}
}
}
protected void invokeNext() {
AtomicOperationInvocation invocation = queuedInvocations.remove(0);
try {
invocation.execute(bpmnStackTrace, processDataContext);
} catch(RuntimeException e) {
// log bpmn stacktrace
bpmnStackTrace.printStackTrace(Context.getProcessEngineConfiguration().isBpmnStacktraceVerbose());
// rethrow
throw e;
}
|
}
protected boolean requiresContextSwitch(ProcessApplicationReference processApplicationReference) {
return ProcessApplicationContextUtil.requiresContextSwitch(processApplicationReference);
}
protected ProcessApplicationReference getTargetProcessApplication(ExecutionEntity execution) {
return ProcessApplicationContextUtil.getTargetProcessApplication(execution);
}
public void rethrow() {
if (throwable != null) {
if (throwable instanceof Error) {
throw (Error) throwable;
} else if (throwable instanceof RuntimeException) {
throw (RuntimeException) throwable;
} else {
throw new ProcessEngineException("exception while executing command " + command, throwable);
}
}
}
public ProcessDataContext getProcessDataContext() {
return processDataContext;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\interceptor\CommandInvocationContext.java
| 1
|
请完成以下Java代码
|
public void setDK_CustomerNumber (java.lang.String DK_CustomerNumber)
{
set_Value (COLUMNNAME_DK_CustomerNumber, DK_CustomerNumber);
}
/** Get Kundennummer.
@return Kundennummer */
@Override
public java.lang.String getDK_CustomerNumber ()
{
return (java.lang.String)get_Value(COLUMNNAME_DK_CustomerNumber);
}
/** Set Gewünschte Lieferuhrzeit von.
@param DK_DesiredDeliveryTime_From Gewünschte Lieferuhrzeit von */
@Override
public void setDK_DesiredDeliveryTime_From (java.sql.Timestamp DK_DesiredDeliveryTime_From)
{
set_Value (COLUMNNAME_DK_DesiredDeliveryTime_From, DK_DesiredDeliveryTime_From);
}
/** Get Gewünschte Lieferuhrzeit von.
@return Gewünschte Lieferuhrzeit von */
@Override
public java.sql.Timestamp getDK_DesiredDeliveryTime_From ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DK_DesiredDeliveryTime_From);
}
/** Set Gewünschte Lieferuhrzeit bis.
@param DK_DesiredDeliveryTime_To Gewünschte Lieferuhrzeit bis */
@Override
public void setDK_DesiredDeliveryTime_To (java.sql.Timestamp DK_DesiredDeliveryTime_To)
{
set_Value (COLUMNNAME_DK_DesiredDeliveryTime_To, DK_DesiredDeliveryTime_To);
}
/** Get Gewünschte Lieferuhrzeit bis.
@return Gewünschte Lieferuhrzeit bis */
@Override
public java.sql.Timestamp getDK_DesiredDeliveryTime_To ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DK_DesiredDeliveryTime_To);
}
/** Set EMail Empfänger.
@param EMail_To
EMail address to send requests to - e.g. edi@manufacturer.com
*/
@Override
public void setEMail_To (java.lang.String EMail_To)
{
set_Value (COLUMNNAME_EMail_To, EMail_To);
}
/** Get EMail Empfänger.
@return EMail address to send requests to - e.g. edi@manufacturer.com
*/
@Override
public java.lang.String getEMail_To ()
{
return (java.lang.String)get_Value(COLUMNNAME_EMail_To);
}
|
@Override
public org.compiere.model.I_M_Shipper getM_Shipper() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class);
}
@Override
public void setM_Shipper(org.compiere.model.I_M_Shipper M_Shipper)
{
set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper);
}
/** Set Lieferweg.
@param M_Shipper_ID
Methode oder Art der Warenlieferung
*/
@Override
public void setM_Shipper_ID (int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, Integer.valueOf(M_Shipper_ID));
}
/** Get Lieferweg.
@return Methode oder Art der Warenlieferung
*/
@Override
public int getM_Shipper_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipper_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java-gen\de\metas\shipper\gateway\derkurier\model\X_DerKurier_Shipper_Config.java
| 1
|
请完成以下Java代码
|
public static VersionProperty of(String property, boolean internal) {
return new VersionProperty(property, internal);
}
/**
* Create an internal {@link VersionProperty}.
* @param property the name of the property
* @return a version property whose format can be tuned according to the build system
*/
public static VersionProperty of(String property) {
return of(property, true);
}
/**
* Specify if the property is internally defined and can be tuned according to the
* build system.
* @return {@code true} if the property is defined within the scope of this project
*/
public boolean isInternal() {
return this.internal;
}
/**
* Return a camel cased representation of this instance.
* @return the property in camel case format
*/
public String toCamelCaseFormat() {
String[] tokens = this.property.split("[-.]");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < tokens.length; i++) {
String part = tokens[i];
if (i > 0) {
part = StringUtils.capitalize(part);
}
sb.append(part);
}
return sb.toString();
}
public String toStandardFormat() {
return this.property;
}
private static String validateFormat(String property) {
for (char c : property.toCharArray()) {
if (Character.isUpperCase(c)) {
throw new IllegalArgumentException("Invalid property '" + property + "', must not contain upper case");
}
if (!Character.isLetterOrDigit(c) && !SUPPORTED_CHARS.contains(c)) {
throw new IllegalArgumentException("Unsupported character '" + c + "' for '" + property + "'");
}
}
return property;
}
@Override
public int compareTo(VersionProperty o) {
|
return this.property.compareTo(o.property);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
VersionProperty that = (VersionProperty) o;
return this.internal == that.internal && this.property.equals(that.property);
}
@Override
public int hashCode() {
return Objects.hash(this.property, this.internal);
}
@Override
public String toString() {
return this.property;
}
}
|
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\version\VersionProperty.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public int hashCode() {
return this.options.hashCode();
}
@Override
public String toString() {
return this.options.toString();
}
/**
* Create a new {@link Options} instance that contains the options in this set
* excluding the given option.
* @param option the option to exclude
* @return a new {@link Options} instance
*/
public Options without(Option option) {
return copy((options) -> options.remove(option));
}
/**
* Create a new {@link Options} instance that contains the options in this set
* including the given option.
* @param option the option to include
* @return a new {@link Options} instance
*/
public Options with(Option option) {
return copy((options) -> options.add(option));
}
private Options copy(Consumer<EnumSet<Option>> processor) {
EnumSet<Option> options = (!this.options.isEmpty()) ? EnumSet.copyOf(this.options)
: EnumSet.noneOf(Option.class);
processor.accept(options);
return new Options(options);
}
/**
* Create a new instance with the given {@link Option} values.
* @param options the options to include
* @return a new {@link Options} instance
*/
public static Options of(Option... options) {
Assert.notNull(options, "'options' must not be null");
if (options.length == 0) {
return NONE;
}
return new Options(EnumSet.copyOf(Arrays.asList(options)));
}
}
|
/**
* Option flags that can be applied.
*/
public enum Option {
/**
* Ignore all imports properties from the source.
*/
IGNORE_IMPORTS,
/**
* Ignore all profile activation and include properties.
* @since 2.4.3
*/
IGNORE_PROFILES,
/**
* Indicates that the source is "profile specific" and should be included after
* profile specific sibling imports.
* @since 2.4.5
*/
PROFILE_SPECIFIC
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigData.java
| 2
|
请完成以下Java代码
|
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;
|
}
/** Set Send.
@param SendIt Send */
public void setSendIt (String SendIt)
{
set_Value (COLUMNNAME_SendIt, SendIt);
}
/** Get Send.
@return Send */
public String getSendIt ()
{
return (String)get_Value(COLUMNNAME_SendIt);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DunningRun.java
| 1
|
请完成以下Java代码
|
public void setM_CostRevaluation(final org.compiere.model.I_M_CostRevaluation M_CostRevaluation)
{
set_ValueFromPO(COLUMNNAME_M_CostRevaluation_ID, org.compiere.model.I_M_CostRevaluation.class, M_CostRevaluation);
}
@Override
public void setM_CostRevaluation_ID (final int M_CostRevaluation_ID)
{
if (M_CostRevaluation_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_CostRevaluation_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_CostRevaluation_ID, M_CostRevaluation_ID);
}
@Override
public int getM_CostRevaluation_ID()
{
return get_ValueAsInt(COLUMNNAME_M_CostRevaluation_ID);
}
@Override
public void setM_CostRevaluationLine_ID (final int M_CostRevaluationLine_ID)
{
if (M_CostRevaluationLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_CostRevaluationLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_CostRevaluationLine_ID, M_CostRevaluationLine_ID);
}
@Override
public int getM_CostRevaluationLine_ID()
{
return get_ValueAsInt(COLUMNNAME_M_CostRevaluationLine_ID);
}
@Override
public org.compiere.model.I_M_CostType getM_CostType()
{
return get_ValueAsPO(COLUMNNAME_M_CostType_ID, org.compiere.model.I_M_CostType.class);
}
@Override
public void setM_CostType(final org.compiere.model.I_M_CostType M_CostType)
{
set_ValueFromPO(COLUMNNAME_M_CostType_ID, org.compiere.model.I_M_CostType.class, M_CostType);
}
@Override
public void setM_CostType_ID (final int M_CostType_ID)
{
if (M_CostType_ID < 1)
set_Value (COLUMNNAME_M_CostType_ID, null);
else
set_Value (COLUMNNAME_M_CostType_ID, M_CostType_ID);
}
@Override
public int getM_CostType_ID()
{
|
return get_ValueAsInt(COLUMNNAME_M_CostType_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setNewCostPrice (final BigDecimal NewCostPrice)
{
set_Value (COLUMNNAME_NewCostPrice, NewCostPrice);
}
@Override
public BigDecimal getNewCostPrice()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_NewCostPrice);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostRevaluationLine.java
| 1
|
请完成以下Java代码
|
public class AccumuloDataOperations {
private final AccumuloClient client = createAccumuloClient();
public AccumuloClient createAccumuloClient() {
AccumuloClient client = Accumulo.newClient()
.to("accumuloInstanceName", "localhost:2181")
.as("username", "password").build();
return client;
}
public void createTable(String tableName) throws TableExistsException, AccumuloException, AccumuloSecurityException {
client.tableOperations().create(tableName);
}
public void performBatchWrite(String tableName) throws TableNotFoundException, MutationsRejectedException {
try (BatchWriter writer = client.createBatchWriter(tableName, new BatchWriterConfig())) {
Mutation mutation1 = new Mutation("row1");
mutation1.at()
.family("column family 1")
.qualifier("column family 1 qualifier 1")
.visibility("public").put("value 1");
|
Mutation mutation2 = new Mutation("row2");
mutation2.at()
.family("column family 1")
.qualifier("column family 1 qualifier 2")
.visibility("private").put("value 2");
writer.addMutation(mutation1);
writer.addMutation(mutation2);
}
}
public void scanTableData(String tableName) throws TableNotFoundException {
try (var scanner = client.createScanner(tableName, new Authorizations("public"))) {
String keyValue = "";
scanner.setRange(new Range());
for (Map.Entry<Key, Value> entry : scanner) {
keyValue = entry.getKey() + " -> " + entry.getValue();
}
}
}
}
|
repos\tutorials-master\apache-libraries-3\src\main\java\com\baeldung\apache\accumulo\AccumuloDataOperations.java
| 1
|
请完成以下Java代码
|
public ImmutableList<I_M_ProductPrice> getProductPricesByPLVAndProduct(@NonNull final PriceListVersionId priceListVersionId, @NonNull final ProductId productId)
{
return priceListsRepo.retrieveProductPrices(priceListVersionId, productId);
}
@NonNull
public ImmutableMap<ProductId, String> getProductValues(final ImmutableSet<ProductId> productIds)
{
return productsService.getProductValues(productIds);
}
@NonNull
public String getProductValue(@NonNull final ProductId productId)
{
return productsService.getProductValue(productId);
}
// TODO move this method to de.metas.bpartner.service.IBPartnerDAO since it has nothing to do with price list
// TODO: IdentifierString must also be moved to the module containing IBPartnerDAO
public Optional<BPartnerId> getBPartnerId(final IdentifierString bpartnerIdentifier, final OrgId orgId)
{
final BPartnerQuery query = createBPartnerQuery(bpartnerIdentifier, orgId);
return bpartnersRepo.retrieveBPartnerIdBy(query);
}
private static BPartnerQuery createBPartnerQuery(@NonNull final IdentifierString bpartnerIdentifier, final OrgId orgId)
{
final Type type = bpartnerIdentifier.getType();
final BPartnerQuery.BPartnerQueryBuilder builder = BPartnerQuery.builder();
if (orgId != null)
{
builder.onlyOrgId(orgId);
}
if (Type.METASFRESH_ID.equals(type))
{
return builder
.bPartnerId(bpartnerIdentifier.asMetasfreshId(BPartnerId::ofRepoId))
.build();
}
|
else if (Type.EXTERNAL_ID.equals(type))
{
return builder
.externalId(bpartnerIdentifier.asExternalId())
.build();
}
else if (Type.VALUE.equals(type))
{
return builder
.bpartnerValue(bpartnerIdentifier.asValue())
.build();
}
else if (Type.GLN.equals(type))
{
return builder
.gln(bpartnerIdentifier.asGLN())
.build();
}
else
{
throw new AdempiereException("Invalid bpartnerIdentifier: " + bpartnerIdentifier);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\bpartner_pricelist\BpartnerPriceListServicesFacade.java
| 1
|
请完成以下Java代码
|
public List<I_C_Country> getAll()
{
return countries;
}
/**
* @return the country with the given ID, even if the `C_Country` record is not active.
*/
public I_C_Country getByIdOrNull(final CountryId countryId)
{
return countriesById.get(countryId);
}
/**
* @return the country with the given ID, even if the `C_Country` record is not active.
*/
public I_C_Country getById(final CountryId countryId)
{
final I_C_Country country = getByIdOrNull(countryId);
if (country == null)
{
throw new AdempiereException("No country found for countryId=" + countryId);
}
return country;
}
/**
* @return the country with the given code, unless the `C_Country` record is inactive.
*/
public I_C_Country getByCountryCodeOrNull(@Nullable final String countryCode)
{
return countriesByCountryCode.get(countryCode);
}
/**
* @return the country with the given code, unless the `C_Country` record is inactive.
*/
public I_C_Country getByCountryCode(final String countryCode)
{
final I_C_Country country = getByCountryCodeOrNull(countryCode);
if (country == null)
{
throw new AdempiereException("No active country found for countryCode=" + countryCode);
}
|
return country;
}
/**
* @return the country with the given code, unless the `C_Country` record is inactive.
*/
@NonNull
public CountryId getIdByCountryCode(@NonNull final String countryCode)
{
final I_C_Country country = getByCountryCode(countryCode);
return CountryId.ofRepoId(country.getC_Country_ID());
}
@NonNull
public CountryId getIdByCountryCode(@NonNull final CountryCode countryCode)
{
return getIdByCountryCode(countryCode.getAlpha2());
}
@Nullable
public CountryId getIdByCountryCodeOrNull(@Nullable final String countryCode)
{
final I_C_Country country = getByCountryCodeOrNull(countryCode);
return country != null ? CountryId.ofRepoId(country.getC_Country_ID()) : null;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\impl\CountryDAO.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static class DropTo
{
@Nullable ScannedCode qrCode;
}
@Nullable DropTo dropTo;
@Builder
@Jacksonized
private JsonDistributionEvent(
@NonNull final String wfProcessId,
@NonNull final String wfActivityId,
@Nullable final DistributionJobLineId lineId,
@Nullable final DistributionJobStepId distributionStepId,
//
@Nullable final PickFrom pickFrom,
@Nullable final Unpick unpick,
@Nullable final DropTo dropTo)
{
if (CoalesceUtil.countNotNulls(pickFrom, dropTo, unpick) != 1)
{
throw new AdempiereException("One and only one action like pickFrom, dropTo etc shall be specified in an event.");
}
this.wfProcessId = wfProcessId;
this.wfActivityId = wfActivityId;
|
this.lineId = lineId;
this.distributionStepId = distributionStepId;
//
this.pickFrom = pickFrom;
this.dropTo = dropTo;
this.unpick = unpick;
}
@NonNull
@JsonIgnore
public DropTo getDropToNonNull()
{
return Check.assumeNotNull(dropTo, "dropTo shall not be null: {}", this);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\rest_api\json\JsonDistributionEvent.java
| 2
|
请完成以下Java代码
|
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getRepeat() {
return repeat;
}
public void setRepeat(String repeat) {
this.repeat = repeat;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public int getMaxIterations() {
return maxIterations;
}
public void setMaxIterations(int maxIterations) {
this.maxIterations = maxIterations;
}
public String getJobHandlerType() {
return jobHandlerType;
}
public void setJobHandlerType(String jobHandlerType) {
this.jobHandlerType = jobHandlerType;
}
public String getJobHandlerConfiguration() {
return jobHandlerConfiguration;
}
public void setJobHandlerConfiguration(String jobHandlerConfiguration) {
this.jobHandlerConfiguration = jobHandlerConfiguration;
}
public String getJobType() {
return jobType;
}
public void setJobType(String jobType) {
this.jobType = jobType;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getExceptionStacktrace() {
if (exceptionByteArrayRef == null) {
return null;
}
byte[] bytes = exceptionByteArrayRef.getBytes();
if (bytes == null) {
return null;
}
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new ActivitiException("UTF-8 is not a supported encoding");
}
|
}
public void setExceptionStacktrace(String exception) {
if (exceptionByteArrayRef == null) {
exceptionByteArrayRef = new ByteArrayRef();
}
exceptionByteArrayRef.setValue("stacktrace", getUtf8Bytes(exception));
}
public String getExceptionMessage() {
return exceptionMessage;
}
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = StringUtils.abbreviate(exceptionMessage, MAX_EXCEPTION_MESSAGE_LENGTH);
}
public ByteArrayRef getExceptionByteArrayRef() {
return exceptionByteArrayRef;
}
protected byte[] getUtf8Bytes(String str) {
if (str == null) {
return null;
}
try {
return str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new ActivitiException("UTF-8 is not a supported encoding");
}
}
@Override
public String toString() {
return getClass().getName() + " [id=" + id + "]";
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AbstractJobEntityImpl.java
| 1
|
请完成以下Java代码
|
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setDisableCommand (final @Nullable java.lang.String DisableCommand)
{
set_Value (COLUMNNAME_DisableCommand, DisableCommand);
}
@Override
public java.lang.String getDisableCommand()
{
return get_ValueAsString(COLUMNNAME_DisableCommand);
}
@Override
public void setEnableCommand (final @Nullable java.lang.String EnableCommand)
{
set_Value (COLUMNNAME_EnableCommand, EnableCommand);
}
@Override
public java.lang.String getEnableCommand()
{
return get_ValueAsString(COLUMNNAME_EnableCommand);
}
@Override
public de.metas.externalsystem.model.I_ExternalSystem getExternalSystem()
{
return get_ValueAsPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class);
}
@Override
public void setExternalSystem(final de.metas.externalsystem.model.I_ExternalSystem ExternalSystem)
{
set_ValueFromPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class, ExternalSystem);
}
@Override
public void setExternalSystem_ID (final int ExternalSystem_ID)
{
if (ExternalSystem_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID);
}
@Override
public int getExternalSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID);
}
@Override
public void setExternalSystem_Service_ID (final int ExternalSystem_Service_ID)
{
|
if (ExternalSystem_Service_ID < 1)
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Service_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Service_ID, ExternalSystem_Service_ID);
}
@Override
public int getExternalSystem_Service_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Service_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Service.java
| 1
|
请完成以下Java代码
|
public class Doc_DDOrder extends Doc<DocLine<Doc_DDOrder>>
{
public Doc_DDOrder(final AcctDocContext ctx)
{
super(ctx, DocBaseType.DistributionOrder);
final I_DD_Order ddOrder = getModel(I_DD_Order.class);
setDateAcct(ddOrder.getDateOrdered());
}
@Override
protected void loadDocumentDetails()
{
// nothing
|
}
@Override
public BigDecimal getBalance()
{
return BigDecimal.ZERO;
}
@Override
public List<Fact> createFacts(final AcctSchema as)
{
return ImmutableList.of();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\acct\Doc_DDOrder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Map<String, String> getContextParameters() {
return this.contextParameters;
}
public Encoding getEncoding() {
return this.encoding;
}
public Jsp getJsp() {
return this.jsp;
}
public Session getSession() {
return this.session;
}
}
/**
* Reactive server properties.
*/
public static class Reactive {
private final Session session = new Session();
public Session getSession() {
return this.session;
}
public static class Session {
/**
* Session timeout. If a duration suffix is not specified, seconds will be
* used.
*/
@DurationUnit(ChronoUnit.SECONDS)
private Duration timeout = Duration.ofMinutes(30);
/**
* Maximum number of sessions that can be stored.
*/
private int maxSessions = 10000;
@NestedConfigurationProperty
private final Cookie cookie = new Cookie();
public Duration getTimeout() {
return this.timeout;
}
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
public int getMaxSessions() {
return this.maxSessions;
}
|
public void setMaxSessions(int maxSessions) {
this.maxSessions = maxSessions;
}
public Cookie getCookie() {
return this.cookie;
}
}
}
/**
* Strategies for supporting forward headers.
*/
public enum ForwardHeadersStrategy {
/**
* Use the underlying container's native support for forwarded headers.
*/
NATIVE,
/**
* Use Spring's support for handling forwarded headers.
*/
FRAMEWORK,
/**
* Ignore X-Forwarded-* headers.
*/
NONE
}
public static class Encoding {
/**
* Mapping of locale to charset for response encoding.
*/
private @Nullable Map<Locale, Charset> mapping;
public @Nullable Map<Locale, Charset> getMapping() {
return this.mapping;
}
public void setMapping(@Nullable Map<Locale, Charset> mapping) {
this.mapping = mapping;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\autoconfigure\ServerProperties.java
| 2
|
请完成以下Java代码
|
public void setIsManual (boolean IsManual)
{
set_Value (COLUMNNAME_IsManual, Boolean.valueOf(IsManual));
}
/** Get Manual.
@return This is a manual process
*/
public boolean isManual ()
{
Object oo = get_Value(COLUMNNAME_IsManual);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Keyword.
@param Keyword
Case insensitive keyword
*/
public void setKeyword (String Keyword)
{
set_Value (COLUMNNAME_Keyword, Keyword);
}
/** Get Keyword.
@return Case insensitive keyword
*/
public String getKeyword ()
{
return (String)get_Value(COLUMNNAME_Keyword);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getKeyword());
}
/** Set Index Stop.
@param K_IndexStop_ID
Keyword not to be indexed
*/
public void setK_IndexStop_ID (int K_IndexStop_ID)
{
if (K_IndexStop_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_IndexStop_ID, null);
else
|
set_ValueNoCheck (COLUMNNAME_K_IndexStop_ID, Integer.valueOf(K_IndexStop_ID));
}
/** Get Index Stop.
@return Keyword not to be indexed
*/
public int getK_IndexStop_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_IndexStop_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_R_RequestType getR_RequestType() throws RuntimeException
{
return (I_R_RequestType)MTable.get(getCtx(), I_R_RequestType.Table_Name)
.getPO(getR_RequestType_ID(), get_TrxName()); }
/** Set Request Type.
@param R_RequestType_ID
Type of request (e.g. Inquiry, Complaint, ..)
*/
public void setR_RequestType_ID (int R_RequestType_ID)
{
if (R_RequestType_ID < 1)
set_Value (COLUMNNAME_R_RequestType_ID, null);
else
set_Value (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID));
}
/** Get Request Type.
@return Type of request (e.g. Inquiry, Complaint, ..)
*/
public int getR_RequestType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_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_K_IndexStop.java
| 1
|
请完成以下Java代码
|
public ReportResultData exportToCsv(
@NonNull final PaySelectionId paySelectionId,
@NonNull final List<RevolutPaymentExport> exportList)
{
final StringBuilder csvBuilder = new StringBuilder(RevolutExportCsvRow.getCSVHeader());
exportList.stream()
.map(RevolutExportCsvRow::new)
.map(row -> row.toCSVRow(countryDAO))
.forEach(row -> csvBuilder.append("\n").append(row));
return buildResult(csvBuilder.toString(), paySelectionId);
}
@NonNull
|
private ReportResultData buildResult(
@NonNull final String fileData,
@NonNull final PaySelectionId paySelectionId)
{
final byte[] fileDataBytes = fileData.getBytes(StandardCharsets.UTF_8);
return ReportResultData.builder()
.reportData(new ByteArrayResource(fileDataBytes))
.reportFilename(EXPORT_FILE_NAME_TEMPLATE
.replace(EXPORT_ID_PLACEHOLDER, String.valueOf(paySelectionId.getRepoId()))
.replace(TIMESTAMP_PLACEHOLDER, String.valueOf(System.currentTimeMillis())))
.reportContentType(CSV_FORMAT)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.revolut\src\main\java\de\metas\payment\revolut\RevolutExportService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected CommandContext getCommandContext() {
return Context.getCommandContext();
}
protected <T> T getSession(Class<T> sessionClass) {
return getCommandContext().getSession(sessionClass);
}
// Engine scoped
protected TaskServiceConfiguration getTaskServiceConfiguration() {
return taskServiceConfiguration;
}
protected Clock getClock() {
|
return getTaskServiceConfiguration().getClock();
}
protected FlowableEventDispatcher getEventDispatcher() {
return getTaskServiceConfiguration().getEventDispatcher();
}
protected TaskEntityManager getTaskEntityManager() {
return getTaskServiceConfiguration().getTaskEntityManager();
}
protected HistoricTaskInstanceEntityManager getHistoricTaskInstanceEntityManager() {
return getTaskServiceConfiguration().getHistoricTaskInstanceEntityManager();
}
}
|
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\AbstractManager.java
| 2
|
请完成以下Java代码
|
public void setA_Asset_ID (int A_Asset_ID)
{
if (A_Asset_ID < 1)
set_Value (COLUMNNAME_A_Asset_ID, null);
else
set_Value (COLUMNNAME_A_Asset_ID, Integer.valueOf(A_Asset_ID));
}
/** Get Asset.
@return Asset used internally or by customers
*/
public int getA_Asset_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_Asset_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_AD_WF_Node getAD_WF_Node() throws RuntimeException
{
return (I_AD_WF_Node)MTable.get(getCtx(), I_AD_WF_Node.Table_Name)
.getPO(getAD_WF_Node_ID(), get_TrxName()); }
/** Set Node.
@param AD_WF_Node_ID
Workflow Node (activity), step or process
*/
public void setAD_WF_Node_ID (int AD_WF_Node_ID)
{
if (AD_WF_Node_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_WF_Node_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_WF_Node_ID, Integer.valueOf(AD_WF_Node_ID));
}
/** Get Node.
@return Workflow Node (activity), step or process
*/
public int getAD_WF_Node_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_WF_Node_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Workflow Node Asset.
@param PP_WF_Node_Asset_ID Workflow Node Asset */
public void setPP_WF_Node_Asset_ID (int PP_WF_Node_Asset_ID)
{
|
if (PP_WF_Node_Asset_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_WF_Node_Asset_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_WF_Node_Asset_ID, Integer.valueOf(PP_WF_Node_Asset_ID));
}
/** Get Workflow Node Asset.
@return Workflow Node Asset */
public int getPP_WF_Node_Asset_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PP_WF_Node_Asset_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_ValueNoCheck (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\eevolution\model\X_PP_WF_Node_Asset.java
| 1
|
请完成以下Java代码
|
public void setIsSplitAcctTrx (final boolean IsSplitAcctTrx)
{
set_Value (COLUMNNAME_IsSplitAcctTrx, IsSplitAcctTrx);
}
@Override
public boolean isSplitAcctTrx()
{
return get_ValueAsBoolean(COLUMNNAME_IsSplitAcctTrx);
}
@Override
public void setLine (final int Line)
{
set_Value (COLUMNNAME_Line, Line);
}
@Override
public int getLine()
{
return get_ValueAsInt(COLUMNNAME_Line);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
|
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* Type AD_Reference_ID=540534
* Reference name: GL_JournalLine_Type
*/
public static final int TYPE_AD_Reference_ID=540534;
/** Normal = N */
public static final String TYPE_Normal = "N";
/** Tax = T */
public static final String TYPE_Tax = "T";
@Override
public void setType (final java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_JournalLine.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected boolean shouldGenerateId() {
return false;
}
@Override
protected boolean shouldGenerateIdAsFallback() {
return true;
}
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
String connectionFactoryRef = element.getAttribute(CONNECTION_FACTORY_ATTRIBUTE);
// At least one of 'templateRef' or 'connectionFactoryRef' attribute must be set.
if (!StringUtils.hasText(connectionFactoryRef)) {
parserContext.getReaderContext().error("A '" + CONNECTION_FACTORY_ATTRIBUTE + "' attribute must be set.",
element);
}
if (StringUtils.hasText(connectionFactoryRef)) {
|
// Use constructor with connectionFactory parameter
builder.addConstructorArgReference(connectionFactoryRef);
}
String attributeValue;
attributeValue = element.getAttribute(AUTO_STARTUP_ATTRIBUTE);
if (StringUtils.hasText(attributeValue)) {
builder.addPropertyValue("autoStartup", attributeValue);
}
NamespaceUtils.setValueIfAttributeDefined(builder, element, IGNORE_DECLARATION_EXCEPTIONS);
NamespaceUtils.setValueIfAttributeDefined(builder, element, "explicit-declarations-only");
}
}
|
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\config\AdminParser.java
| 2
|
请完成以下Java代码
|
public boolean isCompleted()
{
return this == Completed;
}
public boolean isClosed()
{
return this == Closed;
}
public boolean isCompletedOrClosed()
{
return COMPLETED_OR_CLOSED_STATUSES.contains(this);
}
public static Set<DocStatus> completedOrClosedStatuses()
{
return COMPLETED_OR_CLOSED_STATUSES;
}
public boolean isCompletedOrClosedOrReversed()
{
return this == Completed
|| this == Closed
|| this == Reversed;
}
public boolean isCompletedOrClosedReversedOrVoided()
{
return this == Completed
|| this == Closed
|| this == Reversed
|| this == Voided;
}
public boolean isWaitingForPayment()
{
return this == WaitingPayment;
}
public boolean isInProgress()
{
return this == InProgress;
}
|
public boolean isInProgressCompletedOrClosed()
{
return this == InProgress
|| this == Completed
|| this == Closed;
}
public boolean isDraftedInProgressOrInvalid()
{
return this == Drafted
|| this == InProgress
|| this == Invalid;
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean isDraftedInProgressOrCompleted()
{
return this == Drafted
|| this == InProgress
|| this == Completed;
}
public boolean isNotProcessed()
{
return isDraftedInProgressOrInvalid()
|| this == Approved
|| this == NotApproved;
}
public boolean isVoided() {return this == Voided;}
public boolean isAccountable()
{
return this == Completed
|| this == Reversed
|| this == Voided;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\engine\DocStatus.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public LdapAuthenticationProviderConfigurer<B> and() {
return LdapAuthenticationProviderConfigurer.this;
}
private DefaultSpringSecurityContextSource build() {
if (this.url == null) {
startEmbeddedLdapServer();
}
DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(getProviderUrl());
if (this.managerDn != null) {
contextSource.setUserDn(this.managerDn);
if (this.managerPassword == null) {
throw new IllegalStateException("managerPassword is required if managerDn is supplied");
}
contextSource.setPassword(this.managerPassword);
}
contextSource = postProcess(contextSource);
return contextSource;
}
private void startEmbeddedLdapServer() {
if (unboundIdPresent) {
UnboundIdContainer unboundIdContainer = new UnboundIdContainer(this.root, this.ldif);
unboundIdContainer.setPort(getPort());
postProcess(unboundIdContainer);
this.port = unboundIdContainer.getPort();
}
else {
throw new IllegalStateException("Embedded LDAP server is not provided");
}
}
|
private int getPort() {
if (this.port == null) {
this.port = getDefaultPort();
}
return this.port;
}
private int getDefaultPort() {
try (ServerSocket serverSocket = new ServerSocket(DEFAULT_PORT)) {
return serverSocket.getLocalPort();
}
catch (IOException ex) {
return RANDOM_PORT;
}
}
private String getProviderUrl() {
if (this.url == null) {
return "ldap://127.0.0.1:" + getPort() + "/" + this.root;
}
return this.url;
}
private ContextSourceBuilder() {
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\authentication\configurers\ldap\LdapAuthenticationProviderConfigurer.java
| 2
|
请完成以下Java代码
|
protected String doIt() throws Exception
{
final List<HUToReport> topLevelHus = new ArrayList<>();
final ImmutableList<HUToReport> hus = handlingUnitsDAO.streamByQuery(retrieveSelectedRecordsQueryBuilder(I_M_HU.class), HUToReportWrapper::of)
.filter(hu -> hu.getHUUnitType() != VHU)
.peek(topLevelHus::add)
.flatMap(hu -> {
if (hu.getHUUnitType() == LU)
{
return Stream.concat(Stream.of(hu), hu.getIncludedHUs().stream());
}
else
{
return Stream.of(hu);
}
})
.filter(hu -> hu.getHUUnitType() != VHU)
.collect(ImmutableList.toImmutableList());
final Set<HuId> huIdSet = hus.stream().map(HUToReport::getHUId).collect(ImmutableSet.toImmutableSet());
huqrCodesService.generateForExistingHUs(huIdSet);
topLevelHus.stream()
.sorted(Comparator.comparing(hu -> hu.getHUId().getRepoId()))
.forEach(topLevelHu -> {
labelService.printNow(HULabelDirectPrintRequest.builder()
.onlyOneHUPerPrint(true)
.printCopies(PrintCopies.ofIntOrOne(p_PrintCopies))
.printFormatProcessId(p_AD_Process_ID)
.hu(topLevelHu)
.build());
|
if (topLevelHu.getHUUnitType() == LU && !topLevelHu.getIncludedHUs().isEmpty())
{
final List<HUToReport> sortedIncludedHUs = topLevelHu.getIncludedHUs()
.stream()
.sorted(Comparator.comparing(hu -> hu.getHUId().getRepoId()))
.collect(ImmutableList.toImmutableList());
labelService.printNow(HULabelDirectPrintRequest.builder()
.onlyOneHUPerPrint(true)
.printCopies(PrintCopies.ofIntOrOne(p_PrintCopies))
.printFormatProcessId(p_AD_Process_ID)
.hus(sortedIncludedHUs)
.build());
}
});
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\process\M_HU_MultipleSelection_Report_Print_Label.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_OLCand_AlbertaTherapyType_ID (final int C_OLCand_AlbertaTherapyType_ID)
{
if (C_OLCand_AlbertaTherapyType_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_OLCand_AlbertaTherapyType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_OLCand_AlbertaTherapyType_ID, C_OLCand_AlbertaTherapyType_ID);
}
@Override
public int getC_OLCand_AlbertaTherapyType_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OLCand_AlbertaTherapyType_ID);
}
@Override
public void setC_OLCand_ID (final int C_OLCand_ID)
{
if (C_OLCand_ID < 1)
|
set_Value (COLUMNNAME_C_OLCand_ID, null);
else
set_Value (COLUMNNAME_C_OLCand_ID, C_OLCand_ID);
}
@Override
public int getC_OLCand_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OLCand_ID);
}
@Override
public void setTherapyType (final java.lang.String TherapyType)
{
set_Value (COLUMNNAME_TherapyType, TherapyType);
}
@Override
public java.lang.String getTherapyType()
{
return get_ValueAsString(COLUMNNAME_TherapyType);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_C_OLCand_AlbertaTherapyType.java
| 1
|
请完成以下Java代码
|
public class DataEntryDetailsView extends AbstractCustomView<DataEntryDetailsRow> implements IEditableView
{
private final ImmutableList<RelatedProcessDescriptor> processes;
@Builder
protected DataEntryDetailsView(
@NonNull final WindowId windowId,
@Nullable final ITranslatableString description,
@NonNull final IRowsData<DataEntryDetailsRow> rowsData,
@NonNull final ImmutableList<RelatedProcessDescriptor> processes)
{
super(ViewId.random(windowId), description, rowsData, NullDocumentFilterDescriptorsProvider.instance);
this.processes = processes;
}
public static DataEntryDetailsView cast(@NonNull final Object viewObj)
{
return (DataEntryDetailsView)viewObj;
}
@Override
public LookupValuesPage getFieldTypeahead(final RowEditingContext ctx, final String fieldName, final String query)
{
return null;
}
@Override
public LookupValuesList getFieldDropdown(final RowEditingContext ctx, final String fieldName)
|
{
return null;
}
@Nullable
@Override
public String getTableNameOrNull(@Nullable final DocumentId documentId_ignored)
{
return I_C_Flatrate_DataEntry_Detail.Table_Name;
}
@Override
public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors()
{
return processes;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\contract\flatrate\view\DataEntryDetailsView.java
| 1
|
请完成以下Java代码
|
public static final class Builder
{
private final List<IValidationRule> rules = new ArrayList<>();
private Builder() {}
public IValidationRule build()
{
if (rules.isEmpty())
{
return NullValidationRule.instance;
}
else if (rules.size() == 1)
{
return rules.get(0);
}
else
{
return new CompositeValidationRule(this);
}
}
public Builder add(final IValidationRule rule)
{
add(rule, false);
return this;
}
public Builder addExploded(final IValidationRule rule)
{
add(rule, true);
return this;
}
private Builder add(final IValidationRule rule, final boolean explodeComposite)
{
// Don't add null rules
if (NullValidationRule.isNull(rule))
{
return this;
}
// Don't add if already exists
if (rules.contains(rule))
{
return this;
}
if (explodeComposite && rule instanceof CompositeValidationRule)
{
final CompositeValidationRule compositeRule = (CompositeValidationRule)rule;
|
addAll(compositeRule.getValidationRules(), true);
}
else
{
rules.add(rule);
}
return this;
}
private Builder addAll(final Collection<IValidationRule> rules)
{
return addAll(rules, false);
}
private Builder addAll(final Collection<IValidationRule> rules, final boolean explodeComposite)
{
rules.forEach(includedRule -> add(includedRule, explodeComposite));
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\validationRule\impl\CompositeValidationRule.java
| 1
|
请完成以下Java代码
|
public DeploymentEntity findLatestDeploymentByName(String deploymentName) {
List<?> list = getDbSqlSession().selectList("selectDeploymentsByName", deploymentName, 0, 1);
if (list != null && !list.isEmpty()) {
return (DeploymentEntity) list.get(0);
}
return null;
}
@Override
public DeploymentEntity findDeploymentByVersion(Integer version) {
return getDbSqlSession().getSqlSession().selectOne("selectDeploymentByVersion", version);
}
@Override
public long findDeploymentCountByQueryCriteria(DeploymentQueryImpl deploymentQuery) {
return (Long) getDbSqlSession().selectOne("selectDeploymentCountByQueryCriteria", deploymentQuery);
}
@Override
@SuppressWarnings("unchecked")
public List<Deployment> findDeploymentsByQueryCriteria(DeploymentQueryImpl deploymentQuery, Page page) {
final String query = "selectDeploymentsByQueryCriteria";
return getDbSqlSession().selectList(query, deploymentQuery, page);
}
@Override
public List<String> getDeploymentResourceNames(String deploymentId) {
|
return getDbSqlSession().getSqlSession().selectList("selectResourceNamesByDeploymentId", deploymentId);
}
@Override
@SuppressWarnings("unchecked")
public List<Deployment> findDeploymentsByNativeQuery(
Map<String, Object> parameterMap,
int firstResult,
int maxResults
) {
return getDbSqlSession().selectListWithRawParameter(
"selectDeploymentByNativeQuery",
parameterMap,
firstResult,
maxResults
);
}
@Override
public long findDeploymentCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectDeploymentCountByNativeQuery", parameterMap);
}
@Override
public Deployment selectLatestDeployment(String deploymentName) {
return (Deployment) getDbSqlSession().selectOne("selectLatestDeployment", deploymentName);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisDeploymentDataManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void createCostCollector_RepairingConsumption(
@NonNull final ServiceRepairProjectTask task,
@NonNull final RepairManufacturingCostCollector mfgCostCollector)
{
serviceRepairProjectService.createCostCollector(CreateProjectCostCollectorRequest.builder()
.taskId(task.getId())
.type(ServiceRepairProjectCostCollectorType.RepairingConsumption)
.productId(mfgCostCollector.getProductId())
.qtyConsumed(mfgCostCollector.getQtyConsumed())
.repairOrderCostCollectorId(mfgCostCollector.getId())
.warrantyCase(task.getWarrantyCase())
.build());
}
private void createCostCollector_RepairedProductToReturn(
@NonNull final ServiceRepairProjectTask task)
{
|
final ProductId repairedProductId = repairOrder.getRepairedProductId();
final HuId repairedVhuId = Objects.requireNonNull(task.getRepairVhuId());
final AttributeSetInstanceId asiId = handlingUnitsBL.createASIFromHUAttributes(repairedProductId, repairedVhuId);
serviceRepairProjectService.createCostCollector(CreateProjectCostCollectorRequest.builder()
.taskId(task.getId())
.type(ServiceRepairProjectCostCollectorType.RepairedProductToReturn)
.productId(repairedProductId)
.asiId(asiId)
.warrantyCase(task.getWarrantyCase())
.qtyReserved(repairOrder.getRepairedQty())
.reservedVhuId(repairedVhuId)
.build());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\service\commands\ImportProjectCostsFromRepairOrderCommand.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.baeldung.books.models" });
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(additionalProperties());
return em;
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
if (env.getProperty("hibernate.hbm2ddl.auto") != null) {
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
}
if (env.getProperty("hibernate.dialect") != null) {
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
}
if (env.getProperty("hibernate.show_sql") != null) {
hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
}
return hibernateProperties;
}
}
@Configuration
@Profile("h2")
@PropertySource("classpath:persistence-h2.properties")
class H2Config {
}
|
@Configuration
@Profile("hsqldb")
@PropertySource("classpath:persistence-hsqldb.properties")
class HsqldbConfig {
}
@Configuration
@Profile("derby")
@PropertySource("classpath:persistence-derby.properties")
class DerbyConfig {
}
@Configuration
@Profile("sqlite")
@PropertySource("classpath:persistence-sqlite.properties")
class SqliteConfig {
}
|
repos\tutorials-master\persistence-modules\spring-data-rest\src\main\java\com\baeldung\books\config\DbConfig.java
| 2
|
请完成以下Java代码
|
public static void main(String args[]) {
int x_axis_length = 2;
int y_axis_length = 2;
int z_axis_length = 2;
ArrayList< ArrayList< ArrayList<String> > > space = new ArrayList<>(x_axis_length);
//Initializing each element of ArrayList with ArrayList< ArrayList<String> >
for(int i = 0; i < x_axis_length; i++) {
space.add(new ArrayList< ArrayList<String> >(y_axis_length));
for(int j = 0; j < y_axis_length; j++) {
space.get(i).add(new ArrayList<String>(z_axis_length));
}
}
//Set Red color for points (0,0,0) and (0,0,1)
space.get(0).get(0).add(0,"Red");
space.get(0).get(0).add(1,"Red");
//Set Blue color for points (0,1,0) and (0,1,1)
space.get(0).get(1).add(0,"Blue");
space.get(0).get(1).add(1,"Blue");
//Set Green color for points (1,0,0) and (1,0,1)
space.get(1).get(0).add(0,"Green");
|
space.get(1).get(0).add(1,"Green");
//Set Yellow color for points (1,1,0) and (1,1,1)
space.get(1).get(1).add(0,"Yellow");
space.get(1).get(1).add(1,"Yellow");
//Printing colors for all the points
for(int i = 0; i < x_axis_length; i++) {
for(int j = 0; j < y_axis_length; j++) {
for(int k = 0; k < z_axis_length; k++) {
System.out.println("Color of point ("+i+","+j+","+k+") is :"+space.get(i).get(j).get(k));
}
}
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-array-list\src\main\java\com\baeldung\list\multidimensional\ThreeDimensionalArrayList.java
| 1
|
请完成以下Java代码
|
public void setAD_Role_Record_Access_Config_ID (int AD_Role_Record_Access_Config_ID)
{
if (AD_Role_Record_Access_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Role_Record_Access_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Role_Record_Access_Config_ID, Integer.valueOf(AD_Role_Record_Access_Config_ID));
}
/** Get Role Record Access Config.
@return Role Record Access Config */
@Override
public int getAD_Role_Record_Access_Config_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_Record_Access_Config_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Table getAD_Table() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Table_ID, org.compiere.model.I_AD_Table.class);
}
@Override
public void setAD_Table(org.compiere.model.I_AD_Table AD_Table)
{
set_ValueFromPO(COLUMNNAME_AD_Table_ID, org.compiere.model.I_AD_Table.class, AD_Table);
}
/** Set DB-Tabelle.
@param AD_Table_ID
Database Table information
*/
@Override
public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get DB-Tabelle.
@return Database Table information
*/
@Override
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
|
if (ii == null)
return 0;
return ii.intValue();
}
/**
* Type AD_Reference_ID=540987
* Reference name: AD_Role_Record_Access_Config_Type
*/
public static final int TYPE_AD_Reference_ID=540987;
/** Table = T */
public static final String TYPE_Table = "T";
/** Business Partner Hierarchy = BPH */
public static final String TYPE_BusinessPartnerHierarchy = "BPH";
/** Set Art.
@param Type Art */
@Override
public void setType (java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
/** Get Art.
@return Art */
@Override
public java.lang.String getType ()
{
return (java.lang.String)get_Value(COLUMNNAME_Type);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role_Record_Access_Config.java
| 1
|
请完成以下Java代码
|
private int getNextTransportationOrderId()
{
final ShipperId shipperId = ShipperId.ofRepoId(shipperRecordId);
final ShipperTransportationId nextShipperTransportationForShipper = shipperTransportationRepo.retrieveNextOpenShipperTransportationIdOrNull(shipperId, null);
return nextShipperTransportationForShipper == null ? -1 : nextShipperTransportationForShipper.getRepoId();
}
@Override
protected String doIt()
{
if (!isPartialDeliveryAllowed())
{
if (!getView().isApproved())
{
throw new AdempiereException("Not all rows were approved");
}
}
final ImmutableSet<PickingCandidateId> validPickingCandidates = getValidPickingCandidates();
if (!validPickingCandidates.isEmpty())
{
deliverAndInvoice(validPickingCandidates);
}
return MSG_OK;
}
private ImmutableSet<PickingCandidateId> getValidPickingCandidates()
{
return getRowsNotAlreadyProcessed()
.stream()
.filter(ProductsToPickRow::isEligibleForProcessing)
.map(ProductsToPickRow::getPickingCandidateId)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
}
private void deliverAndInvoice(final ImmutableSet<PickingCandidateId> validPickingCandidates)
{
final List<PickingCandidate> pickingCandidates = processAllPickingCandidates(validPickingCandidates);
final Set<HuId> huIdsToDeliver = pickingCandidates
.stream()
.filter(PickingCandidate::isPacked)
.map(PickingCandidate::getPackedToHuId)
.collect(ImmutableSet.toImmutableSet());
final List<I_M_HU> husToDeliver = handlingUnitsRepo.getByIds(huIdsToDeliver);
|
HUShippingFacade.builder()
.hus(husToDeliver)
.addToShipperTransportationId(shipperTransportationId)
.completeShipments(true)
.failIfNoShipmentCandidatesFound(true)
.invoiceMode(BillAssociatedInvoiceCandidates.IF_INVOICE_SCHEDULE_PERMITS)
.createShipperDeliveryOrders(true)
.build()
.generateShippingDocuments();
}
private List<ProductsToPickRow> getRowsNotAlreadyProcessed()
{
return streamAllRows()
.filter(row -> !row.isProcessed())
.collect(ImmutableList.toImmutableList());
}
private boolean isPartialDeliveryAllowed()
{
return sysConfigBL.getBooleanValue(SYSCONFIG_AllowPartialDelivery, false);
}
private ImmutableList<PickingCandidate> processAllPickingCandidates(final ImmutableSet<PickingCandidateId> pickingCandidateIdsToProcess)
{
return trxManager.callInNewTrx(() -> pickingCandidatesService
.process(pickingCandidateIdsToProcess)
.getPickingCandidates());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\process\ProductsToPick_4EyesReview_ProcessAll.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
class S3BucketOperationService {
private final S3Client s3Client;
public S3BucketOperationService(S3Client s3Client) {
this.s3Client = s3Client;
}
public boolean bucketExists(String bucketName) {
try {
s3Client.headBucket(request -> request.bucket(bucketName));
return true;
} catch (NoSuchBucketException exception) {
return false;
}
}
public void createBucket(String bucketName) {
s3Client.createBucket(request -> request.bucket(bucketName));
}
public List<Bucket> listBuckets() {
List<Bucket> allBuckets = new ArrayList<>();
String nextToken = null;
do {
|
String continuationToken = nextToken;
ListBucketsResponse listBucketsResponse = s3Client.listBuckets(
request -> request.continuationToken(continuationToken)
);
allBuckets.addAll(listBucketsResponse.buckets());
nextToken = listBucketsResponse.continuationToken();
} while (nextToken != null);
return allBuckets;
}
public void deleteBucket(String bucketName) {
try {
s3Client.deleteBucket(request -> request.bucket(bucketName));
} catch (S3Exception exception) {
if (exception.statusCode() == HttpStatus.SC_CONFLICT) {
throw new BucketNotEmptyException();
}
throw exception;
}
}
}
|
repos\tutorials-master\aws-modules\aws-s3\src\main\java\com\baeldung\s3\S3BucketOperationService.java
| 2
|
请完成以下Java代码
|
public class ProcessInstanceSuspensionStateAsyncDto extends SuspensionStateDto {
protected List<String> processInstanceIds;
protected ProcessInstanceQueryDto processInstanceQuery;
protected HistoricProcessInstanceQueryDto historicProcessInstanceQuery;
public List<String> getProcessInstanceIds() {
return processInstanceIds;
}
public void setProcessInstanceIds(List<String> processInstanceIds) {
this.processInstanceIds = processInstanceIds;
}
public ProcessInstanceQueryDto getProcessInstanceQuery() {
return processInstanceQuery;
}
public void setProcessInstanceQuery(ProcessInstanceQueryDto processInstanceQuery) {
this.processInstanceQuery = processInstanceQuery;
}
public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) {
this.historicProcessInstanceQuery = historicProcessInstanceQuery;
}
public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() {
return historicProcessInstanceQuery;
}
public Batch updateSuspensionStateAsync(ProcessEngine engine) {
int params = parameterCount(processInstanceIds, processInstanceQuery, historicProcessInstanceQuery);
if (params == 0) {
String message = "Either processInstanceIds, processInstanceQuery or historicProcessInstanceQuery should be set to update the suspension state.";
throw new InvalidRequestException(Status.BAD_REQUEST, message);
}
UpdateProcessInstancesSuspensionStateBuilder updateSuspensionStateBuilder = createUpdateSuspensionStateGroupBuilder(engine);
if (getSuspended()) {
return updateSuspensionStateBuilder.suspendAsync();
} else {
return updateSuspensionStateBuilder.activateAsync();
}
}
|
protected UpdateProcessInstancesSuspensionStateBuilder createUpdateSuspensionStateGroupBuilder(ProcessEngine engine) {
UpdateProcessInstanceSuspensionStateSelectBuilder selectBuilder = engine.getRuntimeService().updateProcessInstanceSuspensionState();
UpdateProcessInstancesSuspensionStateBuilder groupBuilder = null;
if (processInstanceIds != null) {
groupBuilder = selectBuilder.byProcessInstanceIds(processInstanceIds);
}
if (processInstanceQuery != null) {
if (groupBuilder == null) {
groupBuilder = selectBuilder.byProcessInstanceQuery(processInstanceQuery.toQuery(engine));
} else {
groupBuilder.byProcessInstanceQuery(processInstanceQuery.toQuery(engine));
}
}
if (historicProcessInstanceQuery != null) {
if (groupBuilder == null) {
groupBuilder = selectBuilder.byHistoricProcessInstanceQuery(historicProcessInstanceQuery.toQuery(engine));
} else {
groupBuilder.byHistoricProcessInstanceQuery(historicProcessInstanceQuery.toQuery(engine));
}
}
return groupBuilder;
}
protected int parameterCount(Object... o) {
int count = 0;
for (Object o1 : o) {
count += (o1 != null ? 1 : 0);
}
return count;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\ProcessInstanceSuspensionStateAsyncDto.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public JwtDecoder jwtDecoder(SecurityMetersService metersService) {
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withSecretKey(getSecretKey()).macAlgorithm(JWT_ALGORITHM).build();
return token -> {
try {
return jwtDecoder.decode(token);
} catch (Exception e) {
if (e.getMessage().contains("Invalid signature")) {
metersService.trackTokenInvalidSignature();
} else if (e.getMessage().contains("Jwt expired at")) {
metersService.trackTokenExpired();
} else if (
e.getMessage().contains("Invalid JWT serialization") ||
e.getMessage().contains("Malformed token") ||
e.getMessage().contains("Invalid unsecured/JWS/JWE")
) {
metersService.trackTokenMalformed();
} else {
log.error("Unknown JWT error {}", e.getMessage());
}
throw e;
}
};
}
@Bean
public JwtEncoder jwtEncoder() {
|
return new NimbusJwtEncoder(new ImmutableSecret<>(getSecretKey()));
}
@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
grantedAuthoritiesConverter.setAuthorityPrefix("");
grantedAuthoritiesConverter.setAuthoritiesClaimName(AUTHORITIES_KEY);
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
return jwtAuthenticationConverter;
}
private SecretKey getSecretKey() {
byte[] keyBytes = Base64.from(jwtKey).decode();
return new SecretKeySpec(keyBytes, 0, keyBytes.length, JWT_ALGORITHM.getName());
}
}
|
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\car-app\src\main\java\com\cars\app\config\SecurityJwtConfiguration.java
| 2
|
请完成以下Java代码
|
public class MutableHUTransactionAttribute implements IHUTransactionAttribute
{
private final HUTransactionAttributeOperation operation;
private final AttributeId attributeId;
private final String valueString;
private final String valueStringInitial;
private final BigDecimal valueNumber;
private final BigDecimal valueNumberInitial;
private final Date valueDate;
private final Date valueDateInitial;
//
// Updateable attributes
private HuPackingInstructionsAttributeId piAttributeId;
private Object referencedObject = null;
private I_M_HU_Attribute huAttribute = null;
@Builder
private MutableHUTransactionAttribute(
@NonNull final HUTransactionAttributeOperation operation,
@NonNull final AttributeId attributeId,
@Nullable final String valueString,
|
@Nullable final String valueStringInitial,
@Nullable final BigDecimal valueNumber,
@Nullable final BigDecimal valueNumberInitial,
@Nullable final Date valueDate,
@Nullable final Date valueDateInitial)
{
this.operation = operation;
this.attributeId = attributeId;
this.valueString = valueString;
this.valueStringInitial = valueStringInitial;
this.valueNumber = valueNumber;
this.valueNumberInitial = valueNumberInitial;
this.valueDate = valueDate;
this.valueDateInitial = valueDateInitial;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\hutransaction\MutableHUTransactionAttribute.java
| 1
|
请完成以下Java代码
|
public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Server Process.
@param IsServerProcess
Run this Process on Server only
*/
public void setIsServerProcess (boolean IsServerProcess)
{
set_Value (COLUMNNAME_IsServerProcess, Boolean.valueOf(IsServerProcess));
}
/** Get Server Process.
@return Run this Process on Server only
*/
public boolean isServerProcess ()
{
Object oo = get_Value(COLUMNNAME_IsServerProcess);
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());
}
/** Set OS Command.
@param OS_Command
Operating System Command
*/
public void setOS_Command (String OS_Command)
{
set_Value (COLUMNNAME_OS_Command, OS_Command);
}
/** Get OS Command.
@return Operating System Command
*/
public String getOS_Command ()
{
return (String)get_Value(COLUMNNAME_OS_Command);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Task.java
| 1
|
请完成以下Java代码
|
protected String getXMLElementName() {
return ELEMENT_TASK_BUSINESSRULE;
}
@Override
protected BaseElement convertXMLToElement(XMLStreamReader xtr, BpmnModel model) throws Exception {
BusinessRuleTask businessRuleTask = new BusinessRuleTask();
BpmnXMLUtil.addXMLLocation(businessRuleTask, xtr);
businessRuleTask.setInputVariables(parseDelimitedList(BpmnXMLUtil.getAttributeValue(ATTRIBUTE_TASK_RULE_VARIABLES_INPUT, xtr)));
businessRuleTask.setRuleNames(parseDelimitedList(BpmnXMLUtil.getAttributeValue(ATTRIBUTE_TASK_RULE_RULES, xtr)));
businessRuleTask.setResultVariableName(BpmnXMLUtil.getAttributeValue(ATTRIBUTE_TASK_RULE_RESULT_VARIABLE, xtr));
businessRuleTask.setClassName(BpmnXMLUtil.getAttributeValue(ATTRIBUTE_TASK_RULE_CLASS, xtr));
String exclude = BpmnXMLUtil.getAttributeValue(ATTRIBUTE_TASK_RULE_EXCLUDE, xtr);
if (ATTRIBUTE_VALUE_TRUE.equalsIgnoreCase(exclude)) {
businessRuleTask.setExclude(true);
}
parseChildElements(getXMLElementName(), businessRuleTask, model, xtr);
return businessRuleTask;
}
@Override
protected void writeAdditionalAttributes(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception {
BusinessRuleTask businessRuleTask = (BusinessRuleTask) element;
String inputVariables = convertToDelimitedString(businessRuleTask.getInputVariables());
if (StringUtils.isNotEmpty(inputVariables)) {
writeQualifiedAttribute(ATTRIBUTE_TASK_RULE_VARIABLES_INPUT, inputVariables, xtw);
}
String ruleNames = convertToDelimitedString(businessRuleTask.getRuleNames());
if (StringUtils.isNotEmpty(ruleNames)) {
writeQualifiedAttribute(ATTRIBUTE_TASK_RULE_RULES, ruleNames, xtw);
}
|
if (StringUtils.isNotEmpty(businessRuleTask.getResultVariableName())) {
writeQualifiedAttribute(ATTRIBUTE_TASK_RULE_RESULT_VARIABLE, businessRuleTask.getResultVariableName(), xtw);
}
if (StringUtils.isNotEmpty(businessRuleTask.getClassName())) {
writeQualifiedAttribute(ATTRIBUTE_TASK_RULE_CLASS, businessRuleTask.getClassName(), xtw);
}
if (businessRuleTask.isExclude()) {
writeQualifiedAttribute(ATTRIBUTE_TASK_RULE_EXCLUDE, ATTRIBUTE_VALUE_TRUE, xtw);
}
}
@Override
protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception {
}
}
|
repos\flowable-engine-main\modules\flowable-bpmn-converter\src\main\java\org\flowable\bpmn\converter\BusinessRuleTaskXMLConverter.java
| 1
|
请完成以下Java代码
|
public class DecisionServiceXMLConverter extends BaseDmnXMLConverter {
@Override
protected String getXMLElementName() {
return ELEMENT_DECISION_SERVICE;
}
@Override
protected DmnElement convertXMLToElement(XMLStreamReader xtr, ConversionHelper conversionHelper) throws Exception {
DecisionService decisionService = new DecisionService();
decisionService.setId(xtr.getAttributeValue(null, ATTRIBUTE_ID));
decisionService.setName(xtr.getAttributeValue(null, ATTRIBUTE_NAME));
decisionService.setLabel(xtr.getAttributeValue(null, ATTRIBUTE_LABEL));
boolean readyWithDecisionService = false;
try {
while (!readyWithDecisionService && xtr.hasNext()) {
xtr.next();
if (xtr.isStartElement() && ELEMENT_OUTPUT_DECISION.equalsIgnoreCase(xtr.getLocalName())) {
DmnElementReference ref = new DmnElementReference();
ref.setHref(xtr.getAttributeValue(null, ATTRIBUTE_HREF));
decisionService.addOutputDecision(ref);
} if (xtr.isStartElement() && ELEMENT_ENCAPSULATED_DECISION.equalsIgnoreCase(xtr.getLocalName())) {
DmnElementReference ref = new DmnElementReference();
ref.setHref(xtr.getAttributeValue(null, ATTRIBUTE_HREF));
decisionService.addEncapsulatedDecision(ref);
} if (xtr.isStartElement() && ELEMENT_INPUT_DATA.equalsIgnoreCase(xtr.getLocalName())) {
DmnElementReference ref = new DmnElementReference();
ref.setHref(xtr.getAttributeValue(null, ATTRIBUTE_HREF));
decisionService.addInputData(ref);
} else if (xtr.isEndElement() && getXMLElementName().equalsIgnoreCase(xtr.getLocalName())) {
|
readyWithDecisionService = true;
}
}
} catch (Exception e) {
LOGGER.warn("Error parsing output entry", e);
}
return decisionService;
}
@Override
protected void writeAdditionalAttributes(DmnElement element, DmnDefinition model, XMLStreamWriter xtw) throws Exception {
}
@Override
protected void writeAdditionalChildElements(DmnElement element, DmnDefinition model, XMLStreamWriter xtw) throws Exception {
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-xml-converter\src\main\java\org\flowable\dmn\xml\converter\DecisionServiceXMLConverter.java
| 1
|
请完成以下Java代码
|
public class POModelInternalAccessor implements IModelInternalAccessor
{
private final PO po;
public POModelInternalAccessor(final PO po)
{
super();
Check.assumeNotNull(po, "po not null");
this.po = po;
}
private final POInfo getPOInfo()
{
return po.getPOInfo();
}
@Override
public Set<String> getColumnNames()
{
return getPOInfo().getColumnNames();
}
@Override
public int getColumnIndex(final String propertyName)
{
return getPOInfo().getColumnIndex(propertyName);
}
@Override
public boolean isVirtualColumn(final String columnName)
{
return getPOInfo().isVirtualColumn(columnName);
}
@Override
public boolean isKeyColumnName(final String columnName)
{
return getPOInfo().isKey(columnName);
}
@Override
public Object getValue(final String propertyName, final int idx, final Class<?> returnType)
{
return po.get_Value(idx);
}
@Override
public Object getValue(final String propertyName, final Class<?> returnType)
{
return po.get_Value(propertyName);
}
@Override
public boolean setValue(final String columnName, final Object value)
{
final Object valueToSet = POWrapper.checkZeroIdValue(columnName, value);
final POInfo poInfo = po.getPOInfo();
if (!poInfo.isColumnUpdateable(columnName))
{
// If the column is not updateable we need to use set_ValueNoCheck
// because else is not consistent with how the generated classes were created
// see org.adempiere.util.ModelClassGenerator.createColumnMethods
return po.set_ValueNoCheck(columnName, valueToSet);
}
else
{
return po.set_ValueOfColumn(columnName, valueToSet);
}
}
@Override
public boolean setValueNoCheck(String propertyName, Object value)
{
return po.set_ValueOfColumn(propertyName, value);
}
@Override
public Object getReferencedObject(final String propertyName, final Method interfaceMethod) throws Exception
{
|
final Class<?> returnType = interfaceMethod.getReturnType();
return po.get_ValueAsPO(propertyName, returnType);
}
@Override
public void setValueFromPO(final String idPropertyName, final Class<?> parameterType, final Object value)
{
po.set_ValueFromPO(idPropertyName, parameterType, value);
}
@Override
public boolean invokeEquals(final Object[] methodArgs)
{
if (methodArgs == null || methodArgs.length != 1)
{
throw new IllegalArgumentException("Invalid method arguments to be used for equals(): " + methodArgs);
}
return po.equals(methodArgs[0]);
}
@Override
public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception
{
return method.invoke(po, methodArgs);
}
@Override
public boolean isCalculated(final String columnName)
{
return getPOInfo().isCalculated(columnName);
}
@Override
public boolean hasColumnName(final String columnName)
{
return getPOInfo().hasColumnName(columnName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POModelInternalAccessor.java
| 1
|
请完成以下Java代码
|
public TableInfo getTableInfoOrNull(final String tableName)
{
final TableNameKey tableNameKey = TableNameKey.of(tableName);
return tableInfoByTableName.get(tableNameKey);
}
@Nullable
public TableInfo getTableInfoOrNull(final AdTableId adTableId)
{
return tableInfoByTableId.get(adTableId);
}
}
private static class JUnitGeneratedTableInfoMap
{
private final AtomicInteger nextTableId2 = new AtomicInteger(1);
private final HashMap<TableNameKey, TableInfo> tableInfoByTableName = new HashMap<>();
private final HashMap<AdTableId, TableInfo> tableInfoByTableId = new HashMap<>();
public AdTableId getOrCreateTableId(@NonNull final String tableName)
{
final TableNameKey tableNameKey = TableNameKey.of(tableName);
TableInfo tableInfo = tableInfoByTableName.get(tableNameKey);
if (tableInfo == null)
{
tableInfo = TableInfo.builder()
.adTableId(AdTableId.ofRepoId(nextTableId2.getAndIncrement()))
.tableName(tableName)
.entityType("D")
.tooltipType(TooltipType.DEFAULT)
.build();
tableInfoByTableName.put(tableNameKey, tableInfo);
tableInfoByTableId.put(tableInfo.getAdTableId(), tableInfo);
}
return tableInfo.getAdTableId();
}
public String getTableName(@NonNull final AdTableId adTableId)
{
final TableInfo tableInfo = tableInfoByTableId.get(adTableId);
if (tableInfo != null)
{
|
return tableInfo.getTableName();
}
//noinspection ConstantConditions
final I_AD_Table adTable = POJOLookupMap.get().lookup("AD_Table", adTableId.getRepoId());
if (adTable != null)
{
final String tableName = adTable.getTableName();
if (Check.isBlank(tableName))
{
throw new AdempiereException("No TableName set for " + adTable);
}
return tableName;
}
//
throw new AdempiereException("No TableName found for AD_Table_ID=" + adTableId);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\api\impl\TableIdsCache.java
| 1
|
请完成以下Java代码
|
protected void validateParams(String taskId, String identityId, int identityIdType, String identityType) {
if (taskId == null) {
throw new ActivitiIllegalArgumentException("taskId is null");
}
if (identityType == null) {
throw new ActivitiIllegalArgumentException("type is required when adding a new task identity link");
}
if (
identityId == null &&
(identityIdType == IDENTITY_GROUP ||
(!IdentityLinkType.ASSIGNEE.equals(identityType) && !IdentityLinkType.OWNER.equals(identityType)))
) {
throw new ActivitiIllegalArgumentException("identityId is null");
}
if (identityIdType != IDENTITY_USER && identityIdType != IDENTITY_GROUP) {
throw new ActivitiIllegalArgumentException("identityIdType allowed values are 1 and 2");
}
}
protected Void execute(CommandContext commandContext, TaskEntity task) {
boolean assignedToNoOne = false;
if (IdentityLinkType.ASSIGNEE.equals(identityType)) {
commandContext.getTaskEntityManager().changeTaskAssignee(task, identityId);
assignedToNoOne = identityId == null;
} else if (IdentityLinkType.OWNER.equals(identityType)) {
commandContext.getTaskEntityManager().changeTaskOwner(task, identityId);
} else if (IDENTITY_USER == identityIdType) {
|
task.addUserIdentityLink(identityId, identityType, details);
} else if (IDENTITY_GROUP == identityIdType) {
task.addGroupIdentityLink(identityId, identityType);
}
boolean forceNullUserId = false;
if (assignedToNoOne) {
// ACT-1317: Special handling when assignee is set to NULL, a
// CommentEntity notifying of assignee-delete should be created
forceNullUserId = true;
}
if (IDENTITY_USER == identityIdType) {
commandContext
.getHistoryManager()
.createUserIdentityLinkComment(taskId, identityId, identityType, true, forceNullUserId);
} else {
commandContext.getHistoryManager().createGroupIdentityLinkComment(taskId, identityId, identityType, true);
}
return null;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\AddIdentityLinkCmd.java
| 1
|
请完成以下Java代码
|
public java.lang.String getUserElementString6()
{
return get_ValueAsString(COLUMNNAME_UserElementString6);
}
@Override
public void setUserElementString7 (final @Nullable java.lang.String UserElementString7)
{
set_Value (COLUMNNAME_UserElementString7, UserElementString7);
}
@Override
public java.lang.String getUserElementString7()
{
return get_ValueAsString(COLUMNNAME_UserElementString7);
}
@Override
public org.compiere.model.I_C_CostClassification_Category getC_CostClassification_Category()
{
return get_ValueAsPO(COLUMNNAME_C_CostClassification_Category_ID, org.compiere.model.I_C_CostClassification_Category.class);
}
@Override
public void setC_CostClassification_Category(final org.compiere.model.I_C_CostClassification_Category C_CostClassification_Category)
{
set_ValueFromPO(COLUMNNAME_C_CostClassification_Category_ID, org.compiere.model.I_C_CostClassification_Category.class, C_CostClassification_Category);
}
@Override
public void setC_CostClassification_Category_ID (final int C_CostClassification_Category_ID)
{
if (C_CostClassification_Category_ID < 1)
set_Value (COLUMNNAME_C_CostClassification_Category_ID, null);
else
set_Value (COLUMNNAME_C_CostClassification_Category_ID, C_CostClassification_Category_ID);
}
@Override
public int getC_CostClassification_Category_ID()
{
return get_ValueAsInt(COLUMNNAME_C_CostClassification_Category_ID);
}
@Override
public org.compiere.model.I_C_CostClassification getC_CostClassification()
{
return get_ValueAsPO(COLUMNNAME_C_CostClassification_ID, org.compiere.model.I_C_CostClassification.class);
}
|
@Override
public void setC_CostClassification(final org.compiere.model.I_C_CostClassification C_CostClassification)
{
set_ValueFromPO(COLUMNNAME_C_CostClassification_ID, org.compiere.model.I_C_CostClassification.class, C_CostClassification);
}
@Override
public void setC_CostClassification_ID (final int C_CostClassification_ID)
{
if (C_CostClassification_ID < 1)
set_Value (COLUMNNAME_C_CostClassification_ID, null);
else
set_Value (COLUMNNAME_C_CostClassification_ID, C_CostClassification_ID);
}
@Override
public int getC_CostClassification_ID()
{
return get_ValueAsInt(COLUMNNAME_C_CostClassification_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Fact_Acct.java
| 1
|
请完成以下Java代码
|
public void hit(int begin, int end, String value)
{
int length = end - begin;
if (length > lengthNet[begin])
{
wordNet[begin] = value;
lengthNet[begin] = length;
}
}
});
StringBuilder sb = new StringBuilder(charArray.length);
for (int offset = 0; offset < wordNet.length; )
{
if (wordNet[offset] == null)
{
sb.append(charArray[offset]);
++offset;
continue;
}
sb.append(wordNet[offset]);
offset += lengthNet[offset];
}
return sb.toString();
}
/**
* 最长分词
*/
public static class Searcher extends BaseSearcher<String>
{
/**
* 分词从何处开始,这是一个状态
*/
int begin;
DoubleArrayTrie<String> trie;
protected Searcher(char[] c, DoubleArrayTrie<String> trie)
{
super(c);
this.trie = trie;
}
protected Searcher(String text, DoubleArrayTrie<String> trie)
{
|
super(text);
this.trie = trie;
}
@Override
public Map.Entry<String, String> next()
{
// 保证首次调用找到一个词语
Map.Entry<String, String> result = null;
while (begin < c.length)
{
LinkedList<Map.Entry<String, String>> entryList = trie.commonPrefixSearchWithValue(c, begin);
if (entryList.size() == 0)
{
++begin;
}
else
{
result = entryList.getLast();
offset = begin;
begin += result.getKey().length();
break;
}
}
if (result == null)
{
return null;
}
return result;
}
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\ts\BaseChineseDictionary.java
| 1
|
请完成以下Java代码
|
public boolean isLock() {
return locked;
}
/**
* 重写redisTemplate的set方法
* <p>
* 命令 SET resource-name anystring NX EX max-lock-time 是一种在 Redis 中实现锁的简单方法。
* <p>
* 客户端执行以上的命令:
* <p>
* 如果服务器返回 OK ,那么这个客户端获得锁。
* 如果服务器返回 NIL ,那么客户端获取锁失败,可以在稍后再重试。
*
* @param key 锁的Key
* @param value 锁里面的值
* @param seconds 过去时间(秒)
* @return
*/
private String set(final String key, final String value, final long seconds) {
Assert.isTrue(!StringUtils.isEmpty(key), "key不能为空");
return redisTemplate.execute(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
Object nativeConnection = connection.getNativeConnection();
String result = null;
if (nativeConnection instanceof JedisCommands) {
result = ((JedisCommands) nativeConnection).set(key, value, NX, EX, seconds);
}
if (!StringUtils.isEmpty(lockKeyLog) && !StringUtils.isEmpty(result)) {
logger.info("获取锁{}的时间:{}", lockKeyLog, System.currentTimeMillis());
}
return result;
}
});
}
/**
* 获取redis里面的值
*
* @param key key
* @param aClass class
* @return T
*/
private <T> T get(final String key, Class<T> aClass) {
Assert.isTrue(!StringUtils.isEmpty(key), "key不能为空");
return redisTemplate.execute((RedisConnection connection) -> {
Object nativeConnection = connection.getNativeConnection();
Object result = null;
if (nativeConnection instanceof JedisCommands) {
result = ((JedisCommands) nativeConnection).get(key);
}
return (T) result;
});
}
/**
* @param millis 毫秒
* @param nanos 纳秒
* @Title: seleep
* @Description: 线程等待时间
|
* @author yuhao.wang
*/
private void seleep(long millis, int nanos) {
try {
Thread.sleep(millis, random.nextInt(nanos));
} catch (InterruptedException e) {
logger.info("获取分布式锁休眠被中断:", e);
}
}
public String getLockKeyLog() {
return lockKeyLog;
}
public void setLockKeyLog(String lockKeyLog) {
this.lockKeyLog = lockKeyLog;
}
public int getExpireTime() {
return expireTime;
}
public void setExpireTime(int expireTime) {
this.expireTime = expireTime;
}
public long getTimeOut() {
return timeOut;
}
public void setTimeOut(long timeOut) {
this.timeOut = timeOut;
}
}
|
repos\spring-boot-student-master\spring-boot-student-data-redis-distributed-lock\src\main\java\com\xiaolyuh\redis\lock\RedisLock3.java
| 1
|
请完成以下Java代码
|
public boolean isHandleCmmnEngineExecutorsAfterEngineCreate() {
return handleCmmnEngineExecutorsAfterEngineCreate;
}
public CmmnEngineConfiguration setHandleCmmnEngineExecutorsAfterEngineCreate(boolean handleCmmnEngineExecutorsAfterEngineCreate) {
this.handleCmmnEngineExecutorsAfterEngineCreate = handleCmmnEngineExecutorsAfterEngineCreate;
return this;
}
public boolean isAlwaysUseArraysForDmnMultiHitPolicies() {
return alwaysUseArraysForDmnMultiHitPolicies;
}
public CmmnEngineConfiguration setAlwaysUseArraysForDmnMultiHitPolicies(boolean alwaysUseArraysForDmnMultiHitPolicies) {
this.alwaysUseArraysForDmnMultiHitPolicies = alwaysUseArraysForDmnMultiHitPolicies;
return this;
}
public CaseDefinitionLocalizationManager getCaseDefinitionLocalizationManager() {
return caseDefinitionLocalizationManager;
}
public CmmnEngineConfiguration setCaseDefinitionLocalizationManager(CaseDefinitionLocalizationManager caseDefinitionLocalizationManager) {
this.caseDefinitionLocalizationManager = caseDefinitionLocalizationManager;
return this;
}
|
public CaseLocalizationManager getCaseLocalizationManager() {
return caseLocalizationManager;
}
public CmmnEngineConfiguration setCaseLocalizationManager(CaseLocalizationManager caseLocalizationManager) {
this.caseLocalizationManager = caseLocalizationManager;
return this;
}
public PlanItemLocalizationManager getPlanItemLocalizationManager() {
return planItemLocalizationManager;
}
public CmmnEngineConfiguration setPlanItemLocalizationManager(PlanItemLocalizationManager planItemLocalizationManager) {
this.planItemLocalizationManager = planItemLocalizationManager;
return this;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\CmmnEngineConfiguration.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static HistoryLevelDeterminator historyLevelDeterminatorMultiDatabase(CamundaBpmProperties camundaBpmProperties,
@Qualifier("camundaBpmJdbcTemplate") JdbcTemplate jdbcTemplate) {
return createHistoryLevelDeterminator(camundaBpmProperties, jdbcTemplate);
}
@Bean
@ConditionalOnMissingBean(CamundaAuthorizationConfiguration.class)
public static CamundaAuthorizationConfiguration camundaAuthorizationConfiguration() {
return new DefaultAuthorizationConfiguration();
}
@Bean
@ConditionalOnMissingBean(CamundaDeploymentConfiguration.class)
public static CamundaDeploymentConfiguration camundaDeploymentConfiguration() {
return new DefaultDeploymentConfiguration();
}
@Bean
public GenericPropertiesConfiguration genericPropertiesConfiguration() {
return new GenericPropertiesConfiguration();
}
@Bean
@ConditionalOnProperty(prefix = "camunda.bpm.admin-user", name = "id")
public CreateAdminUserConfiguration createAdminUserConfiguration() {
return new CreateAdminUserConfiguration();
}
@Bean
@ConditionalOnMissingBean(CamundaFailedJobConfiguration.class)
public static CamundaFailedJobConfiguration failedJobConfiguration() {
return new DefaultFailedJobConfiguration();
|
}
@Bean
@ConditionalOnProperty(prefix = "camunda.bpm.filter", name = "create")
public CreateFilterConfiguration createFilterConfiguration() {
return new CreateFilterConfiguration();
}
@Bean
public EventPublisherPlugin eventPublisherPlugin(CamundaBpmProperties properties, ApplicationEventPublisher publisher) {
return new EventPublisherPlugin(properties.getEventing(), publisher);
}
@Bean
public CamundaIntegrationDeterminator camundaIntegrationDeterminator() {
return new CamundaIntegrationDeterminator();
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\CamundaBpmConfiguration.java
| 2
|
请完成以下Java代码
|
public class PropertyChange {
/** the empty change */
public static final PropertyChange EMPTY_CHANGE = new PropertyChange(null, null, null);
/** the name of the property which has been changed */
protected String propertyName;
/** the original value */
protected Object orgValue;
/** the new value */
protected Object newValue;
public PropertyChange(String propertyName, Object orgValue, Object newValue) {
this.propertyName = propertyName;
this.orgValue = orgValue;
this.newValue = newValue;
}
public String getPropertyName() {
return propertyName;
}
public void setPropertyName(String propertyName) {
this.propertyName = propertyName;
}
public Object getOrgValue() {
return orgValue;
}
public void setOrgValue(Object orgValue) {
this.orgValue = orgValue;
}
public Object getNewValue() {
return newValue;
}
|
public void setNewValue(Object newValue) {
this.newValue = newValue;
}
public String getNewValueString() {
return valueAsString(newValue);
}
public String getOrgValueString() {
return valueAsString(orgValue);
}
protected String valueAsString(Object value) {
if(value == null) {
return null;
} else if(value instanceof Date){
return String.valueOf(((Date)value).getTime());
} else {
return value.toString();
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\PropertyChange.java
| 1
|
请完成以下Java代码
|
public Integer getBurst() {
return burst;
}
public void setBurst(Integer burst) {
this.burst = burst;
}
public Integer getMaxQueueingTimeoutMs() {
return maxQueueingTimeoutMs;
}
public void setMaxQueueingTimeoutMs(Integer maxQueueingTimeoutMs) {
this.maxQueueingTimeoutMs = maxQueueingTimeoutMs;
}
@Override
public boolean equals(Object o) {
if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; }
GatewayFlowRuleEntity that = (GatewayFlowRuleEntity) o;
return Objects.equals(id, that.id) &&
Objects.equals(app, that.app) &&
Objects.equals(ip, that.ip) &&
Objects.equals(port, that.port) &&
Objects.equals(gmtCreate, that.gmtCreate) &&
Objects.equals(gmtModified, that.gmtModified) &&
Objects.equals(resource, that.resource) &&
Objects.equals(resourceMode, that.resourceMode) &&
Objects.equals(grade, that.grade) &&
Objects.equals(count, that.count) &&
Objects.equals(interval, that.interval) &&
Objects.equals(intervalUnit, that.intervalUnit) &&
Objects.equals(controlBehavior, that.controlBehavior) &&
Objects.equals(burst, that.burst) &&
|
Objects.equals(maxQueueingTimeoutMs, that.maxQueueingTimeoutMs) &&
Objects.equals(paramItem, that.paramItem);
}
@Override
public int hashCode() {
return Objects.hash(id, app, ip, port, gmtCreate, gmtModified, resource, resourceMode, grade, count, interval, intervalUnit, controlBehavior, burst, maxQueueingTimeoutMs, paramItem);
}
@Override
public String toString() {
return "GatewayFlowRuleEntity{" +
"id=" + id +
", app='" + app + '\'' +
", ip='" + ip + '\'' +
", port=" + port +
", gmtCreate=" + gmtCreate +
", gmtModified=" + gmtModified +
", resource='" + resource + '\'' +
", resourceMode=" + resourceMode +
", grade=" + grade +
", count=" + count +
", interval=" + interval +
", intervalUnit=" + intervalUnit +
", controlBehavior=" + controlBehavior +
", burst=" + burst +
", maxQueueingTimeoutMs=" + maxQueueingTimeoutMs +
", paramItem=" + paramItem +
'}';
}
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\gateway\GatewayFlowRuleEntity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PmsMenu extends PermissionBaseEntity {
private static final long serialVersionUID = 1L;
/** 菜单名称 **/
private String name;
/** 菜单地址 **/
private String url;
/** 菜单编号(用于显示时排序) **/
private String number;
/** 是否为叶子节点 **/
private String isLeaf;
/** 菜单层级 **/
private Long level;
/** 父节点:一级菜单为0 **/
private PmsMenu parent;
/** 目标名称(用于DWZUI的NAVTABID) **/
private String targetName;
public PmsMenu() {
super();
}
/** 菜单名称 **/
public String getName() {
return name;
}
/** 菜单名称 **/
public void setName(String name) {
this.name = name;
}
/** 菜单地址 **/
public String getUrl() {
return url;
}
/** 菜单地址 **/
public void setUrl(String url) {
this.url = url;
}
/** 菜单编号(用于显示时排序) **/
public String getNumber() {
return number;
}
/** 菜单编号(用于显示时排序) **/
public void setNumber(String number) {
this.number = number;
}
/** 是否为叶子节点 **/
public String getIsLeaf() {
return isLeaf;
}
/** 是否为叶子节点 **/
public void setIsLeaf(String isLeaf) {
this.isLeaf = isLeaf;
|
}
/** 菜单层级 **/
public Long getLevel() {
return level;
}
/** 菜单层级 **/
public void setLevel(Long level) {
this.level = level;
}
/** 父节点:一级菜单为0 **/
public PmsMenu getParent() {
return parent;
}
/** 父节点:一级菜单为0 **/
public void setParent(PmsMenu parent) {
this.parent = parent;
}
/** 目标名称(用于DWZUI的NAVTABID) **/
public String getTargetName() {
return targetName;
}
/** 目标名称(用于DWZUI的NAVTABID) **/
public void setTargetName(String targetName) {
this.targetName = targetName;
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\entity\PmsMenu.java
| 2
|
请完成以下Java代码
|
public XMLGregorianCalendar getVldtnDt() {
return vldtnDt;
}
/**
* Sets the value of the vldtnDt property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setVldtnDt(XMLGregorianCalendar value) {
this.vldtnDt = value;
}
/**
* Gets the value of the vldtnSeqNb property.
*
* @return
* possible object is
|
* {@link String }
*
*/
public String getVldtnSeqNb() {
return vldtnSeqNb;
}
/**
* Sets the value of the vldtnSeqNb property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVldtnSeqNb(String value) {
this.vldtnSeqNb = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\CardIndividualTransaction1.java
| 1
|
请完成以下Java代码
|
public void setCookieName(String cookieName) {
Assert.notNull(cookieName, "cookieName cannot be null");
this.cookieName = cookieName;
}
private String getRequestContext(HttpServletRequest request) {
String contextPath = request.getContextPath();
return (contextPath.length() > 0) ? contextPath : "/";
}
/**
* Factory method to conveniently create an instance that creates cookies where
* {@link Cookie#isHttpOnly()} is set to false.
* @return an instance of CookieCsrfTokenRepository that creates cookies where
* {@link Cookie#isHttpOnly()} is set to false.
*/
public static CookieCsrfTokenRepository withHttpOnlyFalse() {
CookieCsrfTokenRepository result = new CookieCsrfTokenRepository();
result.cookieHttpOnly = false;
return result;
}
private String createNewToken() {
return UUID.randomUUID().toString();
}
private Cookie mapToCookie(ResponseCookie responseCookie) {
Cookie cookie = new Cookie(responseCookie.getName(), responseCookie.getValue());
cookie.setSecure(responseCookie.isSecure());
|
cookie.setPath(responseCookie.getPath());
cookie.setMaxAge((int) responseCookie.getMaxAge().getSeconds());
cookie.setHttpOnly(responseCookie.isHttpOnly());
if (StringUtils.hasLength(responseCookie.getDomain())) {
cookie.setDomain(responseCookie.getDomain());
}
if (StringUtils.hasText(responseCookie.getSameSite())) {
cookie.setAttribute("SameSite", responseCookie.getSameSite());
}
return cookie;
}
/**
* Set the path that the Cookie will be created with. This will override the default
* functionality which uses the request context as the path.
* @param path the path to use
*/
public void setCookiePath(String path) {
this.cookiePath = path;
}
/**
* Get the path that the CSRF cookie will be set to.
* @return the path to be used.
*/
public @Nullable String getCookiePath() {
return this.cookiePath;
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\csrf\CookieCsrfTokenRepository.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getComment() {
return comment;
}
/**
* Sets the value of the comment property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setComment(String value) {
this.comment = value;
}
/**
* The amount of "other tax".
*
* @return
* possible object is
|
* {@link BigDecimal }
*
*/
public BigDecimal getAmount() {
return amount;
}
/**
* Sets the value of the amount property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setAmount(BigDecimal value) {
this.amount = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\OtherTaxType.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Oauth2Controller {
/**
* 授权码模式跳转到登录页面
*
* @return view
*/
@GetMapping("/login")
public String loginView() {
return "login";
}
/**
* 退出登录
*
* @param redirectUrl 退出完成后的回调地址
* @param principal 用户信息
|
* @return 结果
*/
@GetMapping("/logout")
public ModelAndView logoutView(@RequestParam("redirect_url") String redirectUrl, Principal principal) {
if (Objects.isNull(principal)) {
throw new ResourceAccessException("请求错误,用户尚未登录");
}
ModelAndView view = new ModelAndView();
view.setViewName("logout");
view.addObject("user", principal.getName());
view.addObject("redirectUrl", redirectUrl);
return view;
}
}
|
repos\spring-boot-demo-master\demo-oauth\oauth-authorization-server\src\main\java\com\xkcoding\oauth\controller\Oauth2Controller.java
| 2
|
请完成以下Java代码
|
private void handleOrderLineReactivate(final I_C_OrderLine ol)
{
logger.info("Setting order line's processed status " + ol + " back to Processed='Y'" + " as it references a contract term");
ol.setProcessed(true);
InterfaceWrapperHelper.save(ol);
}
@DocValidate(timings = { ModelValidator.TIMING_AFTER_COMPLETE })
public void updateCustomerRetention(final I_C_Order order)
{
final CustomerRetentionRepository customerRetentionRepo = SpringContextHolder.instance.getBean(CustomerRetentionRepository.class);
if (!order.isSOTrx())
{
// nothing to do
return;
}
|
final OrderId orderId = OrderId.ofRepoId(order.getC_Order_ID());
customerRetentionRepo.updateCustomerRetentionOnOrderComplete(orderId);
}
@ModelChange(timings = {
ModelValidator.TYPE_BEFORE_CHANGE
}, ifColumnsChanged = I_C_Order.COLUMNNAME_DatePromised)
public void updateOrderLineFromContract(final I_C_Order order)
{
orderDAO.retrieveOrderLines(order)
.stream()
.map(ol -> InterfaceWrapperHelper.create(ol, de.metas.contracts.order.model.I_C_OrderLine.class))
.filter(subscriptionBL::isSubscription)
.forEach(orderLineBL::updatePrices);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\interceptor\C_Order.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void cleanUp() {
PageDataIterable<TenantId> tenants = new PageDataIterable<>(tenantService::findTenantsIds, 10_000);
for (TenantId tenantId : tenants) {
try {
cleanUp(tenantId);
} catch (Exception e) {
getLogger().warn("Failed to clean up alarms by ttl for tenant {}", tenantId, e);
}
}
}
private void cleanUp(TenantId tenantId) {
if (!partitionService.resolve(ServiceType.TB_CORE, tenantId, tenantId).isMyPartition()) {
return;
}
Optional<DefaultTenantProfileConfiguration> tenantProfileConfiguration = tenantProfileCache.get(tenantId).getProfileConfiguration();
if (tenantProfileConfiguration.isEmpty() || tenantProfileConfiguration.get().getAlarmsTtlDays() == 0) {
return;
}
long ttl = TimeUnit.DAYS.toMillis(tenantProfileConfiguration.get().getAlarmsTtlDays());
long expirationTime = System.currentTimeMillis() - ttl;
PageLink removalBatchRequest = new PageLink(removalBatchSize, 0);
long totalRemoved = 0;
Set<String> typesToRemove = new HashSet<>();
while (true) {
PageData<AlarmId> toRemove = alarmDao.findAlarmsIdsByEndTsBeforeAndTenantId(expirationTime, tenantId, removalBatchRequest);
for (AlarmId alarmId : toRemove.getData()) {
Alarm alarm = alarmService.delAlarm(tenantId, alarmId, false).getAlarm();
if (alarm != null) {
entityActionService.pushEntityActionToRuleEngine(alarm.getOriginator(), alarm, tenantId, null, ActionType.ALARM_DELETE, null);
totalRemoved++;
typesToRemove.add(alarm.getType());
}
|
}
if (!toRemove.hasNext()) {
break;
}
}
alarmService.delAlarmTypes(tenantId, typesToRemove);
if (totalRemoved > 0) {
getLogger().info("Removed {} outdated alarm(s) for tenant {} older than {}", totalRemoved, tenantId, new Date(expirationTime));
}
}
// wrapper for tests to spy on static logger
Logger getLogger() {
return log;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\ttl\AlarmsCleanUpService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class RuntimeParametersRepository
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
@NonNull
public RuntimeParameter upsertRuntimeParameter(@NonNull final RuntimeParameterUpsertRequest request)
{
final RuntimeParamUniqueKey uniqueKey = request.getRuntimeParamUniqueKey();
final I_ExternalSystem_RuntimeParameter record = getRecordByUniqueKey(uniqueKey)
.orElseGet(() -> InterfaceWrapperHelper.newInstance(I_ExternalSystem_RuntimeParameter.class));
record.setExternalSystem_Config_ID(uniqueKey.getExternalSystemParentConfigId().getRepoId());
record.setExternal_Request(uniqueKey.getRequest());
record.setName(uniqueKey.getName());
record.setValue(request.getValue());
saveRecord(record);
return recordToModel(record);
}
@NonNull
public ImmutableList<RuntimeParameter> getByConfigIdAndRequest(@NonNull final ExternalSystemParentConfigId configId, @NonNull final String externalRequest)
{
return queryBL.createQueryBuilder(I_ExternalSystem_RuntimeParameter.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_ExternalSystem_RuntimeParameter.COLUMNNAME_ExternalSystem_Config_ID, configId.getRepoId())
.addEqualsFilter(I_ExternalSystem_RuntimeParameter.COLUMNNAME_External_Request, externalRequest)
.create()
.list()
.stream()
.map(this::recordToModel)
.collect(ImmutableList.toImmutableList());
|
}
@NonNull
private RuntimeParameter recordToModel(@NonNull final I_ExternalSystem_RuntimeParameter record)
{
return RuntimeParameter.builder()
.runtimeParameterId(RuntimeParameterId.ofRepoId(record.getExternalSystem_RuntimeParameter_ID()))
.externalSystemParentConfigId(ExternalSystemParentConfigId.ofRepoId(record.getExternalSystem_Config_ID()))
.request(record.getExternal_Request())
.name(record.getName())
.value(record.getValue())
.build();
}
@NonNull
private Optional<I_ExternalSystem_RuntimeParameter> getRecordByUniqueKey(@NonNull final RuntimeParamUniqueKey uniqueKey)
{
return queryBL.createQueryBuilder(I_ExternalSystem_RuntimeParameter.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_ExternalSystem_RuntimeParameter.COLUMNNAME_External_Request, uniqueKey.getRequest())
.addEqualsFilter(I_ExternalSystem_RuntimeParameter.COLUMNNAME_Name, uniqueKey.getName())
.addEqualsFilter(I_ExternalSystem_RuntimeParameter.COLUMNNAME_ExternalSystem_Config_ID, uniqueKey.getExternalSystemParentConfigId().getRepoId())
.create()
.firstOnlyOptional(I_ExternalSystem_RuntimeParameter.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\runtimeparameters\RuntimeParametersRepository.java
| 2
|
请完成以下Java代码
|
public void setUnitsCycles (final @Nullable BigDecimal UnitsCycles)
{
set_Value (COLUMNNAME_UnitsCycles, UnitsCycles);
}
@Override
public BigDecimal getUnitsCycles()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_UnitsCycles);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setWaitingTime (final int WaitingTime)
{
set_Value (COLUMNNAME_WaitingTime, WaitingTime);
}
@Override
public int getWaitingTime()
{
return get_ValueAsInt(COLUMNNAME_WaitingTime);
}
@Override
public void setWaitTime (final int WaitTime)
{
set_Value (COLUMNNAME_WaitTime, WaitTime);
}
@Override
public int getWaitTime()
{
return get_ValueAsInt(COLUMNNAME_WaitTime);
}
@Override
public void setWorkflow_ID (final int Workflow_ID)
{
if (Workflow_ID < 1)
set_Value (COLUMNNAME_Workflow_ID, null);
else
set_Value (COLUMNNAME_Workflow_ID, Workflow_ID);
}
@Override
public int getWorkflow_ID()
|
{
return get_ValueAsInt(COLUMNNAME_Workflow_ID);
}
@Override
public void setWorkingTime (final int WorkingTime)
{
set_Value (COLUMNNAME_WorkingTime, WorkingTime);
}
@Override
public int getWorkingTime()
{
return get_ValueAsInt(COLUMNNAME_WorkingTime);
}
@Override
public void setXPosition (final int XPosition)
{
set_Value (COLUMNNAME_XPosition, XPosition);
}
@Override
public int getXPosition()
{
return get_ValueAsInt(COLUMNNAME_XPosition);
}
@Override
public void setYield (final int Yield)
{
set_Value (COLUMNNAME_Yield, Yield);
}
@Override
public int getYield()
{
return get_ValueAsInt(COLUMNNAME_Yield);
}
@Override
public void setYPosition (final int YPosition)
{
set_Value (COLUMNNAME_YPosition, YPosition);
}
@Override
public int getYPosition()
{
return get_ValueAsInt(COLUMNNAME_YPosition);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Node.java
| 1
|
请完成以下Java代码
|
public class DateIncrementer {
private static final Logger log = Logger.getLogger(DateIncrementer.class.getName());
private static final int INCREMENT_BY_IN_DAYS = 1;
public static String addOneDay(String date) {
return LocalDate
.parse(date)
.plusDays(INCREMENT_BY_IN_DAYS)
.toString();
}
public static String addOneDayJodaTime(String date) {
DateTime dateTime = new DateTime(date);
return dateTime
.plusDays(INCREMENT_BY_IN_DAYS)
.toString("yyyy-MM-dd");
}
public static String addOneDayCalendar(String date) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(date));
c.add(Calendar.DATE, 1);
return sdf.format(c.getTime());
}
public static String addOneDayApacheCommons(String date) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date incrementedDate = DateUtils.addDays(sdf.parse(date), 1);
return sdf.format(incrementedDate);
|
}
public static void main(String[] args) throws ParseException {
String date = LocalDate
.now()
.toString();
log.info("Current date = " + date);
String incrementedDateJava8 = DateIncrementer.addOneDay(date);
log.info("Date incremented by one day using (Java 8): " + incrementedDateJava8);
String incrementedDateJodaTime = DateIncrementer.addOneDayJodaTime(date);
log.info("Date incremented by one day using (Joda-Time): " + incrementedDateJodaTime);
String incrementedDateCalendar = addOneDayCalendar(date);
log.info("Date incremented by one day using (java.util.Calendar): " + incrementedDateCalendar);
String incrementedDateApacheCommons = addOneDayApacheCommons(date);
log.info("Date incremented by one day using (Apache Commons DateUtils): " + incrementedDateApacheCommons);
}
}
|
repos\tutorials-master\core-java-modules\core-java-date-operations-4\src\main\java\com\baeldung\datetime\modify\DateIncrementer.java
| 1
|
请完成以下Java代码
|
public final class OidcLogoutAuthenticationConverter implements AuthenticationConverter {
private static final Authentication ANONYMOUS_AUTHENTICATION = new AnonymousAuthenticationToken("anonymous",
"anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
@Override
public Authentication convert(HttpServletRequest request) {
MultiValueMap<String, String> parameters = "GET".equals(request.getMethod())
? OAuth2EndpointUtils.getQueryParameters(request) : OAuth2EndpointUtils.getFormParameters(request);
// id_token_hint (REQUIRED) // RECOMMENDED as per spec
String idTokenHint = parameters.getFirst("id_token_hint");
if (!StringUtils.hasText(idTokenHint) || parameters.get("id_token_hint").size() != 1) {
throwError(OAuth2ErrorCodes.INVALID_REQUEST, "id_token_hint");
}
Authentication principal = SecurityContextHolder.getContext().getAuthentication();
if (principal == null) {
principal = ANONYMOUS_AUTHENTICATION;
}
String sessionId = null;
HttpSession session = request.getSession(false);
if (session != null) {
sessionId = session.getId();
}
// client_id (OPTIONAL)
String clientId = parameters.getFirst(OAuth2ParameterNames.CLIENT_ID);
if (StringUtils.hasText(clientId) && parameters.get(OAuth2ParameterNames.CLIENT_ID).size() != 1) {
throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.CLIENT_ID);
|
}
// post_logout_redirect_uri (OPTIONAL)
String postLogoutRedirectUri = parameters.getFirst("post_logout_redirect_uri");
if (StringUtils.hasText(postLogoutRedirectUri) && parameters.get("post_logout_redirect_uri").size() != 1) {
throwError(OAuth2ErrorCodes.INVALID_REQUEST, "post_logout_redirect_uri");
}
// state (OPTIONAL)
String state = parameters.getFirst(OAuth2ParameterNames.STATE);
if (StringUtils.hasText(state) && parameters.get(OAuth2ParameterNames.STATE).size() != 1) {
throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE);
}
return new OidcLogoutAuthenticationToken(idTokenHint, principal, sessionId, clientId, postLogoutRedirectUri,
state);
}
private static void throwError(String errorCode, String parameterName) {
OAuth2Error error = new OAuth2Error(errorCode, "OpenID Connect 1.0 Logout Request Parameter: " + parameterName,
"https://openid.net/specs/openid-connect-rpinitiated-1_0.html#ValidationAndErrorHandling");
throw new OAuth2AuthenticationException(error);
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\web\authentication\OidcLogoutAuthenticationConverter.java
| 1
|
请完成以下Java代码
|
public static boolean hasUrlEncoded(String str) {
/**
* 支持JAVA的URLEncoder.encode出来的string做判断。 即: 将' '转成'+' <br>
* 0-9a-zA-Z保留 <br>
* '-','_','.','*'保留 <br>
* 其他字符转成%XX的格式,X是16进制的大写字符,范围是[0-9A-F]
*/
boolean needEncode = false;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (dontNeedEncoding.get((int) c)) {
continue;
}
if (c == '%' && (i + 2) < str.length()) {
// 判断是否符合urlEncode规范
char c1 = str.charAt(++i);
char c2 = str.charAt(++i);
if (isDigit16Char(c1) && isDigit16Char(c2)) {
continue;
}
}
// 其他字符,肯定需要urlEncode
needEncode = true;
|
break;
}
return !needEncode;
}
/**
* 判断c是否是16进制的字符
*
* @param c
* @return
*/
private static boolean isDigit16Char(char c) {
return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F');
}
}
|
repos\kkFileView-master\server\src\main\java\cn\keking\utils\UrlEncoderUtils.java
| 1
|
请完成以下Java代码
|
class StudentSimple {
private String firstName;
private String lastName;
private String[] courses;
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 String[] getCourses() {
return courses;
}
public void setCourses(String[] courses) {
this.courses = courses;
}
}
|
repos\tutorials-master\spring-web-modules\spring-rest-http-3\src\main\java\com\baeldung\xwwwformurlencoded\StudentSimple.java
| 1
|
请完成以下Java代码
|
protected String doIt()
{
final CreateMatchInvoiceRequest request = createMatchInvoiceRequest().orElseThrow();
orderCostService.createMatchInvoice(request);
invalidateView();
return MSG_OK;
}
private ExplainedOptional<CreateMatchInvoiceRequest> createMatchInvoiceRequest()
{
final ImmutableSet<InOutCostId> selectedInOutCostIds = getSelectedInOutCostIds();
if (selectedInOutCostIds.isEmpty())
{
|
return ExplainedOptional.emptyBecause("No selection");
}
return ExplainedOptional.of(
CreateMatchInvoiceRequest.builder()
.invoiceAndLineId(getView().getInvoiceLineId())
.inoutCostIds(selectedInOutCostIds)
.build());
}
private ImmutableSet<InOutCostId> getSelectedInOutCostIds()
{
final ImmutableList<InOutCostRow> rows = getSelectedRows();
return rows.stream().map(InOutCostRow::getInoutCostId).collect(ImmutableSet.toImmutableSet());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\invoice\match_inout_costs\InOutCostsView_CreateMatchInv.java
| 1
|
请完成以下Java代码
|
public void setPickFrom_Warehouse_ID (final int PickFrom_Warehouse_ID)
{
if (PickFrom_Warehouse_ID < 1)
set_Value (COLUMNNAME_PickFrom_Warehouse_ID, null);
else
set_Value (COLUMNNAME_PickFrom_Warehouse_ID, PickFrom_Warehouse_ID);
}
@Override
public int getPickFrom_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_PickFrom_Warehouse_ID);
}
@Override
public void setQtyRejectedToPick (final @Nullable BigDecimal QtyRejectedToPick)
{
set_Value (COLUMNNAME_QtyRejectedToPick, QtyRejectedToPick);
}
@Override
public BigDecimal getQtyRejectedToPick()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyRejectedToPick);
|
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* RejectReason AD_Reference_ID=541422
* Reference name: QtyNotPicked RejectReason
*/
public static final int REJECTREASON_AD_Reference_ID=541422;
/** NotFound = N */
public static final String REJECTREASON_NotFound = "N";
/** Damaged = D */
public static final String REJECTREASON_Damaged = "D";
@Override
public void setRejectReason (final @Nullable java.lang.String RejectReason)
{
set_Value (COLUMNNAME_RejectReason, RejectReason);
}
@Override
public java.lang.String getRejectReason()
{
return get_ValueAsString(COLUMNNAME_RejectReason);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job_Step_HUAlternative.java
| 1
|
请完成以下Java代码
|
public IDataSet load(String folderPath, String charsetName, double percentage) throws IllegalArgumentException, IOException
{
if (folderPath == null) throw new IllegalArgumentException("参数 folderPath == null");
File root = new File(folderPath);
if (!root.exists()) throw new IllegalArgumentException(String.format("目录 %s 不存在", root.getAbsolutePath()));
if (!root.isDirectory())
throw new IllegalArgumentException(String.format("目录 %s 不是一个目录", root.getAbsolutePath()));
if (percentage > 1.0 || percentage < -1.0) throw new IllegalArgumentException("percentage 的绝对值必须介于[0, 1]之间");
File[] folders = root.listFiles();
if (folders == null) return null;
ConsoleLogger.logger.start("模式:%s\n文本编码:%s\n根目录:%s\n加载中...\n", testingDataSet ? "测试集" : "训练集", charsetName, folderPath);
for (File folder : folders)
{
if (folder.isFile()) continue;
File[] files = folder.listFiles();
if (files == null) continue;
String category = folder.getName();
ConsoleLogger.logger.out("[%s]...", category);
int b, e;
if (percentage > 0)
{
b = 0;
e = (int) (files.length * percentage);
}
else
{
b = (int) (files.length * (1 + percentage));
e = files.length;
}
int logEvery = (int) Math.ceil((e - b) / 10000f);
for (int i = b; i < e; i++)
{
add(folder.getName(), TextProcessUtility.readTxt(files[i], charsetName));
if (i % logEvery == 0)
{
ConsoleLogger.logger.out("%c[%s]...%.2f%%", 13, category, MathUtility.percentage(i - b + 1, e - b));
}
}
ConsoleLogger.logger.out(" %d 篇文档\n", e - b);
|
}
ConsoleLogger.logger.finish(" 加载了 %d 个类目,共 %d 篇文档\n", getCatalog().size(), size());
return this;
}
@Override
public IDataSet load(String folderPath, double rate) throws IllegalArgumentException, IOException
{
return null;
}
@Override
public IDataSet add(Map<String, String[]> testingDataSet)
{
for (Map.Entry<String, String[]> entry : testingDataSet.entrySet())
{
for (String document : entry.getValue())
{
add(entry.getKey(), document);
}
}
return this;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\corpus\AbstractDataSet.java
| 1
|
请完成以下Java代码
|
public Substitutionsgrund getSubstitutionsgrund() {
return substitutionsgrund;
}
/**
* Sets the value of the substitutionsgrund property.
*
* @param value
* allowed object is
* {@link Substitutionsgrund }
*
*/
public void setSubstitutionsgrund(Substitutionsgrund value) {
this.substitutionsgrund = value;
}
/**
* Gets the value of the grund property.
*
* @return
* possible object is
* {@link BestellungDefektgrund }
*
*/
public BestellungDefektgrund getGrund() {
return grund;
}
/**
* Sets the value of the grund property.
*
* @param value
|
* allowed object is
* {@link BestellungDefektgrund }
*
*/
public void setGrund(BestellungDefektgrund value) {
this.grund = value;
}
/**
* Gets the value of the lieferPzn property.
*
*/
public long getLieferPzn() {
return lieferPzn;
}
/**
* Sets the value of the lieferPzn property.
*
*/
public void setLieferPzn(long value) {
this.lieferPzn = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\BestellungSubstitution.java
| 1
|
请完成以下Java代码
|
public class BoundaryTimerEventActivityBehavior extends BoundaryEventActivityBehavior {
private static final long serialVersionUID = 1L;
protected TimerEventDefinition timerEventDefinition;
public BoundaryTimerEventActivityBehavior(TimerEventDefinition timerEventDefinition, boolean interrupting) {
super(interrupting);
this.timerEventDefinition = timerEventDefinition;
}
@Override
public void execute(DelegateExecution execution) {
ExecutionEntity executionEntity = (ExecutionEntity) execution;
if (!(execution.getCurrentFlowElement() instanceof BoundaryEvent)) {
throw new ActivitiException(
"Programmatic error: " + this.getClass() + " should not be used for anything else than a boundary event"
);
}
|
JobManager jobManager = Context.getCommandContext().getJobManager();
TimerJobEntity timerJob = jobManager.createTimerJob(
timerEventDefinition,
interrupting,
executionEntity,
TriggerTimerEventJobHandler.TYPE,
TimerEventHandler.createConfiguration(
execution.getCurrentActivityId(),
timerEventDefinition.getEndDate(),
timerEventDefinition.getCalendarName()
)
);
if (timerJob != null) {
jobManager.scheduleTimerJob(timerJob);
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\BoundaryTimerEventActivityBehavior.java
| 1
|
请完成以下Java代码
|
private static DetailId createDetailIdFor(@NonNull final DataEntryTab dataEntryTab)
{
return DetailId.fromPrefixAndId(I_DataEntry_Tab.Table_Name, dataEntryTab.getId().getRepoId());
}
private static DetailId createDetailIdFor(@NonNull final DataEntrySubTab subTab)
{
return DetailId.fromPrefixAndId(I_DataEntry_SubTab.Table_Name, subTab.getId().getRepoId());
}
private static DocumentFieldWidgetType ofFieldType(@NonNull final FieldType fieldType)
{
switch (fieldType)
{
case DATE:
return DocumentFieldWidgetType.LocalDate;
case LIST:
return DocumentFieldWidgetType.List;
case NUMBER:
|
return DocumentFieldWidgetType.Number;
case TEXT:
return DocumentFieldWidgetType.Text;
case LONG_TEXT:
return DocumentFieldWidgetType.LongText;
case YESNO:
return DocumentFieldWidgetType.YesNo;
case CREATED_UPDATED_INFO:
return DocumentFieldWidgetType.Text;
case SUB_TAB_ID:
return DocumentFieldWidgetType.Integer;
case PARENT_LINK_ID:
return DocumentFieldWidgetType.Integer;
default:
throw new AdempiereException("Unexpected DataEntryField.Type=" + fieldType);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dataentry\window\descriptor\factory\DataEntryTabLoader.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SupplyRequiredHandler implements MaterialEventHandler<SupplyRequiredEvent>
{
@NonNull private final PostMaterialEventService postMaterialEventService;
@NonNull private final List<SupplyRequiredAdvisor> supplyRequiredAdvisors;
@NonNull private final SupplyRequiredHandlerHelper helper;
@Override
public Collection<Class<? extends SupplyRequiredEvent>> getHandledEventType()
{
return ImmutableList.of(SupplyRequiredEvent.class);
}
@Override
public void handleEvent(@NonNull final SupplyRequiredEvent event)
{
handleSupplyRequiredEvent(event.getSupplyRequiredDescriptor());
}
private void handleSupplyRequiredEvent(@NonNull final SupplyRequiredDescriptor descriptor)
{
final ArrayList<MaterialEvent> events = new ArrayList<>();
final MaterialPlanningContext context = helper.createContextOrNull(descriptor);
if (context != null)
{
|
for (final SupplyRequiredAdvisor advisor : supplyRequiredAdvisors)
{
events.addAll(advisor.createAdvisedEvents(descriptor, context));
}
}
if (events.isEmpty())
{
final NoSupplyAdviceEvent noSupplyAdviceEvent = NoSupplyAdviceEvent.of(descriptor.withNewEventId());
Loggables.addLog("No advice events were created. Firing {}", noSupplyAdviceEvent);
postMaterialEventService.enqueueEventNow(noSupplyAdviceEvent);
}
else
{
events.forEach(postMaterialEventService::enqueueEventNow);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\event\SupplyRequiredHandler.java
| 2
|
请完成以下Java代码
|
public List<HistoricVariableInstance> findHistoricVariableInstancesByQueryCriteria(HistoricVariableInstanceQueryImpl historicProcessVariableQuery, Page page) {
return getDbSqlSession().selectList("selectHistoricVariableInstanceByQueryCriteria", historicProcessVariableQuery, page);
}
public HistoricVariableInstanceEntity findHistoricVariableInstanceByVariableInstanceId(String variableInstanceId) {
return (HistoricVariableInstanceEntity) getDbSqlSession().selectOne("selectHistoricVariableInstanceByVariableInstanceId", variableInstanceId);
}
public void deleteHistoricVariableInstancesByTaskId(String taskId) {
if (getHistoryManager().isHistoryLevelAtLeast(HistoryLevel.ACTIVITY)) {
List<HistoricVariableInstance> historicProcessVariables = new HistoricVariableInstanceQueryImpl().taskId(taskId).list();
for (HistoricVariableInstance historicProcessVariable : historicProcessVariables) {
((HistoricVariableInstanceEntity) historicProcessVariable).delete();
}
}
}
|
@Override
public void delete(PersistentObject persistentObject) {
HistoricVariableInstanceEntity variableInstanceEntity = (HistoricVariableInstanceEntity) persistentObject;
variableInstanceEntity.delete();
}
@SuppressWarnings("unchecked")
public List<HistoricVariableInstance> findHistoricVariableInstancesByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) {
return getDbSqlSession().selectListWithRawParameter("selectHistoricVariableInstanceByNativeQuery", parameterMap, firstResult, maxResults);
}
public long findHistoricVariableInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectHistoricVariableInstanceCountByNativeQuery", parameterMap);
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricVariableInstanceEntityManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void processField(VariableElement field) {
String name = field.getSimpleName().toString();
this.fields.putIfAbsent(name, field);
}
private void processRecordComponent(RecordComponentElement recordComponent) {
String name = recordComponent.getSimpleName().toString();
this.recordComponents.putIfAbsent(name, recordComponent);
}
Map<String, VariableElement> getFields() {
return Collections.unmodifiableMap(this.fields);
}
Map<String, RecordComponentElement> getRecordComponents() {
return Collections.unmodifiableMap(this.recordComponents);
}
Map<String, List<ExecutableElement>> getPublicGetters() {
return Collections.unmodifiableMap(this.publicGetters);
}
ExecutableElement getPublicGetter(String name, TypeMirror type) {
List<ExecutableElement> candidates = this.publicGetters.get(name);
return getPublicAccessor(candidates, type, (specificType) -> getMatchingGetter(candidates, specificType));
}
|
ExecutableElement getPublicSetter(String name, TypeMirror type) {
List<ExecutableElement> candidates = this.publicSetters.get(name);
return getPublicAccessor(candidates, type, (specificType) -> getMatchingSetter(candidates, specificType));
}
private ExecutableElement getPublicAccessor(List<ExecutableElement> candidates, TypeMirror type,
Function<TypeMirror, ExecutableElement> matchingAccessorExtractor) {
if (candidates != null) {
ExecutableElement matching = matchingAccessorExtractor.apply(type);
if (matching != null) {
return matching;
}
TypeMirror alternative = this.env.getTypeUtils().getWrapperOrPrimitiveFor(type);
if (alternative != null) {
return matchingAccessorExtractor.apply(alternative);
}
}
return null;
}
}
|
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\TypeElementMembers.java
| 2
|
请完成以下Java代码
|
private final String getModelPackageForTableName(final String tableName)
{
final String entityType = getEntityTypeForTableName(tableName);
final String modelpackage = entityTypesCache.getModelPackage(entityType);
return modelpackage;
}
@VisibleForTesting
String getEntityTypeForTableName(final String tableName)
{
return TableIdsCache.instance.getEntityType(tableName);
}
/**
* Get PO class.
*
* @param className fully qualified class name
* @return class or <code>null</code> if model class was not found or it's not valid
*/
private Class<?> loadModelClassForClassname(final String className)
{
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try
{
final Class<?> clazz = classLoader.loadClass(className);
// Make sure that it is a PO class
if (!PO.class.isAssignableFrom(clazz))
{
log.debug("Skip {} because it does not have PO class as supertype", clazz);
return null;
}
return clazz;
}
catch (ClassNotFoundException e)
{
if (log.isDebugEnabled())
{
log.debug("No class found for " + className + " (classloader: " + classLoader + ")", e);
}
}
return null;
|
}
private final Constructor<?> findIDConstructor(final Class<?> modelClass) throws NoSuchMethodException, SecurityException
{
return modelClass.getDeclaredConstructor(new Class[] { Properties.class, int.class, String.class });
}
public Constructor<?> getIDConstructor(final Class<?> modelClass)
{
try
{
return class2idConstructor.get(modelClass);
}
catch (ExecutionException e)
{
throw new AdempiereException("Cannot get ID constructor for " + modelClass, e);
}
}
private final Constructor<?> findResultSetConstructor(final Class<?> modelClass) throws NoSuchMethodException, SecurityException
{
return modelClass.getDeclaredConstructor(new Class[] { Properties.class, ResultSet.class, String.class });
}
public Constructor<?> getResultSetConstructor(final Class<?> modelClass)
{
try
{
return class2resultSetConstructor.get(modelClass);
}
catch (ExecutionException e)
{
throw new AdempiereException("Cannot get ResultSet constructor for " + modelClass, e);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\TableModelClassLoader.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.