instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public class BestellenResponse {
@XmlElement(name = "return", namespace = "", required = true)
protected BestellungAntwort _return;
/**
* Gets the value of the return property.
*
* @return
* possible object is
* {@link BestellungAntwort }
*
*/
public BestellungAntwort getReturn() {
return _return;
|
}
/**
* Sets the value of the return property.
*
* @param value
* allowed object is
* {@link BestellungAntwort }
*
*/
public void setReturn(BestellungAntwort value) {
this._return = 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\BestellenResponse.java
| 1
|
请完成以下Java代码
|
public Optional<SalesRegion> getBySalesRepId(@NonNull final UserId salesRepId)
{
return getMap().stream()
.filter(salesRegion -> salesRegion.isActive()
&& UserId.equals(salesRegion.getSalesRepId(), salesRepId))
.max(Comparator.comparing(SalesRegion::getId));
}
//
//
//
private static class SalesRegionsMap
{
private final ImmutableMap<SalesRegionId, SalesRegion> byId;
public SalesRegionsMap(final List<SalesRegion> list)
|
{
this.byId = Maps.uniqueIndex(list, SalesRegion::getId);
}
public SalesRegion getById(final SalesRegionId salesRegionId)
{
final SalesRegion salesRegion = byId.get(salesRegionId);
if (salesRegion == null)
{
throw new AdempiereException("No sales region found for " + salesRegionId);
}
return salesRegion;
}
public Stream<SalesRegion> stream() {return byId.values().stream();}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\sales_region\SalesRegionRepository.java
| 1
|
请完成以下Java代码
|
public class NonAlphaNumRegexChecker {
private static final Pattern PATTERN_NON_ALPHNUM_ANYLANG = Pattern.compile("[^\\p{IsAlphabetic}\\p{IsDigit}]");
private static final Pattern PATTERN_NON_ALPHNUM_USASCII = Pattern.compile("[^a-zA-Z0-9]+");
/**
* checks if a non-alphanumeric character is present. this method would return true if
* it comes across a non english or non US-ASCII letter
*
* @param str - String to check for special character
* @return true if special character found else false
*/
public static boolean isNonAlphanumeric(String str) {
// Pattern pattern = Pattern.compile("\\W"); //same as [^a-zA-Z0-9]+
// Pattern pattern = Pattern.compile("[^a-zA-Z0-9||\\s]+"); //ignores space
Matcher matcher = PATTERN_NON_ALPHNUM_USASCII.matcher(str);
return matcher.find();
}
/**
* Checks for non-alphanumeric characters from all language scripts
*
* @param input - String to check for special character
* @return true if special character found else false
*/
public static boolean containsNonAlphanumeric(String input) {
// Pattern pattern = Pattern.compile("[^\\p{Alnum}]", Pattern.UNICODE_CHARACTER_CLASS); //Binary properties
Matcher matcher = PATTERN_NON_ALPHNUM_ANYLANG.matcher(input);
return matcher.find();
|
}
/**
* checks for non-alphanumeric character. it returns true if it detects any character other than the
* specified script argument. example of script - Character.UnicodeScript.GEORGIAN.name()
*
* @param input - String to check for special character
* @param script - language script
* @return true if special character found else false
*/
public static boolean containsNonAlphanumeric(String input, String script) {
String regexScriptClass = "\\p{" + "Is" + script + "}";
Pattern pattern = Pattern.compile("[^" + regexScriptClass + "\\p{IsDigit}]"); //Binary properties
Matcher matcher = pattern.matcher(input);
return matcher.find();
}
}
|
repos\tutorials-master\core-java-modules\core-java-string-operations-6\src\main\java\com\baeldung\nonalphanumeric\NonAlphaNumRegexChecker.java
| 1
|
请完成以下Java代码
|
public void showWindow(final Object model)
{
Check.assumeNotNull(model, "model not null");
final int adTableId = InterfaceWrapperHelper.getModelTableId(model);
final int recordId = InterfaceWrapperHelper.getId(model);
AEnv.zoom(adTableId, recordId);
}
@Override
public IClientUIInvoker invoke()
{
return new SwingClientUIInvoker(this);
}
@Override
public IClientUIAsyncInvoker invokeAsync()
|
{
return new SwingClientUIAsyncInvoker();
}
@Override
public void showURL(final String url)
{
try
{
final URI uri = new URI(url);
Desktop.getDesktop().browse(uri);
}
catch (Exception e)
{
logger.warn("Failed opening " + url, e.getLocalizedMessage());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\adempiere\form\swing\SwingClientUIInstance.java
| 1
|
请完成以下Java代码
|
public de.metas.async.model.I_C_Async_Batch getC_Async_Batch()
{
return get_ValueAsPO(COLUMNNAME_C_Async_Batch_ID, de.metas.async.model.I_C_Async_Batch.class);
}
@Override
public void setC_Async_Batch(final de.metas.async.model.I_C_Async_Batch C_Async_Batch)
{
set_ValueFromPO(COLUMNNAME_C_Async_Batch_ID, de.metas.async.model.I_C_Async_Batch.class, C_Async_Batch);
}
@Override
public void setC_Async_Batch_ID (final int C_Async_Batch_ID)
{
if (C_Async_Batch_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Async_Batch_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Async_Batch_ID, C_Async_Batch_ID);
}
@Override
public int getC_Async_Batch_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Async_Batch_ID);
}
@Override
public void setCountEnqueued (final int CountEnqueued)
{
set_ValueNoCheck (COLUMNNAME_CountEnqueued, CountEnqueued);
}
@Override
public int getCountEnqueued()
{
return get_ValueAsInt(COLUMNNAME_CountEnqueued);
}
@Override
public void setCountProcessed (final int CountProcessed)
{
set_ValueNoCheck (COLUMNNAME_CountProcessed, CountProcessed);
}
@Override
public int getCountProcessed()
|
{
return get_ValueAsInt(COLUMNNAME_CountProcessed);
}
@Override
public de.metas.async.model.I_C_Queue_PackageProcessor getC_Queue_PackageProcessor()
{
return get_ValueAsPO(COLUMNNAME_C_Queue_PackageProcessor_ID, de.metas.async.model.I_C_Queue_PackageProcessor.class);
}
@Override
public void setC_Queue_PackageProcessor(final de.metas.async.model.I_C_Queue_PackageProcessor C_Queue_PackageProcessor)
{
set_ValueFromPO(COLUMNNAME_C_Queue_PackageProcessor_ID, de.metas.async.model.I_C_Queue_PackageProcessor.class, C_Queue_PackageProcessor);
}
@Override
public void setC_Queue_PackageProcessor_ID (final int C_Queue_PackageProcessor_ID)
{
if (C_Queue_PackageProcessor_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Queue_PackageProcessor_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Queue_PackageProcessor_ID, C_Queue_PackageProcessor_ID);
}
@Override
public int getC_Queue_PackageProcessor_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Queue_PackageProcessor_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_RV_Async_batch_statistics.java
| 1
|
请完成以下Java代码
|
public RemittanceLocationMethod2Code getMtd() {
return mtd;
}
/**
* Sets the value of the mtd property.
*
* @param value
* allowed object is
* {@link RemittanceLocationMethod2Code }
*
*/
public void setMtd(RemittanceLocationMethod2Code value) {
this.mtd = value;
}
/**
* Gets the value of the elctrncAdr property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getElctrncAdr() {
return elctrncAdr;
}
/**
* Sets the value of the elctrncAdr property.
*
* @param value
* allowed object is
* {@link String }
|
*
*/
public void setElctrncAdr(String value) {
this.elctrncAdr = value;
}
/**
* Gets the value of the pstlAdr property.
*
* @return
* possible object is
* {@link NameAndAddress10 }
*
*/
public NameAndAddress10 getPstlAdr() {
return pstlAdr;
}
/**
* Sets the value of the pstlAdr property.
*
* @param value
* allowed object is
* {@link NameAndAddress10 }
*
*/
public void setPstlAdr(NameAndAddress10 value) {
this.pstlAdr = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\RemittanceLocationDetails1.java
| 1
|
请完成以下Java代码
|
public void applyTo(final I_C_OrderLine orderLine)
{
logger.debug("Applying {} to {}", this, orderLine);
orderLine.setPriceEntered(priceEntered);
orderLine.setDiscount(discount.toBigDecimal());
orderLine.setPriceActual(priceActual);
orderLine.setPriceLimit(priceLimit);
orderLine.setPriceLimitNote(buildPriceLimitNote());
}
private String buildPriceLimitNote()
{
final ITranslatableString msg;
if (priceLimitEnforced)
{
msg = TranslatableStrings.builder()
.appendADMessage(AdMessageKey.of("Enforced"))
.append(": ")
.append(priceLimitEnforcedExplanation)
|
.build();
}
else
{
msg = TranslatableStrings.builder()
.appendADMessage(AdMessageKey.of("NotEnforced"))
.append(": ")
.append(priceLimitNotEnforcedExplanation)
.build();
}
final String adLanguage = Language.getBaseAD_Language();
return msg.translate(adLanguage);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderLinePriceAndDiscount.java
| 1
|
请完成以下Java代码
|
protected IScriptFactory createScriptFactory()
{
return new RolloutDirScriptFactory();
}
@Override
protected void configureScriptExecutorFactory(final IScriptExecutorFactory scriptExecutorFactory)
{
scriptExecutorFactory.setDryRunMode(false);
}
@Override
protected IScriptScanner createScriptScanner(final IScriptScannerFactory scriptScannerFactory)
{
final IScriptScanner result = new SingletonScriptScanner(dbScript);
return result;
}
|
@Override
protected IScriptsApplierListener createScriptsApplierListener()
{
return NullScriptsApplierListener.instance;
}
@Override
protected IDatabase createDatabase()
{
return db;
};
};
return prepareNewDBCopy;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\rollout_migrate\DBCopyMaker.java
| 1
|
请完成以下Java代码
|
private static Predicate<String> toAdMessageStartingWithIgnoreCaseFilter(@Nullable final String filterString)
{
if (filterString == null || Check.isBlank(filterString))
{
return null;
}
else
{
final String filterStringUC = filterString.trim().toUpperCase();
return adMessageKey -> adMessageKey.trim().toUpperCase().startsWith(filterStringUC);
}
}
public AdMessagesTree load(@NonNull final String adLanguage) {return build().load(adLanguage);}
}
public AdMessagesTree load(@NonNull final String adLanguage)
{
final LinkedHashMap<String, Object> tree = new LinkedHashMap<>();
//tree.put("_language", adLanguage);
loadInto(tree, adLanguage, adMessageKey -> adMessageKey);
return AdMessagesTree.builder()
.adLanguage(adLanguage)
.map(tree)
.build();
}
private void loadInto(
@NonNull Map<String, Object> tree,
@NonNull final String adLanguage,
@NonNull final UnaryOperator<String> keyMapper)
{
msgBL.getMsgMap(adLanguage, adMessagePrefix, true /* removePrefix */)
.forEach((adMessageKey, msgText) -> {
if (filterAdMessagesBy == null || filterAdMessagesBy.test(adMessageKey))
{
addMessageToTree(tree, keyMapper.apply(adMessageKey), msgText);
|
}
});
}
private static void addMessageToTree(final Map<String, Object> tree, final String key, final String value)
{
final List<String> keyParts = SPLIT_BY_DOT.splitToList(key);
Map<String, Object> currentNode = tree;
for (int i = 0; i < keyParts.size() - 1; i++)
{
final String keyPart = keyParts.get(i);
final Object currentNodeObj = currentNode.get(keyPart);
if (currentNodeObj == null)
{
final Map<String, Object> parentNode = currentNode;
currentNode = new LinkedHashMap<>();
parentNode.put(keyPart, currentNode);
}
else if (currentNodeObj instanceof Map)
{
//noinspection unchecked
currentNode = (Map<String, Object>)currentNodeObj;
}
else
{
// discarding the old value, shall not happen
final Map<String, Object> parentNode = currentNode;
currentNode = new LinkedHashMap<>();
parentNode.put(keyPart, currentNode);
}
}
final String keyPart = keyParts.get(keyParts.size() - 1);
currentNode.put(keyPart, value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\AdMessagesTreeLoader.java
| 1
|
请完成以下Java代码
|
public RefreshTokenGrantBuilder accessTokenResponseClient(
ReactiveOAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> accessTokenResponseClient) {
this.accessTokenResponseClient = accessTokenResponseClient;
return this;
}
/**
* Sets the maximum acceptable clock skew, which is used when checking the access
* token expiry. An access token is considered expired if
* {@code OAuth2Token#getExpiresAt() - clockSkew} is before the current time
* {@code clock#instant()}.
* @param clockSkew the maximum acceptable clock skew
* @return the {@link RefreshTokenGrantBuilder}
* @see RefreshTokenReactiveOAuth2AuthorizedClientProvider#setClockSkew(Duration)
*/
public RefreshTokenGrantBuilder clockSkew(Duration clockSkew) {
this.clockSkew = clockSkew;
return this;
}
/**
* Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the
* access token expiry.
* @param clock the clock
* @return the {@link RefreshTokenGrantBuilder}
*/
public RefreshTokenGrantBuilder clock(Clock clock) {
this.clock = clock;
|
return this;
}
/**
* Builds an instance of
* {@link RefreshTokenReactiveOAuth2AuthorizedClientProvider}.
* @return the {@link RefreshTokenReactiveOAuth2AuthorizedClientProvider}
*/
@Override
public ReactiveOAuth2AuthorizedClientProvider build() {
RefreshTokenReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = new RefreshTokenReactiveOAuth2AuthorizedClientProvider();
if (this.accessTokenResponseClient != null) {
authorizedClientProvider.setAccessTokenResponseClient(this.accessTokenResponseClient);
}
if (this.clockSkew != null) {
authorizedClientProvider.setClockSkew(this.clockSkew);
}
if (this.clock != null) {
authorizedClientProvider.setClock(this.clock);
}
return authorizedClientProvider;
}
}
}
|
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\ReactiveOAuth2AuthorizedClientProviderBuilder.java
| 1
|
请完成以下Java代码
|
public Result beforeHUItemStorage(final IMutable<IHUItemStorage> itemStorage)
{
// don't go downstream because we don't care what's there
return Result.SKIP_DOWNSTREAM;
}
@Override
public Result afterHUItemStorage(final IHUItemStorage itemStorage)
{
final ZonedDateTime date = getHUIterator().getDate();
final I_M_HU_Item huItem = itemStorage.getM_HU_Item();
//noinspection UnnecessaryLocalVariable
final I_M_HU_Item referenceModel = huItem;
for (final IProductStorage productStorage : itemStorage.getProductStorages(date))
{
final IAllocationRequest productStorageRequest = createAllocationRequest(productStorage);
final IAllocationSource productStorageAsSource = new GenericAllocationSourceDestination(
productStorage,
huItem,
referenceModel);
final IAllocationResult productStorageResult = productStorageAsSource.unload(productStorageRequest);
result.add(ImmutablePair.of(productStorageRequest, productStorageResult));
}
return Result.CONTINUE;
}
};
final HUIterator iterator = new HUIterator();
iterator.setDate(huContext.getDate());
iterator.setStorageFactory(huContext.getHUStorageFactory());
iterator.setListener(huIteratorListener);
iterator.iterate(hu);
return result;
}
@Override
public void unloadComplete(final IHUContext huContext)
{
performDestroyEmptyHUsIfNeeded(huContext);
}
private void performDestroyEmptyHUsIfNeeded(final IHUContext huContext)
{
if (!destroyEmptyHUs)
|
{
return;
}
for (final I_M_HU hu : sourceHUs)
{
// Skip it if already destroyed
if (handlingUnitsBL.isDestroyed(hu))
{
continue;
}
handlingUnitsBL.destroyIfEmptyStorage(huContext, hu);
}
}
private void createHUSnapshotsIfRequired(final IHUContext huContext)
{
if (!createHUSnapshots)
{
return;
}
// Make sure no snapshots were already created
// shall not happen
if (snapshotId != null)
{
throw new IllegalStateException("Snapshot was already created: " + snapshotId);
}
snapshotId = Services.get(IHUSnapshotDAO.class)
.createSnapshot()
.setContext(huContext)
.addModels(sourceHUs)
.createSnapshots()
.getSnapshotId();
}
public I_M_HU getSingleSourceHU()
{
return CollectionUtils.singleElement(sourceHUs);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\HUListAllocationSourceDestination.java
| 1
|
请完成以下Java代码
|
public String getTradeNo() {
return tradeNo;
}
/** 银行流水 **/
public void setTradeNo(String tradeNo) {
this.tradeNo = tradeNo;
}
/** 交易类型 **/
public String getTransType() {
return transType;
}
/** 交易类型 **/
public void setTransType(String transType) {
this.transType = transType;
}
/** 交易时间 **/
public Date getTransDate() {
return transDate;
}
|
/** 交易时间 **/
public void setTransDate(Date transDate) {
this.transDate = transDate;
}
/** 银行(支付宝)该笔订单收取的手续费 **/
public BigDecimal getBankFee() {
return bankFee;
}
/** 银行(支付宝)该笔订单收取的手续费 **/
public void setBankFee(BigDecimal bankFee) {
this.bankFee = bankFee;
}
}
|
repos\roncoo-pay-master\roncoo-pay-app-reconciliation\src\main\java\com\roncoo\pay\app\reconciliation\vo\AlipayAccountLogVO.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
application:
name: account-service
datasource:
url: jdbc:mysql://127.0.0.1:3306/seata_account?useSSL=false&useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.jdbc.Driver
username: root
password:
# dubbo 配置项,对应 DubboConfigurationProperties 配置类
dubbo:
# Dubbo 应用配置
application:
name: ${spring.application.name} # 应用名
# Dubbo 注册中心配
registry:
address: nacos://127.0.0.1:8848 # 注册中心地址。个鞥多注册中心,可见 http://dubbo.apache.org/zh-cn/docs/user/references/registry/introduction.html 文档。
# Dubbo 服务提供者协议配置
protocol:
port: -1 # 协议端口。使用 -1 表示随机端口。
name: dubbo # 使用 `dubbo://` 协议。更多协议,可见 http://dubbo.apache.org/zh-cn/docs/user/references/protocol/introduction.html 文档
# 配置扫描 Dubbo 自定义的 @Service 注解,暴露成 Dubbo 服务提供者
scan:
base-packages: cn.iocoder.springboot.lab53.accountservice.service
# Seata 配置项,对应
|
SeataProperties 类
seata:
application-id: ${spring.application.name} # Seata 应用编号,默认为 ${spring.application.name}
tx-service-group: ${spring.application.name}-group # Seata 事务组编号,用于 TC 集群名
# 服务配置项,对应 ServiceProperties 类
service:
# 虚拟组和分组的映射
vgroup-mapping:
account-service-group: default
# 分组和 Seata 服务的映射
grouplist:
default: 127.0.0.1:8091
|
repos\SpringBoot-Labs-master\lab-53\lab-53-seata-at-dubbo-demo\lab-53-seata-at-dubbo-demo-account-service\src\main\resources\application-file.yaml
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class DpdDeliveryOrderService implements DeliveryOrderService
{
private final DpdDeliveryOrderRepository dpdDeliveryOrderRepository;
@Override
public ShipperGatewayId getShipperGatewayId()
{
return DpdConstants.SHIPPER_GATEWAY_ID;
}
@NonNull
@Override
public ITableRecordReference toTableRecordReference(@NonNull final DeliveryOrder deliveryOrder)
{
final DeliveryOrderId deliveryOrderRepoId = deliveryOrder.getId();
Check.assumeNotNull(deliveryOrderRepoId, "DeliveryOrder ID must not be null");
return TableRecordReference.of(I_DPD_StoreOrder.Table_Name, deliveryOrderRepoId);
}
@Override
public DeliveryOrder getByRepoId(final DeliveryOrderId deliveryOrderRepoId)
{
return dpdDeliveryOrderRepository.getByRepoId(deliveryOrderRepoId);
}
|
/**
* Explanation of the different data structures:
* <p>
* - DeliveryOrder is the DTO
* - I_Dpd_StoreOrder is the persisted object for that DTO (which has lines), with data relevant for DPD.
* Each different shipper has its own "shipper-po" with its own relevant data.
*/
@Override
@NonNull
public DeliveryOrder save(@NonNull final DeliveryOrder deliveryOrder)
{
return dpdDeliveryOrderRepository.save(deliveryOrder);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java\de\metas\shipper\gateway\dpd\DpdDeliveryOrderService.java
| 2
|
请完成以下Java代码
|
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
@Override
public String getParentTaskId() {
return parentTaskId;
}
public void setParentTaskId(String parentTaskId) {
this.parentTaskId = parentTaskId;
}
@Override
public Date getClaimTime() {
return claimTime;
}
public void setClaimTime(Date claimTime) {
this.claimTime = claimTime;
}
@Override
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public Date getTime() {
return getStartTime();
}
@Override
public Long getWorkTimeInMillis() {
if (endTime == null || claimTime == null) {
return null;
}
return endTime.getTime() - claimTime.getTime();
}
@Override
public Map<String, Object> getTaskLocalVariables() {
Map<String, Object> variables = new HashMap<>();
if (queryVariables != null) {
for (HistoricVariableInstanceEntity variableInstance : queryVariables) {
if (variableInstance.getId() != null && variableInstance.getTaskId() != null) {
variables.put(variableInstance.getName(), variableInstance.getValue());
|
}
}
}
return variables;
}
@Override
public Map<String, Object> getProcessVariables() {
Map<String, Object> variables = new HashMap<>();
if (queryVariables != null) {
for (HistoricVariableInstanceEntity variableInstance : queryVariables) {
if (variableInstance.getId() != null && variableInstance.getTaskId() == null) {
variables.put(variableInstance.getName(), variableInstance.getValue());
}
}
}
return variables;
}
public List<HistoricVariableInstanceEntity> getQueryVariables() {
if (queryVariables == null && Context.getCommandContext() != null) {
queryVariables = new HistoricVariableInitializingList();
}
return queryVariables;
}
public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) {
this.queryVariables = queryVariables;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("HistoricTaskInstanceEntity[");
sb.append("id=").append(id);
sb.append(", name=").append(name);
sb.append("]");
return sb.toString();
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricTaskInstanceEntity.java
| 1
|
请完成以下Java代码
|
public Criteria andSortBetween(Integer value1, Integer value2) {
addCriterion("sort between", value1, value2, "sort");
return (Criteria) this;
}
public Criteria andSortNotBetween(Integer value1, Integer value2) {
addCriterion("sort not between", value1, value2, "sort");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
|
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsHelpCategoryExample.java
| 1
|
请完成以下Java代码
|
public void setClassnameForProcessType(@NonNull final I_AD_Process process)
{
switch (ProcessType.ofCode(process.getType()))
{
case SQL:
process.setClassname(ExecuteUpdateSQL.class.getName());
break;
case Excel:
process.setClassname(ExportToSpreadsheetProcess.class.getName());
break;
case POSTGREST:
process.setClassname(PostgRESTProcessExecutor.class.getName());
if (Check.isBlank(process.getJSONPath()))
{
throw new FillMandatoryException(I_AD_Process.COLUMNNAME_JSONPath);
}
break;
}
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE, ifColumnsChanged = I_AD_Process.COLUMNNAME_Classname)
public void validateClassName(@NonNull final I_AD_Process process)
{
final String classname = process.getClassname();
if (Check.isBlank(classname))
{
throw new FillMandatoryException(I_AD_Process.COLUMNNAME_Classname);
}
final ProcessType processType = ProcessType.ofCode(process.getType());
if (processType.equals(POSTGREST))
{
Util.validateJavaClassname(classname, PostgRESTProcessExecutor.class);
}
else if (processType.equals(Java))
{
Util.validateJavaClassname(classname, JavaProcess.class);
}
// for the other cases, the user can't edit the classname
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE, ifColumnsChanged = { I_AD_Process.COLUMNNAME_IsActive, I_AD_Process.COLUMNNAME_Name, I_AD_Process.COLUMNNAME_Description,
I_AD_Process.COLUMNNAME_Help })
public void propagateNamesAndTrl(final I_AD_Process adProcess)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(adProcess);
final String trxName = InterfaceWrapperHelper.getTrxName(adProcess);
for (final I_AD_Menu menu : MMenu.get(ctx, I_AD_Menu.COLUMNNAME_AD_Process_ID + "=" + adProcess.getAD_Process_ID(), trxName))
{
|
menu.setIsActive(adProcess.isActive());
menu.setName(adProcess.getName());
menu.setDescription(adProcess.getDescription());
InterfaceWrapperHelper.save(menu);
}
for (final I_AD_WF_Node node : MWindow.getWFNodes(ctx, I_AD_WF_Node.COLUMNNAME_AD_Process_ID + "=" + adProcess.getAD_Process_ID(), trxName))
{
boolean changed = false;
if (node.isActive() != adProcess.isActive())
{
node.setIsActive(adProcess.isActive());
changed = true;
}
if (node.isCentrallyMaintained())
{
node.setName(adProcess.getName());
node.setDescription(adProcess.getDescription());
node.setHelp(adProcess.getHelp());
changed = true;
}
//
if (changed)
{
InterfaceWrapperHelper.save(node);
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\model\interceptor\AD_Process.java
| 1
|
请完成以下Java代码
|
public void setDepreciationType (String DepreciationType)
{
set_Value (COLUMNNAME_DepreciationType, DepreciationType);
}
/** Get DepreciationType.
@return DepreciationType */
public String getDepreciationType ()
{
return (String)get_Value(COLUMNNAME_DepreciationType);
}
/** 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 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);
|
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Text.
@param Text Text */
public void setText (String Text)
{
set_Value (COLUMNNAME_Text, Text);
}
/** Get Text.
@return Text */
public String getText ()
{
return (String)get_Value(COLUMNNAME_Text);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation.java
| 1
|
请完成以下Java代码
|
public int getWindowCount()
{
return windows.size();
}
/**
* Find window by ID
*
* @param AD_Window_ID
* @return AWindow reference, null if not found
*/
public AWindow find(final AdWindowId adWindowId)
{
for (Window w : windows)
{
if (w instanceof AWindow)
{
AWindow a = (AWindow)w;
if (AdWindowId.equals(a.getAdWindowId(), adWindowId))
{
return a;
}
}
}
return null;
}
public FormFrame findForm(int AD_FORM_ID)
{
for (Window w : windows)
{
if (w instanceof FormFrame)
{
FormFrame ff = (FormFrame)w;
if (ff.getAD_Form_ID() == AD_FORM_ID)
{
return ff;
}
}
}
return null;
}
}
class WindowEventListener implements ComponentListener, WindowListener
{
WindowManager windowManager;
protected WindowEventListener(WindowManager windowManager)
{
this.windowManager = windowManager;
}
@Override
public void componentHidden(ComponentEvent e)
{
Component c = e.getComponent();
if (c instanceof Window)
{
c.removeComponentListener(this);
((Window)c).removeWindowListener(this);
windowManager.remove((Window)c);
}
}
@Override
public void componentMoved(ComponentEvent e)
{
|
}
@Override
public void componentResized(ComponentEvent e)
{
}
@Override
public void componentShown(ComponentEvent e)
{
}
@Override
public void windowActivated(WindowEvent e)
{
}
@Override
public void windowClosed(WindowEvent e)
{
Window w = e.getWindow();
if (w instanceof Window)
{
w.removeComponentListener(this);
w.removeWindowListener(this);
windowManager.remove(w);
}
}
@Override
public void windowClosing(WindowEvent e)
{
}
@Override
public void windowDeactivated(WindowEvent e)
{
}
@Override
public void windowDeiconified(WindowEvent e)
{
}
@Override
public void windowIconified(WindowEvent e)
{
}
@Override
public void windowOpened(WindowEvent e)
{
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\WindowManager.java
| 1
|
请完成以下Java代码
|
public static AttributesKeyPart ofAttributeIdAndValue(@NonNull final AttributeId attributeId, @NonNull final String value)
{
final String stringRepresentation = attributeId.getRepoId() + "=" + value;
final int specialCode = -1;
final AttributeValueId attributeValueId = null;
return new AttributesKeyPart(AttributeKeyPartType.AttributeIdAndValue, stringRepresentation, specialCode, attributeValueId, attributeId, value);
}
private static AttributesKeyPart newForSpecialType(final AttributeKeyPartType type)
{
final int specialCode = type.getSpecialCode();
final String stringRepresentation = String.valueOf(specialCode);
final AttributeValueId attributeValueId = null;
final AttributeId attributeId = null;
final String value = null;
return new AttributesKeyPart(type, stringRepresentation, specialCode, attributeValueId, attributeId, value);
}
private final AttributeKeyPartType type;
private final String stringRepresentation;
private final int specialCode;
private final AttributeValueId attributeValueId;
private final AttributeId attributeId;
private final String value;
private AttributesKeyPart(
@NonNull final AttributeKeyPartType type,
@NonNull final String stringRepresentation,
final int specialCode,
final AttributeValueId attributeValueId,
final AttributeId attributeId,
final String value)
{
this.type = type;
this.stringRepresentation = stringRepresentation;
this.specialCode = specialCode;
this.attributeValueId = attributeValueId;
this.attributeId = attributeId;
this.value = value;
}
@Override
@Deprecated
public String toString()
{
return stringRepresentation;
}
@Override
public int compareTo(@NonNull final AttributesKeyPart other)
{
final int cmp1 = compareNullsLast(getAttributeValueIdOrSpecialCodeOrNull(), other.getAttributeValueIdOrSpecialCodeOrNull());
if (cmp1 != 0)
{
return cmp1;
}
final int cmp2 = compareNullsLast(getAttributeIdOrNull(), getAttributeIdOrNull());
if (cmp2 != 0)
{
return cmp2;
}
return stringRepresentation.compareTo(other.stringRepresentation);
}
private Integer getAttributeValueIdOrSpecialCodeOrNull()
{
if (type == AttributeKeyPartType.AttributeValueId)
{
return attributeValueId.getRepoId();
}
else if (type == AttributeKeyPartType.All
|
|| type == AttributeKeyPartType.Other
|| type == AttributeKeyPartType.None)
{
return specialCode;
}
else
{
return null;
}
}
private Integer getAttributeIdOrNull()
{
return AttributeKeyPartType.AttributeIdAndValue == type ? attributeId.getRepoId() : null;
}
private static int compareNullsLast(final Integer i1, final Integer i2)
{
if (i1 == null)
{
return +1;
}
else if (i2 == null)
{
return -1;
}
else
{
return i1 - i2;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\commons\AttributesKeyPart.java
| 1
|
请完成以下Java代码
|
public boolean isQualityInspection(@NonNull final I_PP_Order ppOrder)
{
// NOTE: keep in sync with #qualityInspectionFilter
final String orderType = ppOrder.getOrderType();
return C_DocType_DOCSUBTYPE_QualityInspection.equals(orderType);
}
@Override
public void assertQualityInspectionOrder(@NonNull final I_PP_Order ppOrder)
{
Check.assume(isQualityInspection(ppOrder), "Order shall be Quality Inspection Order: {}", ppOrder);
}
@Override
public IQueryFilter<I_PP_Order> getQualityInspectionFilter()
{
return qualityInspectionFilter;
}
@Override
public Timestamp getDateOfProduction(final I_PP_Order ppOrder)
{
final Timestamp dateOfProduction;
if (ppOrder.getDateDelivered() != null)
{
dateOfProduction = ppOrder.getDateDelivered();
}
else
{
dateOfProduction = ppOrder.getDateFinishSchedule();
|
}
Check.assumeNotNull(dateOfProduction, "dateOfProduction not null for PP_Order {}", ppOrder);
return dateOfProduction;
}
@Override
public List<I_M_InOutLine> retrieveIssuedInOutLines(final I_PP_Order ppOrder)
{
// services
final IPPOrderMInOutLineRetrievalService ppOrderMInOutLineRetrievalService = Services.get(IPPOrderMInOutLineRetrievalService.class);
final IPPCostCollectorBL ppCostCollectorBL = Services.get(IPPCostCollectorBL.class);
final IPPCostCollectorDAO ppCostCollectorDAO = Services.get(IPPCostCollectorDAO.class);
final List<I_M_InOutLine> allIssuedInOutLines = new ArrayList<>();
final PPOrderId ppOrderId = PPOrderId.ofRepoId(ppOrder.getPP_Order_ID());
for (final I_PP_Cost_Collector cc : ppCostCollectorDAO.getByOrderId(ppOrderId))
{
if (!ppCostCollectorBL.isAnyComponentIssueOrCoProduct(cc))
{
continue;
}
final List<I_M_InOutLine> issuedInOutLinesForCC = ppOrderMInOutLineRetrievalService.provideIssuedInOutLines(cc);
allIssuedInOutLines.addAll(issuedInOutLinesForCC);
}
return allIssuedInOutLines;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\impl\MaterialTrackingPPOrderBL.java
| 1
|
请完成以下Java代码
|
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 Default.
@param IsDefault
Default value
*/
public void setIsDefault (boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
}
/** Get Default.
@return Default value
*/
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Demand.
@param M_Demand_ID
Material Demand
*/
public void setM_Demand_ID (int M_Demand_ID)
{
if (M_Demand_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Demand_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Demand_ID, Integer.valueOf(M_Demand_ID));
}
/** Get Demand.
@return Material Demand
*/
public int getM_Demand_ID ()
{
|
Integer ii = (Integer)get_Value(COLUMNNAME_M_Demand_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Demand.java
| 1
|
请完成以下Java代码
|
public Date getEvaluationTime() {
return evaluationTime;
}
public void setEvaluationTime(Date evaluationTime) {
this.evaluationTime = evaluationTime;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public List<HistoricDecisionInputInstance> getInputs() {
if(inputs != null) {
return inputs;
} else {
throw LOG.historicDecisionInputInstancesNotFetchedException();
}
}
@Override
public List<HistoricDecisionOutputInstance> getOutputs() {
if(outputs != null) {
return outputs;
} else {
throw LOG.historicDecisionOutputInstancesNotFetchedException();
}
}
public void setInputs(List<HistoricDecisionInputInstance> inputs) {
this.inputs = inputs;
}
public void setOutputs(List<HistoricDecisionOutputInstance> outputs) {
this.outputs = outputs;
}
public void delete() {
Context
.getCommandContext()
.getDbEntityManager()
.delete(this);
}
public void addInput(HistoricDecisionInputInstance decisionInputInstance) {
if(inputs == null) {
inputs = new ArrayList<HistoricDecisionInputInstance>();
}
inputs.add(decisionInputInstance);
}
public void addOutput(HistoricDecisionOutputInstance decisionOutputInstance) {
if(outputs == null) {
outputs = new ArrayList<HistoricDecisionOutputInstance>();
}
outputs.add(decisionOutputInstance);
}
public Double getCollectResultValue() {
|
return collectResultValue;
}
public void setCollectResultValue(Double collectResultValue) {
this.collectResultValue = collectResultValue;
}
public String getRootDecisionInstanceId() {
return rootDecisionInstanceId;
}
public void setRootDecisionInstanceId(String rootDecisionInstanceId) {
this.rootDecisionInstanceId = rootDecisionInstanceId;
}
public String getDecisionRequirementsDefinitionId() {
return decisionRequirementsDefinitionId;
}
public void setDecisionRequirementsDefinitionId(String decisionRequirementsDefinitionId) {
this.decisionRequirementsDefinitionId = decisionRequirementsDefinitionId;
}
public String getDecisionRequirementsDefinitionKey() {
return decisionRequirementsDefinitionKey;
}
public void setDecisionRequirementsDefinitionKey(String decisionRequirementsDefinitionKey) {
this.decisionRequirementsDefinitionKey = decisionRequirementsDefinitionKey;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricDecisionInstanceEntity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getCsvExeOffice() {
return csvExeOffice;
}
public void setCsvExeOffice(String csvExeOffice) {
this.csvExeOffice = csvExeOffice;
}
public String getCsvVtoll() {
return csvVtoll;
}
public void setCsvVtoll(String csvVtoll) {
this.csvVtoll = csvVtoll;
}
public String getCsvApp() {
return csvApp;
}
public void setCsvApp(String csvApp) {
this.csvApp = csvApp;
}
public String getCsvLog() {
return csvLog;
}
|
public void setCsvLog(String csvLog) {
this.csvLog = csvLog;
}
public String getCsvCanton() {
return csvCanton;
}
public void setCsvCanton(String csvCanton) {
this.csvCanton = csvCanton;
}
public Integer getLocation() {
return location;
}
public void setLocation(Integer location) {
this.location = location;
}
}
|
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\config\properties\CommonProperties.java
| 2
|
请完成以下Java代码
|
protected String doIt() throws Exception
{
final I_M_Material_Tracking materialTracking = getM_Material_Tracking();
final IMaterialTrackingDocuments materialTrackingDocuments = qualityBasedInvoicingDAO.retrieveMaterialTrackingDocuments(materialTracking);
final PPOrderQualityCalculator calculator = new PPOrderQualityCalculator();
calculator.update(materialTrackingDocuments);
return MSG_OK;
}
private I_M_Material_Tracking getM_Material_Tracking()
{
if (p_PP_Order_ID <= 0)
{
throw new FillMandatoryException(I_PP_Order.COLUMNNAME_PP_Order_ID);
|
}
final I_PP_Order ppOrder = getRecord(I_PP_Order.class);
// note that a quality inspection has at most one material-tracking
final I_M_Material_Tracking materialTracking = materialTrackingDAO.retrieveSingleMaterialTrackingForModel(ppOrder);
if (materialTracking == null)
{
throw new AdempiereException("@NotFound@ @M_Material_Tracking_ID@"
+ "\n @PP_Order_ID@: " + ppOrder);
}
return materialTracking;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\process\PP_Order_UpdateQualityFields.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public SimpleMailMessage templateSimpleMessage() {
SimpleMailMessage message = new SimpleMailMessage();
message.setText("This is the test email template for your email:\n%s\n");
return message;
}
@Bean
public SpringTemplateEngine thymeleafTemplateEngine(ITemplateResolver templateResolver) {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
templateEngine.setTemplateEngineMessageSource(emailMessageSource());
return templateEngine;
}
@Bean
public ITemplateResolver thymeleafClassLoaderTemplateResolver() {
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setPrefix(mailTemplatesPath + "/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML");
templateResolver.setCharacterEncoding("UTF-8");
return templateResolver;
}
// @Bean
// public ITemplateResolver thymeleafFilesystemTemplateResolver() {
// FileTemplateResolver templateResolver = new FileTemplateResolver();
// templateResolver.setPrefix(mailTemplatesPath + "/");
// templateResolver.setSuffix(".html");
// templateResolver.setTemplateMode("HTML");
// templateResolver.setCharacterEncoding("UTF-8");
// return templateResolver;
// }
@Bean
public FreeMarkerConfigurer freemarkerClassLoaderConfig() {
Configuration configuration = new Configuration(Configuration.VERSION_2_3_27);
TemplateLoader templateLoader = new ClassTemplateLoader(this.getClass(), "/" + mailTemplatesPath);
configuration.setTemplateLoader(templateLoader);
FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
freeMarkerConfigurer.setConfiguration(configuration);
return freeMarkerConfigurer;
}
|
// @Bean
// public FreeMarkerConfigurer freemarkerFilesystemConfig() throws IOException {
// Configuration configuration = new Configuration(Configuration.VERSION_2_3_27);
// TemplateLoader templateLoader = new FileTemplateLoader(new File(mailTemplatesPath));
// configuration.setTemplateLoader(templateLoader);
// FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
// freeMarkerConfigurer.setConfiguration(configuration);
// return freeMarkerConfigurer;
// }
@Bean
public ResourceBundleMessageSource emailMessageSource() {
final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("mailMessages");
return messageSource;
}
}
|
repos\tutorials-master\spring-web-modules\spring-mvc-basics-2\src\main\java\com\baeldung\spring\configuration\EmailConfiguration.java
| 2
|
请完成以下Java代码
|
protected void initializeIncidentsHandlers(IncidentHandler mainIncidentHandler,
final List<IncidentHandler> incidentHandlers) {
EnsureUtil.ensureNotNull("Incident handler", mainIncidentHandler);
this.mainIncidentHandler = mainIncidentHandler;
EnsureUtil.ensureNotNull("Incident handlers", incidentHandlers);
for (IncidentHandler incidentHandler : incidentHandlers) {
add(incidentHandler);
}
}
/**
* Adds the {@link IncidentHandler} to the list of
* {@link IncidentHandler} that consume the incident.
*
* @param incidentHandler the {@link IncidentHandler} that consume the incident.
*/
public void add(final IncidentHandler incidentHandler) {
EnsureUtil.ensureNotNull("Incident handler", incidentHandler);
String incidentHandlerType = getIncidentHandlerType();
if (!incidentHandlerType.equals(incidentHandler.getIncidentHandlerType())) {
throw new ProcessEngineException(
"Incorrect incident type handler in composite handler with type: " + incidentHandlerType);
}
this.incidentHandlers.add(incidentHandler);
}
@Override
|
public String getIncidentHandlerType() {
return mainIncidentHandler.getIncidentHandlerType();
}
@Override
public Incident handleIncident(IncidentContext context, String message) {
Incident incident = mainIncidentHandler.handleIncident(context, message);
for (IncidentHandler incidentHandler : this.incidentHandlers) {
incidentHandler.handleIncident(context, message);
}
return incident;
}
@Override
public void resolveIncident(IncidentContext context) {
mainIncidentHandler.resolveIncident(context);
for (IncidentHandler incidentHandler : this.incidentHandlers) {
incidentHandler.resolveIncident(context);
}
}
@Override
public void deleteIncident(IncidentContext context) {
mainIncidentHandler.deleteIncident(context);
for (IncidentHandler incidentHandler : this.incidentHandlers) {
incidentHandler.deleteIncident(context);
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\incident\CompositeIncidentHandler.java
| 1
|
请完成以下Java代码
|
private static final boolean decodeReadonly(final String readonlyStr)
{
return "ro".equals(readonlyStr);
}
private static final String encodeReadonly(final boolean readonly)
{
return readonly ? "ro" : "rw";
}
public void assertRowType(@NonNull final PurchaseRowType expectedRowType)
{
final PurchaseRowType rowType = getType();
if (rowType != expectedRowType)
{
throw new AdempiereException("Expected " + expectedRowType + " but it was " + rowType + ": " + this);
}
}
public PurchaseRowId toGroupRowId()
{
if (isGroupRowId())
{
return this;
}
else
{
return groupId(purchaseDemandId);
}
}
public PurchaseRowId toLineRowId()
{
if (isLineRowId())
{
return this;
}
else
{
final boolean readonly = false;
return lineId(purchaseDemandId, vendorId, readonly);
}
}
public boolean isGroupRowId()
|
{
return type == PurchaseRowType.GROUP;
}
public boolean isLineRowId()
{
return type == PurchaseRowType.LINE;
}
public boolean isAvailabilityRowId()
{
return type == PurchaseRowType.AVAILABILITY_DETAIL;
}
public boolean isAvailableOnVendor()
{
assertRowType(PurchaseRowType.AVAILABILITY_DETAIL);
return getAvailabilityType().equals(Type.AVAILABLE);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseRowId.java
| 1
|
请完成以下Java代码
|
class PrefixedConfigurationPropertySource implements ConfigurationPropertySource {
private final ConfigurationPropertySource source;
private final ConfigurationPropertyName prefix;
PrefixedConfigurationPropertySource(ConfigurationPropertySource source, String prefix) {
Assert.notNull(source, "'source' must not be null");
Assert.hasText(prefix, "'prefix' must not be empty");
this.source = source;
this.prefix = ConfigurationPropertyName.of(prefix);
}
protected final ConfigurationPropertyName getPrefix() {
return this.prefix;
}
@Override
public @Nullable ConfigurationProperty getConfigurationProperty(ConfigurationPropertyName name) {
ConfigurationProperty configurationProperty = this.source.getConfigurationProperty(getPrefixedName(name));
if (configurationProperty == null) {
return null;
}
return ConfigurationProperty.of(configurationProperty.getSource(), name, configurationProperty.getValue(),
configurationProperty.getOrigin());
}
|
private ConfigurationPropertyName getPrefixedName(ConfigurationPropertyName name) {
return this.prefix.append(name);
}
@Override
public ConfigurationPropertyState containsDescendantOf(ConfigurationPropertyName name) {
return this.source.containsDescendantOf(getPrefixedName(name));
}
@Override
public @Nullable Object getUnderlyingSource() {
return this.source.getUnderlyingSource();
}
protected ConfigurationPropertySource getSource() {
return this.source;
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\PrefixedConfigurationPropertySource.java
| 1
|
请完成以下Java代码
|
public BigDecimal getQty()
{
return storage.getQtyCapacity();
}
@Override
public I_C_UOM getC_UOM()
{
return storage.getC_UOM();
}
@Override
public BigDecimal getQtyAllocated()
{
return storage.getQtyFree();
}
@Override
public BigDecimal getQtyToAllocate()
{
return storage.getQty().toBigDecimal();
}
@Override
public Object getTrxReferencedModel()
{
return referenceModel;
}
protected IProductStorage getStorage()
{
return storage;
}
@Override
public IAllocationSource createAllocationSource(final I_M_HU hu)
{
|
return HUListAllocationSourceDestination.of(hu);
}
@Override
public boolean isReadOnly()
{
return readonly;
}
@Override
public void setReadOnly(final boolean readonly)
{
this.readonly = readonly;
}
@Override
public I_M_HU_Item getInnerHUItem()
{
return null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\document\impl\AbstractHUDocumentLine.java
| 1
|
请完成以下Java代码
|
public class ProductsToPick_PickSelected extends ProductsToPickViewBasedProcess
{
private final ProductsToPickRowsService rowsService = SpringContextHolder.instance.getBean(ProductsToPickRowsService.class);
@Override
protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (!isPickerProfile())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("only picker shall pick");
}
if (rowsService.noRowsEligibleForPicking(getSelectedRows()))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("select only rows that can be picked");
}
|
return ProcessPreconditionsResolution.accept();
}
@Override
@RunOutOfTrx
protected String doIt()
{
final ImmutableList<WebuiPickHUResult> result = rowsService.pick(getSelectedRows());
updateViewRowFromPickingCandidate(result);
invalidateView();
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\process\ProductsToPick_PickSelected.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class EventSubscriptionRestServiceImpl extends AbstractRestProcessEngineAware implements EventSubscriptionRestService {
public EventSubscriptionRestServiceImpl(String engineName, ObjectMapper objectMapper) {
super(engineName, objectMapper);
}
@Override
public List<EventSubscriptionDto> getEventSubscriptions(UriInfo uriInfo, Integer firstResult, Integer maxResults) {
EventSubscriptionQueryDto queryDto = new EventSubscriptionQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
return queryEventSubscriptions(queryDto, firstResult, maxResults);
}
public List<EventSubscriptionDto> queryEventSubscriptions(EventSubscriptionQueryDto queryDto, Integer firstResult, Integer maxResults) {
ProcessEngine engine = getProcessEngine();
queryDto.setObjectMapper(getObjectMapper());
EventSubscriptionQuery query = queryDto.toQuery(engine);
List<EventSubscription> matchingEventSubscriptions = QueryUtil.list(query, firstResult, maxResults);
List<EventSubscriptionDto> eventSubscriptionResults = new ArrayList<EventSubscriptionDto>();
for (EventSubscription eventSubscription : matchingEventSubscriptions) {
EventSubscriptionDto resultEventSubscription = EventSubscriptionDto.fromEventSubscription(eventSubscription);
eventSubscriptionResults.add(resultEventSubscription);
}
return eventSubscriptionResults;
}
@Override
|
public CountResultDto getEventSubscriptionsCount(UriInfo uriInfo) {
EventSubscriptionQueryDto queryDto = new EventSubscriptionQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
return queryEventSubscriptionsCount(queryDto);
}
public CountResultDto queryEventSubscriptionsCount(EventSubscriptionQueryDto queryDto) {
ProcessEngine engine = getProcessEngine();
queryDto.setObjectMapper(getObjectMapper());
EventSubscriptionQuery query = queryDto.toQuery(engine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\EventSubscriptionRestServiceImpl.java
| 2
|
请完成以下Java代码
|
private void checkForPrice(@NonNull final I_C_OLCand olCand, @Nullable final ProductId packingMaterialProductId)
{
final PricingSystemId pricingSystemId = PricingSystemId.ofRepoIdOrNull(olCand.getM_PricingSystem_ID());
final IOLCandEffectiveValuesBL olCandEffectiveValuesBL = Services.get(IOLCandEffectiveValuesBL.class);
final LocalDate datePromisedEffective = TimeUtil.asLocalDate(olCandEffectiveValuesBL.getDatePromised_Effective(olCand));
final BPartnerLocationAndCaptureId billBPLocationId = olCandEffectiveValuesBL.getBillLocationAndCaptureEffectiveId(olCand);
final PriceListId plId = Services.get(IPriceListDAO.class).retrievePriceListIdByPricingSyst(pricingSystemId, billBPLocationId, SOTrx.SALES);
if (plId == null)
{
throw new AdempiereException("@PriceList@ @NotFound@: @M_PricingSystem@ " + pricingSystemId + ", @Bill_Location@ " + billBPLocationId);
}
final IPricingBL pricingBL = Services.get(IPricingBL.class);
|
final IEditablePricingContext pricingCtx = pricingBL.createPricingContext();
pricingCtx.setBPartnerId(BPartnerId.ofRepoIdOrNull(olCand.getBill_BPartner_ID()));
pricingCtx.setSOTrx(SOTrx.SALES);
pricingCtx.setQty(BigDecimal.ONE); // we don't care for the actual quantity we just want to verify that there is a price
pricingCtx.setPricingSystemId(pricingSystemId);
pricingCtx.setPriceListId(plId);
pricingCtx.setProductId(packingMaterialProductId);
pricingCtx.setPriceDate(datePromisedEffective);
pricingCtx.setCurrencyId(CurrencyId.ofRepoId(olCand.getC_Currency_ID()));
pricingCtx.setFailIfNotCalculated();
Services.get(IPricingBL.class).calculatePrice(pricingCtx);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\ordercandidate\spi\impl\OLCandPIIPPriceValidator.java
| 1
|
请完成以下Java代码
|
public Process parse(XMLStreamReader xtr, BpmnModel model) throws Exception {
Process process = null;
if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, ATTRIBUTE_ID))) {
String processId = xtr.getAttributeValue(null, ATTRIBUTE_ID);
process = new Process();
process.setId(processId);
BpmnXMLUtil.addXMLLocation(process, xtr);
process.setName(xtr.getAttributeValue(null, ATTRIBUTE_NAME));
if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, ATTRIBUTE_PROCESS_EXECUTABLE))) {
process.setExecutable(Boolean.parseBoolean(xtr.getAttributeValue(null, ATTRIBUTE_PROCESS_EXECUTABLE)));
}
String candidateUsersString = xtr.getAttributeValue(
ACTIVITI_EXTENSIONS_NAMESPACE,
ATTRIBUTE_PROCESS_CANDIDATE_USERS
);
if (candidateUsersString != null) {
process.setCandidateStarterUsersDefined(true);
}
if (StringUtils.isNotEmpty(candidateUsersString)) {
List<String> candidateUsers = BpmnXMLUtil.parseDelimitedList(candidateUsersString);
process.setCandidateStarterUsers(candidateUsers);
}
String candidateGroupsString = xtr.getAttributeValue(
|
ACTIVITI_EXTENSIONS_NAMESPACE,
ATTRIBUTE_PROCESS_CANDIDATE_GROUPS
);
if (candidateGroupsString != null) {
process.setCandidateStarterGroupsDefined(true);
}
if (StringUtils.isNotEmpty(candidateGroupsString)) {
List<String> candidateGroups = BpmnXMLUtil.parseDelimitedList(candidateGroupsString);
process.setCandidateStarterGroups(candidateGroups);
}
BpmnXMLUtil.addCustomAttributes(xtr, process, ProcessExport.defaultProcessAttributes);
model.getProcesses().add(process);
}
return process;
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\parser\ProcessParser.java
| 1
|
请完成以下Java代码
|
public class CaseInstanceBatchMigrationPartResult {
protected String batchId;
protected String status = CaseInstanceBatchMigrationResult.STATUS_WAITING;
protected String result;
protected String caseInstanceId;
protected String sourceCaseDefinitionId;
protected String targetCaseDefinitionId;
protected String migrationMessage;
protected String migrationStacktrace;
public String getBatchId() {
return batchId;
}
public void setBatchId(String batchId) {
this.batchId = batchId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public void setCaseInstanceId(String caseInstanceId) {
this.caseInstanceId = caseInstanceId;
}
public String getSourceCaseDefinitionId() {
return sourceCaseDefinitionId;
}
|
public void setSourceCaseDefinitionId(String sourceCaseDefinitionId) {
this.sourceCaseDefinitionId = sourceCaseDefinitionId;
}
public String getTargetCaseDefinitionId() {
return targetCaseDefinitionId;
}
public void setTargetCaseDefinitionId(String targetCaseDefinitionId) {
this.targetCaseDefinitionId = targetCaseDefinitionId;
}
public String getMigrationMessage() {
return migrationMessage;
}
public void setMigrationMessage(String migrationMessage) {
this.migrationMessage = migrationMessage;
}
public String getMigrationStacktrace() {
return migrationStacktrace;
}
public void setMigrationStacktrace(String migrationStacktrace) {
this.migrationStacktrace = migrationStacktrace;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-api\src\main\java\org\flowable\cmmn\api\migration\CaseInstanceBatchMigrationPartResult.java
| 1
|
请完成以下Java代码
|
public String getUmsatzsteuerID() {
return umsatzsteuerID;
}
/**
* Sets the value of the umsatzsteuerID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUmsatzsteuerID(String value) {
this.umsatzsteuerID = value;
}
/**
* Gets the value of the steuernummer property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSteuernummer() {
return steuernummer;
}
/**
* Sets the value of the steuernummer property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSteuernummer(String value) {
this.steuernummer = value;
}
/**
* Gets the value of the bankname property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBankname() {
return bankname;
}
/**
* Sets the value of the bankname property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBankname(String value) {
this.bankname = value;
}
/**
* Gets the value of the bic property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBIC() {
return bic;
|
}
/**
* Sets the value of the bic property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBIC(String value) {
this.bic = value;
}
/**
* Gets the value of the iban property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIBAN() {
return iban;
}
/**
* Sets the value of the iban property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIBAN(String value) {
this.iban = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\RetourenavisAnkuendigungType.java
| 1
|
请完成以下Java代码
|
public ConversationAssociation newInstance(ModelTypeInstanceContext instanceContext) {
return new ConversationAssociationImpl(instanceContext);
}
});
innerConversationNodeRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_INNER_CONVERSATION_NODE_REF)
.required()
.qNameAttributeReference(ConversationNode.class)
.build();
outerConversationNodeRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_OUTER_CONVERSATION_NODE_REF)
.required()
.qNameAttributeReference(ConversationNode.class)
.build();
typeBuilder.build();
}
public ConversationAssociationImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public ConversationNode getInnerConversationNode() {
|
return innerConversationNodeRefAttribute.getReferenceTargetElement(this);
}
public void setInnerConversationNode(ConversationNode innerConversationNode) {
innerConversationNodeRefAttribute.setReferenceTargetElement(this, innerConversationNode);
}
public ConversationNode getOuterConversationNode() {
return outerConversationNodeRefAttribute.getReferenceTargetElement(this);
}
public void setOuterConversationNode(ConversationNode outerConversationNode) {
outerConversationNodeRefAttribute.setReferenceTargetElement(this, outerConversationNode);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ConversationAssociationImpl.java
| 1
|
请完成以下Java代码
|
public static PriceSpecification fixedPrice(@NonNull final Money fixedPrice)
{
return new PriceSpecification(
PriceSpecificationType.FIXED_PRICE,
null/* pricingSystemId */,
null/* basePriceAddAmt */,
fixedPrice/* fixedPriceAmt */
);
}
private static final PriceSpecification NONE = new PriceSpecification(
PriceSpecificationType.NONE,
null/* basePricingSystemId */,
null/* pricingSystemSurchargeAmt */,
null/* fixedPriceAmt */);
PriceSpecificationType type;
//
// Base pricing system related fields
PricingSystemId basePricingSystemId;
Money pricingSystemSurcharge;
//
// Fixed price related fields
Money fixedPrice;
private PriceSpecification(
@NonNull final PriceSpecificationType type,
|
@Nullable final PricingSystemId basePricingSystemId,
@Nullable final Money pricingSystemSurcharge,
@Nullable final Money fixedPrice)
{
this.type = type;
this.basePricingSystemId = basePricingSystemId;
this.pricingSystemSurcharge = pricingSystemSurcharge;
this.fixedPrice = fixedPrice;
}
public boolean isNoPrice()
{
return type == PriceSpecificationType.NONE;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\conditions\PriceSpecification.java
| 1
|
请完成以下Java代码
|
public void setIsAutoApproval (boolean IsAutoApproval)
{
set_Value (COLUMNNAME_IsAutoApproval, Boolean.valueOf(IsAutoApproval));
}
/** Get Auto Approval.
@return Auto Approval */
@Override
public boolean isAutoApproval ()
{
Object oo = get_Value(COLUMNNAME_IsAutoApproval);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
|
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CreditLimit_Type.java
| 1
|
请完成以下Java代码
|
public void endpointActivation(MessageEndpointFactory endpointFactory, ActivationSpec spec) throws ResourceException {
if(jobHandlerActivation != null) {
throw new ResourceException("The Camunda Platform job executor can only service a single MessageEndpoint for job execution. " +
"Make sure not to deploy more than one MDB implementing the '"+JobExecutionHandler.class.getName()+"' interface.");
}
JobExecutionHandlerActivation activation = new JobExecutionHandlerActivation(this, endpointFactory, (JobExecutionHandlerActivationSpec) spec);
activation.start();
jobHandlerActivation = activation;
}
public void endpointDeactivation(MessageEndpointFactory endpointFactory, ActivationSpec spec) {
try {
if(jobHandlerActivation != null) {
jobHandlerActivation.stop();
}
} finally {
jobHandlerActivation = null;
}
}
// unsupported (No TX Support) ////////////////////////////////////////////
public XAResource[] getXAResources(ActivationSpec[] specs) throws ResourceException {
log.finest("getXAResources()");
return null;
}
// getters ///////////////////////////////////////////////////////////////
public ExecutorServiceWrapper getExecutorServiceWrapper() {
return executorServiceWrapper;
}
public JobExecutionHandlerActivation getJobHandlerActivation() {
return jobHandlerActivation;
}
public Boolean getIsUseCommonJWorkManager() {
return isUseCommonJWorkManager;
}
public void setIsUseCommonJWorkManager(Boolean isUseCommonJWorkManager) {
this.isUseCommonJWorkManager = isUseCommonJWorkManager;
|
}
public String getCommonJWorkManagerName() {
return commonJWorkManagerName;
}
public void setCommonJWorkManagerName(String commonJWorkManagerName) {
this.commonJWorkManagerName = commonJWorkManagerName;
}
// misc //////////////////////////////////////////////////////////////////
@Override
public int hashCode() {
return 17;
}
@Override
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (other == this) {
return true;
}
if (!(other instanceof JcaExecutorServiceConnector)) {
return false;
}
return true;
}
}
|
repos\camunda-bpm-platform-master\javaee\jobexecutor-ra\src\main\java\org\camunda\bpm\container\impl\threading\ra\JcaExecutorServiceConnector.java
| 1
|
请完成以下Java代码
|
public static List<Object> streamTokenizerWithCustomConfiguration(Reader reader) throws IOException {
StreamTokenizer streamTokenizer = new StreamTokenizer(reader);
List<Object> tokens = new ArrayList<>();
streamTokenizer.wordChars('!', '-');
streamTokenizer.ordinaryChar('/');
streamTokenizer.commentChar('#');
streamTokenizer.eolIsSignificant(true);
int currentToken = streamTokenizer.nextToken();
while (currentToken != StreamTokenizer.TT_EOF) {
if (streamTokenizer.ttype == StreamTokenizer.TT_NUMBER) {
tokens.add(streamTokenizer.nval);
} else if (streamTokenizer.ttype == StreamTokenizer.TT_WORD
|| streamTokenizer.ttype == QUOTE_CHARACTER
|| streamTokenizer.ttype == DOUBLE_QUOTE_CHARACTER) {
tokens.add(streamTokenizer.sval);
} else {
tokens.add((char) currentToken);
}
currentToken = streamTokenizer.nextToken();
}
return tokens;
|
}
public static Reader createReaderFromFile() throws FileNotFoundException {
String inputFile = StreamTokenizerDemo.class.getResource(INPUT_FILE).getFile();
return new FileReader(inputFile);
}
public static void main(String[] args) throws IOException {
List<Object> tokens1 = streamTokenizerWithDefaultConfiguration(createReaderFromFile());
List<Object> tokens2 = streamTokenizerWithCustomConfiguration(createReaderFromFile());
System.out.println(tokens1);
System.out.println(tokens2);
}
}
|
repos\tutorials-master\core-java-modules\core-java-string-apis-2\src\main\java\com\baeldung\streamtokenizer\StreamTokenizerDemo.java
| 1
|
请完成以下Java代码
|
public void setTaxIdAndUpdateVatCode(@Nullable final TaxId taxId)
{
if (TaxId.equals(this.taxId, taxId))
{
return;
}
this.taxId = taxId;
this.vatCode = computeVATCode().map(VATCode::getCode).orElse(null);
}
private Optional<VATCode> computeVATCode()
{
if (taxId == null)
{
return Optional.empty();
}
final boolean isSOTrx = m_docLine != null ? m_docLine.isSOTrx() : m_doc.isSOTrx();
return services.findVATCode(VATCodeMatchingRequest.builder()
.setC_AcctSchema_ID(getAcctSchemaId().getRepoId())
.setC_Tax_ID(taxId.getRepoId())
.setIsSOTrx(isSOTrx)
.setDate(this.dateAcct)
.build());
}
public void updateFAOpenItemTrxInfo()
{
if (openItemTrxInfo != null)
{
return;
}
this.openItemTrxInfo = services.computeOpenItemTrxInfo(this).orElse(null);
}
void setOpenItemTrxInfo(@Nullable final FAOpenItemTrxInfo openItemTrxInfo)
|
{
this.openItemTrxInfo = openItemTrxInfo;
}
public void updateFrom(@NonNull FactAcctChanges changes)
{
setAmtSource(changes.getAmtSourceDr(), changes.getAmtSourceCr());
setAmtAcct(changes.getAmtAcctDr(), changes.getAmtAcctCr());
updateCurrencyRate();
if (changes.getAccountId() != null)
{
this.accountId = changes.getAccountId();
}
setTaxIdAndUpdateVatCode(changes.getTaxId());
setDescription(changes.getDescription());
this.M_Product_ID = changes.getProductId();
this.userElementString1 = changes.getUserElementString1();
this.C_OrderSO_ID = changes.getSalesOrderId();
this.C_Activity_ID = changes.getActivityId();
this.appliedUserChanges = changes;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\FactLine.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public DomesticAmountType getDomesticAmount() {
return domesticAmount;
}
/**
* Sets the value of the domesticAmount property.
*
* @param value
* allowed object is
* {@link DomesticAmountType }
*
*/
public void setDomesticAmount(DomesticAmountType value) {
this.domesticAmount = value;
}
/**
* Gets the value of the description property.
*
* @return
* possible object is
|
* {@link String }
*
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDescription(String value) {
this.description = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ItemType.java
| 2
|
请完成以下Java代码
|
public class CompensationBehavior {
/**
* With compensation, we have a dedicated scope execution for every handler, even if the handler is not
* a scope activity; this must be respected when invoking end listeners, etc.
*/
public static boolean executesNonScopeCompensationHandler(PvmExecutionImpl execution) {
ActivityImpl activity = execution.getActivity();
return execution.isScope() && activity != null && activity.isCompensationHandler() && !activity.isScope();
}
public static boolean isCompensationThrowing(PvmExecutionImpl execution) {
ActivityImpl currentActivity = execution.getActivity();
if (currentActivity != null) {
Boolean isCompensationThrowing = (Boolean) currentActivity.getProperty(BpmnParse.PROPERTYNAME_THROWS_COMPENSATION);
if (isCompensationThrowing != null && isCompensationThrowing) {
return true;
}
}
return false;
}
/**
* Determines whether an execution is responsible for default compensation handling.
*
* This is the case if
* <ul>
* <li>the execution has an activity
* <li>the execution is a scope
* <li>the activity is a scope
* <li>the execution has children
* <li>the execution does not throw compensation
* </ul>
*/
public static boolean executesDefaultCompensationHandler(PvmExecutionImpl scopeExecution) {
ActivityImpl currentActivity = scopeExecution.getActivity();
if (currentActivity != null) {
|
return scopeExecution.isScope()
&& currentActivity.isScope()
&& !scopeExecution.getNonEventScopeExecutions().isEmpty()
&& !isCompensationThrowing(scopeExecution);
}
else {
return false;
}
}
public static String getParentActivityInstanceId(PvmExecutionImpl execution) {
Map<ScopeImpl, PvmExecutionImpl> activityExecutionMapping = execution.createActivityExecutionMapping();
PvmExecutionImpl parentScopeExecution = activityExecutionMapping.get(execution.getActivity().getFlowScope());
return parentScopeExecution.getParentActivityInstanceId();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\CompensationBehavior.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UserController {
@Autowired
private UserRepository userRepository;
@Autowired
private UserUtils userUtils;
@Autowired
private UserService userService;
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
@GetMapping("/user/me")
@PreAuthorize("hasRole('USER')")
public UserSummary getCurrentUser(@CurrentUser UserPrincipal currentUser)
{
UserSummary userSummary = new UserSummary(currentUser.getId(), currentUser.getUsername(),currentUser.getSurname(), currentUser.getName(), currentUser.getLastname(), currentUser.getCity());
return userSummary;
}
@GetMapping("/user/checkUsernameAvailability")
public UserIdentityAvailability checkUsernameAvailability(@RequestParam(value = "username") String username)
{
Boolean isAvailable = !userRepository.existsByUsername(username);
return new UserIdentityAvailability(isAvailable);
}
@GetMapping("/user/checkEmailAvialability")
public UserIdentityAvailability checkEmailAvailability(@RequestParam(value = "email") String email)
{
Boolean isAvailable = !userRepository.existsByEmail(email);
return new UserIdentityAvailability(isAvailable);
}
@PostMapping("/users/getBySearch")
public Optional<User> getUserBySearch(@RequestParam(value = "username") String username)
|
{
return userRepository.findByUsername(username);
}
@GetMapping("/users/getAllUsers")
public List<String> getAllUsers(@PathVariable(value = "id") Long id)
{
return userRepository.findAllUsers();
}
@GetMapping("/users/{id}")
public UserProfile getUserProfile(@PathVariable(value = "id") Long id)
{
User user = userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User", "username", id));
UserProfile userProfile = new UserProfile(user.getId(), user.getSurname(), user.getName(), user.getLastname(), user.getUsername(), user.getCreatedAt(), user.getPhone(), user.getEmail(), user.getPassword(), user.getCity());
userUtils.initUserAvatar(userProfile, user);
return userProfile;
}
@PostMapping("/users/saveUserProfile")
public ResponseEntity<?> saveUserProfile(@CurrentUser UserPrincipal userPrincipal, @RequestBody UserProfile userProfileForm)
{
return userService.saveUserProfile(userPrincipal, userProfileForm);
}
@PostMapping("/users/saveCity")
public Boolean saveCity(@CurrentUser UserPrincipal userPrincipal, @RequestBody String city)
{
return userService.saveCity(userPrincipal, city);
}
}
|
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\controller\UserController.java
| 2
|
请完成以下Java代码
|
public Amount toAmount(@NonNull final Function<CurrencyId, CurrencyCode> currencyCodeMapper)
{
return Amount.of(toBigDecimal(), currencyCodeMapper.apply(getCurrencyId()));
}
public Money round(@NonNull final CurrencyPrecision precision)
{
return withValue(precision.round(this.value));
}
public Money roundIfNeeded(@NonNull final CurrencyPrecision precision)
{
return withValue(precision.roundIfNeeded(this.value));
}
public Money round(@NonNull final Function<CurrencyId, CurrencyPrecision> precisionProvider)
{
final CurrencyPrecision precision = precisionProvider.apply(currencyId);
if (precision == null)
{
throw new AdempiereException("No precision was returned by " + precisionProvider + " for " + currencyId);
}
return round(precision);
}
private Money withValue(@NonNull final BigDecimal newValue)
{
return value.compareTo(newValue) != 0 ? of(newValue, currencyId) : this;
}
public static int countNonZero(final Money... array)
{
if (array == null || array.length == 0)
{
return 0;
}
|
int count = 0;
for (final Money money : array)
{
if (money != null && money.signum() != 0)
{
count++;
}
}
return count;
}
public static boolean equals(@Nullable Money money1, @Nullable Money money2) {return Objects.equals(money1, money2);}
public Percent percentageOf(@NonNull final Money whole)
{
assertCurrencyIdMatching(whole);
return Percent.of(toBigDecimal(), whole.toBigDecimal());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\money\Money.java
| 1
|
请完成以下Spring Boot application配置
|
quarkus.langchain4j.timeout=180s
quarkus.langchain4j.chat-model.provider=ollama
quarkus.langchain4j.ollama.chat-model.model-id=mistral
quarkus.langchain4j.ollama.base-url=http://localhost:11434
quarkus.langchain4j.mcp
|
.default.transport-type=http
quarkus.langchain4j.mcp.default.url=http://localhost:9000/mcp/sse
|
repos\tutorials-master\quarkus-modules\quarkus-mcp-langchain\quarkus-mcp-client\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
private Set<String> validateVariablesAgainstDefinitions(
Map<String, Object> variables,
Map<String, VariableDefinition> variableDefinitionMap
) {
Set<String> mismatchedVars = new HashSet<>();
variableDefinitionMap.forEach((k, v) -> {
//if we have definition for this variable then validate it
if (variables.containsKey(v.getName())) {
if (!variableValidationService.validate(variables.get(v.getName()), v)) {
mismatchedVars.add(v.getName());
}
}
});
return mismatchedVars;
}
public void startProcessInstance(
ExecutionEntity processInstance,
CommandContext commandContext,
Map<String, Object> variables,
FlowElement initialFlowElement,
Map<String, Object> transientVariables,
String linkedProcessInstanceId,
String linkedProcessInstanceType
|
) {
ProcessDefinition processDefinition = ProcessDefinitionUtil.getProcessDefinition(
processInstance.getProcessDefinitionId()
);
Map<String, Object> calculatedVariables = calculateOutputVariables(
variables,
processDefinition,
initialFlowElement
);
super.startProcessInstance(
processInstance,
commandContext,
calculatedVariables,
initialFlowElement,
transientVariables,
linkedProcessInstanceId,
linkedProcessInstanceType
);
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\spring\process\ProcessVariablesInitiator.java
| 1
|
请完成以下Java代码
|
public void addNotifications(final List<I_AD_Note> list)
{
if (list != null && !list.isEmpty())
{
this.notifications.addAll(list);
this.notificationsWhereClause = null;
}
}
@Override
public String getNotificationsWhereClause()
{
if (this.notificationsWhereClause == null)
{
final Accessor accessor = new Accessor()
{
@Override
public Object getValue(Object o)
{
return ((I_AD_Note)o).getAD_Note_ID();
}
};
this.notificationsWhereClause = buildSqlInArrayWhereClause(
I_AD_Note.COLUMNNAME_AD_Note_ID,
this.notifications,
accessor,
null // params
);
}
return this.notificationsWhereClause;
}
private String buildSqlInArrayWhereClause(String columnName, List<?> values, Accessor accessor, List<Object> params)
{
if (values == null || values.isEmpty())
return "";
boolean hasNull = false;
StringBuffer whereClause = new StringBuffer();
StringBuffer whereClauseCurrent = new StringBuffer();
int count = 0;
for (Object v : values)
{
final Object value;
if (accessor != null)
value = accessor.getValue(v);
else
value = v;
if (value == null)
{
hasNull = true;
continue;
}
if (whereClauseCurrent.length() > 0)
whereClauseCurrent.append(",");
if (params == null)
{
whereClauseCurrent.append(value);
}
else
{
whereClauseCurrent.append("?");
params.add(value);
}
if (count >= 30)
{
if (whereClause.length() > 0)
whereClause.append(" OR ");
whereClause.append(columnName).append(" IN (").append(whereClauseCurrent).append(")");
whereClauseCurrent = new StringBuffer();
count = 0;
}
}
if (whereClauseCurrent.length() > 0)
|
{
if (whereClause.length() > 0)
whereClause.append(" OR ");
whereClause.append(columnName).append(" IN (").append(whereClauseCurrent).append(")");
whereClauseCurrent = null;
}
if (hasNull)
{
if (whereClause.length() > 0)
whereClause.append(" OR ");
whereClause.append(columnName).append(" IS NULL");
}
if (whereClause.length() > 0)
whereClause.insert(0, "(").append(")");
return whereClause.toString();
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder("InvoiceGenerateResult [");
sb.append("invoiceCount=").append(getInvoiceCount());
if (storeInvoices)
{
sb.append(", invoices=").append(invoices);
}
if (notifications != null && !notifications.isEmpty())
{
sb.append(", notifications=").append(notifications);
}
sb.append("]");
return sb.toString();
}
@Override
public String getSummary(final Properties ctx)
{
return Services.get(IMsgBL.class).getMsg(ctx, MSG_Summary, new Object[] { getInvoiceCount(), getNotificationCount() });
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceGenerateResult.java
| 1
|
请完成以下Java代码
|
public BatchStatisticsQuery startedBefore(final Date date) {
this.startedBefore = date;
return this;
}
@Override
public BatchStatisticsQuery startedAfter(final Date date) {
this.startedAfter = date;
return this;
}
@Override
public BatchStatisticsQuery withFailures() {
this.hasFailure = true;
return this;
}
@Override
public BatchStatisticsQuery withoutFailures() {
this.hasFailure = false;
return this;
}
public SuspensionState getSuspensionState() {
return suspensionState;
}
public BatchStatisticsQuery orderById() {
return orderBy(BatchQueryProperty.ID);
}
@Override
public BatchStatisticsQuery orderByTenantId() {
return orderBy(BatchQueryProperty.TENANT_ID);
}
|
@Override
public BatchStatisticsQuery orderByStartTime() {
return orderBy(BatchQueryProperty.START_TIME);
}
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getStatisticsManager()
.getStatisticsCountGroupedByBatch(this);
}
public List<BatchStatistics> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getStatisticsManager()
.getStatisticsGroupedByBatch(this, page);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\BatchStatisticsQueryImpl.java
| 1
|
请完成以下Java代码
|
public static Long[] get(String key)
{
return dictionary.get(key);
}
/**
* 语义距离
* @param itemA
* @param itemB
* @return
*/
public static long distance(CommonSynonymDictionary.SynonymItem itemA, CommonSynonymDictionary.SynonymItem itemB)
{
return itemA.distance(itemB);
}
/**
* 将分词结果转换为同义词列表
* @param sentence 句子
* @param withUndefinedItem 是否保留词典中没有的词语
* @return
*/
public static List<Long[]> convert(List<Term> sentence, boolean withUndefinedItem)
{
List<Long[]> synonymItemList = new ArrayList<Long[]>(sentence.size());
for (Term term : sentence)
{
// 除掉停用词
if (term.nature == null) continue;
String nature = term.nature.toString();
char firstChar = nature.charAt(0);
switch (firstChar)
{
case 'm':
{
if (!TextUtility.isAllChinese(term.word)) continue;
}break;
case 'w':
{
continue;
}
}
// 停用词
if (CoreStopWordDictionary.contains(term.word)) continue;
Long[] item = get(term.word);
// logger.trace("{} {}", wordResult.word, Arrays.toString(item));
if (item == null)
{
if (withUndefinedItem)
{
item = new Long[]{Long.MAX_VALUE / 3};
synonymItemList.add(item);
}
|
}
else
{
synonymItemList.add(item);
}
}
return synonymItemList;
}
/**
* 获取语义标签
* @return
*/
public static long[] getLexemeArray(List<CommonSynonymDictionary.SynonymItem> synonymItemList)
{
long[] array = new long[synonymItemList.size()];
int i = 0;
for (CommonSynonymDictionary.SynonymItem item : synonymItemList)
{
array[i++] = item.entry.id;
}
return array;
}
public long distance(List<CommonSynonymDictionary.SynonymItem> synonymItemListA, List<CommonSynonymDictionary.SynonymItem> synonymItemListB)
{
return EditDistance.compute(synonymItemListA, synonymItemListB);
}
public long distance(long[] arrayA, long[] arrayB)
{
return EditDistance.compute(arrayA, arrayB);
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\CoreSynonymDictionaryEx.java
| 1
|
请完成以下Java代码
|
private static void applyCountingSortOn(int[] numbers, int placeValue) {
int range = 10; // radix or the base
int length = numbers.length;
int[] frequency = new int[range];
int[] sortedValues = new int[length];
for (int i = 0; i < length; i++) {
int digit = (numbers[i] / placeValue) % range;
frequency[digit]++;
}
for (int i = 1; i < range; i++) {
frequency[i] += frequency[i - 1];
}
for (int i = length - 1; i >= 0; i--) {
int digit = (numbers[i] / placeValue) % range;
sortedValues[frequency[digit] - 1] = numbers[i];
|
frequency[digit]--;
}
System.arraycopy(sortedValues, 0, numbers, 0, length);
}
private static int calculateNumberOfDigitsIn(int number) {
return (int) Math.log10(number) + 1; // valid only if number > 0
}
private static int findMaximumNumberIn(int[] arr) {
return Arrays.stream(arr).max().getAsInt();
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-sorting-2\src\main\java\com\baeldung\algorithms\radixsort\RadixSort.java
| 1
|
请完成以下Java代码
|
public void setPlanItemDefinitionMap(Map<String, PlanItemDefinition> planItemDefinitionMap) {
this.planItemDefinitionMap = planItemDefinitionMap;
}
public boolean isPlanModel() {
return isPlanModel;
}
public void setPlanModel(boolean isPlanModel) {
this.isPlanModel = isPlanModel;
}
public boolean isAutoComplete() {
return autoComplete;
}
public void setAutoComplete(boolean autoComplete) {
this.autoComplete = autoComplete;
}
public String getAutoCompleteCondition() {
return autoCompleteCondition;
}
public void setAutoCompleteCondition(String autoCompleteCondition) {
this.autoCompleteCondition = autoCompleteCondition;
}
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
public boolean isSameDeployment() {
return sameDeployment;
}
public void setSameDeployment(boolean sameDeployment) {
this.sameDeployment = sameDeployment;
}
public String getValidateFormFields() {
return validateFormFields;
}
public void setValidateFormFields(String validateFormFields) {
this.validateFormFields = validateFormFields;
}
@Override
public void addExitCriterion(Criterion exitCriterion) {
exitCriteria.add(exitCriterion);
}
public Integer getDisplayOrder() {
return displayOrder;
}
public void setDisplayOrder(Integer displayOrder) {
|
this.displayOrder = displayOrder;
}
public String getIncludeInStageOverview() {
return includeInStageOverview;
}
public void setIncludeInStageOverview(String includeInStageOverview) {
this.includeInStageOverview = includeInStageOverview;
}
@Override
public List<Criterion> getExitCriteria() {
return exitCriteria;
}
@Override
public void setExitCriteria(List<Criterion> exitCriteria) {
this.exitCriteria = exitCriteria;
}
public String getBusinessStatus() {
return businessStatus;
}
public void setBusinessStatus(String businessStatus) {
this.businessStatus = businessStatus;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\Stage.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ServiceRepairProjectTask reduce(@NonNull final AddQtyToProjectTaskRequest request)
{
if (!ProductId.equals(getProductId(), request.getProductId()))
{
return this;
}
return toBuilder()
.qtyReserved(getQtyReserved().add(request.getQtyReserved()))
.qtyConsumed(getQtyConsumed().add(request.getQtyConsumed()))
.build()
.withUpdatedStatus();
}
public ServiceRepairProjectTask withUpdatedStatus()
{
final ServiceRepairProjectTaskStatus newStatus = computeStatus();
return !newStatus.equals(getStatus())
? toBuilder().status(newStatus).build()
: this;
}
private ServiceRepairProjectTaskStatus computeStatus()
{
final @NonNull ServiceRepairProjectTaskType type = getType();
switch (type)
{
case REPAIR_ORDER:
return computeStatusForRepairOrderType();
case SPARE_PARTS:
return computeStatusForSparePartsType();
default:
throw new AdempiereException("Unknown type for " + this);
}
}
private ServiceRepairProjectTaskStatus computeStatusForRepairOrderType()
{
if (getRepairOrderId() == null)
{
return ServiceRepairProjectTaskStatus.NOT_STARTED;
}
else
{
return isRepairOrderDone()
? ServiceRepairProjectTaskStatus.COMPLETED
: ServiceRepairProjectTaskStatus.IN_PROGRESS;
}
}
private ServiceRepairProjectTaskStatus computeStatusForSparePartsType()
{
if (getQtyToReserve().signum() <= 0)
{
return ServiceRepairProjectTaskStatus.COMPLETED;
}
else if (getQtyReservedOrConsumed().signum() == 0)
{
return ServiceRepairProjectTaskStatus.NOT_STARTED;
}
else
{
return ServiceRepairProjectTaskStatus.IN_PROGRESS;
|
}
}
public ServiceRepairProjectTask withRepairOrderId(@NonNull final PPOrderId repairOrderId)
{
return toBuilder()
.repairOrderId(repairOrderId)
.build()
.withUpdatedStatus();
}
public ServiceRepairProjectTask withRepairOrderDone(
@Nullable final String repairOrderSummary,
@Nullable final ProductId repairServicePerformedId)
{
return toBuilder()
.isRepairOrderDone(true)
.repairOrderSummary(repairOrderSummary)
.repairServicePerformedId(repairServicePerformedId)
.build()
.withUpdatedStatus();
}
public ServiceRepairProjectTask withRepairOrderNotDone()
{
return toBuilder()
.isRepairOrderDone(false)
.repairOrderSummary(null)
.repairServicePerformedId(null)
.build()
.withUpdatedStatus();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\model\ServiceRepairProjectTask.java
| 2
|
请完成以下Java代码
|
public @Nullable ConfigurationProperty get(ConfigurationPropertyName name) {
return this.properties.get(name);
}
/**
* Get all bound properties.
* @return a map of all bound properties
*/
public Map<ConfigurationPropertyName, ConfigurationProperty> getAll() {
return Collections.unmodifiableMap(this.properties);
}
/**
* Return the {@link BoundConfigurationProperties} from the given
* {@link ApplicationContext} if it is available.
* @param context the context to search
* @return a {@link BoundConfigurationProperties} or {@code null}
*/
public static @Nullable BoundConfigurationProperties get(ApplicationContext context) {
|
return (!context.containsBeanDefinition(BEAN_NAME)) ? null
: context.getBean(BEAN_NAME, BoundConfigurationProperties.class);
}
static void register(BeanDefinitionRegistry registry) {
Assert.notNull(registry, "'registry' must not be null");
if (!registry.containsBeanDefinition(BEAN_NAME)) {
BeanDefinition definition = BeanDefinitionBuilder.rootBeanDefinition(BoundConfigurationProperties.class)
.setRole(BeanDefinition.ROLE_INFRASTRUCTURE)
.getBeanDefinition();
registry.registerBeanDefinition(BEAN_NAME, definition);
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\BoundConfigurationProperties.java
| 1
|
请完成以下Java代码
|
public List<Object[]> searchProductNameByMoreLikeThisQuery(Product entity) {
Query moreLikeThisQuery = getQueryBuilder()
.moreLikeThis()
.comparingField("productName")
.toEntity(entity)
.createQuery();
List<Object[]> results = getJpaQuery(moreLikeThisQuery).setProjection(ProjectionConstants.THIS, ProjectionConstants.SCORE)
.getResultList();
return results;
}
public List<Product> searchProductNameAndDescriptionByKeywordQuery(String text) {
Query keywordQuery = getQueryBuilder()
.keyword()
.onFields("productName", "description")
.matching(text)
.createQuery();
List<Product> results = getJpaQuery(keywordQuery).getResultList();
return results;
}
public List<Object[]> searchProductNameAndDescriptionByMoreLikeThisQuery(Product entity) {
Query moreLikeThisQuery = getQueryBuilder()
.moreLikeThis()
.comparingField("productName")
.toEntity(entity)
.createQuery();
List<Object[]> results = getJpaQuery(moreLikeThisQuery).setProjection(ProjectionConstants.THIS, ProjectionConstants.SCORE)
.getResultList();
return results;
}
public List<Product> searchProductNameAndDescriptionByCombinedQuery(String manufactorer, int memoryLow, int memoryTop, String extraFeature, String exclude) {
Query combinedQuery = getQueryBuilder()
.bool()
.must(getQueryBuilder().keyword()
.onField("productName")
.matching(manufactorer)
.createQuery())
.must(getQueryBuilder()
.range()
.onField("memory")
.from(memoryLow)
.to(memoryTop)
.createQuery())
|
.should(getQueryBuilder()
.phrase()
.onField("description")
.sentence(extraFeature)
.createQuery())
.must(getQueryBuilder()
.keyword()
.onField("productName")
.matching(exclude)
.createQuery())
.not()
.createQuery();
List<Product> results = getJpaQuery(combinedQuery).getResultList();
return results;
}
private FullTextQuery getJpaQuery(org.apache.lucene.search.Query luceneQuery) {
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
return fullTextEntityManager.createFullTextQuery(luceneQuery, Product.class);
}
private QueryBuilder getQueryBuilder() {
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
return fullTextEntityManager.getSearchFactory()
.buildQueryBuilder()
.forEntity(Product.class)
.get();
}
}
|
repos\tutorials-master\persistence-modules\spring-hibernate-5\src\main\java\com\baeldung\hibernatesearch\ProductSearchDao.java
| 1
|
请完成以下Java代码
|
public class DmnDecisionTableTransformHandler implements DmnElementTransformHandler<DecisionTable, DmnDecisionTableImpl> {
protected static final DmnTransformLogger LOG = DmnLogger.TRANSFORM_LOGGER;
public DmnDecisionTableImpl handleElement(DmnElementTransformContext context, DecisionTable decisionTable) {
return createFromDecisionTable(context, decisionTable);
}
protected DmnDecisionTableImpl createFromDecisionTable(DmnElementTransformContext context, DecisionTable decisionTable) {
DmnDecisionTableImpl dmnDecisionTable = createDmnElement(context, decisionTable);
dmnDecisionTable.setHitPolicyHandler(getHitPolicyHandler(context, decisionTable, dmnDecisionTable));
return dmnDecisionTable;
}
protected DmnDecisionTableImpl createDmnElement(DmnElementTransformContext context, DecisionTable decisionTable) {
return new DmnDecisionTableImpl();
}
protected DmnHitPolicyHandler getHitPolicyHandler(DmnElementTransformContext context, DecisionTable decisionTable, DmnDecisionTableImpl dmnDecisionTable) {
HitPolicy hitPolicy = decisionTable.getHitPolicy();
|
if (hitPolicy == null) {
// use default hit policy
hitPolicy = HitPolicy.UNIQUE;
}
BuiltinAggregator aggregation = decisionTable.getAggregation();
DmnHitPolicyHandler hitPolicyHandler = context.getHitPolicyHandlerRegistry().getHandler(hitPolicy, aggregation);
if (hitPolicyHandler != null) {
return hitPolicyHandler;
}
else {
throw LOG.hitPolicyNotSupported(dmnDecisionTable, hitPolicy, aggregation);
}
}
}
|
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\transform\DmnDecisionTableTransformHandler.java
| 1
|
请完成以下Java代码
|
public class CacheControlServerHttpHeadersWriter implements ServerHttpHeadersWriter {
/**
* The value for expires value
*/
public static final String EXPIRES_VALUE = "0";
/**
* The value for pragma value
*/
public static final String PRAGMA_VALUE = "no-cache";
/**
* The value for cache control value
*/
public static final String CACHE_CONTROL_VALUE = "no-cache, no-store, max-age=0, must-revalidate";
/**
* The value for the cache control value.
* @deprecated Please use {@link #CACHE_CONTROL_VALUE}
*/
@Deprecated(forRemoval = true, since = "7.0")
|
public static final String CACHE_CONTRTOL_VALUE = CACHE_CONTROL_VALUE;
/**
* The delegate to write all the cache control related headers
*/
private static final ServerHttpHeadersWriter CACHE_HEADERS = StaticServerHttpHeadersWriter.builder()
.header(HttpHeaders.CACHE_CONTROL, CacheControlServerHttpHeadersWriter.CACHE_CONTROL_VALUE)
.header(HttpHeaders.PRAGMA, CacheControlServerHttpHeadersWriter.PRAGMA_VALUE)
.header(HttpHeaders.EXPIRES, CacheControlServerHttpHeadersWriter.EXPIRES_VALUE)
.build();
@Override
public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) {
if (exchange.getResponse().getStatusCode() == HttpStatus.NOT_MODIFIED) {
return Mono.empty();
}
return CACHE_HEADERS.writeHttpHeaders(exchange);
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\header\CacheControlServerHttpHeadersWriter.java
| 1
|
请完成以下Java代码
|
public class JsonMinifier {
public String removeExtraWhitespace(String json) {
StringBuilder result = new StringBuilder(json.length());
boolean inQuotes = false;
boolean escapeMode = false;
for (char character : json.toCharArray()) {
if (escapeMode) {
result.append(character);
escapeMode = false;
} else if (character == '"') {
inQuotes = !inQuotes;
result.append(character);
} else if (character == '\\') {
escapeMode = true;
result.append(character);
} else if (!inQuotes && character == ' ') {
continue;
} else {
result.append(character);
}
}
return result.toString();
}
public String removeExtraWhitespaceUsingJackson(String json) throws Exception {
|
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(json);
return objectMapper.writeValueAsString(jsonNode);
}
public String removeWhitespacesUsingGson(String json) {
Gson gson = new GsonBuilder().registerTypeAdapter(String.class, new StringSerializer()).create();
JsonElement jsonElement = gson.fromJson(json, JsonElement.class);
return gson.toJson(jsonElement);
}
class StringSerializer implements JsonSerializer<String> {
@Override
public JsonElement serialize(String src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.trim());
}
}
}
|
repos\tutorials-master\json-modules\json-2\src\main\java\com\baeldung\jsonminifier\JsonMinifier.java
| 1
|
请完成以下Java代码
|
public ParameterValueProvider getVersionValueProvider() {
return versionValueProvider;
}
public void setVersionValueProvider(ParameterValueProvider version) {
this.versionValueProvider = version;
}
public String getVersionTag(VariableScope variableScope) {
Object result = versionTagValueProvider.getValue(variableScope);
if (result != null) {
if (result instanceof String) {
return (String) result;
} else {
throw new ProcessEngineException("It is not possible to transform '"+result+"' into a string.");
}
}
return null;
}
public ParameterValueProvider getVersionTagValueProvider() {
return versionTagValueProvider;
}
public void setVersionTagValueProvider(ParameterValueProvider version) {
this.versionTagValueProvider = version;
}
public void setTenantIdProvider(ParameterValueProvider tenantIdProvider) {
this.tenantIdProvider = tenantIdProvider;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public String getDefinitionTenantId(VariableScope variableScope, String defaultTenantId) {
if (tenantIdProvider != null) {
return (String) tenantIdProvider.getValue(variableScope);
|
} else {
return defaultTenantId;
}
}
public ParameterValueProvider getTenantIdProvider() {
return tenantIdProvider;
}
/**
* @return true if any of the references that specify the callable element are non-literal and need to be resolved with
* potential side effects to determine the process or case definition that is to be called.
*/
public boolean hasDynamicReferences() {
return (tenantIdProvider != null && tenantIdProvider.isDynamic())
|| definitionKeyValueProvider.isDynamic()
|| versionValueProvider.isDynamic()
|| versionTagValueProvider.isDynamic();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\model\BaseCallableElement.java
| 1
|
请完成以下Java代码
|
public String[] likeCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final SessionFactory sessionFactory = HibernateUtil.getHibernateSessionFactory();
CriteriaDefinition<Item> query = new CriteriaDefinition<>(sessionFactory, Item.class) {
{
JpaRoot<Item> item = from(Item.class);
where(like(item.get("itemName"), "%chair%"));
}
};
List<Item> items = session.createSelectionQuery(query).list();
final String likeItems[] = new String[items.size()];
for (int i = 0; i < items.size(); i++) {
likeItems[i] = items.get(i).getItemName();
}
session.close();
return likeItems;
}
public String[] likeCaseCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final SessionFactory sessionFactory = HibernateUtil.getHibernateSessionFactory();
CriteriaDefinition<Item> query = new CriteriaDefinition<>(sessionFactory, Item.class) {
{
JpaRoot<Item> item = from(Item.class);
where(like(lower(item.get("itemName")), "%chair%"));
}
};
List<Item> items = session.createSelectionQuery(query).list();
final String likeItems[] = new String[items.size()];
|
for (int i = 0; i < items.size(); i++) {
likeItems[i] = items.get(i).getItemName();
}
session.close();
return likeItems;
}
public String[] betweenCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final SessionFactory sessionFactory = HibernateUtil.getHibernateSessionFactory();
CriteriaDefinition<Item> query = new CriteriaDefinition<>(sessionFactory, Item.class) {
{
JpaRoot<Item> item = from(Item.class);
where(between(item.get("itemPrice"), 100, 200));
}
};
List<Item> items = session.createSelectionQuery(query).list();
final String betweenItems[] = new String[items.size()];
for (int i = 0; i < items.size(); i++) {
betweenItems[i] = items.get(i).getItemName();
}
session.close();
return betweenItems;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-queries\src\main\java\com\baeldung\hibernate\criteria\view\CriteriaDefinitionApplicationView.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public BatchQuery orderByBatchCreateTime() {
return orderBy(BatchQueryProperty.CREATETIME);
}
@Override
public BatchQuery orderByBatchId() {
return orderBy(BatchQueryProperty.BATCH_ID);
}
@Override
public BatchQuery orderByBatchTenantId() {
return orderBy(BatchQueryProperty.TENANT_ID);
}
// results //////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
return batchServiceConfiguration.getBatchEntityManager().findBatchCountByQueryCriteria(this);
}
@Override
public List<Batch> executeList(CommandContext commandContext) {
return batchServiceConfiguration.getBatchEntityManager().findBatchesByQueryCriteria(this);
}
@Override
public void delete() {
if (commandExecutor != null) {
commandExecutor.execute(context -> {
executeDelete(context);
return null;
});
} else {
executeDelete(Context.getCommandContext());
}
}
protected void executeDelete(CommandContext commandContext) {
batchServiceConfiguration.getBatchEntityManager().deleteBatches(this);
}
@Override
@Deprecated
public void deleteWithRelatedData() {
delete();
}
// getters //////////////////////////////////////////
@Override
public String getId() {
return id;
}
public String getBatchType() {
return batchType;
}
public Collection<String> getBatchTypes() {
return batchTypes;
}
public String getSearchKey() {
return searchKey;
|
}
public String getSearchKey2() {
return searchKey2;
}
public Date getCreateTimeHigherThan() {
return createTimeHigherThan;
}
public Date getCreateTimeLowerThan() {
return createTimeLowerThan;
}
public String getStatus() {
return status;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\BatchQueryImpl.java
| 2
|
请完成以下Java代码
|
public void updateBPSupplierApproval(@NonNull final BPSupplierApprovalId bpSupplierApprovalId,
@Nullable final String supplierApproval,
@Nullable final Instant supplierApprovalDateParameter)
{
final I_C_BP_SupplierApproval bpSupplierApprovalRecord = getById(bpSupplierApprovalId);
bpSupplierApprovalRecord.setSupplierApproval(supplierApproval);
final Timestamp supplierApprovalDate = supplierApproval == null ? null : TimeUtil.asTimestamp(supplierApprovalDateParameter);
bpSupplierApprovalRecord.setSupplierApproval_Date(supplierApprovalDate);
save(bpSupplierApprovalRecord);
}
public ImmutableList<I_C_BP_SupplierApproval> retrieveBPSupplierApprovalsAboutToExpire(final int maxMonthsUntilExpirationDate)
{
final LocalDate today = SystemTime.asLocalDate();
final LocalDate maxExpirationDate = today.plusMonths(maxMonthsUntilExpirationDate);
final IQueryFilter<I_C_BP_SupplierApproval> filterThreeYears =
queryBL.createCompositeQueryFilter(I_C_BP_SupplierApproval.class)
.addEqualsFilter(I_C_BP_SupplierApproval.COLUMNNAME_SupplierApproval, SupplierApproval.ThreeYears)
.addCompareFilter(I_C_BP_SupplierApproval.COLUMNNAME_SupplierApproval_Date,
CompareQueryFilter.Operator.LESS_OR_EQUAL,
maxExpirationDate.minusYears(3));
final IQueryFilter<I_C_BP_SupplierApproval> filterTwoYears =
queryBL.createCompositeQueryFilter(I_C_BP_SupplierApproval.class)
.addEqualsFilter(I_C_BP_SupplierApproval.COLUMNNAME_SupplierApproval, SupplierApproval.TwoYears)
.addCompareFilter(I_C_BP_SupplierApproval.COLUMNNAME_SupplierApproval_Date,
CompareQueryFilter.Operator.LESS_OR_EQUAL,
maxExpirationDate.minusYears(2));
final IQueryFilter<I_C_BP_SupplierApproval> filterOneYear =
queryBL.createCompositeQueryFilter(I_C_BP_SupplierApproval.class)
.addEqualsFilter(I_C_BP_SupplierApproval.COLUMNNAME_SupplierApproval, SupplierApproval.OneYear)
|
.addCompareFilter(I_C_BP_SupplierApproval.COLUMNNAME_SupplierApproval_Date,
CompareQueryFilter.Operator.LESS_OR_EQUAL,
maxExpirationDate.minusYears(1));
final IQueryFilter<I_C_BP_SupplierApproval> supplierApprovalOptionFilter
= queryBL.createCompositeQueryFilter(I_C_BP_SupplierApproval.class)
.setJoinOr()
.addFilter(filterThreeYears)
.addFilter(filterTwoYears)
.addFilter(filterOneYear);
return queryBL.createQueryBuilder(I_C_BP_SupplierApproval.class)
.filter(supplierApprovalOptionFilter)
.create()
.listImmutable(I_C_BP_SupplierApproval.class)
;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\BPartnerSupplierApprovalRepository.java
| 1
|
请完成以下Java代码
|
static ConfigurationPropertyCaching get(Environment environment, @Nullable Object underlyingSource) {
Iterable<ConfigurationPropertySource> sources = ConfigurationPropertySources.get(environment);
return get(sources, underlyingSource);
}
/**
* Get for all specified configuration property sources.
* @param sources the configuration property sources
* @return a caching instance that controls the sources
*/
static ConfigurationPropertyCaching get(Iterable<ConfigurationPropertySource> sources) {
return get(sources, null);
}
/**
* Get for a specific configuration property source in the specified configuration
* property sources.
* @param sources the configuration property sources
* @param underlyingSource the
* {@link ConfigurationPropertySource#getUnderlyingSource() underlying source} that
* must match
* @return a caching instance that controls the matching source
*/
static ConfigurationPropertyCaching get(Iterable<ConfigurationPropertySource> sources,
@Nullable Object underlyingSource) {
Assert.notNull(sources, "'sources' must not be null");
if (underlyingSource == null) {
|
return new ConfigurationPropertySourcesCaching(sources);
}
for (ConfigurationPropertySource source : sources) {
if (source.getUnderlyingSource() == underlyingSource) {
ConfigurationPropertyCaching caching = CachingConfigurationPropertySource.find(source);
if (caching != null) {
return caching;
}
}
}
throw new IllegalStateException("Unable to find cache from configuration property sources");
}
/**
* {@link AutoCloseable} used to control a
* {@link ConfigurationPropertyCaching#override() cache override}.
*
* @since 3.5.0
*/
interface CacheOverride extends AutoCloseable {
@Override
void close();
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\ConfigurationPropertyCaching.java
| 1
|
请完成以下Java代码
|
public class EncryptableMutablePropertySourcesInterceptor implements MethodInterceptor {
private final EncryptablePropertySourceConverter propertyConverter;
private final EnvCopy envCopy;
/**
* <p>Constructor for EncryptableMutablePropertySourcesInterceptor.</p>
*
* @param propertyConverter a {@link com.ulisesbocchio.jasyptspringboot.EncryptablePropertySourceConverter} object
* @param envCopy a {@link com.ulisesbocchio.jasyptspringboot.configuration.EnvCopy} object
*/
public EncryptableMutablePropertySourcesInterceptor(EncryptablePropertySourceConverter propertyConverter, EnvCopy envCopy) {
this.propertyConverter = propertyConverter;
this.envCopy = envCopy;
}
private Object makeEncryptable(Object propertySource) {
return propertyConverter.makeEncryptable((PropertySource<?>) propertySource);
}
/** {@inheritDoc} */
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
String method = invocation.getMethod().getName();
Object[] arguments = invocation.getArguments();
switch (method) {
case "addFirst":
envCopy.addFirst((PropertySource<?>) arguments[0]);
return invocation.getMethod().invoke(invocation.getThis(), makeEncryptable(arguments[0]));
case "addLast":
envCopy.addLast((PropertySource<?>) arguments[0]);
return invocation.getMethod().invoke(invocation.getThis(), makeEncryptable(arguments[0]));
|
case "addBefore":
envCopy.addBefore((String) arguments[0], (PropertySource<?>) arguments[1]);
return invocation.getMethod().invoke(invocation.getThis(), arguments[0], makeEncryptable(arguments[1]));
case "addAfter":
envCopy.addAfter((String) arguments[0], (PropertySource<?>) arguments[1]);
return invocation.getMethod().invoke(invocation.getThis(), arguments[0], makeEncryptable(arguments[1]));
case "replace":
envCopy.replace((String) arguments[0], (PropertySource<?>) arguments[1]);
return invocation.getMethod().invoke(invocation.getThis(), arguments[0], makeEncryptable(arguments[1]));
case "remove":
envCopy.remove((String) arguments[0]);
return invocation.proceed();
default:
return invocation.proceed();
}
}
}
|
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\aop\EncryptableMutablePropertySourcesInterceptor.java
| 1
|
请完成以下Java代码
|
public class NumberAsSumOfTwoSquares {
private static final Logger LOGGER = LoggerFactory.getLogger(NumberAsSumOfTwoSquares.class);
/**
* Checks if a non-negative integer n can be written as the
* sum of two squares i.e. (a^2 + b^2)
* This implementation is based on Fermat's theorem on sums of two squares.
*
* @param n The number to check (must be non-negative).
* @return true if n can be written as a sum of two squares, false otherwise.
*/
public static boolean isSumOfTwoSquares(int n) {
if (n < 0) {
LOGGER.warn("Input must be non-negative. Returning false for n = {}", n);
return false;
}
if (n == 0) {
return true; // 0 = 0^2 + 0^2
}
// 1. Reduce n to an odd number if n is even.
while (n % 2 == 0) {
n /= 2;
}
// 2. Iterate through odd prime factors starting from 3
|
for (int i = 3; i * i <= n; i += 2) {
// 2a. Find the exponent of the factor i
int count = 0;
while (n % i == 0) {
count++;
n /= i;
}
// 2b. Check the condition from Fermat's theorem
// If i is of form 4k+3 (i % 4 == 3) and has an odd exponent
if (i % 4 == 3 && count % 2 != 0) {
LOGGER.debug("Failing condition: factor {} (form 4k+3) has odd exponent {}", i, count);
return false;
}
}
// 3. Handle the last remaining factor (which is prime if > 1)
// If n itself is a prime of the form 4k+3, its exponent is 1 (odd).
if (n % 4 == 3) {
LOGGER.debug("Failing condition: remaining factor {} is of form 4k+3", n);
return false;
}
// 4. All 4k+3 primes had even exponents.
return true;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-numeric\src\main\java\com\baeldung\algorithms\sumoftwosquares\NumberAsSumOfTwoSquares.java
| 1
|
请完成以下Java代码
|
public ClassLoader getClassLoader() {
return classLoader;
}
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
public boolean isUseClassForNameClassLoading() {
return useClassForNameClassLoading;
}
public void setUseClassForNameClassLoading(boolean useClassForNameClassLoading) {
this.useClassForNameClassLoading = useClassForNameClassLoading;
}
public Clock getClock() {
return clock;
}
public void setClock(Clock clock) {
this.clock = clock;
}
public ObjectMapper getObjectMapper() {
return objectMapper;
}
public void setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
// getters and setters
// //////////////////////////////////////////////////////
public Command<?> getCommand() {
return command;
}
public Map<Class<?>, Session> getSessions() {
return sessions;
|
}
public Throwable getException() {
return exception;
}
public boolean isReused() {
return reused;
}
public void setReused(boolean reused) {
this.reused = reused;
}
public Object getResult() {
return resultStack.pollLast();
}
public void setResult(Object result) {
resultStack.add(result);
}
public long getStartTime() {
return startTime;
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\interceptor\CommandContext.java
| 1
|
请完成以下Java代码
|
public class StudentJson {
private int id;
private String firstName;
private String lastName;
private String email;
private List<PhoneNumJson> phoneNumList;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<PhoneNumJson> getPhoneNumList() {
return phoneNumList;
}
public void setPhoneNumList(List<PhoneNumJson> phoneNumList) {
this.phoneNumList = phoneNumList;
}
}
|
repos\springboot-demo-master\protobuf\src\main\java\com\et\protobuf\StudentJson.java
| 1
|
请完成以下Java代码
|
public int getAsyncExecutorAsyncJobLockTimeInMillis() {
return asyncExecutorAsyncJobLockTimeInMillis;
}
public ProcessEngineConfigurationImpl setAsyncExecutorAsyncJobLockTimeInMillis(
int asyncExecutorAsyncJobLockTimeInMillis
) {
this.asyncExecutorAsyncJobLockTimeInMillis = asyncExecutorAsyncJobLockTimeInMillis;
return this;
}
public int getAsyncExecutorResetExpiredJobsInterval() {
return asyncExecutorResetExpiredJobsInterval;
}
public ProcessEngineConfigurationImpl setAsyncExecutorResetExpiredJobsInterval(
int asyncExecutorResetExpiredJobsInterval
) {
this.asyncExecutorResetExpiredJobsInterval = asyncExecutorResetExpiredJobsInterval;
return this;
}
public ExecuteAsyncRunnableFactory getAsyncExecutorExecuteAsyncRunnableFactory() {
return asyncExecutorExecuteAsyncRunnableFactory;
}
public ProcessEngineConfigurationImpl setAsyncExecutorExecuteAsyncRunnableFactory(
ExecuteAsyncRunnableFactory asyncExecutorExecuteAsyncRunnableFactory
) {
this.asyncExecutorExecuteAsyncRunnableFactory = asyncExecutorExecuteAsyncRunnableFactory;
return this;
}
public int getAsyncExecutorResetExpiredJobsPageSize() {
return asyncExecutorResetExpiredJobsPageSize;
}
public ProcessEngineConfigurationImpl setAsyncExecutorResetExpiredJobsPageSize(
int asyncExecutorResetExpiredJobsPageSize
) {
|
this.asyncExecutorResetExpiredJobsPageSize = asyncExecutorResetExpiredJobsPageSize;
return this;
}
public boolean isAsyncExecutorIsMessageQueueMode() {
return asyncExecutorMessageQueueMode;
}
public ProcessEngineConfigurationImpl setAsyncExecutorMessageQueueMode(boolean asyncExecutorMessageQueueMode) {
this.asyncExecutorMessageQueueMode = asyncExecutorMessageQueueMode;
return this;
}
public boolean isRollbackDeployment() {
return isRollbackDeployment;
}
public void setRollbackDeployment(boolean rollbackDeployment) {
isRollbackDeployment = rollbackDeployment;
}
public EventSubscriptionPayloadMappingProvider getEventSubscriptionPayloadMappingProvider() {
return eventSubscriptionPayloadMappingProvider;
}
public void setEventSubscriptionPayloadMappingProvider(
EventSubscriptionPayloadMappingProvider eventSubscriptionPayloadMappingProvider
) {
this.eventSubscriptionPayloadMappingProvider = eventSubscriptionPayloadMappingProvider;
}
public ProcessDefinitionHelper getProcessDefinitionHelper() {
return processDefinitionHelper;
}
public ProcessEngineConfigurationImpl setProcessDefinitionHelper(ProcessDefinitionHelper processDefinitionHelper) {
this.processDefinitionHelper = processDefinitionHelper;
return this;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cfg\ProcessEngineConfigurationImpl.java
| 1
|
请完成以下Java代码
|
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
public static class Car extends Vehicle {
private int seatingCapacity;
private double topSpeed;
public Car() {
}
public Car(String make, String model, int seatingCapacity, double topSpeed) {
super(make, model);
this.seatingCapacity = seatingCapacity;
this.topSpeed = topSpeed;
}
public int getSeatingCapacity() {
return seatingCapacity;
}
public void setSeatingCapacity(int seatingCapacity) {
this.seatingCapacity = seatingCapacity;
}
public double getTopSpeed() {
return topSpeed;
}
public void setTopSpeed(double topSpeed) {
this.topSpeed = topSpeed;
}
}
|
public static class Truck extends Vehicle {
private double payloadCapacity;
public Truck() {
}
public Truck(String make, String model, double payloadCapacity) {
super(make, model);
this.payloadCapacity = payloadCapacity;
}
public double getPayloadCapacity() {
return payloadCapacity;
}
public void setPayloadCapacity(double payloadCapacity) {
this.payloadCapacity = payloadCapacity;
}
}
}
|
repos\tutorials-master\jackson-modules\jackson-core\src\main\java\com\baeldung\jackson\inheritance\TypeInfoAnnotatedStructure.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class GrpcHealthServiceAutoConfiguration {
/**
* Creates a new HealthStatusManager instance.
*
* @return The newly created bean.
*/
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "grpc.server", name = "health-service.type", havingValue = "GRPC",
matchIfMissing = true)
HealthStatusManager healthStatusManager() {
return new HealthStatusManager();
}
|
@Bean
@GrpcService
@ConditionalOnProperty(prefix = "grpc.server", name = "health-service.type", havingValue = "GRPC",
matchIfMissing = true)
BindableService grpcHealthService(final HealthStatusManager healthStatusManager) {
return healthStatusManager.getHealthService();
}
@Bean
@GrpcService
@ConditionalOnProperty(prefix = "grpc.server", name = "health-service.type", havingValue = "ACTUATOR")
BindableService grpcHealthServiceActuator(final HealthEndpoint healthStatusManager) {
return new ActuatorGrpcHealth(healthStatusManager);
}
}
|
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\autoconfigure\GrpcHealthServiceAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public class GetStartFormCmd implements Command<StartFormData>, Serializable {
private static final long serialVersionUID = 1L;
protected String processDefinitionId;
public GetStartFormCmd(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
@Override
public StartFormData execute(CommandContext commandContext) {
ProcessDefinition processDefinition = CommandContextUtil.getProcessEngineConfiguration(commandContext).getDeploymentManager().findDeployedProcessDefinitionById(processDefinitionId);
if (processDefinition == null) {
throw new FlowableObjectNotFoundException("No process definition found for id '" + processDefinitionId + "'", ProcessDefinition.class);
}
|
if (Flowable5Util.isFlowable5ProcessDefinition(processDefinition, commandContext)) {
return Flowable5Util.getFlowable5CompatibilityHandler().getStartFormData(processDefinitionId);
}
FormHandlerHelper formHandlerHelper = CommandContextUtil.getProcessEngineConfiguration(commandContext).getFormHandlerHelper();
StartFormHandler startFormHandler = formHandlerHelper.getStartFormHandler(commandContext, processDefinition);
if (startFormHandler == null) {
throw new FlowableException("No startFormHandler defined in process definition '" + processDefinitionId + "'");
}
return startFormHandler.createStartFormData(processDefinition);
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\GetStartFormCmd.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class RedisConfig {
@Bean
JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory();
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
final RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
template.setValueSerializer(new GenericToStringSerializer<>(Object.class));
return template;
}
@Bean
MessageListenerAdapter messageListener() {
return new MessageListenerAdapter(new RedisMessageSubscriber());
}
@Bean
RedisMessageListenerContainer redisContainer() {
|
final RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(jedisConnectionFactory());
container.addMessageListener(messageListener(), topic());
return container;
}
@Bean
MessagePublisher redisPublisher() {
return new RedisMessagePublisher(redisTemplate(), topic());
}
@Bean
ChannelTopic topic() {
return new ChannelTopic("pubsub:queue");
}
}
|
repos\tutorials-master\persistence-modules\spring-data-redis\src\main\java\com\baeldung\spring\data\redis\config\RedisConfig.java
| 2
|
请完成以下Java代码
|
public Builder setReservedForOrderLine(@Nullable final OrderLineId orderLineId)
{
orderLineReservation = orderLineId;
huReserved = orderLineId != null;
return this;
}
public Builder setClearanceStatus(@Nullable final JSONLookupValue clearanceStatusLookupValue)
{
clearanceStatus = clearanceStatusLookupValue;
return this;
}
public Builder setCustomProcessApplyPredicate(@Nullable final BiPredicate<HUEditorRow, ProcessDescriptor> processApplyPredicate)
{
this.customProcessApplyPredicate = processApplyPredicate;
return this;
}
@Nullable
private BiPredicate<HUEditorRow, ProcessDescriptor> getCustomProcessApplyPredicate()
{
return this.customProcessApplyPredicate;
}
/**
* @param currentRow the row that is currently constructed using this builder
*/
private ImmutableMultimap<OrderLineId, HUEditorRow> prepareIncludedOrderLineReservations(@NonNull final HUEditorRow currentRow)
{
final ImmutableMultimap.Builder<OrderLineId, HUEditorRow> includedOrderLineReservationsBuilder = ImmutableMultimap.builder();
for (final HUEditorRow includedRow : buildIncludedRows())
{
includedOrderLineReservationsBuilder.putAll(includedRow.getIncludedOrderLineReservations());
}
if (orderLineReservation != null)
{
|
includedOrderLineReservationsBuilder.put(orderLineReservation, currentRow);
}
return includedOrderLineReservationsBuilder.build();
}
}
@lombok.Builder
@lombok.Value
public static class HUEditorRowHierarchy
{
@NonNull HUEditorRow cuRow;
@Nullable
HUEditorRow parentRow;
@Nullable
HUEditorRow topLevelRow;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorRow.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setHttpMethodEnum(HttpMethodEnum httpMethodEnum) {
this.httpMethodEnum = httpMethodEnum;
}
public boolean isLogin() {
return isLogin;
}
public void setLogin(boolean login) {
isLogin = login;
}
public String getPermission() {
return permission;
}
|
public void setPermission(String permission) {
this.permission = permission;
}
@Override
public String toString() {
return "AccessAuthEntity{" +
"url='" + url + '\'' +
", methodName='" + methodName + '\'' +
", httpMethodEnum=" + httpMethodEnum +
", isLogin=" + isLogin +
", permission='" + permission + '\'' +
'}';
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\user\AccessAuthEntity.java
| 2
|
请完成以下Java代码
|
public synchronized void unloadById(final InboundEMailConfigId configId)
{
final InboundEMailConfig loadedConfig = loadedConfigs.remove(configId);
if (loadedConfig == null)
{
logger.info("Skip unloading inbound mail for {} because it's not loaded", configId);
return;
}
try
{
flowContext.remove(toFlowId(configId));
logger.info("Unloaded inbound mail for {}", configId);
}
catch (final Exception ex)
{
logger.warn("Unloading inbound mail for {} failed. Ignored.", configId, ex);
}
}
private synchronized void load(final InboundEMailConfig config)
{
final IntegrationFlow flow = createIntegrationFlow(config);
flowContext.registration(flow)
.id(toFlowId(config.getId()))
.register();
loadedConfigs.put(config.getId(), config);
logger.info("Loaded inbound mail for {}", config);
}
private IntegrationFlow createIntegrationFlow(final InboundEMailConfig config)
|
{
return IntegrationFlows
.from(Mail.imapIdleAdapter(config.getUrl())
.javaMailProperties(p -> p.put("mail.debug", Boolean.toString(config.isDebugProtocol())))
.userFlag(IMAP_USER_FLAG)
.shouldMarkMessagesAsRead(false)
.shouldDeleteMessages(false)
.shouldReconnectAutomatically(true)
.embeddedPartsAsBytes(false)
.headerMapper(InboundEMailHeaderAndContentMapper.newInstance()))
.handle(InboundEMailMessageHandler.builder()
.config(config)
.emailService(emailService)
.build())
.get();
}
@Override
public void onInboundEMailConfigChanged(final Set<InboundEMailConfigId> changedConfigIds)
{
final List<InboundEMailConfig> newOrChangedConfigs = configsRepo.getByIds(changedConfigIds);
final Set<InboundEMailConfigId> newOrChangedConfigIds = newOrChangedConfigs.stream()
.map(InboundEMailConfig::getId)
.collect(ImmutableSet.toImmutableSet());
final Set<InboundEMailConfigId> deletedConfigIds = Sets.difference(changedConfigIds, newOrChangedConfigIds);
deletedConfigIds.forEach(this::unloadById);
reload(newOrChangedConfigs);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.inbound.mail\src\main\java\de\metas\inbound\mail\InboundEMailServer.java
| 1
|
请完成以下Java代码
|
public Map<String, VariableValueDto> getProcessVariablesLocal() {
return processVariablesLocal;
}
public void setProcessVariablesLocal(Map<String, VariableValueDto> processVariablesLocal) {
this.processVariablesLocal = processVariablesLocal;
}
public Map<String, VariableValueDto> getProcessVariablesToTriggeredScope() {
return processVariablesToTriggeredScope;
}
public void setProcessVariablesToTriggeredScope(Map<String, VariableValueDto> processVariablesToTriggeredScope) {
this.processVariablesToTriggeredScope = processVariablesToTriggeredScope;
}
public boolean isAll() {
return all;
}
public void setAll(boolean all) {
this.all = all;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
|
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public boolean isResultEnabled() {
return resultEnabled;
}
public void setResultEnabled(boolean resultEnabled) {
this.resultEnabled = resultEnabled;
}
public boolean isVariablesInResultEnabled() {
return variablesInResultEnabled;
}
public void setVariablesInResultEnabled(boolean variablesInResultEnabled) {
this.variablesInResultEnabled = variablesInResultEnabled;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\message\CorrelationMessageDto.java
| 1
|
请完成以下Java代码
|
public OAuth2TokenValidatorResult validate(Jwt jwt) {
Assert.notNull(jwt, "jwt cannot be null");
Instant issuedAt = jwt.getIssuedAt();
if (issuedAt == null && this.required) {
OAuth2Error error = createOAuth2Error("iat claim is required.");
return OAuth2TokenValidatorResult.failure(error);
}
if (issuedAt != null) {
// Check time window of validity
Instant now = Instant.now(this.clock);
Instant notBefore = now.minus(this.clockSkew);
Instant notAfter = now.plus(this.clockSkew);
if (issuedAt.isBefore(notBefore) || issuedAt.isAfter(notAfter)) {
OAuth2Error error = createOAuth2Error("iat claim is invalid.");
return OAuth2TokenValidatorResult.failure(error);
}
}
return OAuth2TokenValidatorResult.success();
}
/**
* Sets the clock skew. The default is 60 seconds.
* @param clockSkew the clock skew
*/
|
public void setClockSkew(Duration clockSkew) {
Assert.notNull(clockSkew, "clockSkew cannot be null");
Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0");
this.clockSkew = clockSkew;
}
/**
* Sets the {@link Clock} used in {@link Instant#now(Clock)}.
* @param clock the clock
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.clock = clock;
}
private static OAuth2Error createOAuth2Error(String reason) {
return new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, reason, null);
}
}
|
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JwtIssuedAtValidator.java
| 1
|
请完成以下Java代码
|
public Enumeration<String> getHeaderNames() {
Set<String> names = headers.headerNames();
if (names.isEmpty()) {
return super.getHeaderNames();
}
Set<String> result = new LinkedHashSet<>(names);
result.addAll(Collections.list(super.getHeaderNames()));
return new Vector<String>(result).elements();
}
@Override
public Enumeration<String> getHeaders(String name) {
List<String> list = header(name);
if (list != null) {
return new Vector<String>(list).elements();
}
return super.getHeaders(name);
}
@Override
public String getHeader(String name) {
List<String> list = header(name);
if (list != null && !list.isEmpty()) {
return list.iterator().next();
}
return super.getHeader(name);
}
}
}
/**
* Convenience class that converts an incoming request input stream into a form that can
* be easily deserialized to a Java object using Spring message converters. It is only
* used in a local forward dispatch, in which case there is a danger that the request body
* will need to be read and analysed more than once. Apart from using the message
* converters the other main feature of this class is that the request body is cached and
* can be read repeatedly as necessary.
*
* @author Dave Syer
*
*/
class ServletOutputToInputConverter extends HttpServletResponseWrapper {
private StringBuilder builder = new StringBuilder();
ServletOutputToInputConverter(HttpServletResponse response) {
super(response);
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
return new ServletOutputStream() {
@Override
|
public void write(int b) throws IOException {
builder.append(Character.valueOf((char) b));
}
@Override
public void setWriteListener(WriteListener listener) {
}
@Override
public boolean isReady() {
return true;
}
};
}
public ServletInputStream getInputStream() {
ByteArrayInputStream body = new ByteArrayInputStream(builder.toString().getBytes());
return new ServletInputStream() {
@Override
public int read() throws IOException {
return body.read();
}
@Override
public void setReadListener(ReadListener listener) {
}
@Override
public boolean isReady() {
return true;
}
@Override
public boolean isFinished() {
return body.available() <= 0;
}
};
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-proxyexchange-webmvc\src\main\java\org\springframework\cloud\gateway\mvc\ProxyExchange.java
| 1
|
请完成以下Java代码
|
public class OAuth2RefreshTokenGrantRequest extends AbstractOAuth2AuthorizationGrantRequest {
private final OAuth2AccessToken accessToken;
private final OAuth2RefreshToken refreshToken;
private final Set<String> scopes;
/**
* Constructs an {@code OAuth2RefreshTokenGrantRequest} using the provided parameters.
* @param clientRegistration the authorized client's registration
* @param accessToken the access token credential granted
* @param refreshToken the refresh token credential granted
*/
public OAuth2RefreshTokenGrantRequest(ClientRegistration clientRegistration, OAuth2AccessToken accessToken,
OAuth2RefreshToken refreshToken) {
this(clientRegistration, accessToken, refreshToken, Collections.emptySet());
}
/**
* Constructs an {@code OAuth2RefreshTokenGrantRequest} using the provided parameters.
* @param clientRegistration the authorized client's registration
* @param accessToken the access token credential granted
* @param refreshToken the refresh token credential granted
* @param scopes the scopes to request
*/
public OAuth2RefreshTokenGrantRequest(ClientRegistration clientRegistration, OAuth2AccessToken accessToken,
OAuth2RefreshToken refreshToken, Set<String> scopes) {
super(AuthorizationGrantType.REFRESH_TOKEN, clientRegistration);
Assert.notNull(accessToken, "accessToken cannot be null");
Assert.notNull(refreshToken, "refreshToken cannot be null");
this.accessToken = accessToken;
this.refreshToken = refreshToken;
this.scopes = Collections
.unmodifiableSet((scopes != null) ? new LinkedHashSet<>(scopes) : Collections.emptySet());
}
/**
* Returns the {@link OAuth2AccessToken access token} credential granted.
* @return the {@link OAuth2AccessToken}
*/
public OAuth2AccessToken getAccessToken() {
return this.accessToken;
}
|
/**
* Returns the {@link OAuth2RefreshToken refresh token} credential granted.
* @return the {@link OAuth2RefreshToken}
*/
public OAuth2RefreshToken getRefreshToken() {
return this.refreshToken;
}
/**
* Returns the scope(s) to request.
* @return the scope(s) to request
*/
public Set<String> getScopes() {
return this.scopes;
}
/**
* Populate default parameters for the Refresh Token Grant.
* @param grantRequest the authorization grant request
* @return a {@link MultiValueMap} of the parameters used in the OAuth 2.0 Access
* Token Request body
*/
static MultiValueMap<String, String> defaultParameters(OAuth2RefreshTokenGrantRequest grantRequest) {
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
if (!CollectionUtils.isEmpty(grantRequest.getScopes())) {
parameters.set(OAuth2ParameterNames.SCOPE,
StringUtils.collectionToDelimitedString(grantRequest.getScopes(), " "));
}
parameters.set(OAuth2ParameterNames.REFRESH_TOKEN, grantRequest.getRefreshToken().getTokenValue());
return parameters;
}
}
|
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\endpoint\OAuth2RefreshTokenGrantRequest.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public MessageChannel holdingTank() {
return MessageChannels.queue().get();
}
// @Bean
public IntegrationFlow fileReader() {
return IntegrationFlow.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10)))
.filter(onlyJpgs())
.channel("holdingTank")
.get();
}
// @Bean
public IntegrationFlow fileWriter() {
return IntegrationFlow.from("holdingTank")
.bridge(e -> e.poller(Pollers.fixedRate(Duration.of(1, TimeUnit.SECONDS.toChronoUnit()), Duration.of(20, TimeUnit.SECONDS.toChronoUnit()))))
.handle(targetDirectory())
.get();
}
// @Bean
public IntegrationFlow anotherFileWriter() {
return IntegrationFlow.from("holdingTank")
.bridge(e -> e.poller(Pollers.fixedRate(Duration.of(2, TimeUnit.SECONDS.toChronoUnit()), Duration.of(10, TimeUnit.SECONDS.toChronoUnit()))))
.handle(anotherTargetDirectory())
|
.get();
}
public static void main(final String... args) {
final AbstractApplicationContext context = new AnnotationConfigApplicationContext(JavaDSLFileCopyConfig.class);
context.registerShutdownHook();
final Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a string and press <enter>: ");
while (true) {
final String input = scanner.nextLine();
if ("q".equals(input.trim())) {
context.close();
scanner.close();
break;
}
}
System.exit(0);
}
}
|
repos\tutorials-master\spring-integration\src\main\java\com\baeldung\dsl\JavaDSLFileCopyConfig.java
| 2
|
请完成以下Java代码
|
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getId() {
return this.id;
}
public ServiceCapabilityType getType() {
return this.type;
}
/**
* Return the "content" of this capability. The structure of the content vastly
* depends on the {@link ServiceCapability type} of the capability.
* @return the content
*/
public abstract T getContent();
|
/**
* Merge the content of this instance with the specified content.
* @param otherContent the content to merge
* @see #merge(io.spring.initializr.metadata.ServiceCapability)
*/
public abstract void merge(T otherContent);
/**
* Merge this capability with the specified argument. The service capabilities should
* match (i.e have the same {@code id} and {@code type}). Sub-classes may merge
* additional content.
* @param other the content to merge
*/
public void merge(ServiceCapability<T> other) {
Assert.notNull(other, "Other must not be null");
Assert.isTrue(this.id.equals(other.id), "Ids must be equals");
Assert.isTrue(this.type.equals(other.type), "Types must be equals");
if (StringUtils.hasText(other.title)) {
this.title = other.title;
}
if (StringUtils.hasText(other.description)) {
this.description = other.description;
}
merge(other.getContent());
}
}
|
repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\ServiceCapability.java
| 1
|
请完成以下Java代码
|
public JobQuery orderByJobDuedate() {
return orderBy(JobQueryProperty.DUEDATE);
}
public JobQuery orderByExecutionId() {
return orderBy(JobQueryProperty.EXECUTION_ID);
}
public JobQuery orderByJobId() {
return orderBy(JobQueryProperty.JOB_ID);
}
public JobQuery orderByProcessInstanceId() {
return orderBy(JobQueryProperty.PROCESS_INSTANCE_ID);
}
public JobQuery orderByJobRetries() {
return orderBy(JobQueryProperty.RETRIES);
}
public JobQuery orderByTenantId() {
return orderBy(JobQueryProperty.TENANT_ID);
}
// results //////////////////////////////////////////
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext.getJobEntityManager().findJobCountByQueryCriteria(this);
}
public List<Job> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext.getJobEntityManager().findJobsByQueryCriteria(this, page);
}
// getters //////////////////////////////////////////
public String getProcessInstanceId() {
return processInstanceId;
}
public String getExecutionId() {
return executionId;
}
public boolean getRetriesLeft() {
return retriesLeft;
}
public boolean getExecutable() {
return executable;
}
public Date getNow() {
return Context.getProcessEngineConfiguration().getClock().getCurrentTime();
}
public boolean isWithException() {
return withException;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public String getId() {
return id;
}
public String getProcessDefinitionId() {
return processDefinitionId;
|
}
public boolean isOnlyTimers() {
return onlyTimers;
}
public boolean isOnlyMessages() {
return onlyMessages;
}
public Date getDuedateHigherThan() {
return duedateHigherThan;
}
public Date getDuedateLowerThan() {
return duedateLowerThan;
}
public Date getDuedateHigherThanOrEqual() {
return duedateHigherThanOrEqual;
}
public Date getDuedateLowerThanOrEqual() {
return duedateLowerThanOrEqual;
}
public boolean isNoRetriesLeft() {
return noRetriesLeft;
}
public boolean isOnlyLocked() {
return onlyLocked;
}
public boolean isOnlyUnlocked() {
return onlyUnlocked;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\JobQueryImpl.java
| 1
|
请完成以下Java代码
|
public final int executeUpdate(final String sql, final String[] columnNames) throws SQLException
{
final String sqlConverted = convertSqlAndSet(sql);
return getStatementImpl().executeUpdate(sqlConverted, columnNames);
}
@Override
public final boolean execute(final String sql, final int autoGeneratedKeys) throws SQLException
{
final String sqlConverted = convertSqlAndSet(sql);
return getStatementImpl().execute(sqlConverted, autoGeneratedKeys);
}
@Override
public final boolean execute(final String sql, final int[] columnIndexes) throws SQLException
{
final String sqlConverted = convertSqlAndSet(sql);
return getStatementImpl().execute(sqlConverted, columnIndexes);
}
@Override
public final boolean execute(final String sql, final String[] columnNames) throws SQLException
{
final String sqlConverted = convertSqlAndSet(sql);
return getStatementImpl().execute(sqlConverted, columnNames);
}
@Override
public final int getResultSetHoldability() throws SQLException
{
return getStatementImpl().getResultSetHoldability();
}
@Override
public final boolean isClosed() throws SQLException
{
return closed;
}
@Override
public final void setPoolable(final boolean poolable) throws SQLException
{
getStatementImpl().setPoolable(poolable);
}
@Override
public final boolean isPoolable() throws SQLException
{
return getStatementImpl().isPoolable();
}
@Override
public final void closeOnCompletion() throws SQLException
{
getStatementImpl().closeOnCompletion();
}
@Override
public final boolean isCloseOnCompletion() throws SQLException
{
return getStatementImpl().isCloseOnCompletion();
}
@Override
public final String getSql()
{
return this.vo.getSql();
}
protected final String convertSqlAndSet(final String sql)
{
final String sqlConverted = DB.getDatabase().convertStatement(sql);
vo.setSql(sqlConverted);
MigrationScriptFileLoggerHolder.logMigrationScript(sql);
return sqlConverted;
|
}
@Override
public final void commit() throws SQLException
{
if (this.ownedConnection != null && !this.ownedConnection.getAutoCommit())
{
this.ownedConnection.commit();
}
}
@Nullable
private static Trx getTrx(@NonNull final CStatementVO vo)
{
final ITrxManager trxManager = Services.get(ITrxManager.class);
final String trxName = vo.getTrxName();
if (trxManager.isNull(trxName))
{
return (Trx)ITrx.TRX_None;
}
else
{
final ITrx trx = trxManager.get(trxName, false); // createNew=false
// NOTE: we assume trx if of type Trx because we need to invoke getConnection()
return (Trx)trx;
}
}
@Override
public String toString()
{
return "AbstractCStatementProxy [ownedConnection=" + this.ownedConnection + ", closed=" + closed + ", p_vo=" + vo + "]";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\sql\impl\AbstractCStatementProxy.java
| 1
|
请完成以下Java代码
|
public void setMessageSource(MessageSource messageSource) {
this.messages = new MessageSourceAccessor(messageSource);
}
public void setUserCache(UserCache userCache) {
this.userCache = userCache;
}
@Override
public boolean supports(Class<?> authentication) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}
protected UserDetailsChecker getPreAuthenticationChecks() {
return this.preAuthenticationChecks;
}
/**
* Sets the policy will be used to verify the status of the loaded
* <tt>UserDetails</tt> <em>before</em> validation of the credentials takes place.
* @param preAuthenticationChecks strategy to be invoked prior to authentication.
*/
public void setPreAuthenticationChecks(UserDetailsChecker preAuthenticationChecks) {
this.preAuthenticationChecks = preAuthenticationChecks;
}
protected UserDetailsChecker getPostAuthenticationChecks() {
return this.postAuthenticationChecks;
}
public void setPostAuthenticationChecks(UserDetailsChecker postAuthenticationChecks) {
this.postAuthenticationChecks = postAuthenticationChecks;
}
public void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) {
this.authoritiesMapper = authoritiesMapper;
}
private class DefaultPreAuthenticationChecks implements UserDetailsChecker {
@Override
public void check(UserDetails user) {
if (!user.isAccountNonLocked()) {
AbstractUserDetailsAuthenticationProvider.this.logger
.debug("Failed to authenticate since user account is locked");
throw new LockedException(AbstractUserDetailsAuthenticationProvider.this.messages
.getMessage("AbstractUserDetailsAuthenticationProvider.locked", "User account is locked"));
}
if (!user.isEnabled()) {
|
AbstractUserDetailsAuthenticationProvider.this.logger
.debug("Failed to authenticate since user account is disabled");
throw new DisabledException(AbstractUserDetailsAuthenticationProvider.this.messages
.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled"));
}
if (!user.isAccountNonExpired()) {
AbstractUserDetailsAuthenticationProvider.this.logger
.debug("Failed to authenticate since user account has expired");
throw new AccountExpiredException(AbstractUserDetailsAuthenticationProvider.this.messages
.getMessage("AbstractUserDetailsAuthenticationProvider.expired", "User account has expired"));
}
}
}
private class DefaultPostAuthenticationChecks implements UserDetailsChecker {
@Override
public void check(UserDetails user) {
if (!user.isCredentialsNonExpired()) {
AbstractUserDetailsAuthenticationProvider.this.logger
.debug("Failed to authenticate since user account credentials have expired");
throw new CredentialsExpiredException(AbstractUserDetailsAuthenticationProvider.this.messages
.getMessage("AbstractUserDetailsAuthenticationProvider.credentialsExpired",
"User credentials have expired"));
}
}
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\dao\AbstractUserDetailsAuthenticationProvider.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JsonPaymentAllocationLine
{
@NonNull
@ApiModelProperty(required = true,
dataType = "java.lang.String",
value = "Identifier of the Invoice in question. Can be\n"
+ "* a plain `<C_Invoice.C_Invoice_ID>`\n"
+ "* or something like `doc-<C_Invoice.documentNo>`"
+ "* or something like `ext-<C_Invoice.ExternalId>`")
String invoiceIdentifier;
@ApiModelProperty(position = 10)
@Nullable
String docBaseType;
@ApiModelProperty(position = 20)
@Nullable
String docSubType;
@ApiModelProperty(position = 30)
@Nullable
|
BigDecimal amount;
@ApiModelProperty(position = 40)
@Nullable
BigDecimal discountAmt;
@ApiModelProperty(position = 50)
@Nullable
BigDecimal writeOffAmt;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPOJOBuilder(withPrefix = "")
public static class JsonPaymentAllocationLineBuilder
{
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-rest_api\src\main\java\de\metas\common\rest_api\v2\invoice\JsonPaymentAllocationLine.java
| 2
|
请完成以下Java代码
|
public boolean has_Variable(final String variableName)
{
return POJOWrapper.this.hasColumnName(variableName);
}
@Override
public String get_ValueOldAsString(final String variableName)
{
throw new UnsupportedOperationException("not implemented");
}
};
}
public IModelInternalAccessor getModelInternalAccessor()
{
if (_modelInternalAccessor == null)
{
_modelInternalAccessor = new POJOModelInternalAccessor(this);
}
return _modelInternalAccessor;
|
}
POJOModelInternalAccessor _modelInternalAccessor = null;
public static IModelInternalAccessor getModelInternalAccessor(final Object model)
{
final POJOWrapper wrapper = getWrapper(model);
if (wrapper == null)
{
return null;
}
return wrapper.getModelInternalAccessor();
}
public boolean isProcessed()
{
return hasColumnName("Processed")
? StringUtils.toBoolean(getValue("Processed", Object.class))
: false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POJOWrapper.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static class Proxy {
/**
* The host of the proxy to use to connect to the remote application.
*/
private @Nullable String host;
/**
* The port of the proxy to use to connect to the remote application.
*/
private @Nullable Integer port;
public @Nullable String getHost() {
return this.host;
}
|
public void setHost(@Nullable String host) {
this.host = host;
}
public @Nullable Integer getPort() {
return this.port;
}
public void setPort(@Nullable Integer port) {
this.port = port;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\autoconfigure\RemoteDevToolsProperties.java
| 2
|
请完成以下Java代码
|
protected void transfer(OrderProcessContext orderProcessContext) {
// 获取订单ID 和 购买者ID
String orderId = orderProcessContext.getOrderProcessReq().getOrderId();
String buyerId = orderProcessContext.getOrderProcessReq().getUserId();
// 构造查询请求
OrderQueryReq orderQueryReq = buildOrderQueryReq(orderId, buyerId);
// 查询该笔订单
OrdersEntity ordersEntity = query(orderQueryReq);
// 构建prodIdCountMap
Map<String, Integer> prodIdCountMap = buildProdIdCountMap(ordersEntity);
// 装入context
setIntoContext(prodIdCountMap, ordersEntity.getPayModeEnum(), orderProcessContext);
}
/**
* 订单查询
* @param orderQueryReq 订单查询请求
* @return 订单结果
*/
private OrdersEntity query(OrderQueryReq orderQueryReq) {
List<OrdersEntity> ordersEntityList = orderDAO.findOrders(orderQueryReq);
if (CollectionUtils.isEmpty(ordersEntityList)) {
throw new CommonBizException(ExpCodeEnum.ORDER_NULL);
}
return ordersEntityList.get(0);
}
/**
* 构造订单查询请求
* @param orderId 订单ID
* @param buyerId 购买者ID
* @return 订单查询请求
*/
private OrderQueryReq buildOrderQueryReq(String orderId, String buyerId) {
OrderQueryReq orderQueryReq = new OrderQueryReq();
orderQueryReq.setId(orderId);
orderQueryReq.setBuyerId(buyerId);
return orderQueryReq;
}
/**
* 构建prodIdCountMap
* @param ordersEntity 订单详情
|
* @return prodIdCountMap
*/
private Map<String, Integer> buildProdIdCountMap(OrdersEntity ordersEntity) {
// 初始化结果集
Map<String, Integer> prodIdCountMap = Maps.newHashMap();
// 获取产品列表
List<ProductOrderEntity> productOrderList = ordersEntity.getProductOrderList();
// 构造结果集
for (ProductOrderEntity productOrderEntity : productOrderList) {
// 产品ID
String prodId = productOrderEntity.getProductEntity().getId();
// 购买数量
Integer count = productOrderEntity.getCount();
prodIdCountMap.put(prodId, count);
}
return prodIdCountMap;
}
/**
* 将prodIdCountMap装入Context
* @param prodIdCountMap
* @param payModeEnum
* @param orderProcessContext
*/
private void setIntoContext(Map<String, Integer> prodIdCountMap, PayModeEnum payModeEnum, OrderProcessContext orderProcessContext) {
// 构造 订单插入请求
OrderInsertReq orderInsertReq = new OrderInsertReq();
// 插入prodIdCountMap
orderInsertReq.setProdIdCountMap(prodIdCountMap);
// 插入支付方式
orderInsertReq.setPayModeCode(payModeEnum.getCode());
orderProcessContext.getOrderProcessReq().setReqData(orderInsertReq);
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\component\datatransfer\ProdIdCountMapTransferComponent.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public BeetlGroupUtilConfiguration getBeetlGroupUtilConfiguration() {
BeetlGroupUtilConfiguration beetlGroupUtilConfiguration = new BeetlGroupUtilConfiguration();
ResourcePatternResolver patternResolver = ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader());
try {
// WebAppResourceLoader 配置root路径是关键
WebAppResourceLoader webAppResourceLoader = new WebAppResourceLoader(patternResolver.getResource("classpath:/templates").getFile().getPath());
beetlGroupUtilConfiguration.setResourceLoader(webAppResourceLoader);
} catch (IOException e) {
e.printStackTrace();
}
//读取配置文件信息
return beetlGroupUtilConfiguration;
}
@Bean(name = "beetlViewResolver")
public BeetlSpringViewResolver getBeetlSpringViewResolver(@Qualifier("beetlConfig") BeetlGroupUtilConfiguration beetlGroupUtilConfiguration) {
BeetlSpringViewResolver beetlSpringViewResolver = new BeetlSpringViewResolver();
beetlSpringViewResolver.setContentType("text/html;charset=UTF-8");
beetlSpringViewResolver.setOrder(0);
beetlSpringViewResolver.setConfig(beetlGroupUtilConfiguration);
return beetlSpringViewResolver;
}
//配置包扫描
@Bean(name = "beetlSqlScannerConfigurer")
public BeetlSqlScannerConfigurer getBeetlSqlScannerConfigurer() {
BeetlSqlScannerConfigurer conf = new BeetlSqlScannerConfigurer();
conf.setBasePackage("com.forezp.dao");
conf.setDaoSuffix("Dao");
conf.setSqlManagerFactoryBeanName("sqlManagerFactoryBean");
return conf;
}
@Bean(name = "sqlManagerFactoryBean")
@Primary
public SqlManagerFactoryBean getSqlManagerFactoryBean(@Qualifier("datasource") DataSource datasource) {
SqlManagerFactoryBean factory = new SqlManagerFactoryBean();
BeetlSqlDataSource source = new BeetlSqlDataSource();
source.setMasterSource(datasource);
factory.setCs(source);
factory.setDbStyle(new MySqlStyle());
factory.setInterceptors(new Interceptor[]{new DebugInterceptor()});
|
factory.setNc(new UnderlinedNameConversion());//开启驼峰
factory.setSqlLoader(new ClasspathLoader("/sql"));//sql文件路径
return factory;
}
//配置数据库
@Bean(name = "datasource")
public DataSource getDataSource() {
return DataSourceBuilder.create().url("jdbc:mysql://127.0.0.1:3306/test").username("root").password("123456").build();
}
//开启事务
@Bean(name = "txManager")
public DataSourceTransactionManager getDataSourceTransactionManager(@Qualifier("datasource") DataSource datasource) {
DataSourceTransactionManager dsm = new DataSourceTransactionManager();
dsm.setDataSource(datasource);
return dsm;
}
}
|
repos\SpringBootLearning-master\springboot-beatlsql\src\main\java\com\forezp\SpringbootBeatlsqlApplication.java
| 2
|
请完成以下Java代码
|
public void setR_RequestProcessor_Route_ID (int R_RequestProcessor_Route_ID)
{
if (R_RequestProcessor_Route_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_RequestProcessor_Route_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_RequestProcessor_Route_ID, Integer.valueOf(R_RequestProcessor_Route_ID));
}
/** Get Request Routing.
@return Automatic routing of requests
*/
public int getR_RequestProcessor_Route_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestProcessor_Route_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();
|
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getSeqNo()));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_RequestProcessor_Route.java
| 1
|
请完成以下Java代码
|
public static void main(String[] args) {
try {
generateTxtFromPDF(PDF);
generatePDFFromTxt(TXT);
} catch (IOException | DocumentException e) {
e.printStackTrace();
}
}
private static void generateTxtFromPDF(String filename) throws IOException {
File f = new File(filename);
String parsedText;
PDFParser parser = new PDFParser(new RandomAccessFile(f, "r"));
parser.parse();
COSDocument cosDoc = parser.getDocument();
PDFTextStripper pdfStripper = new PDFTextStripper();
PDDocument pdDoc = new PDDocument(cosDoc);
parsedText = pdfStripper.getText(pdDoc);
if (cosDoc != null)
cosDoc.close();
if (pdDoc != null)
pdDoc.close();
PrintWriter pw = new PrintWriter("src/output/pdf.txt");
pw.print(parsedText);
pw.close();
}
private static void generatePDFFromTxt(String filename) throws IOException, DocumentException {
Document pdfDoc = new Document(PageSize.A4);
PdfWriter.getInstance(pdfDoc, new FileOutputStream("src/output/txt.pdf"))
.setPdfVersion(PdfWriter.PDF_VERSION_1_7);
pdfDoc.open();
Font myfont = new Font();
|
myfont.setStyle(Font.NORMAL);
myfont.setSize(11);
pdfDoc.add(new Paragraph("\n"));
BufferedReader br = new BufferedReader(new FileReader(filename));
String strLine;
while ((strLine = br.readLine()) != null) {
Paragraph para = new Paragraph(strLine + "\n", myfont);
para.setAlignment(Element.ALIGN_JUSTIFIED);
pdfDoc.add(para);
}
pdfDoc.close();
br.close();
}
}
|
repos\tutorials-master\text-processing-libraries-modules\pdf\src\main\java\com\baeldung\pdf\PDF2TextExample.java
| 1
|
请完成以下Java代码
|
private ImmutableList<JsonRawMaterialsIssueLine> getLines(final ManufacturingJob job, final @NonNull WFActivityId wfActivityId, final @NonNull JsonOpts jsonOpts)
{
return job.getActivityById(wfActivityId)
.getRawMaterialsIssueAssumingNotNull()
.getLines().stream()
.map(line -> toJson(line, jsonOpts))
.collect(ImmutableList.toImmutableList());
}
private JsonRawMaterialsIssueLine toJson(final @NonNull RawMaterialsIssueLine line, final @NonNull JsonOpts jsonOpts)
{
return JsonRawMaterialsIssueLine.builderFrom(line, jsonOpts)
.hazardSymbols(getJsonHazardSymbols(line.getProductId(), jsonOpts.getAdLanguage()))
.allergens(getJsonAllergens(line.getProductId(), jsonOpts.getAdLanguage()))
.build();
}
private ImmutableList<JsonHazardSymbol> getJsonHazardSymbols(final @NonNull ProductId productId, final String adLanguage)
{
return productHazardSymbolService.getHazardSymbolsByProductId(productId)
.stream()
.map(hazardSymbol -> JsonHazardSymbol.of(hazardSymbol, adLanguage))
.collect(ImmutableList.toImmutableList());
}
private ImmutableList<JsonAllergen> getJsonAllergens(final @NonNull ProductId productId, final String adLanguage)
{
|
return productAllergensService.getAllergensByProductId(productId)
.stream()
.map(allergen -> JsonAllergen.of(allergen, adLanguage))
.collect(ImmutableList.toImmutableList());
}
private JsonRejectReasonsList getJsonRejectReasonsList(final @NonNull JsonOpts jsonOpts)
{
return JsonRejectReasonsList.of(adReferenceService.getRefListById(QtyRejectedReasonCode.REFERENCE_ID), jsonOpts);
}
@Override
public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity wfActivity)
{
return wfActivity.getStatus();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\activity_handlers\issue\RawMaterialsIssueActivityHandler.java
| 1
|
请完成以下Java代码
|
public class IntermediateCatchTimerEventActivityBehavior extends IntermediateCatchEventActivityBehavior {
private static final long serialVersionUID = 1L;
protected TimerEventDefinition timerEventDefinition;
public IntermediateCatchTimerEventActivityBehavior(TimerEventDefinition timerEventDefinition) {
this.timerEventDefinition = timerEventDefinition;
}
@Override
public void execute(DelegateExecution execution) {
// end date should be ignored for intermediate timer events.
FlowElement currentFlowElement = execution.getCurrentFlowElement();
TimerJobEntity timerJob = TimerUtil.createTimerEntityForTimerEventDefinition(timerEventDefinition, currentFlowElement,
false, (ExecutionEntity) execution, TriggerTimerEventJobHandler.TYPE,
TimerEventHandler.createConfiguration(execution.getCurrentActivityId(), null, timerEventDefinition.getCalendarName()));
if (timerJob != null) {
CommandContextUtil.getTimerJobService().scheduleTimerJob(timerJob);
}
|
}
@Override
public void eventCancelledByEventGateway(DelegateExecution execution) {
JobService jobService = CommandContextUtil.getJobService();
List<JobEntity> jobEntities = jobService.findJobsByExecutionId(execution.getId());
for (JobEntity jobEntity : jobEntities) { // Should be only one
jobService.deleteJob(jobEntity);
}
CommandContextUtil.getExecutionEntityManager().deleteExecutionAndRelatedData((ExecutionEntity) execution,
DeleteReason.EVENT_BASED_GATEWAY_CANCEL, false);
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\behavior\IntermediateCatchTimerEventActivityBehavior.java
| 1
|
请完成以下Java代码
|
public static boolean isNumeric(String str) {
if (StringUtils.isBlank(str)) {
return false;
} else {
return str.matches("\\d*");
}
}
/**
* 计算采用utf-8编码方式时字符串所占字节数
*
* @param content
* @return
*/
public static int getByteSize(String content) {
int size = 0;
if (null != content) {
try {
// 汉字采用utf-8编码时占3个字节
size = content.getBytes("utf-8").length;
} catch (UnsupportedEncodingException e) {
LOG.error(e);
}
}
return size;
}
/**
* 函数功能说明 : 截取字符串拼接in查询参数. 修改者名字: 修改日期: 修改内容:
*
* @参数: @param ids
* @参数: @return
* @return String
* @throws
*/
public static List<String> getInParam(String param) {
boolean flag = param.contains(",");
List<String> list = new ArrayList<String>();
if (flag) {
|
list = Arrays.asList(param.split(","));
} else {
list.add(param);
}
return list;
}
/**
* 判断对象是否为空
*
* @param obj
* @return
*/
public static boolean isNotNull(Object obj) {
if (obj != null && obj.toString() != null && !"".equals(obj.toString().trim())) {
return true;
} else {
return false;
}
}
}
|
repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\utils\StringUtil.java
| 1
|
请完成以下Java代码
|
public class URLDemo {
private final Logger log = LoggerFactory.getLogger(URLDemo.class);
String URLSTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
// parsed locator
String URLPROTOCOL = "https";
// final static String URLAUTHORITY = "wordpress.org:443";
String URLHOST = "wordpress.org";
String URLPATH = "/support/topic/page-jumps-within-wordpress/";
// final static String URLFILENAME = "/support/topic/page-jumps-within-wordpress/?replies=3";
// final static int URLPORT = 443;
int URLDEFAULTPORT = 443;
String URLQUERY = "replies=3";
String URLREFERENCE = "post-2278484";
String URLCOMPOUND = URLPROTOCOL + "://" + URLHOST + ":" + URLDEFAULTPORT + URLPATH + "?" + URLQUERY + "#" + URLREFERENCE;
URL url;
URLConnection urlConnection = null;
HttpURLConnection connection = null;
BufferedReader in = null;
String urlContent = "";
public String testURL(String urlString) throws IOException, IllegalArgumentException, URISyntaxException {
String urlStringCont = "";
// comment the if clause if experiment with URL
/*if (!URLSTRING.equals(urlString)) {
throw new IllegalArgumentException("URL String argument is not proper: " + urlString);
}*/
// creating URL object
url = new URI(urlString).toURL();
// get URL connection
urlConnection = url.openConnection();
connection = null;
// we can check, if connection is proper type
if (urlConnection instanceof HttpURLConnection) {
connection = (HttpURLConnection) urlConnection;
} else {
log.info("Please enter an HTTP URL");
throw new IOException("HTTP URL is not correct");
|
}
// we can check response code (200 OK is expected)
log.info(connection.getResponseCode() + " " + connection.getResponseMessage());
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String current;
while ((current = in.readLine()) != null) {
urlStringCont += current;
}
return urlStringCont;
}
public static void main(String[] args) throws Exception {
URLDemo demo = new URLDemo();
String content = demo.testURL(demo.URLCOMPOUND);
demo.log.info(content);
}
}
|
repos\tutorials-master\core-java-modules\core-java-networking-5\src\main\java\com\baeldung\networking\uriurl\URLDemo.java
| 1
|
请完成以下Java代码
|
public List<I_C_DunningLevel> getC_DunningLevels()
{
return C_DunningLevels;
}
public void setC_DunningLevels(List<I_C_DunningLevel> c_DunningLevels)
{
C_DunningLevels = c_DunningLevels;
}
@Override
public boolean isActive()
{
return active;
}
public void setActive(boolean active)
{
this.active = active;
}
@Override
public boolean isApplyClientSecurity()
{
return applyClientSecurity;
}
public void setApplyClientSecurity(boolean applyClientSecurity)
{
this.applyClientSecurity = applyClientSecurity;
}
@Override
public Boolean getProcessed()
{
return processed;
}
|
public void setProcessed(Boolean processed)
{
this.processed = processed;
}
@Override
public Boolean getWriteOff()
{
return writeOff;
}
public void setWriteOff(Boolean writeOff)
{
this.writeOff = writeOff;
}
@Override
public String getAdditionalWhere()
{
return additionalWhere;
}
public void setAdditionalWhere(String additionalWhere)
{
this.additionalWhere = additionalWhere;
}
@Override
public ApplyAccessFilter getApplyAccessFilter()
{
return applyAccessFilter;
}
public void setApplyAccessFilter(ApplyAccessFilter applyAccessFilter)
{
this.applyAccessFilter = applyAccessFilter;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunningCandidateQuery.java
| 1
|
请完成以下Java代码
|
public class CompositeConnectionListener implements ConnectionListener {
private List<ConnectionListener> delegates = new CopyOnWriteArrayList<>();
@Override
public void onCreate(@Nullable Connection connection) {
this.delegates.forEach(delegate -> delegate.onCreate(connection));
}
@Override
public void onClose(Connection connection) {
this.delegates.forEach(delegate -> delegate.onClose(connection));
}
@Override
public void onShutDown(ShutdownSignalException signal) {
this.delegates.forEach(delegate -> delegate.onShutDown(signal));
}
@Override
public void onFailed(Exception exception) {
|
this.delegates.forEach(delegate -> delegate.onFailed(exception));
}
public void setDelegates(List<? extends ConnectionListener> delegates) {
this.delegates = new ArrayList<>(delegates);
}
public void addDelegate(ConnectionListener delegate) {
this.delegates.add(delegate);
}
public boolean removeDelegate(ConnectionListener delegate) {
return this.delegates.remove(delegate);
}
public void clearDelegates() {
this.delegates.clear();
}
}
|
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\connection\CompositeConnectionListener.java
| 1
|
请完成以下Java代码
|
public class ArmoredCar extends Car implements Floatable, Flyable{
private int bulletProofWindows;
private String model;
public void remoteStartCar() {
// this vehicle can be started by using a remote control
}
public String registerModel() {
return model;
}
public String getAValue() {
return super.model; // returns value of model defined in base class Car
// return this.model; // will return value of model defined in ArmoredCar
// return model; // will return value of model defined in ArmoredCar
}
public static String msg() {
// return super.msg(); // this won't compile.
return "ArmoredCar";
}
|
@Override
public void floatOnWater() {
System.out.println("I can float!");
}
@Override
public void fly() {
System.out.println("I can fly!");
}
public void aMethod() {
// System.out.println(duration); // Won't compile
System.out.println(Floatable.duration); // outputs 10
System.out.println(Flyable.duration); // outputs 20
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-oop-inheritance-2\src\main\java\com\baeldung\inheritance\ArmoredCar.java
| 1
|
请完成以下Java代码
|
public class MSchedulerRecipient extends X_AD_SchedulerRecipient
{
/**
*
*/
private static final long serialVersionUID = -6521993049769786393L;
/**
* Standard Constructor
* @param ctx context
* @param AD_SchedulerRecipient_ID id
* @param trxName transaction
*/
public MSchedulerRecipient (Properties ctx, int AD_SchedulerRecipient_ID,
String trxName)
{
|
super (ctx, AD_SchedulerRecipient_ID, trxName);
} // MSchedulerRecipient
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MSchedulerRecipient (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MSchedulerRecipient
} // MSchedulerRecipient
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MSchedulerRecipient.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.