instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public PHAND1 getPHAND1() {
return phand1;
}
/**
* Sets the value of the phand1 property.
*
* @param value
* allowed object is
* {@link PHAND1 }
*
*/
public void setPHAND1(PHAND1 value) {
this.phand1 = value;
}
/**
* Gets the value of the detail property.
*
* @return
* possible object is
* {@link DETAILXbest }
*
*/
public DETAILXbest getDETAIL() {
|
return detail;
}
/**
* Sets the value of the detail property.
*
* @param value
* allowed object is
* {@link DETAILXbest }
*
*/
public void setDETAIL(DETAILXbest value) {
this.detail = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_orders\de\metas\edi\esb\jaxb\stepcom\orders\PPACK1.java
| 2
|
请完成以下Java代码
|
public Sale post(@RequestBody Sale sale) {
return saleRepo.insert(sale);
}
@GetMapping("/sale")
public Optional<Sale> getSale(SaleId id) {
return saleRepo.findBySaleId(id);
}
@PostMapping("/company")
public Company post(@RequestBody Company company) {
return companyRepo.insert(company);
}
@PutMapping("/company")
public Company put(@RequestBody Company company) {
return companyRepo.save(company);
}
@GetMapping("/company/{id}")
public Optional<Company> getCompany(@PathVariable String id) {
return companyRepo.findById(id);
}
@PostMapping("/customer")
public Customer post(@RequestBody Customer customer) {
|
return customerRepo.insert(customer);
}
@GetMapping("/customer/{id}")
public Optional<Customer> getCustomer(@PathVariable String id) {
return customerRepo.findById(id);
}
@PostMapping("/asset")
public Asset post(@RequestBody Asset asset) {
return assetRepo.insert(asset);
}
@GetMapping("/asset/{id}")
public Optional<Asset> getAsset(@PathVariable String id) {
return assetRepo.findById(id);
}
}
|
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-2\src\main\java\com\baeldung\boot\unique\field\web\UniqueFieldController.java
| 1
|
请完成以下Java代码
|
public void setQuery (String Query)
{
set_Value (COLUMNNAME_Query, Query);
}
/** Get Query.
@return SQL
*/
public String getQuery ()
{
return (String)get_Value(COLUMNNAME_Query);
}
/** Set Search Type.
@param SearchType
Which kind of search is used (Query or Table)
*/
public void setSearchType (String SearchType)
{
set_Value (COLUMNNAME_SearchType, SearchType);
}
/** Get Search Type.
@return Which kind of search is used (Query or Table)
*/
public String getSearchType ()
{
return (String)get_Value(COLUMNNAME_SearchType);
|
}
/** Set Transaction Code.
@param TransactionCode
The transaction code represents the search definition
*/
public void setTransactionCode (String TransactionCode)
{
set_Value (COLUMNNAME_TransactionCode, TransactionCode);
}
/** Get Transaction Code.
@return The transaction code represents the search definition
*/
public String getTransactionCode ()
{
return (String)get_Value(COLUMNNAME_TransactionCode);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_SearchDefinition.java
| 1
|
请完成以下Java代码
|
public final class ImportGroup<ImportGroupKey, ImportRecordType>
{
public static <ImportGroupKey, ImportRecordType> ImportGroup<ImportGroupKey, ImportRecordType> newInstance(@NonNull final ImportGroupKey groupKey)
{
return new ImportGroup<>(groupKey);
}
@Getter
private final ImportGroupKey groupKey;
private final ArrayList<ImportRecordType> importRecords = new ArrayList<>();
private ImportGroup(@NonNull final ImportGroupKey groupKey)
{
this.groupKey = groupKey;
}
public void addImportRecord(@NonNull final ImportRecordType importRecord)
{
importRecords.add(importRecord);
}
public ImmutableList<ImportRecordType> getImportRecords()
{
return ImmutableList.copyOf(importRecords);
|
}
public boolean isEmpty()
{
return importRecords.isEmpty();
}
public int size() {return importRecords.size();}
public Set<Integer> getImportRecordIds()
{
return importRecords.stream()
.map(InterfaceWrapperHelper::getId)
.collect(ImmutableSet.toImmutableSet());
}
public void markImportRecordsAsStale()
{
importRecords.forEach(InterfaceWrapperHelper::markStaled);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\processing\ImportGroup.java
| 1
|
请完成以下Java代码
|
private void validate()
{
final Set<String> missingMandatoryFields = new HashSet<>();
final int fieldCount = getFieldCount();
for (int fieldIndex = 0; fieldIndex < fieldCount; fieldIndex++)
{
final GridField gridField = getField(fieldIndex);
if (!gridField.validateValue())
{
missingMandatoryFields.add(gridField.getHeader());
}
// Check for Range
final GridField gridFieldTo = getFieldTo(fieldIndex);
if (gridFieldTo != null && !gridFieldTo.validateValue())
{
missingMandatoryFields.add(gridField.getHeader());
} // range field
} // field loop
if (!missingMandatoryFields.isEmpty())
{
throw new FillMandatoryException(true, missingMandatoryFields);
}
}
public List<ProcessInfoParameter> createProcessInfoParameters()
{
validate();
final List<ProcessInfoParameter> params = new ArrayList<>();
final int fieldCount = getFieldCount();
for (int fieldIndex = 0; fieldIndex < fieldCount; fieldIndex++)
{
final ProcessInfoParameter param = createProcessInfoParameter(fieldIndex);
if (param == null)
{
continue;
}
params.add(param);
} // for every parameter
return params;
}
private ProcessInfoParameter createProcessInfoParameter(final int fieldIndex)
{
final GridField gridField = getField(fieldIndex);
final String columnName = gridField.getColumnName();
Object value = gridField.getValue();
final String displayValue = displayValueProvider.getDisplayValue(gridField);
final GridField gridFieldTo = getFieldTo(fieldIndex);
Object valueTo;
final String displayValueTo;
if (gridFieldTo != null)
{
|
valueTo = gridFieldTo.getValue();
displayValueTo = displayValueProvider.getDisplayValue(gridFieldTo);
}
else
{
valueTo = null;
displayValueTo = null;
}
if (value == null && valueTo == null)
{
return null;
}
//
// FIXME: legacy: convert Boolean to String because some of the JavaProcess implementations are checking boolean parametes as:
// boolean value = "Y".equals(ProcessInfoParameter.getParameter());
if (value instanceof Boolean)
{
value = DisplayType.toBooleanString((Boolean)value);
}
if (valueTo instanceof Boolean)
{
valueTo = DisplayType.toBooleanString((Boolean)valueTo);
}
return new ProcessInfoParameter(columnName, value, valueTo, displayValue, displayValueTo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ui\ProcessParameterPanelModel.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class HUDescriptorService
{
private final IHUContextFactory huContextFactory = Services.get(IHUContextFactory.class);
private final IAttributeSetInstanceBL attributeSetInstanceBL = Services.get(IAttributeSetInstanceBL.class);
@NonNull
public ImmutableList<HUDescriptor> createHuDescriptors(@NonNull final I_M_HU huRecord)
{
return createHuDescriptors(huRecord, false);
}
public ImmutableList<HUDescriptor> createHuDescriptors(
@NonNull final I_M_HU huRecord,
final boolean deleted)
{
final IMutableHUContext huContext = huContextFactory.createMutableHUContext();
final IHUStorage storage = huContext.getHUStorageFactory().getStorage(huRecord);
// Important note: we could have the AttributesKey without making an ASI, but we need the ASI-ID for display reasons in the material dispo window.
final IPair<AttributesKey, AttributeSetInstanceId> attributesKeyAndAsiId = createAttributesKeyAndAsiId(huContext, huRecord);
final AttributesKey attributesKey = attributesKeyAndAsiId.getLeft();
final AttributeSetInstanceId asiId = attributesKeyAndAsiId.getRight();
final ImmutableList.Builder<HUDescriptor> descriptors = ImmutableList.builder();
for (final IHUProductStorage productStorage : storage.getProductStorages())
{
final ProductDescriptor productDescriptor = ProductDescriptor.forProductAndAttributes(
productStorage.getProductId().getRepoId(),
attributesKey,
asiId.getRepoId());
final BigDecimal quantity = productStorage.getQtyInStockingUOM()
.toBigDecimal()
.max(BigDecimal.ZERO); // guard against the quantity being e.g. -0.001 for whatever reason
final HUDescriptor descriptor = HUDescriptor.builder()
.huId(huRecord.getM_HU_ID())
.productDescriptor(productDescriptor)
.quantity(deleted ? BigDecimal.ZERO : quantity)
.build();
descriptors.add(descriptor);
}
return descriptors.build();
}
|
private IPair<AttributesKey, AttributeSetInstanceId> createAttributesKeyAndAsiId(
@NonNull final IHUContext huContext,
@NonNull final I_M_HU hu)
{
final IAttributeSet attributeStorage = huContext.getHUAttributeStorageFactory().getAttributeStorage(hu);
// we don't want all the non-storage-relevant attributes to pollute the ASI we will display in the material disposition window
final IAttributeSet storageRelevantSubSet = ImmutableAttributeSet.createSubSet(attributeStorage, I_M_Attribute::isStorageRelevant);
final I_M_AttributeSetInstance asi = attributeSetInstanceBL.createASIFromAttributeSet(storageRelevantSubSet);
final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(asi.getM_AttributeSetInstance_ID());
final AttributesKey attributesKey = AttributesKeys
.createAttributesKeyFromASIStorageAttributes(asiId)
.orElse(AttributesKey.NONE);
return ImmutablePair.of(attributesKey, asiId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\material\interceptor\transactionevent\HUDescriptorService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getLOCATIONQUAL() {
return locationqual;
}
/**
* Sets the value of the locationqual property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLOCATIONQUAL(String value) {
this.locationqual = value;
}
/**
* Gets the value of the locationcode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLOCATIONCODE() {
return locationcode;
}
/**
* Sets the value of the locationcode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLOCATIONCODE(String value) {
this.locationcode = value;
}
/**
* Gets the value of the locationname property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLOCATIONNAME() {
return locationname;
}
/**
* Sets the value of the locationname property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLOCATIONNAME(String value) {
this.locationname = value;
}
/**
* Gets the value of the date property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDATE() {
return date;
}
/**
* Sets the value of the date property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDATE(String value) {
|
this.date = value;
}
/**
* Gets the value of the quantity property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getQUANTITY() {
return quantity;
}
/**
* Sets the value of the quantity property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setQUANTITY(String value) {
this.quantity = value;
}
/**
* Gets the value of the quantitymeasureunit property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getQUANTITYMEASUREUNIT() {
return quantitymeasureunit;
}
/**
* Sets the value of the quantitymeasureunit property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setQUANTITYMEASUREUNIT(String value) {
this.quantitymeasureunit = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DPLAC1.java
| 2
|
请完成以下Java代码
|
public static final class Part
{
private final String name;
private final int index;
private final boolean mandatory;
private Integer _hashcode;
private Part(final String name, final int index, final boolean mandatory)
{
super();
this.name = name;
this.index = index;
this.mandatory = mandatory;
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append(name);
if (mandatory)
{
sb.append("!");
}
return sb.toString();
}
@Override
public int hashCode()
{
if (_hashcode == null)
{
_hashcode = new HashcodeBuilder()
.append(name)
.append(index)
.append(mandatory)
.toHashcode();
}
return _hashcode;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
final Part other = EqualsBuilder.getOther(this, obj);
if (other == null)
{
|
return false;
}
return new EqualsBuilder()
.append(name, other.name)
.append(index, other.index)
.append(mandatory, other.mandatory)
.isEqual();
}
public String getName()
{
return name;
}
public boolean isMandatory()
{
return mandatory;
}
public int getIndex()
{
return index;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\LocationCaptureSequence.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private TbTimeSeriesSubscription createTsSub(EntityData entityData, int subIdx, boolean latestValues, long startTs, long endTs, Map<String, Long> keyStates) {
return createTsSub(entityData, subIdx, latestValues, startTs, endTs, keyStates, latestValues);
}
private TbTimeSeriesSubscription createTsSub(EntityData entityData, int subIdx, boolean latestValues, long startTs, long endTs, Map<String, Long> keyStates, boolean resultToLatestValues) {
log.trace("[{}][{}][{}] Creating time-series subscription for [{}] with keys: {}", serviceId, cmdId, subIdx, entityData.getEntityId(), keyStates);
return TbTimeSeriesSubscription.builder()
.serviceId(serviceId)
.sessionId(sessionRef.getSessionId())
.subscriptionId(subIdx)
.tenantId(sessionRef.getSecurityCtx().getTenantId())
.entityId(entityData.getEntityId())
.updateProcessor((sub, subscriptionUpdate) -> sendWsMsg(sub.getSessionId(), subscriptionUpdate, EntityKeyType.TIME_SERIES, resultToLatestValues))
.queryTs(createdTime)
.allKeys(false)
.keyStates(keyStates)
.latestValues(latestValues)
.startTime(startTs)
.endTime(endTs)
.build();
}
private void sendWsMsg(String sessionId, TelemetrySubscriptionUpdate subscriptionUpdate, EntityKeyType keyType) {
sendWsMsg(sessionId, subscriptionUpdate, keyType, true);
}
private Map<String, Long> buildKeyStats(EntityData entityData, EntityKeyType keysType, List<EntityKey> subKeys, boolean latestValues) {
Map<String, Long> keyStates = new HashMap<>();
|
subKeys.forEach(key -> keyStates.put(key.getKey(), 0L));
if (latestValues && entityData.getLatest() != null) {
Map<String, TsValue> currentValues = entityData.getLatest().get(keysType);
if (currentValues != null) {
currentValues.forEach((k, v) -> {
if (subKeys.contains(new EntityKey(keysType, k))) {
log.trace("[{}][{}] Updating key: {} with ts: {}", serviceId, cmdId, k, v.getTs());
keyStates.put(k, v.getTs());
}
});
}
}
return keyStates;
}
abstract void sendWsMsg(String sessionId, TelemetrySubscriptionUpdate subscriptionUpdate, EntityKeyType keyType, boolean resultToLatestValues);
protected abstract Aggregation getCurrentAggregation();
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\subscription\TbAbstractDataSubCtx.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class DistributionJobAbortCommand
{
private final ITrxManager trxManager = Services.get(ITrxManager.class);
private final DDOrderService ddOrderService;
private final DistributionJobHUReservationService distributionJobHUReservationService;
private final ImmutableList<DistributionJob> jobs;
@Builder
private DistributionJobAbortCommand(
@NonNull final DDOrderService ddOrderService,
@NonNull final DistributionJobHUReservationService distributionJobHUReservationService,
@NonNull @Singular final List<DistributionJob> jobs)
{
this.ddOrderService = ddOrderService;
this.distributionJobHUReservationService = distributionJobHUReservationService;
this.jobs = ImmutableList.copyOf(jobs);
}
public static class DistributionJobAbortCommandBuilder
{
public void execute() {build().execute();}
}
public void execute()
{
if (jobs.isEmpty())
{
return;
}
|
trxManager.runInThreadInheritedTrx(this::executeInTrx);
}
private void executeInTrx()
{
for (final DistributionJob job : jobs)
{
abort(job);
}
}
private void abort(final DistributionJob job)
{
distributionJobHUReservationService.releaseAllReservations(job);
ddOrderService.unassignFromResponsible(job.getDdOrderId());
ddOrderService.removeAllNotStartedSchedules(job.getDdOrderId());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\service\commands\abort_job\DistributionJobAbortCommand.java
| 2
|
请完成以下Java代码
|
public class RedirectServerAuthenticationSuccessHandler implements ServerAuthenticationSuccessHandler {
private URI location = URI.create("/");
private ServerRedirectStrategy redirectStrategy = new DefaultServerRedirectStrategy();
private ServerRequestCache requestCache = new WebSessionServerRequestCache();
/**
* Creates a new instance with location of "/"
*/
public RedirectServerAuthenticationSuccessHandler() {
}
/**
* Creates a new instance with the specified location
* @param location the location to redirect if the no request is cached in
* {@link #setRequestCache(ServerRequestCache)}
*/
public RedirectServerAuthenticationSuccessHandler(String location) {
this.location = URI.create(location);
}
/**
* Sets the {@link ServerRequestCache} used to redirect to. Default is
* {@link WebSessionServerRequestCache}.
* @param requestCache the cache to use
*/
public void setRequestCache(ServerRequestCache requestCache) {
Assert.notNull(requestCache, "requestCache cannot be null");
this.requestCache = requestCache;
}
@Override
|
public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
ServerWebExchange exchange = webFilterExchange.getExchange();
return this.requestCache.getRedirectUri(exchange)
.defaultIfEmpty(this.location)
.flatMap((location) -> this.redirectStrategy.sendRedirect(exchange, location));
}
/**
* Where the user is redirected to upon authentication success
* @param location the location to redirect to. The default is "/"
*/
public void setLocation(URI location) {
Assert.notNull(location, "location cannot be null");
this.location = location;
}
/**
* The RedirectStrategy to use.
* @param redirectStrategy the strategy to use. Default is DefaultRedirectStrategy.
*/
public void setRedirectStrategy(ServerRedirectStrategy redirectStrategy) {
Assert.notNull(redirectStrategy, "redirectStrategy cannot be null");
this.redirectStrategy = redirectStrategy;
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\authentication\RedirectServerAuthenticationSuccessHandler.java
| 1
|
请完成以下Java代码
|
public String toString() {
return this.value;
}
/**
* Factory method to create a new {@link EndpointId} of the specified value.
* @param value the endpoint ID value
* @return an {@link EndpointId} instance
*/
public static EndpointId of(String value) {
return new EndpointId(value);
}
/**
* Factory method to create a new {@link EndpointId} of the specified value. This
* variant will respect the {@code management.endpoints.migrate-legacy-names} property
* if it has been set in the {@link Environment}.
* @param environment the Spring environment
* @param value the endpoint ID value
* @return an {@link EndpointId} instance
* @since 2.2.0
*/
public static EndpointId of(Environment environment, String value) {
Assert.notNull(environment, "'environment' must not be null");
return new EndpointId(migrateLegacyId(environment, value));
}
private static String migrateLegacyId(Environment environment, String value) {
if (environment.getProperty(MIGRATE_LEGACY_NAMES_PROPERTY, Boolean.class, false)) {
|
return value.replaceAll("[-.]+", "");
}
return value;
}
/**
* Factory method to create a new {@link EndpointId} from a property value. More
* lenient than {@link #of(String)} to allow for common "relaxed" property variants.
* @param value the property value to convert
* @return an {@link EndpointId} instance
*/
public static EndpointId fromPropertyValue(String value) {
return new EndpointId(value.replace("-", ""));
}
static void resetLoggedWarnings() {
loggedWarnings.clear();
}
private static void logWarning(String value) {
if (logger.isWarnEnabled() && loggedWarnings.add(value)) {
logger.warn("Endpoint ID '" + value + "' contains invalid characters, please migrate to a valid format.");
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\EndpointId.java
| 1
|
请完成以下Java代码
|
public class DataStreamAPI {
public static void main(String[] args) throws Exception {
// 创建执行环境
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// 从项目根目录下的data目录下的word.txt文件中读取数据
DataStreamSource<String> source = env.readTextFile("D:\\IdeaProjects\\ETFramework\\flink\\src\\main\\resources\\word.txt");
// 处理数据: 切分、转换
SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndOneDS = source
.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
@Override
public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
// 按空格切分
String[] words = value.split(" ");
for (String word : words) {
// 转换成二元组 (word,1)
Tuple2<String, Integer> wordsAndOne = Tuple2.of(word, 1);
// 通过采集器向下游发送数据
out.collect(wordsAndOne);
}
}
});
// 处理数据:分组
KeyedStream<Tuple2<String, Integer>, String> wordAndOneKS = wordAndOneDS.keyBy(
new KeySelector<Tuple2<String, Integer>, String>() {
@Override
public String getKey(Tuple2<String, Integer> value) throws Exception {
|
return value.f0;
}
}
);
// 处理数据:聚合
SingleOutputStreamOperator<Tuple2<String, Integer>> sumDS = wordAndOneKS.sum(1);
// 输出数据
sumDS.print();
// 执行
env.execute();
}
}
|
repos\springboot-demo-master\flink\src\main\java\com\et\flink\job\DataStreamAPI.java
| 1
|
请完成以下Java代码
|
public class VariableQueryParameterDto extends ConditionQueryParameterDto {
public VariableQueryParameterDto() {
}
public VariableQueryParameterDto(TaskQueryVariableValue variableValue) {
this.name = variableValue.getName();
this.operator = OPERATOR_NAME_MAP.get(variableValue.getOperator());
this.value = variableValue.getValue();
}
protected String name;
public String getName() {
return name;
|
}
public void setName(String name) {
this.name = name;
}
public Object resolveValue(ObjectMapper objectMapper) {
Object value = super.resolveValue(objectMapper);
if (value != null && Number.class.isAssignableFrom(value.getClass())) {
return Variables.numberValue((Number) value);
}
return value;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\VariableQueryParameterDto.java
| 1
|
请完成以下Java代码
|
protected void setParent(ScopeImpl parent) {
this.parent = parent;
}
protected void setIncomingTransitions(List<TransitionImpl> incomingTransitions) {
this.incomingTransitions = incomingTransitions;
}
// getters and setters //////////////////////////////////////////////////////
@Override
@SuppressWarnings("unchecked")
public List<PvmTransition> getOutgoingTransitions() {
return (List) outgoingTransitions;
}
public ActivityBehavior getActivityBehavior() {
return activityBehavior;
}
public void setActivityBehavior(ActivityBehavior activityBehavior) {
this.activityBehavior = activityBehavior;
}
@Override
public ScopeImpl getParent() {
return parent;
}
@Override
@SuppressWarnings("unchecked")
public List<PvmTransition> getIncomingTransitions() {
return (List) incomingTransitions;
}
public Map<String, Object> getVariables() {
return variables;
}
public void setVariables(Map<String, Object> variables) {
this.variables = variables;
}
public boolean isScope() {
return isScope;
}
public void setScope(boolean isScope) {
this.isScope = isScope;
}
@Override
public int getX() {
return x;
}
|
@Override
public void setX(int x) {
this.x = x;
}
@Override
public int getY() {
return y;
}
@Override
public void setY(int y) {
this.y = y;
}
@Override
public int getWidth() {
return width;
}
@Override
public void setWidth(int width) {
this.width = width;
}
@Override
public int getHeight() {
return height;
}
@Override
public void setHeight(int height) {
this.height = height;
}
@Override
public boolean isAsync() {
return isAsync;
}
public void setAsync(boolean isAsync) {
this.isAsync = isAsync;
}
@Override
public boolean isExclusive() {
return isExclusive;
}
public void setExclusive(boolean isExclusive) {
this.isExclusive = isExclusive;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\ActivityImpl.java
| 1
|
请完成以下Java代码
|
public ILockCommand setRecordByTableRecordId(final int tableId, final int recordId)
{
_recordsToLock.setRecordByTableRecordId(tableId, recordId);
return this;
}
@Override
public ILockCommand setRecordsBySelection(final Class<?> modelClass, final PInstanceId pinstanceId)
{
_recordsToLock.setRecordsBySelection(modelClass, pinstanceId);
return this;
}
@Override
public <T> ILockCommand setRecordsByFilter(final Class<T> clazz, final IQueryFilter<T> filters)
{
_recordsToLock.setRecordsByFilter(clazz, filters);
return this;
}
@Override
public <T> ILockCommand addRecordsByFilter(final Class<T> clazz, final IQueryFilter<T> filters)
{
_recordsToLock.addRecordsByFilter(clazz, filters);
return this;
}
@Override
public List<LockRecordsByFilter> getSelectionToLock_Filters()
{
return _recordsToLock.getSelection_Filters();
}
@Override
public final AdTableId getSelectionToLock_AD_Table_ID()
{
return _recordsToLock.getSelection_AD_Table_ID();
}
@Override
public final PInstanceId getSelectionToLock_AD_PInstance_ID()
{
return _recordsToLock.getSelection_PInstanceId();
}
|
@Override
public final Iterator<TableRecordReference> getRecordsToLockIterator()
{
return _recordsToLock.getRecordsIterator();
}
@Override
public LockCommand addRecordByModel(final Object model)
{
_recordsToLock.addRecordByModel(model);
return this;
}
@Override
public LockCommand addRecordsByModel(final Collection<?> models)
{
_recordsToLock.addRecordByModels(models);
return this;
}
@Override
public ILockCommand addRecord(@NonNull final TableRecordReference record)
{
_recordsToLock.addRecords(ImmutableSet.of(record));
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\LockCommand.java
| 1
|
请完成以下Java代码
|
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
handle(request, response, authentication);
HttpSession session = request.getSession(false);
if (session != null) {
session.setMaxInactiveInterval(30);
}
clearAuthenticationAttributes(request);
}
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
logger.debug("Response has already been committed. Unable to redirect to " + targetUrl);
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
protected String determineTargetUrl(Authentication authentication) {
return "/home.html";
}
|
protected void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
}
|
repos\tutorials-master\spring-web-modules\spring-static-resources\src\main\java\com\baeldung\security\MySimpleUrlAuthenticationSuccessHandler.java
| 1
|
请完成以下Java代码
|
private String getDescription(Object managedBean, String objectName) {
ManagedResource mr = managedBean.getClass().getAnnotation(ManagedResource.class);
return mr != null ? mr.description() : "";
}
private String getName(Object managedBean, String objectName) {
return managedBean == null ? null : managedBean.getClass().getName();
}
private static final class ManagedAttributeInfo {
private String key;
private String description;
private Method getter;
private Method setter;
private ManagedAttributeInfo(String key, String description) {
this.key = key;
this.description = description;
}
public String getKey() {
return key;
}
public String getDescription() {
return description;
}
public Method getGetter() {
return getter;
}
public void setGetter(Method getter) {
this.getter = getter;
}
public Method getSetter() {
return setter;
}
public void setSetter(Method setter) {
this.setter = setter;
}
|
@Override
public String toString() {
return "ManagedAttributeInfo: [" + key + " + getter: " + getter + ", setter: " + setter + "]";
}
}
private static final class ManagedOperationInfo {
private final String description;
private final Method operation;
private ManagedOperationInfo(String description, Method operation) {
this.description = description;
this.operation = operation;
}
public String getDescription() {
return description;
}
public Method getOperation() {
return operation;
}
@Override
public String toString() {
return "ManagedOperationInfo: [" + operation + "]";
}
}
private static final class MBeanAttributesAndOperations {
private Map<String, ManagedAttributeInfo> attributes;
private Set<ManagedOperationInfo> operations;
}
}
|
repos\flowable-engine-main\modules\flowable-jmx\src\main\java\org\flowable\management\jmx\MBeanInfoAssembler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class User {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String name;
private String about;
@Basic
@Temporal(TemporalType.DATE)
private Date lastModified;
public User() {
}
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getLastModified() {
return lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
|
public long getId() {
return id;
}
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
@Override
public String toString() {
return String.format("ID: %d\nName: %s\nLast Modified: %s\nAbout: %s\n", getId(), getName(), getLastModified(), getAbout());
}
}
|
repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\interceptors\entity\User.java
| 2
|
请完成以下Java代码
|
private DATEVExportFormatColumn toDATEVExportFormatColumn(final I_DATEV_ExportFormatColumn formatColumnPO,
final I_DATEV_ExportFormat exportFormatPO,
final POInfo exportLinePOInfo)
{
final AdColumnId adColumnId = AdColumnId.ofRepoId(formatColumnPO.getAD_Column_ID());
final int columnIndex = exportLinePOInfo.getColumnIndex(adColumnId);
final String columnName = exportLinePOInfo.getColumnName(columnIndex);
if (Check.isEmpty(columnName, true))
{
throw new AdempiereException("No column found for AD_Column_ID=" + adColumnId + " in " + exportLinePOInfo);
}
final DATEVExportFormatColumnBuilder columnBuilder = DATEVExportFormatColumn.builder()
.columnName(columnName)
.csvHeaderName(formatColumnPO.getName());
final int displayType = exportLinePOInfo.getColumnDisplayType(columnIndex);
if (DisplayType.isDate(displayType))
{
final String formatPatternStr = formatColumnPO.getFormatPattern();
if (!Check.isEmpty(formatPatternStr, true))
{
columnBuilder.dateFormatter(DateTimeFormatter.ofPattern(formatPatternStr));
}
}
else if (DisplayType.isNumeric(displayType))
{
columnBuilder.numberFormatter(extractNumberFormatter(formatColumnPO.getFormatPattern(), exportFormatPO));
}
return columnBuilder.build();
}
private static ThreadLocalDecimalFormatter extractNumberFormatter(final String formatPattern, final I_DATEV_ExportFormat formatPO)
{
final String formatPatternEffective = !Check.isEmpty(formatPattern, true) ? formatPattern : "#########.00####";
final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(Locale.getDefault(Locale.Category.FORMAT));
final String decimalSeparator = formatPO.getDecimalSeparator();
if (decimalSeparator != null && !decimalSeparator.isEmpty())
{
symbols.setDecimalSeparator(decimalSeparator.charAt(0));
}
final String groupingSeparator = formatPO.getNumberGroupingSeparator();
if (groupingSeparator != null && !groupingSeparator.isEmpty())
|
{
symbols.setGroupingSeparator(groupingSeparator.charAt(0));
}
return ThreadLocalDecimalFormatter.ofPattern(formatPatternEffective, symbols);
}
private static String extractCsvFieldDelimiter(final I_DATEV_ExportFormat formatPO)
{
String delimiter = formatPO.getCSVFieldDelimiter();
if (delimiter == null)
{
return "";
}
return delimiter
.replace("\\t", "\t")
.replace("\\r", "\r")
.replace("\\n", "\n");
}
private static String extractCsvFieldQuote(final I_DATEV_ExportFormat formatPO)
{
final String quote = formatPO.getCSVFieldQuote();
if (quote == null)
{
return "";
}
else if ("-".equals(quote))
{
return "";
}
else
{
return quote;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java\de\metas\datev\DATEVExportFormatRepository.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DimensionSpecGroup
{
public static DimensionSpecGroup EMPTY_GROUP = new DimensionSpecGroup(
() -> Services.get(IMsgBL.class).getTranslatableMsgText(DimensionConstants.MSG_NoneOrEmpty),
AttributesKey.NONE,
Optional.empty());
public static DimensionSpecGroup OTHER_GROUP = new DimensionSpecGroup(
() -> Services.get(IMsgBL.class).getTranslatableMsgText(AttributesKey.MSG_ATTRIBUTES_KEY_OTHER),
AttributesKey.OTHER,
Optional.empty());
/** Note: we use a supplier because we want to make sure that Services.get(IMsgBL.class) is not called before the system is ready for either production or unit test mode. */
@NonNull
Supplier<ITranslatableString> groupNameSupplier;
/**
* These {@code M_AttributeValue_ID}s belong to this group. Maybe empty, often has just one element.<br>
* Might later be abstracted away so that other kind of data (e.g. "BPartners") could also be mapped to a dimension group.
*/
@NonNull
AttributesKey attributesKey;
|
@NonNull
Optional<AttributeId> attributeId;
public boolean isEmptyGroup()
{
return AttributesKey.NONE.equals(attributesKey);
}
public boolean isOtherGroup()
{
return AttributesKey.OTHER.equals(attributesKey);
}
public ITranslatableString getGroupName()
{
return groupNameSupplier.get();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java\de\metas\dimension\DimensionSpecGroup.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class UserAuthTokenId implements RepoIdAware
{
@JsonCreator
@NonNull
public static UserAuthTokenId ofRepoId(final int repoId)
{
return new UserAuthTokenId(repoId);
}
@Nullable
public static UserAuthTokenId ofRepoIdOrNull(final int repoId)
{
if (repoId <= 0)
{
return null;
}
else
{
return ofRepoId(repoId);
}
}
public static int toRepoId(@Nullable final UserAuthTokenId id)
|
{
return id != null ? id.getRepoId() : -1;
}
int repoId;
private UserAuthTokenId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "AD_User_AuthToken_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\UserAuthTokenId.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class JsonCountRequest
{
@NonNull WFProcessId wfProcessId;
@NonNull InventoryLineId lineId;
@Nullable ScannedCode scannedCode;
@Nullable HuId huId;
@NonNull BigDecimal qtyCount;
boolean lineCountingDone;
@Nullable List<Attribute> attributes;
@JsonIgnore
@NonNull
public Map<AttributeCode, String> getAttributesAsMap()
{
if (attributes == null || attributes.isEmpty())
{
return ImmutableMap.of();
}
final HashMap<AttributeCode, String> result = new HashMap<>();
for (final Attribute attribute : attributes)
{
result.put(attribute.getCode(), attribute.getValue());
}
return result;
}
|
//
//
//
//
//
@Value
@Builder
@Jacksonized
public static class Attribute
{
@NonNull AttributeCode code;
@Nullable String value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\rest_api\json\JsonCountRequest.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
// 设置 securityManager
shiroFilterFactoryBean.setSecurityManager(securityManager);
// 在 Shiro过滤器链上加入 JWTFilter
LinkedHashMap<String, Filter> filters = new LinkedHashMap<>();
filters.put("jwt", new JWTFilter());
shiroFilterFactoryBean.setFilters(filters);
LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
// 所有请求都要经过 jwt过滤器
filterChainDefinitionMap.put("/**", "jwt");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
|
@Bean
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 配置 SecurityManager,并注入 shiroRealm
securityManager.setRealm(shiroRealm());
return securityManager;
}
@Bean
public ShiroRealm shiroRealm() {
// 配置 Realm
return new ShiroRealm();
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
}
|
repos\SpringAll-master\62.Spring-Boot-Shiro-JWT\src\main\java\com\example\demo\authentication\ShiroConfig.java
| 2
|
请完成以下Java代码
|
public int getAD_Column_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Column_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setWEBUI_Board_CardField_ID (final int WEBUI_Board_CardField_ID)
{
if (WEBUI_Board_CardField_ID < 1)
set_ValueNoCheck (COLUMNNAME_WEBUI_Board_CardField_ID, null);
else
set_ValueNoCheck (COLUMNNAME_WEBUI_Board_CardField_ID, WEBUI_Board_CardField_ID);
}
@Override
public int getWEBUI_Board_CardField_ID()
{
return get_ValueAsInt(COLUMNNAME_WEBUI_Board_CardField_ID);
}
@Override
public de.metas.ui.web.base.model.I_WEBUI_Board getWEBUI_Board()
{
return get_ValueAsPO(COLUMNNAME_WEBUI_Board_ID, de.metas.ui.web.base.model.I_WEBUI_Board.class);
|
}
@Override
public void setWEBUI_Board(final de.metas.ui.web.base.model.I_WEBUI_Board WEBUI_Board)
{
set_ValueFromPO(COLUMNNAME_WEBUI_Board_ID, de.metas.ui.web.base.model.I_WEBUI_Board.class, WEBUI_Board);
}
@Override
public void setWEBUI_Board_ID (final int WEBUI_Board_ID)
{
if (WEBUI_Board_ID < 1)
set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, null);
else
set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, WEBUI_Board_ID);
}
@Override
public int getWEBUI_Board_ID()
{
return get_ValueAsInt(COLUMNNAME_WEBUI_Board_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_Board_CardField.java
| 1
|
请完成以下Java代码
|
public HistoricProcessInstanceEntity create(ExecutionEntity processInstanceExecutionEntity) {
return dataManager.create(processInstanceExecutionEntity);
}
@Override
public long findHistoricProcessInstanceCountByQueryCriteria(HistoricProcessInstanceQueryImpl historicProcessInstanceQuery) {
return dataManager.findHistoricProcessInstanceCountByQueryCriteria(historicProcessInstanceQuery);
}
@Override
public List<HistoricProcessInstance> findHistoricProcessInstancesByQueryCriteria(HistoricProcessInstanceQueryImpl historicProcessInstanceQuery) {
return dataManager.findHistoricProcessInstancesByQueryCriteria(historicProcessInstanceQuery);
}
@Override
public List<HistoricProcessInstance> findHistoricProcessInstancesAndVariablesByQueryCriteria(HistoricProcessInstanceQueryImpl historicProcessInstanceQuery) {
return dataManager.findHistoricProcessInstancesAndVariablesByQueryCriteria(historicProcessInstanceQuery);
}
@Override
public List<HistoricProcessInstance> findHistoricProcessInstanceIdsByQueryCriteria(HistoricProcessInstanceQueryImpl historicProcessInstanceQuery) {
return dataManager.findHistoricProcessInstanceIdsByQueryCriteria(historicProcessInstanceQuery);
}
@Override
public List<HistoricProcessInstance> findHistoricProcessInstancesByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findHistoricProcessInstancesByNativeQuery(parameterMap);
}
@Override
public List<HistoricProcessInstance> findHistoricProcessInstancesBySuperProcessInstanceId(String historicProcessInstanceId) {
return dataManager.findHistoricProcessInstancesBySuperProcessInstanceId(historicProcessInstanceId);
}
@Override
public List<String> findHistoricProcessInstanceIdsBySuperProcessInstanceIds(Collection<String> superProcessInstanceIds) {
|
return dataManager.findHistoricProcessInstanceIdsBySuperProcessInstanceIds(superProcessInstanceIds);
}
@Override
public List<String> findHistoricProcessInstanceIdsByProcessDefinitionId(String processDefinitionId) {
return dataManager.findHistoricProcessInstanceIdsByProcessDefinitionId(processDefinitionId);
}
@Override
public long findHistoricProcessInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findHistoricProcessInstanceCountByNativeQuery(parameterMap);
}
@Override
public void deleteHistoricProcessInstances(HistoricProcessInstanceQueryImpl historicProcessInstanceQuery) {
dataManager.deleteHistoricProcessInstances(historicProcessInstanceQuery);
}
@Override
public void bulkDeleteHistoricProcessInstances(Collection<String> processInstanceIds) {
dataManager.bulkDeleteHistoricProcessInstances(processInstanceIds);
}
protected HistoryManager getHistoryManager() {
return engineConfiguration.getHistoryManager();
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\HistoricProcessInstanceEntityManagerImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class TokenAuthenticationFilter extends OncePerRequestFilter {
private static final String BEARER_PREFIX = "Bearer ";
private static final String USER_ID_CLAIM = "user_id";
private static final String AUTHORIZATION_HEADER = "Authorization";
private final FirebaseAuth firebaseAuth;
private final ObjectMapper objectMapper;
public TokenAuthenticationFilter(FirebaseAuth firebaseAuth, ObjectMapper objectMapper) {
this.firebaseAuth = firebaseAuth;
this.objectMapper = objectMapper;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
String authorizationHeader = request.getHeader(AUTHORIZATION_HEADER);
if (authorizationHeader != null && authorizationHeader.startsWith(BEARER_PREFIX)) {
String token = authorizationHeader.replace(BEARER_PREFIX, "");
Optional<String> userId = extractUserIdFromToken(token);
if (userId.isPresent()) {
var authentication = new UsernamePasswordAuthenticationToken(userId.get(), null, null);
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
} else {
setAuthErrorDetails(response);
return;
}
|
}
filterChain.doFilter(request, response);
}
private Optional<String> extractUserIdFromToken(String token) {
try {
FirebaseToken firebaseToken = firebaseAuth.verifyIdToken(token, true);
String userId = String.valueOf(firebaseToken.getClaims().get(USER_ID_CLAIM));
return Optional.of(userId);
} catch (FirebaseAuthException exception) {
return Optional.empty();
}
}
private void setAuthErrorDetails(HttpServletResponse response) throws JsonProcessingException, IOException {
HttpStatus unauthorized = HttpStatus.UNAUTHORIZED;
response.setStatus(unauthorized.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
ProblemDetail problemDetail = ProblemDetail.forStatusAndDetail(unauthorized, "Authentication failure: Token missing, invalid or expired");
response.getWriter().write(objectMapper.writeValueAsString(problemDetail));
}
}
|
repos\tutorials-master\gcp-firebase\src\main\java\com\baeldung\gcp\firebase\auth\TokenAuthenticationFilter.java
| 2
|
请完成以下Java代码
|
public JAXBElement<SendungsRueckmeldung> createGOWebServiceSendungsRueckmeldung(SendungsRueckmeldung value) {
return new JAXBElement<SendungsRueckmeldung>(_GOWebServiceSendungsRueckmeldung_QNAME, SendungsRueckmeldung.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link Fehlerbehandlung }{@code >}
*
* @param value
* Java instance representing xml element's value.
* @return
* the new instance of {@link JAXBElement }{@code <}{@link Fehlerbehandlung }{@code >}
*/
@XmlElementDecl(namespace = "https://wsdemo.ax4.com/ws/GeneralOvernight", name = "GOWebService_Fehlerbehandlung")
public JAXBElement<Fehlerbehandlung> createGOWebServiceFehlerbehandlung(Fehlerbehandlung value) {
return new JAXBElement<Fehlerbehandlung>(_GOWebServiceFehlerbehandlung_QNAME, Fehlerbehandlung.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link Sendungsnummern }{@code >}
*
* @param value
* Java instance representing xml element's value.
|
* @return
* the new instance of {@link JAXBElement }{@code <}{@link Sendungsnummern }{@code >}
*/
@XmlElementDecl(namespace = "https://wsdemo.ax4.com/ws/GeneralOvernight", name = "GOWebService_Sendungsnummern")
public JAXBElement<Sendungsnummern> createGOWebServiceSendungsnummern(Sendungsnummern value) {
return new JAXBElement<Sendungsnummern>(_GOWebServiceSendungsnummern_QNAME, Sendungsnummern.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link Label }{@code >}
*
* @param value
* Java instance representing xml element's value.
* @return
* the new instance of {@link JAXBElement }{@code <}{@link Label }{@code >}
*/
@XmlElementDecl(namespace = "https://wsdemo.ax4.com/ws/GeneralOvernight", name = "GOWebService_Label")
public JAXBElement<Label> createGOWebServiceLabel(Label value) {
return new JAXBElement<Label>(_GOWebServiceLabel_QNAME, Label.class, null, value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java-xjc\de\metas\shipper\gateway\go\schema\ObjectFactory.java
| 1
|
请完成以下Java代码
|
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Nullable
public String getRoomId() {
return roomId;
}
public void setRoomId(String roomId) {
this.roomId = roomId;
}
@Nullable
public String getToken() {
return token;
}
|
public void setToken(String token) {
this.token = token;
}
@Nullable
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\RocketChatNotifier.java
| 1
|
请完成以下Java代码
|
private MethodAuthorizationDeniedHandler resolveHandler(Method method, @Nullable Class<?> targetClass) {
Class<?> targetClassToUse = targetClass(method, targetClass);
HandleAuthorizationDenied deniedHandler = this.handleAuthorizationDeniedScanner.scan(method, targetClassToUse);
if (deniedHandler != null) {
return this.handlerResolver.apply(deniedHandler.handlerClass());
}
return this.defaultHandler;
}
private @Nullable PreAuthorize findPreAuthorizeAnnotation(Method method, @Nullable Class<?> targetClass) {
Class<?> targetClassToUse = targetClass(method, targetClass);
return this.preAuthorizeScanner.scan(method, targetClassToUse);
}
/**
* Uses the provided {@link ApplicationContext} to resolve the
* {@link MethodAuthorizationDeniedHandler} from {@link PreAuthorize}.
* @param context the {@link ApplicationContext} to use
*/
void setApplicationContext(ApplicationContext context) {
Assert.notNull(context, "context cannot be null");
this.handlerResolver = (clazz) -> resolveHandler(context, clazz);
}
void setTemplateDefaults(AnnotationTemplateExpressionDefaults defaults) {
|
this.preAuthorizeScanner = SecurityAnnotationScanners.requireUnique(PreAuthorize.class, defaults);
}
private MethodAuthorizationDeniedHandler resolveHandler(ApplicationContext context,
Class<? extends MethodAuthorizationDeniedHandler> handlerClass) {
if (handlerClass == this.defaultHandler.getClass()) {
return this.defaultHandler;
}
String[] beanNames = context.getBeanNamesForType(handlerClass);
if (beanNames.length == 0) {
throw new IllegalStateException("Could not find a bean of type " + handlerClass.getName());
}
if (beanNames.length > 1) {
throw new IllegalStateException("Expected to find a single bean of type " + handlerClass.getName()
+ " but found " + Arrays.toString(beanNames));
}
return context.getBean(beanNames[0], handlerClass);
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\PreAuthorizeExpressionAttributeRegistry.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void modify(final String username, final String password) {
Name dn = LdapNameBuilder
.newInstance()
.add("ou", "users")
.add("cn", username)
.build();
DirContextOperations context = ldapTemplate.lookupContext(dn);
context.setAttributeValues("objectclass", new String[]{"top", "person", "organizationalPerson", "inetOrgPerson"});
context.setAttributeValue("cn", username);
context.setAttributeValue("sn", username);
context.setAttributeValue("userPassword", digestSHA(password));
ldapTemplate.modifyAttributes(context);
}
|
private String digestSHA(final String password) {
String base64;
try {
MessageDigest digest = MessageDigest.getInstance("SHA");
digest.update(password.getBytes());
base64 = Base64
.getEncoder()
.encodeToString(digest.digest());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
return "{SHA}" + base64;
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-ldap\src\main\java\com\baeldung\ldap\data\service\LdapClient.java
| 2
|
请完成以下Java代码
|
public FlowableEngineEventType getType() {
return type;
}
public void setType(FlowableEngineEventType type) {
this.type = type;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
|
}
@Override
public String getScopeType() {
return ScopeTypes.BPMN;
}
@Override
public String getScopeId() {
return processInstanceId;
}
@Override
public String getSubScopeId() {
return executionId;
}
@Override
public String getScopeDefinitionId() {
return processDefinitionId;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\delegate\event\impl\ActivitiEventImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CityRestController {
@Autowired
private CityService cityService;
/**
* 插入 ES 新城市
*
* @param city
* @return
*/
@RequestMapping(value = "/api/city", method = RequestMethod.POST)
public Long createCity(@RequestBody City city) {
return cityService.saveCity(city);
}
|
/**
* 搜索返回分页结果
*
* @param pageNumber 当前页码
* @param pageSize 每页大小
* @param searchContent 搜索内容
* @return
*/
@RequestMapping(value = "/api/city/search", method = RequestMethod.GET)
public List<City> searchCity(@RequestParam(value = "pageNumber") Integer pageNumber,
@RequestParam(value = "pageSize", required = false) Integer pageSize,
@RequestParam(value = "searchContent") String searchContent) {
return cityService.searchCity(pageNumber, pageSize,searchContent);
}
}
|
repos\springboot-learning-example-master\spring-data-elasticsearch-query\src\main\java\org\spring\springboot\controller\CityRestController.java
| 2
|
请完成以下Java代码
|
public class SysDataSource {
/**
* id
*/
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "id")
private java.lang.String id;
/**
* 数据源编码
*/
@Excel(name = "数据源编码", width = 15)
@Schema(description = "数据源编码")
private java.lang.String code;
/**
* 数据源名称
*/
@Excel(name = "数据源名称", width = 15)
@Schema(description = "数据源名称")
private java.lang.String name;
/**
* 描述
*/
@Excel(name = "备注", width = 15)
@Schema(description = "备注")
private java.lang.String remark;
/**
* 数据库类型
*/
@Dict(dicCode = "database_type")
@Excel(name = "数据库类型", width = 15, dicCode = "database_type")
@Schema(description = "数据库类型")
private java.lang.String dbType;
/**
* 驱动类
*/
@Excel(name = "驱动类", width = 15)
@Schema(description = "驱动类")
private java.lang.String dbDriver;
/**
* 数据源地址
*/
@Excel(name = "数据源地址", width = 15)
@Schema(description = "数据源地址")
private java.lang.String dbUrl;
/**
* 数据库名称
*/
@Excel(name = "数据库名称", width = 15)
@Schema(description = "数据库名称")
private java.lang.String dbName;
/**
* 用户名
*/
@Excel(name = "用户名", width = 15)
@Schema(description = "用户名")
|
private java.lang.String dbUsername;
/**
* 密码
*/
@Excel(name = "密码", width = 15)
@Schema(description = "密码")
private java.lang.String dbPassword;
/**
* 创建人
*/
@Schema(description = "创建人")
private java.lang.String createBy;
/**
* 创建日期
*/
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Schema(description = "创建日期")
private java.util.Date createTime;
/**
* 更新人
*/
@Schema(description = "更新人")
private java.lang.String updateBy;
/**
* 更新日期
*/
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Schema(description = "更新日期")
private java.util.Date updateTime;
/**
* 所属部门
*/
@Excel(name = "所属部门", width = 15)
@Schema(description = "所属部门")
private java.lang.String sysOrgCode;
/**租户ID*/
@Schema(description = "租户ID")
private java.lang.Integer tenantId;
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysDataSource.java
| 1
|
请完成以下Java代码
|
public void assertLaneIdExists(final int laneId)
{
if (lanes.get(laneId) == null)
{
throw new AdempiereException("Lane ID=" + laneId + " found for board ID=" + getBoardId())
.setParameter("board", this)
.setParameter("laneId", laneId);
}
}
public Collection<BoardCardFieldDescriptor> getCardFields()
{
return cardFieldsByFieldName.values();
}
public BoardCardFieldDescriptor getCardFieldByName(final String fieldName)
{
final BoardCardFieldDescriptor cardField = cardFieldsByFieldName.get(fieldName);
|
if (cardField == null)
{
throw new AdempiereException("No card field found for " + fieldName)
.setParameter("board", this);
}
return cardField;
}
public LookupDescriptor getLookupDescriptor()
{
return getDocumentLookupDescriptorProvider()
.provide()
.get();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\board\BoardDescriptor.java
| 1
|
请完成以下Java代码
|
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
if (context.isMoreThanOneSelected())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
final IMaterialTrackingPPOrderBL materialTrackingPPOrderBL = Services.get(IMaterialTrackingPPOrderBL.class);
boolean qualityInspection = materialTrackingPPOrderBL.isQualityInspection(context.getSingleSelectedRecordId());
if(!qualityInspection)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Selected PP_Order is not a quality inspection");
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected void prepare()
{
if (I_PP_Order.Table_Name.equals(getTableName()))
{
p_PP_Order_ID = getRecord_ID();
}
}
@Override
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
|
请完成以下Java代码
|
public class PlanItemCreationType {
protected boolean typeActivate;
protected boolean typeIgnore;
protected boolean typeDefault;
public boolean isTypeActivate() {
return typeActivate;
}
public void setTypeActivate(boolean typeActivate) {
this.typeActivate = typeActivate;
}
public boolean isTypeIgnore() {
return typeIgnore;
}
public void setTypeIgnore(boolean typeIgnore) {
this.typeIgnore = typeIgnore;
}
public boolean isTypeDefault() {
return typeDefault;
}
public void setTypeDefault(boolean typeDefault) {
this.typeDefault = typeDefault;
}
|
public static PlanItemCreationType typeActivate() {
PlanItemCreationType type = new PlanItemCreationType();
type.setTypeActivate(true);
return type;
}
public static PlanItemCreationType typeIgnore() {
PlanItemCreationType type = new PlanItemCreationType();
type.setTypeIgnore(true);
return type;
}
public static PlanItemCreationType typeDefault() {
PlanItemCreationType type = new PlanItemCreationType();
type.setTypeDefault(true);
return type;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\PlanItemCreationType.java
| 1
|
请完成以下Java代码
|
public int getAD_Role_NotificationGroup_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_NotificationGroup_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/**
* NotificationType AD_Reference_ID=344
* Reference name: AD_User NotificationType
*/
public static final int NOTIFICATIONTYPE_AD_Reference_ID=344;
/** EMail = E */
public static final String NOTIFICATIONTYPE_EMail = "E";
/** Notice = N */
public static final String NOTIFICATIONTYPE_Notice = "N";
/** None = X */
public static final String NOTIFICATIONTYPE_None = "X";
/** EMailPlusNotice = B */
public static final String NOTIFICATIONTYPE_EMailPlusNotice = "B";
/** NotifyUserInCharge = O */
public static final String NOTIFICATIONTYPE_NotifyUserInCharge = "O";
/** Set Benachrichtigungs-Art.
|
@param NotificationType
Art der Benachrichtigung
*/
@Override
public void setNotificationType (java.lang.String NotificationType)
{
set_Value (COLUMNNAME_NotificationType, NotificationType);
}
/** Get Benachrichtigungs-Art.
@return Art der Benachrichtigung
*/
@Override
public java.lang.String getNotificationType ()
{
return (java.lang.String)get_Value(COLUMNNAME_NotificationType);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role_NotificationGroup.java
| 1
|
请完成以下Java代码
|
public IHUAllocations getHUAllocations()
{
return null;
}
@Override
public I_M_Transaction getTrxReferencedModel()
{
return (I_M_Transaction)super.getTrxReferencedModel();
}
private MInOutLineHUDocumentLine reversalSourceLine = null;
@Override
public MInOutLineHUDocumentLine getReversal()
{
if (reversalSourceLine == null)
{
final org.compiere.model.I_M_InOutLine reversalLine = ioLine.getReversalLine();
final I_M_Transaction mtrx = getTrxReferencedModel();
final I_M_Transaction reversalMTrx = Services.get(IMTransactionDAO.class).retrieveReversalTransaction(reversalLine, mtrx);
|
reversalSourceLine = new MInOutLineHUDocumentLine(reversalLine, reversalMTrx);
reversalSourceLine.setReversal(this);
}
return reversalSourceLine;
}
private void setReversal(final MInOutLineHUDocumentLine reversalLine)
{
reversalSourceLine = reversalLine;
}
@Override
public int getC_BPartner_Location_ID()
{
final I_M_InOut inout = ioLine.getM_InOut();
return inout.getC_BPartner_Location_ID();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\impl\MInOutLineHUDocumentLine.java
| 1
|
请完成以下Java代码
|
public CoreModelElement getEventSource() {
return eventSource;
}
public void setEventSource(CoreModelElement eventSource) {
this.eventSource = eventSource;
}
public int getListenerIndex() {
return listenerIndex;
}
public void setListenerIndex(int listenerIndex) {
this.listenerIndex = listenerIndex;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void invokeListener(DelegateListener listener) throws Exception {
listener.notify(this);
}
public boolean hasFailedOnEndListeners() {
return false;
}
// getters / setters /////////////////////////////////////////////////
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBusinessKeyWithoutCascade() {
return businessKeyWithoutCascade;
}
public void setBusinessKey(String businessKey) {
this.businessKey = businessKey;
|
this.businessKeyWithoutCascade = businessKey;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public boolean isSkipCustomListeners() {
return skipCustomListeners;
}
public void setSkipCustomListeners(boolean skipCustomListeners) {
this.skipCustomListeners = skipCustomListeners;
}
public boolean isSkipIoMappings() {
return skipIoMapping;
}
public void setSkipIoMappings(boolean skipIoMappings) {
this.skipIoMapping = skipIoMappings;
}
public boolean isSkipSubprocesses() {
return skipSubprocesses;
}
public void setSkipSubprocesseses(boolean skipSubprocesses) {
this.skipSubprocesses = skipSubprocesses;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\instance\CoreExecution.java
| 1
|
请完成以下Java代码
|
public org.compiere.model.I_C_Order getC_Order() throws RuntimeException
{
return (org.compiere.model.I_C_Order)MTable.get(getCtx(), org.compiere.model.I_C_Order.Table_Name)
.getPO(getC_Order_ID(), get_TrxName()); }
/** Set Auftrag.
@param C_Order_ID
Order
*/
public void setC_Order_ID (int C_Order_ID)
{
if (C_Order_ID < 1)
set_Value (COLUMNNAME_C_Order_ID, null);
else
set_Value (COLUMNNAME_C_Order_ID, Integer.valueOf(C_Order_ID));
}
/** Get Auftrag.
@return Order
*/
public int getC_Order_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Order_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Packaging Tree.
@param M_PackagingTree_ID Packaging Tree */
public void setM_PackagingTree_ID (int M_PackagingTree_ID)
{
if (M_PackagingTree_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PackagingTree_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PackagingTree_ID, Integer.valueOf(M_PackagingTree_ID));
}
/** Get Packaging Tree.
@return Packaging Tree */
public int getM_PackagingTree_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PackagingTree_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_M_Warehouse getM_Warehouse_Dest() throws RuntimeException
{
return (org.compiere.model.I_M_Warehouse)MTable.get(getCtx(), org.compiere.model.I_M_Warehouse.Table_Name)
.getPO(getM_Warehouse_Dest_ID(), get_TrxName()); }
/** Set Ziel-Lager.
@param M_Warehouse_Dest_ID Ziel-Lager */
public void setM_Warehouse_Dest_ID (int M_Warehouse_Dest_ID)
|
{
if (M_Warehouse_Dest_ID < 1)
set_Value (COLUMNNAME_M_Warehouse_Dest_ID, null);
else
set_Value (COLUMNNAME_M_Warehouse_Dest_ID, Integer.valueOf(M_Warehouse_Dest_ID));
}
/** Get Ziel-Lager.
@return Ziel-Lager */
public int getM_Warehouse_Dest_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_Dest_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* Set Verarbeitet.
*
* @param Processed
* Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
public void setProcessed(boolean Processed)
{
set_Value(COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/**
* Get Verarbeitet.
*
* @return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
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;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\compiere\model\X_M_PackagingTree.java
| 1
|
请完成以下Java代码
|
public class TbEntityCountSubCtx extends TbAbstractEntityQuerySubCtx<EntityCountQuery> {
private volatile int result;
public TbEntityCountSubCtx(String serviceId, WebSocketService wsService, EntityService entityService,
TbLocalSubscriptionService localSubscriptionService, AttributesService attributesService,
SubscriptionServiceStatistics stats, WebSocketSessionRef sessionRef, int cmdId) {
super(serviceId, wsService, entityService, localSubscriptionService, attributesService, stats, sessionRef, cmdId);
}
@Override
public void fetchData() {
result = (int) entityService.countEntitiesByQuery(getTenantId(), getCustomerId(), query);
sendWsMsg(new EntityCountUpdate(cmdId, result));
}
|
@Override
protected void update() {
int newCount = (int) entityService.countEntitiesByQuery(getTenantId(), getCustomerId(), query);
if (newCount != result) {
result = newCount;
sendWsMsg(new EntityCountUpdate(cmdId, result));
}
}
@Override
public boolean isDynamic() {
return true;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\subscription\TbEntityCountSubCtx.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SecurityDebugBeanFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor {
private final Log logger = LogFactory.getLog(getClass());
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
this.logger.warn("\n\n" + "********************************************************************\n"
+ "********** Security debugging is enabled. *************\n"
+ "********** This may include sensitive information. *************\n"
+ "********** Do not use in a production system! *************\n"
+ "********************************************************************\n\n");
// SPRING_SECURITY_FILTER_CHAIN does not exist yet since it is an alias that has
// not been processed, so use FILTER_CHAIN_PROXY
if (registry.containsBeanDefinition(BeanIds.FILTER_CHAIN_PROXY)) {
BeanDefinition fcpBeanDef = registry.getBeanDefinition(BeanIds.FILTER_CHAIN_PROXY);
|
BeanDefinitionBuilder debugFilterBldr = BeanDefinitionBuilder.genericBeanDefinition(DebugFilter.class);
debugFilterBldr.addConstructorArgValue(fcpBeanDef);
// Remove the alias to SPRING_SECURITY_FILTER_CHAIN, so that it does not
// override the new
// SPRING_SECURITY_FILTER_CHAIN definition
registry.removeAlias(BeanIds.SPRING_SECURITY_FILTER_CHAIN);
registry.registerBeanDefinition(BeanIds.SPRING_SECURITY_FILTER_CHAIN, debugFilterBldr.getBeanDefinition());
}
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\debug\SecurityDebugBeanFactoryPostProcessor.java
| 2
|
请完成以下Java代码
|
public void setPriceList (final BigDecimal PriceList)
{
set_Value (COLUMNNAME_PriceList, PriceList);
}
@Override
public BigDecimal getPriceList()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceList);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPriceStd (final BigDecimal PriceStd)
{
set_Value (COLUMNNAME_PriceStd, PriceStd);
}
@Override
public BigDecimal getPriceStd()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceStd);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
/**
* UseScalePrice AD_Reference_ID=541376
* Reference name: UseScalePrice
*/
public static final int USESCALEPRICE_AD_Reference_ID=541376;
/** Use scale price, fallback to product price = Y */
public static final String USESCALEPRICE_UseScalePriceFallbackToProductPrice = "Y";
|
/** Don't use scale price = N */
public static final String USESCALEPRICE_DonTUseScalePrice = "N";
/** Use scale price (strict) = S */
public static final String USESCALEPRICE_UseScalePriceStrict = "S";
@Override
public void setUseScalePrice (final java.lang.String UseScalePrice)
{
set_Value (COLUMNNAME_UseScalePrice, UseScalePrice);
}
@Override
public java.lang.String getUseScalePrice()
{
return get_ValueAsString(COLUMNNAME_UseScalePrice);
}
@Override
public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom)
{
throw new IllegalArgumentException ("ValidFrom is virtual column"); }
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ProductPrice.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Result<JSONObject> loginGetUserDeparts(@RequestBody JSONObject jsonObject, HttpServletRequest request){
return sysUserService.loginGetUserDeparts(jsonObject);
}
/**
* 校验验证码工具方法,校验失败直接返回Result,校验通过返回realKey
*/
private String validateCaptcha(SysLoginModel sysLoginModel, Result<JSONObject> result) {
// 判断是否启用登录验证码校验
if (jeecgBaseConfig.getFirewall() != null && Boolean.FALSE.equals(jeecgBaseConfig.getFirewall().getEnableLoginCaptcha())) {
log.warn("关闭了登录验证码校验,跳过验证码校验!");
return "LoginWithoutVerifyCode";
}
String captcha = sysLoginModel.getCaptcha();
if (captcha == null) {
|
result.error500("验证码无效");
return null;
}
String lowerCaseCaptcha = captcha.toLowerCase();
String keyPrefix = Md5Util.md5Encode(sysLoginModel.getCheckKey() + jeecgBaseConfig.getSignatureSecret(), "utf-8");
String realKey = keyPrefix + lowerCaseCaptcha;
Object checkCode = redisUtil.get(realKey);
if (checkCode == null || !checkCode.toString().equals(lowerCaseCaptcha)) {
log.warn("验证码错误,key= {} , Ui checkCode= {}, Redis checkCode = {}", sysLoginModel.getCheckKey(), lowerCaseCaptcha, checkCode);
result.error500("验证码错误");
result.setCode(HttpStatus.PRECONDITION_FAILED.value());
return null;
}
return realKey;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\LoginController.java
| 2
|
请完成以下Java代码
|
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setScript (final @Nullable java.lang.String Script)
{
set_Value (COLUMNNAME_Script, Script);
}
@Override
public java.lang.String getScript()
{
|
return get_ValueAsString(COLUMNNAME_Script);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DiscountSchema.java
| 1
|
请完成以下Java代码
|
void clear()
{
_units.clear();
_ranks = null;
}
/**
* 整型大小
*/
private static final int UNIT_SIZE = 32; // sizeof(int) * 8
/**
* 1的数量
* @param unit
* @return
*/
private static int popCount(int unit)
{
unit = ((unit & 0xAAAAAAAA) >>> 1) + (unit & 0x55555555);
unit = ((unit & 0xCCCCCCCC) >>> 2) + (unit & 0x33333333);
unit = ((unit >>> 4) + unit) & 0x0F0F0F0F;
|
unit += unit >>> 8;
unit += unit >>> 16;
return unit & 0xFF;
}
/**
* 储存空间
*/
private AutoIntPool _units = new AutoIntPool();
/**
* 是每个元素的1的个数的累加
*/
private int[] _ranks;
/**
* 1的数量
*/
private int _numOnes;
/**
* 大小
*/
private int _size;
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\BitVector.java
| 1
|
请完成以下Java代码
|
public Optional<PaymentReservation> getBySalesOrderIdNotVoided(@NonNull final OrderId salesOrderId)
{
final I_C_Payment_Reservation record = Services.get(IQueryBL.class)
.createQueryBuilder(I_C_Payment_Reservation.class)
.addEqualsFilter(I_C_Payment_Reservation.COLUMN_C_Order_ID, salesOrderId)
.addNotEqualsFilter(I_C_Payment_Reservation.COLUMN_Status, PaymentReservationStatus.VOIDED)
.addOnlyActiveRecordsFilter()
.create()
.firstOnly(I_C_Payment_Reservation.class);
if (record == null)
{
return Optional.empty();
}
final PaymentReservation reservation = toPaymentReservation(record);
return Optional.of(reservation);
}
public void save(@NonNull final PaymentReservation reservation)
{
final I_C_Payment_Reservation record = reservation.getId() != null
? load(reservation.getId(), I_C_Payment_Reservation.class)
: newInstance(I_C_Payment_Reservation.class);
updateReservationRecord(record, reservation);
saveRecord(record);
reservation.setId(PaymentReservationId.ofRepoId(record.getC_Payment_Reservation_ID()));
}
private static void updateReservationRecord(
@NonNull final I_C_Payment_Reservation record,
@NonNull final PaymentReservation from)
{
InterfaceWrapperHelper.setValue(record, "AD_Client_ID", from.getClientId().getRepoId());
record.setAD_Org_ID(from.getOrgId().getRepoId());
record.setAmount(from.getAmount().toBigDecimal());
record.setBill_BPartner_ID(from.getPayerContactId().getBpartnerId().getRepoId());
record.setBill_User_ID(from.getPayerContactId().getUserId().getRepoId());
record.setBill_EMail(from.getPayerEmail().getAsString());
|
record.setC_Currency_ID(from.getAmount().getCurrencyId().getRepoId());
record.setC_Order_ID(from.getSalesOrderId().getRepoId());
record.setDateTrx(TimeUtil.asTimestamp(from.getDateTrx()));
record.setPaymentRule(from.getPaymentRule().getCode());
record.setStatus(from.getStatus().getCode());
}
private static PaymentReservation toPaymentReservation(@NonNull final I_C_Payment_Reservation record)
{
final CurrencyId currencyId = CurrencyId.ofRepoId(record.getC_Currency_ID());
return PaymentReservation.builder()
.id(PaymentReservationId.ofRepoId(record.getC_Payment_Reservation_ID()))
.clientId(ClientId.ofRepoId(record.getAD_Client_ID()))
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.amount(Money.of(record.getAmount(), currencyId))
.payerContactId(BPartnerContactId.ofRepoId(record.getBill_BPartner_ID(), record.getBill_User_ID()))
.payerEmail(EMailAddress.ofString(record.getBill_EMail()))
.salesOrderId(OrderId.ofRepoId(record.getC_Order_ID()))
.dateTrx(TimeUtil.asLocalDate(record.getDateTrx()))
.paymentRule(PaymentRule.ofCode(record.getPaymentRule()))
.status(PaymentReservationStatus.ofCode(record.getStatus()))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\reservation\PaymentReservationRepository.java
| 1
|
请完成以下Java代码
|
private final CopyPasteActionType getActionType()
{
return _actionType;
}
@Override
public void setContext(final IContextMenuActionContext menuCtx)
{
super.setContext(menuCtx);
getCopyPasteSupport(); // eagerly install the actions
}
private final ICopyPasteSupportEditor getCopyPasteSupport()
{
if (_copyPasteSupport == null)
{
_copyPasteSupport = createCopyPasteSupport(getEditor());
if (!NullCopyPasteSupportEditor.isNull(_copyPasteSupport))
{
// Setup the copy/paste action if needed
CopyPasteAction.getCreateAction(_copyPasteSupport, getActionType());
}
}
return _copyPasteSupport;
}
private static ICopyPasteSupportEditor createCopyPasteSupport(final VEditor editor)
{
if (editor == null)
{
return NullCopyPasteSupportEditor.instance;
}
//
// Check if editor implements our interface
if (editor instanceof ICopyPasteSupportEditor)
{
return (ICopyPasteSupportEditor)editor;
}
//
// Check if editor is aware of ICopyPasteSupport
if (editor instanceof ICopyPasteSupportEditorAware)
{
final ICopyPasteSupportEditorAware copyPasteSupportAware = (ICopyPasteSupportEditorAware)editor;
final ICopyPasteSupportEditor copyPasteSupport = copyPasteSupportAware.getCopyPasteSupport();
return copyPasteSupport == null ? NullCopyPasteSupportEditor.instance : copyPasteSupport;
}
return NullCopyPasteSupportEditor.instance;
}
@Override
public String getName()
{
return getActionType().getAD_Message();
|
}
@Override
public String getIcon()
{
return null;
}
@Override
public KeyStroke getKeyStroke()
{
return getActionType().getKeyStroke();
}
@Override
public boolean isAvailable()
{
return !NullCopyPasteSupportEditor.isNull(getCopyPasteSupport());
}
@Override
public boolean isRunnable()
{
return getCopyPasteSupport().isCopyPasteActionAllowed(getActionType());
}
@Override
public boolean isHideWhenNotRunnable()
{
return false; // just gray it out
}
@Override
public void run()
{
getCopyPasteSupport().executeCopyPasteAction(getActionType());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\CopyPasteContextMenuAction.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private String getTaxCategory(@NonNull final BigDecimal taxRate)
{
return taxCategory2TaxRates
.entrySet()
.stream()
.filter(entry -> entry.getValue().stream().anyMatch(rate -> rate.compareTo(taxRate) == 0))
.map(Map.Entry::getKey)
.findFirst()
.orElseThrow(() -> new RuntimeException("No Tax Category found for Tax Rate = " + taxRate));
}
@NonNull
private static ImmutableMap<String, List<BigDecimal>> getTaxCategoryMappingRules(@NonNull final JsonExternalSystemRequest externalSystemRequest)
{
final String taxCategoryMappings = externalSystemRequest.getParameters().get(ExternalSystemConstants.PARAM_TAX_CATEGORY_MAPPINGS);
if (Check.isBlank(taxCategoryMappings))
{
return ImmutableMap.of();
}
final ObjectMapper mapper = JsonObjectMapperHolder.sharedJsonObjectMapper();
try
{
return mapper.readValue(taxCategoryMappings, JsonTaxCategoryMappings.class)
.getJsonTaxCategoryMappingList()
.stream()
.collect(ImmutableMap.toImmutableMap(JsonTaxCategoryMapping::getTaxCategory, JsonTaxCategoryMapping::getTaxRates));
}
catch (final JsonProcessingException e)
{
throw new RuntimeException(e);
|
}
}
private static boolean hasMissingFields(@NonNull final ProductRow productRow)
{
return Check.isBlank(productRow.getProductIdentifier())
|| Check.isBlank(productRow.getName())
|| Check.isBlank(productRow.getValue());
}
@NonNull
private static JsonRequestProductUpsert wrapUpsertItem(@NonNull final JsonRequestProductUpsertItem upsertItem)
{
return JsonRequestProductUpsert.builder()
.syncAdvise(SyncAdvise.CREATE_OR_MERGE)
.requestItems(ImmutableList.of(upsertItem))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\product\ProductUpsertProcessor.java
| 2
|
请完成以下Java代码
|
protected String doIt() throws Exception {
if ( migrationFrom == null || migrationFrom.getAD_Migration_ID() <= 0
|| migrationTo == null || migrationTo.getAD_Migration_ID() <= 0
|| migrationFrom.getAD_Migration_ID() == migrationTo.getAD_Migration_ID() )
{
addLog("Two different existing migrations required for merge");
return "@Error@";
}
Services.get(IMigrationBL.class).mergeMigration(migrationTo, migrationFrom);
return "@OK@";
}
@Override
protected void prepare() {
int fromId = 0, toId = 0;
ProcessInfoParameter[] params = getParametersAsArray();
for ( ProcessInfoParameter p : params)
{
|
String para = p.getParameterName();
if ( para.equals("AD_MigrationFrom_ID") )
fromId = p.getParameterAsInt();
else if ( para.equals("AD_MigrationTo_ID") )
toId = p.getParameterAsInt();
}
// launched from migration window
if ( toId == 0 )
toId = getRecord_ID();
migrationTo = InterfaceWrapperHelper.create(getCtx(), toId, I_AD_Migration.class, get_TrxName());
migrationFrom = InterfaceWrapperHelper.create(getCtx(), fromId, I_AD_Migration.class, get_TrxName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\MigrationMerge.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SSCC18
{
/**
* Extended digit and assigned by the company
*/
int extensionDigit;
/**
* The manufacturer code (or company code) is assigned by GS1 (formerly known as UCC/EAN organization)
*/
String manufacturerCode;
/**
* Identifies this merchandise container and assigned by the manufacturer.
* <p>
* The manufacturer should not reuse the serial number within a certain time frame, for example, 1 year.
* <p>
* The company code normally comprises 7 or 8 digits. Therefore, the serial number can be 9 or 8 digits.
*/
String serialNumber;
/**
* SSCC-18 check digit to ensure that the data is correctly entered. It is part of the data encoded into the barcode. A receiving system is required to validate this check digit, so you should get
* it correct at the first place.
*/
int checkDigit;
public SSCC18(final int extensionDigit,
@NonNull final String manufacturerCode,
@NonNull final String serialNumber,
final int checkDigit)
{
this.extensionDigit = extensionDigit;
|
this.manufacturerCode = manufacturerCode.trim();
this.serialNumber = serialNumber.trim();
this.checkDigit = checkDigit;
}
@Deprecated
@Override
public String toString()
{
return asString();
}
@Nullable
public static String toString(@Nullable final SSCC18 sscc)
{
return sscc == null ? null : sscc.asString();
}
/**
* @return SSCC18 string representation
*/
public String asString()
{
return getExtensionDigit()
+ getManufacturerCode()
+ getSerialNumber()
+ getCheckDigit();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\sscc18\SSCC18.java
| 2
|
请完成以下Java代码
|
public String getRepeat() {
return repeat;
}
public void setRepeat(String repeat) {
this.repeat = repeat;
}
@Override
public String getType() {
return TYPE;
}
@Override
protected void postExecute(CommandContext commandContext) {
LOG.debugJobExecuted(this);
if (repeat != null && !repeat.isEmpty()) {
init(commandContext, false, true);
} else {
delete(true);
}
commandContext.getHistoricJobLogManager().fireJobSuccessfulEvent(this);
}
@Override
public void init(CommandContext commandContext, boolean shouldResetLock, boolean shouldCallDeleteHandler) {
super.init(commandContext, shouldResetLock, shouldCallDeleteHandler);
repeat = null;
}
@Override
|
public String toString() {
return this.getClass().getSimpleName()
+ "[repeat=" + repeat
+ ", id=" + id
+ ", revision=" + revision
+ ", duedate=" + duedate
+ ", lockOwner=" + lockOwner
+ ", lockExpirationTime=" + lockExpirationTime
+ ", executionId=" + executionId
+ ", processInstanceId=" + processInstanceId
+ ", isExclusive=" + isExclusive
+ ", retries=" + retries
+ ", jobHandlerType=" + jobHandlerType
+ ", jobHandlerConfiguration=" + jobHandlerConfiguration
+ ", exceptionByteArray=" + exceptionByteArray
+ ", exceptionByteArrayId=" + exceptionByteArrayId
+ ", exceptionMessage=" + exceptionMessage
+ ", deploymentId=" + deploymentId
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\MessageEntity.java
| 1
|
请完成以下Java代码
|
public final boolean isQueryRunning()
{
return queryRunning.get();
}
/**
* Filter underlying data model using the active filters,
*
* i.e.
* <ul>
* <li>gets currently active facets from {@link IFacetsPool}
* <li>filter registered {@link IFacetFilterable} using those
* </ul>
*
* @param triggeringFacet facet which triggered this query.
*/
private final void executeQuery(final IFacet<?> triggeringFacet)
{
final boolean alreadyRunning = queryRunning.getAndSet(true);
if (alreadyRunning)
{
// do nothing if query is already running
return;
}
try
{
//
// Get current active facets and filter the data source
final IFacetsPool<ModelType> facetsPool = getFacetsPool();
final Set<IFacet<ModelType>> facets = facetsPool.getActiveFacets();
final IFacetFilterable<ModelType> facetFilterable = getFacetFilterable();
facetFilterable.filter(facets);
//
// After filtering the datasource, we need to update all facet categories which are eager to refresh.
facetCollectors.collect()
.setSource(facetFilterable)
// Don't update facets from the same category as our triggering facets
.excludeFacetCategory(triggeringFacet.getFacetCategory())
// Update only those facet groups on which we also "eager refreshing"
.setOnlyEagerRefreshCategories()
.collectAndUpdate(facetsPool);
}
finally
{
|
queryRunning.set(false);
}
}
/**
* Collect all facets from registered {@link IFacetCollector}s and then set them to {@link IFacetsPool}.
*
* If this executor has already a query which is running ({@link #isQueryRunning()}), this method will do nothing.
*/
public void collectFacetsAndResetPool()
{
// Do nothing if we have query which is currently running,
// because it most of the cases this happends because some business logic
// was triggered when the underlying facet filterable was changed due to our current running query
// and which triggered this method.
// If we would not prevent this, we could run in endless recursive calls.
if (isQueryRunning())
{
return;
}
//
// Before collecting ALL facets from this data source, make sure the database source is reset to it's inital state.
final IFacetFilterable<ModelType> facetFilterable = getFacetFilterable();
facetFilterable.reset();
//
// Collect the facets from facet filterable's current selection
// and set them to facets pool
facetCollectors.collect()
.setSource(facetFilterable)
.collectAndSet(getFacetsPool());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\impl\FacetExecutor.java
| 1
|
请完成以下Java代码
|
public static void fillJsonTypes(Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap) {
convertersToBpmnMap.put(STENCIL_EVENT_SUB_PROCESS, EventSubProcessJsonConverter.class);
}
public static void fillBpmnTypes(
Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap
) {
convertersToJsonMap.put(EventSubProcess.class, EventSubProcessJsonConverter.class);
}
protected String getStencilId(BaseElement baseElement) {
return STENCIL_EVENT_SUB_PROCESS;
}
protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) {
SubProcess subProcess = (SubProcess) baseElement;
propertiesNode.put("activitytype", "Event-Sub-Process");
propertiesNode.put("subprocesstype", "Embedded");
ArrayNode subProcessShapesArrayNode = objectMapper.createArrayNode();
GraphicInfo graphicInfo = model.getGraphicInfo(subProcess.getId());
processor.processFlowElements(
subProcess,
model,
subProcessShapesArrayNode,
formKeyMap,
decisionTableKeyMap,
graphicInfo.getX(),
graphicInfo.getY()
);
flowElementNode.set("childShapes", subProcessShapesArrayNode);
}
protected FlowElement convertJsonToElement(
JsonNode elementNode,
JsonNode modelNode,
Map<String, JsonNode> shapeMap
) {
EventSubProcess subProcess = new EventSubProcess();
JsonNode childShapesArray = elementNode.get(EDITOR_CHILD_SHAPES);
processor.processJsonElements(
childShapesArray,
modelNode,
subProcess,
|
shapeMap,
formMap,
decisionTableMap,
model
);
return subProcess;
}
@Override
public void setFormMap(Map<String, String> formMap) {
this.formMap = formMap;
}
@Override
public void setFormKeyMap(Map<String, ModelInfo> formKeyMap) {
this.formKeyMap = formKeyMap;
}
@Override
public void setDecisionTableMap(Map<String, String> decisionTableMap) {
this.decisionTableMap = decisionTableMap;
}
@Override
public void setDecisionTableKeyMap(Map<String, ModelInfo> decisionTableKeyMap) {
this.decisionTableKeyMap = decisionTableKeyMap;
}
}
|
repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\EventSubProcessJsonConverter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public OffsetDateTime getUpdated() {
return updated;
}
public void setUpdated(OffsetDateTime updated) {
this.updated = updated;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PrescriptedArticleLine prescriptedArticleLine = (PrescriptedArticleLine) o;
return Objects.equals(this._id, prescriptedArticleLine._id) &&
Objects.equals(this.orderedArticleLineId, prescriptedArticleLine.orderedArticleLineId) &&
Objects.equals(this.articleId, prescriptedArticleLine.articleId) &&
Objects.equals(this.pcn, prescriptedArticleLine.pcn) &&
Objects.equals(this.productGroupName, prescriptedArticleLine.productGroupName) &&
Objects.equals(this.quantity, prescriptedArticleLine.quantity) &&
Objects.equals(this.unit, prescriptedArticleLine.unit) &&
Objects.equals(this.annotation, prescriptedArticleLine.annotation) &&
Objects.equals(this.updated, prescriptedArticleLine.updated);
}
@Override
public int hashCode() {
return Objects.hash(_id, orderedArticleLineId, articleId, pcn, productGroupName, quantity, unit, annotation, updated);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PrescriptedArticleLine {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" orderedArticleLineId: ").append(toIndentedString(orderedArticleLineId)).append("\n");
sb.append(" articleId: ").append(toIndentedString(articleId)).append("\n");
|
sb.append(" pcn: ").append(toIndentedString(pcn)).append("\n");
sb.append(" productGroupName: ").append(toIndentedString(productGroupName)).append("\n");
sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n");
sb.append(" unit: ").append(toIndentedString(unit)).append("\n");
sb.append(" annotation: ").append(toIndentedString(annotation)).append("\n");
sb.append(" updated: ").append(toIndentedString(updated)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\PrescriptedArticleLine.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private void save0(@NonNull final InvoicePaySchedule invoicePaySchedule)
{
final InvoiceId invoiceId = invoicePaySchedule.getInvoiceId();
final HashMap<InvoicePayScheduleLineId, I_C_InvoicePaySchedule> records = getRecordsByInvoiceId(invoiceId)
.stream()
.collect(GuavaCollectors.toHashMapByKey(record -> InvoicePayScheduleLineId.ofRepoId(record.getC_InvoicePaySchedule_ID())));
for (final InvoicePayScheduleLine line : invoicePaySchedule.getLines())
{
final I_C_InvoicePaySchedule record = records.remove(line.getId());
if (record == null)
{
throw new AdempiereException("No record found by " + line.getId());
}
InvoicePayScheduleConverter.updateRecord(record, line);
InterfaceWrapperHelper.save(record);
}
InterfaceWrapperHelper.deleteAll(records.values());
invalidateCache(invoiceId);
}
public void updateByIds(@NonNull final Set<InvoiceId> invoiceIds, @NonNull final Consumer<InvoicePaySchedule> updater)
|
{
if (invoiceIds.isEmpty()) {return;}
trxManager.runInThreadInheritedTrx(() -> {
warmUpByInvoiceIds(invoiceIds);
invoiceIds.forEach(invoiceId -> updateById0(invoiceId, updater));
});
}
public void updateById(@NonNull final InvoiceId invoiceId, @NonNull final Consumer<InvoicePaySchedule> updater)
{
trxManager.runInThreadInheritedTrx(() -> updateById0(invoiceId, updater));
}
private void updateById0(@NonNull final InvoiceId invoiceId, @NonNull final Consumer<InvoicePaySchedule> updater)
{
final InvoicePaySchedule paySchedules = loadByInvoiceId(invoiceId).orElse(null);
if (paySchedules == null)
{
return;
}
updater.accept(paySchedules);
save0(paySchedules);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\paymentschedule\repository\InvoicePayScheduleLoaderAndSaver.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
synchronized (this.delegateMonitor) {
if (this.delegate == null) {
Assert.state(this.beanFactory != null,
() -> "BeanFactory must be set to resolve " + this.authMgrBean);
try {
this.delegate = this.beanFactory.getBean(this.authMgrBean, AuthenticationManager.class);
}
catch (NoSuchBeanDefinitionException ex) {
if (BeanIds.AUTHENTICATION_MANAGER.equals(ex.getBeanName())) {
throw new NoSuchBeanDefinitionException(BeanIds.AUTHENTICATION_MANAGER,
AuthenticationManagerFactoryBean.MISSING_BEAN_ERROR_MESSAGE);
}
throw ex;
}
}
}
return this.delegate.authenticate(authentication);
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
}
static class Jsr250MethodSecurityMetadataSourceBeanFactory extends AbstractGrantedAuthorityDefaultsBeanFactory {
private Jsr250MethodSecurityMetadataSource source = new Jsr250MethodSecurityMetadataSource();
Jsr250MethodSecurityMetadataSource getBean() {
this.source.setDefaultRolePrefix(this.rolePrefix);
return this.source;
}
}
static class DefaultMethodSecurityExpressionHandlerBeanFactory extends AbstractGrantedAuthorityDefaultsBeanFactory {
private DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
DefaultMethodSecurityExpressionHandler getBean() {
this.handler.setDefaultRolePrefix(this.rolePrefix);
return this.handler;
}
}
|
abstract static class AbstractGrantedAuthorityDefaultsBeanFactory implements ApplicationContextAware {
protected String rolePrefix = "ROLE_";
@Override
public final void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
applicationContext.getBeanProvider(GrantedAuthorityDefaults.class)
.ifUnique((grantedAuthorityDefaults) -> this.rolePrefix = grantedAuthorityDefaults.getRolePrefix());
}
}
/**
* Delays setting a bean of a given name to be lazyily initialized until after all the
* beans are registered.
*
* @author Rob Winch
* @since 3.2
*/
private static final class LazyInitBeanDefinitionRegistryPostProcessor
implements BeanDefinitionRegistryPostProcessor {
private final String beanName;
private LazyInitBeanDefinitionRegistryPostProcessor(String beanName) {
this.beanName = beanName;
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
if (!registry.containsBeanDefinition(this.beanName)) {
return;
}
BeanDefinition beanDefinition = registry.getBeanDefinition(this.beanName);
beanDefinition.setLazyInit(true);
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\method\GlobalMethodSecurityBeanDefinitionParser.java
| 2
|
请完成以下Java代码
|
public class IntermediateCatchEventValidator extends ProcessLevelValidator {
@Override
protected void executeValidation(BpmnModel bpmnModel, Process process, List<ValidationError> errors) {
List<IntermediateCatchEvent> intermediateCatchEvents = process.findFlowElementsOfType(IntermediateCatchEvent.class);
for (IntermediateCatchEvent intermediateCatchEvent : intermediateCatchEvents) {
EventDefinition eventDefinition = null;
if (!intermediateCatchEvent.getEventDefinitions().isEmpty()) {
eventDefinition = intermediateCatchEvent.getEventDefinitions().get(0);
}
if (eventDefinition == null) {
Map<String, List<ExtensionElement>> extensionElements = intermediateCatchEvent.getExtensionElements();
if (!extensionElements.isEmpty()) {
List<ExtensionElement> eventTypeExtensionElements = intermediateCatchEvent.getExtensionElements().get("eventType");
if (eventTypeExtensionElements != null && !eventTypeExtensionElements.isEmpty()) {
return;
}
}
|
addError(errors, Problems.INTERMEDIATE_CATCH_EVENT_NO_EVENTDEFINITION, process, intermediateCatchEvent, "No event definition for intermediate catch event ");
} else {
if (!(eventDefinition instanceof TimerEventDefinition) &&
!(eventDefinition instanceof SignalEventDefinition) &&
!(eventDefinition instanceof MessageEventDefinition) &&
!(eventDefinition instanceof ConditionalEventDefinition) &&
!(eventDefinition instanceof VariableListenerEventDefinition)) {
addError(errors, Problems.INTERMEDIATE_CATCH_EVENT_INVALID_EVENTDEFINITION, process, intermediateCatchEvent, eventDefinition, "Unsupported intermediate catch event type");
}
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-process-validation\src\main\java\org\flowable\validation\validator\impl\IntermediateCatchEventValidator.java
| 1
|
请完成以下Java代码
|
public class GetProcessDefinitionInfoCmd implements Command<ObjectNode>, Serializable {
private static final long serialVersionUID = 1L;
protected String processDefinitionId;
public GetProcessDefinitionInfoCmd(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
@Override
public ObjectNode execute(CommandContext commandContext) {
if (processDefinitionId == null) {
throw new FlowableIllegalArgumentException("process definition id is null");
}
ObjectNode resultNode = null;
DeploymentManager deploymentManager = CommandContextUtil.getProcessEngineConfiguration(commandContext).getDeploymentManager();
// make sure the process definition is in the cache
|
ProcessDefinition processDefinition = deploymentManager.findDeployedProcessDefinitionById(processDefinitionId);
if (Flowable5Util.isFlowable5ProcessDefinition(processDefinition, commandContext)) {
Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler();
return compatibilityHandler.getProcessDefinitionInfo(processDefinitionId);
}
ProcessDefinitionInfoCacheObject definitionInfoCacheObject = deploymentManager.getProcessDefinitionInfoCache().get(processDefinitionId);
if (definitionInfoCacheObject != null) {
resultNode = definitionInfoCacheObject.getInfoNode();
}
return resultNode;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\GetProcessDefinitionInfoCmd.java
| 1
|
请完成以下Java代码
|
public void deleteAttachedLines(final I_AD_PrinterHW printerHW)
{
final HardwarePrinterId hardwarePrinterId = HardwarePrinterId.ofRepoId(printerHW.getAD_PrinterHW_ID());
hardwarePrinterRepository.deleteCalibrations(hardwarePrinterId);
hardwarePrinterRepository.deleteMediaTrays(hardwarePrinterId);
hardwarePrinterRepository.deleteMediaSizes(hardwarePrinterId);
}
/**
* Needed because we want to order by ConfigHostKey and "unspecified" shall always be last.
*/
@ModelChange(
timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE },
ifColumnsChanged = I_AD_Printer_Config.COLUMNNAME_ConfigHostKey)
public void trimBlankHostKeyToNull(@NonNull final I_AD_PrinterHW printerHW)
{
try (final MDC.MDCCloseable ignored = TableRecordMDC.putTableRecordReference(printerHW))
{
|
final String normalizedString = StringUtils.trimBlankToNull(printerHW.getHostKey());
printerHW.setHostKey(normalizedString);
}
}
/**
* This interceptor shall only fire if the given {@code printerTrayHW} was created with replication.
* If it was created via the REST endpoint, then the business logic is called directly.
*/
@ModelChange(timings = ModelValidator.TYPE_AFTER_NEW_REPLICATION)
public void createPrinterConfigIfNoneExists(final I_AD_PrinterHW printerHW)
{
printerBL.createConfigAndDefaultPrinterMatching(printerHW);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\model\validator\AD_PrinterHW.java
| 1
|
请完成以下Java代码
|
public void afterPreviousIdChange(@NonNull final I_C_BPartner_Location bpLocation)
{
final LocationId newLocationId = LocationId.ofRepoId(bpLocation.getC_Location_ID());
final BPartnerLocationId bpartnerLocationId = BPartnerLocationId.ofRepoIdOrNull(bpLocation.getC_BPartner_ID(), bpLocation.getPrevious_ID());
if (bpartnerLocationId == null)
{
return;
}
final I_C_BPartner_Location bpLocationOld = bPartnerDAO.getBPartnerLocationByIdEvenInactive(bpartnerLocationId);
if (bpLocationOld == null)
{
return;
}
final LocationId oldLocationId = LocationId.ofRepoIdOrNull(bpLocationOld.getC_Location_ID());
showOrgChangeModalIfNeeded(bpLocation, newLocationId, oldLocationId);
}
private void showOrgChangeModalIfNeeded(final @NonNull I_C_BPartner_Location bpLocation, final LocationId newLocationId, @Nullable final LocationId oldLocationId)
{
if (Execution.isCurrentExecutionAvailable()
&& isAskForOrgChangeOnRegionChange())
{
final I_C_Location newLocation = locationDAO.getById(newLocationId);
final PostalId newPostalId = PostalId.ofRepoIdOrNull(newLocation.getC_Postal_ID());
if (newPostalId == null)
{
// nothing to do
return;
}
final I_C_Location oldLocation = oldLocationId != null ? locationDAO.getById(oldLocationId) : null;
final PostalId oldPostalId = oldLocationId == null ? null : PostalId.ofRepoIdOrNull(oldLocation.getC_Postal_ID());
if (newPostalId.equals(oldPostalId))
{
// nothing to do
return;
}
final I_C_Postal newPostalRecord = locationDAO.getPostalById(newPostalId);
final I_C_Postal oldPostalRecord = oldPostalId == null ? null : locationDAO.getPostalById(oldPostalId);
if (oldPostalRecord == null ||
newPostalRecord.getAD_Org_InCharge_ID() != oldPostalRecord.getAD_Org_InCharge_ID())
{
|
Execution.getCurrent().requestFrontendToTriggerAction(moveToAnotherOrgTriggerAction(bpLocation));
}
}
}
private JSONTriggerAction moveToAnotherOrgTriggerAction(final @NonNull I_C_BPartner_Location bpLocation)
{
return JSONTriggerAction.startProcess(
getMoveToAnotherOrgProcessId(),
getBPartnerDocumentPath(bpLocation));
}
private boolean isAskForOrgChangeOnRegionChange()
{
return sysConfigBL.getBooleanValue(SYSCONFIG_AskForOrgChangeOnRegionChange, false);
}
private ProcessId getMoveToAnotherOrgProcessId()
{
final AdProcessId adProcessId = adProcessDAO.retrieveProcessIdByClass(C_BPartner_MoveToAnotherOrg_PostalChange.class);
return ProcessId.ofAD_Process_ID(adProcessId);
}
private DocumentPath getBPartnerDocumentPath(@NonNull final I_C_BPartner_Location bpLocation)
{
return documentZoomIntoService.getDocumentPath(DocumentZoomIntoInfo.of(I_C_BPartner.Table_Name, bpLocation.getC_BPartner_ID()));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bpartner\interceptor\C_BPartner_Location.java
| 1
|
请完成以下Java代码
|
public String getMonitorJobDefinitionId() {
return monitorJobDefinitionId;
}
public void setMonitorJobDefinitionId(String monitorJobDefinitionId) {
this.monitorJobDefinitionId = monitorJobDefinitionId;
}
public String getBatchJobDefinitionId() {
return batchJobDefinitionId;
}
public void setBatchJobDefinitionId(String batchJobDefinitionId) {
this.batchJobDefinitionId = batchJobDefinitionId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getCreateUserId() {
return createUserId;
}
public void setCreateUserId(String createUserId) {
this.createUserId = createUserId;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
@Override
|
public Date getExecutionStartTime() {
return executionStartTime;
}
public void setExecutionStartTime(final Date executionStartTime) {
this.executionStartTime = executionStartTime;
}
@Override
public Object getPersistentState() {
Map<String, Object> persistentState = new HashMap<String, Object>();
persistentState.put("endTime", endTime);
persistentState.put("executionStartTime", executionStartTime);
return persistentState;
}
public void delete() {
HistoricIncidentManager historicIncidentManager = Context.getCommandContext().getHistoricIncidentManager();
historicIncidentManager.deleteHistoricIncidentsByJobDefinitionId(seedJobDefinitionId);
historicIncidentManager.deleteHistoricIncidentsByJobDefinitionId(monitorJobDefinitionId);
historicIncidentManager.deleteHistoricIncidentsByJobDefinitionId(batchJobDefinitionId);
HistoricJobLogManager historicJobLogManager = Context.getCommandContext().getHistoricJobLogManager();
historicJobLogManager.deleteHistoricJobLogsByJobDefinitionId(seedJobDefinitionId);
historicJobLogManager.deleteHistoricJobLogsByJobDefinitionId(monitorJobDefinitionId);
historicJobLogManager.deleteHistoricJobLogsByJobDefinitionId(batchJobDefinitionId);
Context.getCommandContext().getHistoricBatchManager().delete(this);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\history\HistoricBatchEntity.java
| 1
|
请完成以下Java代码
|
public JsonNodeType getNodeType() {
return jsonNode.getNodeType();
}
public SpinJsonPathQuery jsonPath(String expression) {
ensureNotNull("expression", expression);
try {
JsonPath query = JsonPath.compile(expression);
return new JacksonJsonPathQuery(this, query, dataFormat);
} catch(InvalidPathException pex) {
throw LOG.unableToCompileJsonPathExpression(expression, pex);
} catch(IllegalArgumentException aex) {
throw LOG.unableToCompileJsonPathExpression(expression, aex);
}
}
/**
* Maps the json represented by this object to a java object of the given type.<br>
* Note: the desired target type is not validated and needs to be trusted.
*
* @throws SpinJsonException if the json representation cannot be mapped to the specified type
*/
public <C> C mapTo(Class<C> type) {
DataFormatMapper mapper = dataFormat.getMapper();
return mapper.mapInternalToJava(jsonNode, type);
}
/**
|
* Maps the json represented by this object to a java object of the given type.
* Argument is to be supplied in Jackson's canonical type string format
* (see {@link JavaType#toCanonical()}).<br>
* Note: the desired target type is not validated and needs to be trusted.
*
* @throws SpinJsonException if the json representation cannot be mapped to the specified type
* @throws SpinJsonDataFormatException if the parameter does not match a valid type
*/
public <C> C mapTo(String type) {
DataFormatMapper mapper = dataFormat.getMapper();
return mapper.mapInternalToJava(jsonNode, type);
}
/**
* Maps the json represented by this object to a java object of the given type.<br>
* Note: the desired target type is not validated and needs to be trusted.
*
* @throws SpinJsonException if the json representation cannot be mapped to the specified type
*/
public <C> C mapTo(JavaType type) {
JacksonJsonDataFormatMapper mapper = dataFormat.getMapper();
return mapper.mapInternalToJava(jsonNode, type);
}
}
|
repos\camunda-bpm-platform-master\spin\dataformat-json-jackson\src\main\java\org\camunda\spin\impl\json\jackson\JacksonJsonNode.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable Strictness getStrictness() {
return this.strictness;
}
public void setStrictness(@Nullable Strictness strictness) {
this.strictness = strictness;
}
public void setLenient(@Nullable Boolean lenient) {
setStrictness((lenient != null && lenient) ? Strictness.LENIENT : Strictness.STRICT);
}
public @Nullable Boolean getDisableHtmlEscaping() {
return this.disableHtmlEscaping;
}
public void setDisableHtmlEscaping(@Nullable Boolean disableHtmlEscaping) {
this.disableHtmlEscaping = disableHtmlEscaping;
}
public @Nullable String getDateFormat() {
return this.dateFormat;
}
public void setDateFormat(@Nullable String dateFormat) {
this.dateFormat = dateFormat;
}
/**
|
* Enumeration of levels of strictness. Values are the same as those on
* {@link com.google.gson.Strictness} that was introduced in Gson 2.11. To maximize
* backwards compatibility, the Gson enum is not used directly.
*/
public enum Strictness {
/**
* Lenient compliance.
*/
LENIENT,
/**
* Strict compliance with some small deviations for legacy reasons.
*/
LEGACY_STRICT,
/**
* Strict compliance.
*/
STRICT
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-gson\src\main\java\org\springframework\boot\gson\autoconfigure\GsonProperties.java
| 2
|
请完成以下Java代码
|
public class UserUpadtePwdJob implements Job {
@Autowired
private ISysBaseAPI sysBaseAPI;
@Autowired
private ISysUserService userService;
@Override
public void execute(JobExecutionContext context) {
//获取当前时间5个月前的时间
// 获取当前日期
Calendar calendar = Calendar.getInstance();
// 减去5个月
calendar.add(Calendar.MONTH, -5);
// 格式化输出
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = sdf.format(calendar.getTime());
String startTime = formattedDate + " 00:00:00";
String endTime = formattedDate + " 23:59:59";
LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.between(SysUser::getLastPwdUpdateTime, startTime, endTime);
queryWrapper.select(SysUser::getUsername,SysUser::getRealname);
List<SysUser> list = userService.list(queryWrapper);
if (CollectionUtil.isNotEmpty(list)){
for (SysUser sysUser : list) {
this.sendSysMessage(sysUser.getUsername(), sysUser.getRealname());
|
}
}
}
/**
* 发送系统消息
*/
private void sendSysMessage(String username, String realname) {
String fromUser = "system";
String title = "尊敬的"+realname+"您的密码已经5个月未修改了,请修改密码";
MessageDTO messageDTO = new MessageDTO(fromUser, username, title, title);
messageDTO.setNoticeType(NoticeTypeEnum.NOTICE_TYPE_PLAN.getValue());
sysBaseAPI.sendSysAnnouncement(messageDTO);
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\job\UserUpadtePwdJob.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Queue demo05Queue() {
return new Queue(Demo05Message.QUEUE, // Queue 名字
true, // durable: 是否持久化
false, // exclusive: 是否排它
false); // autoDelete: 是否自动删除
}
// 创建 Direct Exchange
@Bean
public DirectExchange demo05Exchange() {
return new DirectExchange(Demo05Message.EXCHANGE,
true, // durable: 是否持久化
false); // exclusive: 是否排它
}
// 创建 Binding
// Exchange:Demo05Message.EXCHANGE
// Routing key:Demo05Message.ROUTING_KEY
// Queue:Demo05Message.QUEUE
@Bean
public Binding demo05Binding() {
return BindingBuilder.bind(demo05Queue()).to(demo05Exchange()).with(Demo05Message.ROUTING_KEY);
}
}
|
@Bean
public BatchingRabbitTemplate batchRabbitTemplate(ConnectionFactory connectionFactory) {
// 创建 BatchingStrategy 对象,代表批量策略
int batchSize = 16384; // 超过收集的消息数量的最大条数。
int bufferLimit = 33554432; // 每次批量发送消息的最大内存
int timeout = 30000; // 超过收集的时间的最大等待时长,单位:毫秒
BatchingStrategy batchingStrategy = new SimpleBatchingStrategy(batchSize, bufferLimit, timeout);
// 创建 TaskScheduler 对象,用于实现超时发送的定时器
TaskScheduler taskScheduler = new ConcurrentTaskScheduler();
// 创建 BatchingRabbitTemplate 对象
BatchingRabbitTemplate batchTemplate = new BatchingRabbitTemplate(batchingStrategy, taskScheduler);
batchTemplate.setConnectionFactory(connectionFactory);
return batchTemplate;
}
}
|
repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-demo-batch\src\main\java\cn\iocoder\springboot\lab04\rabbitmqdemo\config\RabbitConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class HttpAccessAspect {
private Logger logger = LoggerFactory.getLogger(getClass());
@Around("@within(org.springframework.stereotype.Controller)" +
"|| @within(org.springframework.web.bind.annotation.RestController)")
public Object around(ProceedingJoinPoint point) throws Throwable {
// 获取类名
String className = point.getTarget().getClass().getName();
// 获取方法
String methodName = point.getSignature().getName();
// 记录开始时间
long beginTime = System.currentTimeMillis();
// 记录返回结果
Object result = null;
Exception ex = null;
try {
// 执行方法
result = point.proceed();
return result;
} catch (Exception e) {
|
ex = e;
throw e;
} finally {
// 计算消耗时间
long costTime = System.currentTimeMillis() - beginTime;
// 发生异常,则打印 ERROR 日志
if (ex != null) {
logger.error("[className: {}][methodName: {}][cost: {} ms][args: {}][发生异常]",
className, methodName, point.getArgs(), ex);
// 正常执行,则打印 INFO 日志
} else {
logger.info("[className: {}][methodName: {}][cost: {} ms][args: {}][return: {}]",
className, methodName, costTime, point.getArgs(), result);
}
}
}
}
|
repos\SpringBoot-Labs-master\lab-37\lab-37-logging-aop\src\main\java\cn\iocoder\springboot\lab37\loggingdemo\aspect\HttpAccessAspect.java
| 2
|
请完成以下Java代码
|
public int getMaxInactiveInterval() {
return (int) this.session.getMaxInactiveInterval().getSeconds();
}
@Override
public Object getAttribute(String name) {
checkState();
return this.session.getAttribute(name);
}
@Override
public Enumeration<String> getAttributeNames() {
checkState();
return Collections.enumeration(this.session.getAttributeNames());
}
@Override
public void setAttribute(String name, Object value) {
checkState();
Object oldValue = this.session.getAttribute(name);
this.session.setAttribute(name, value);
if (value != oldValue) {
if (oldValue instanceof HttpSessionBindingListener) {
try {
((HttpSessionBindingListener) oldValue)
.valueUnbound(new HttpSessionBindingEvent(this, name, oldValue));
}
catch (Throwable th) {
logger.error("Error invoking session binding event listener", th);
}
}
if (value instanceof HttpSessionBindingListener) {
try {
((HttpSessionBindingListener) value).valueBound(new HttpSessionBindingEvent(this, name, value));
}
catch (Throwable th) {
logger.error("Error invoking session binding event listener", th);
}
}
}
}
@Override
public void removeAttribute(String name) {
checkState();
Object oldValue = this.session.getAttribute(name);
this.session.removeAttribute(name);
if (oldValue instanceof HttpSessionBindingListener) {
|
try {
((HttpSessionBindingListener) oldValue).valueUnbound(new HttpSessionBindingEvent(this, name, oldValue));
}
catch (Throwable th) {
logger.error("Error invoking session binding event listener", th);
}
}
}
@Override
public void invalidate() {
checkState();
this.invalidated = true;
}
@Override
public boolean isNew() {
checkState();
return !this.old;
}
void markNotNew() {
this.old = true;
}
private void checkState() {
if (this.invalidated) {
throw new IllegalStateException("The HttpSession has already be invalidated.");
}
}
}
|
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\HttpSessionAdapter.java
| 1
|
请完成以下Java代码
|
private static BigDecimal computeQtyDemand_Sum(@NonNull final I_MD_Cockpit dataRecord)
{
return dataRecord.getQtyDemand_SalesOrder_AtDate()
.add(dataRecord.getQtyDemand_PP_Order_AtDate())
.add(dataRecord.getQtyDemand_DD_Order_AtDate());
}
/**
* Computes sum of all pending supply quantities
*
* @param dataRecord I_MD_Cockpit
* @return dataRecord.QtySupply_PP_Order + dataRecord.QtySupply_PurchaseOrder + dataRecord.QtySupply_DD_Order
*/
@NonNull
private static BigDecimal computeQtySupply_Sum(@NonNull final I_MD_Cockpit dataRecord)
{
return dataRecord.getQtySupply_PurchaseOrder_AtDate()
.add(dataRecord.getQtySupply_PP_Order_AtDate())
.add(dataRecord.getQtySupply_DD_Order_AtDate());
}
/**
* The quantity required according to material disposition that is not yet addressed by purchase order, production-receipt or distribution order.
*
* @param dataRecord I_MD_Cockpit
* @return dataRecord.QtySupplyRequired - dataRecord.QtySupplySum
*/
public static BigDecimal computeQtySupplyToSchedule(@NonNull final I_MD_Cockpit dataRecord)
{
return CoalesceUtil.firstPositiveOrZero(
dataRecord.getQtySupplyRequired_AtDate().subtract(dataRecord.getQtySupplySum_AtDate()));
}
/**
|
* Current pending supplies minus pending demands
*
* @param dataRecord I_MD_Cockpit
* @return dataRecord.QtyStockCurrent + dataRecord.QtySupplySum - dataRecord.QtyDemandSum
*/
public static BigDecimal computeQtyExpectedSurplus(@NonNull final I_MD_Cockpit dataRecord)
{
return dataRecord.getQtySupplySum_AtDate().subtract(dataRecord.getQtyDemandSum_AtDate());
}
@NonNull
private static BigDecimal computeSum(@NonNull final BigDecimal... args)
{
final BigDecimal sum = Stream.of(args)
.reduce(BigDecimal::add)
.orElse(BigDecimal.ZERO);
return stripTrailingDecimalZeros(sum);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\view\mainrecord\MainDataRequestHandler.java
| 1
|
请完成以下Java代码
|
public boolean isEnabled(NotificationType notificationType, NotificationDeliveryMethod deliveryMethod) {
NotificationPref pref = prefs.get(notificationType);
if (pref == null) {
return true;
}
if (!pref.isEnabled()) {
return false;
}
return pref.getEnabledDeliveryMethods().getOrDefault(deliveryMethod, true);
}
@Data
public static class NotificationPref {
private boolean enabled;
@NotNull
private Map<NotificationDeliveryMethod, Boolean> enabledDeliveryMethods;
|
public static NotificationPref createDefault() {
NotificationPref pref = new NotificationPref();
pref.setEnabled(true);
pref.setEnabledDeliveryMethods(deliveryMethods.stream().collect(Collectors.toMap(v -> v, v -> true)));
return pref;
}
@JsonIgnore
@AssertTrue(message = "Only email, Web and SMS delivery methods are allowed")
public boolean isValid() {
return enabledDeliveryMethods.entrySet().stream()
.allMatch(entry -> deliveryMethods.contains(entry.getKey()) && entry.getValue() != null);
}
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\notification\settings\UserNotificationSettings.java
| 1
|
请完成以下Java代码
|
public void setTrxItemProcessorCtx(final ITrxItemProcessorContext processorCtx)
{
this.processorCtx = processorCtx;
}
@Override
public void process(final I_C_OLCand olCand) throws Exception
{
if (olCand.isProcessed())
{
result.incSkipped();
return;
}
final IParams params = processorCtx.getParams();
Check.errorIf(params == null, "Given processorCtx {} needs to contain params", processorCtx);
// Partner
final int bpartnerId = params.getParameterAsInt(I_C_OLCand.COLUMNNAME_C_BPartner_Override_ID, -1);
olCand.setC_BPartner_Override_ID(bpartnerId);
// Location
final BPartnerLocationId bpartnerLocationId = getBPartnerLocationId(olCand, params, bpartnerId);
olCand.setC_BP_Location_Override_ID(BPartnerLocationId.toRepoId(bpartnerLocationId));
// DatePrommissed
final Timestamp datePromissed = params.getParameterAsTimestamp(I_C_OLCand.COLUMNNAME_DatePromised_Override);
olCand.setDatePromised_Override(datePromissed);
//AD_User_ID
final UserId userId = UserId.ofRepoIdOrNull(olCand.getAD_User_ID());
final BPartnerLocationId bPartnerLocationId = BPartnerLocationId.ofRepoIdOrNull(bpartnerId, BPartnerLocationId.toRepoId(bpartnerLocationId));
if (bPartnerLocationId != null && userId != null)
{
|
final boolean userIsValidForBpartner = bpartnerDAO.getUserIdsForBpartnerLocation(bPartnerLocationId).anyMatch(userId::equals);
if (!userIsValidForBpartner)
{
Loggables.withLogger(logger, Level.INFO).addLog("For OLCand: {}, userId {} is not valid for locationId: {}. Setting to null", olCand.getC_OLCand_ID(), userId, bPartnerLocationId);
olCand.setAD_User_ID(-1);
}
}
InterfaceWrapperHelper.save(olCand);
result.incUpdated();
}
@Nullable
private BPartnerLocationId getBPartnerLocationId(final I_C_OLCand olCand, final IParams params, final int bpartnerId)
{
final BPartnerLocationId bpartnerLocationId;
if (params.hasParameter(PARAM_C_BPARTNER_LOCATION_MAP))
{
final Map<BPartnerLocationId, BPartnerLocationId> oldToNewLocationIds = (Map<BPartnerLocationId, BPartnerLocationId>)params.getParameterAsObject(PARAM_C_BPARTNER_LOCATION_MAP);
bpartnerLocationId = oldToNewLocationIds.get(BPartnerLocationId.ofRepoId(olCand.getC_BPartner_ID(), olCand.getC_BPartner_Location_ID()));
}
else
{
bpartnerLocationId = BPartnerLocationId.ofRepoIdOrNull(bpartnerId, params.getParameterAsInt(I_C_OLCand.COLUMNNAME_C_BP_Location_Override_ID, -1));
}
return bpartnerLocationId;
}
@Override
public OLCandUpdateResult getResult()
{
return result;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\impl\OLCandUpdater.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static boolean isGroupAttributesKeyMatching(
@NonNull final AvailableToPromiseResultGroupBuilder group,
@NonNull final AttributesKey requestStorageAttributesKey)
{
final AttributesKey groupAttributesKey = group.getStorageAttributesKey();
if (groupAttributesKey.isAll())
{
return true;
}
else if (groupAttributesKey.isOther())
{
// accept it. We assume that the actual matching was done on Bucket level and not on Group level
return true;
}
else if (groupAttributesKey.isNone())
{
// shall not happen
return false;
}
else
{
final AttributesKeyPattern groupAttributePattern = AttributesKeyPatternsUtil.ofAttributeKey(groupAttributesKey);
return groupAttributePattern.matches(requestStorageAttributesKey);
}
}
private AvailableToPromiseResultGroupBuilder newGroup(
@NonNull final AddToResultGroupRequest request,
@NonNull final AttributesKey storageAttributesKey)
{
final AvailableToPromiseResultGroupBuilder group = AvailableToPromiseResultGroupBuilder.builder()
.bpartner(request.getBpartner())
.warehouse(WarehouseClassifier.specific(request.getWarehouseId()))
.productId(request.getProductId())
.storageAttributesKey(storageAttributesKey)
.build();
groups.add(group);
return group;
}
void addDefaultEmptyGroupIfPossible()
{
if (product.isAny())
|
{
return;
}
final AttributesKey defaultAttributesKey = this.storageAttributesKeyMatcher.toAttributeKeys().orElse(null);
if (defaultAttributesKey == null)
{
return;
}
final AvailableToPromiseResultGroupBuilder group = AvailableToPromiseResultGroupBuilder.builder()
.bpartner(bpartner)
.warehouse(warehouse)
.productId(ProductId.ofRepoId(product.getProductId()))
.storageAttributesKey(defaultAttributesKey)
.build();
groups.add(group);
}
@VisibleForTesting
boolean isZeroQty()
{
if (groups.isEmpty())
{
return true;
}
for (AvailableToPromiseResultGroupBuilder group : groups)
{
if (!group.isZeroQty())
{
return false;
}
}
return true;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\atp\AvailableToPromiseResultBucket.java
| 2
|
请完成以下Java代码
|
default void setJsp(Jsp jsp) {
getSettings().setJsp(jsp);
}
/**
* Sets the Locale to Charset mappings.
* @param localeCharsetMappings the Locale to Charset mappings
*/
default void setLocaleCharsetMappings(Map<Locale, Charset> localeCharsetMappings) {
getSettings().setLocaleCharsetMappings(localeCharsetMappings);
}
/**
* Sets the init parameters that are applied to the container's
* {@link ServletContext}.
* @param initParameters the init parameters
*/
default void setInitParameters(Map<String, String> initParameters) {
getSettings().setInitParameters(initParameters);
}
/**
* Sets {@link CookieSameSiteSupplier CookieSameSiteSuppliers} that should be used to
* obtain the {@link SameSite} attribute of any added cookie. This method will replace
|
* any previously set or added suppliers.
* @param cookieSameSiteSuppliers the suppliers to add
* @see #addCookieSameSiteSuppliers
*/
default void setCookieSameSiteSuppliers(List<? extends CookieSameSiteSupplier> cookieSameSiteSuppliers) {
getSettings().setCookieSameSiteSuppliers(cookieSameSiteSuppliers);
}
/**
* Add {@link CookieSameSiteSupplier CookieSameSiteSuppliers} to those that should be
* used to obtain the {@link SameSite} attribute of any added cookie.
* @param cookieSameSiteSuppliers the suppliers to add
* @see #setCookieSameSiteSuppliers
*/
default void addCookieSameSiteSuppliers(CookieSameSiteSupplier... cookieSameSiteSuppliers) {
getSettings().addCookieSameSiteSuppliers(cookieSameSiteSuppliers);
}
@Override
default void addWebListeners(String... webListenerClassNames) {
getSettings().addWebListenerClassNames(webListenerClassNames);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\ConfigurableServletWebServerFactory.java
| 1
|
请完成以下Java代码
|
public void assertChangeAllowed(@NonNull final I_C_OrderLine orderLine)
{
// dev-note: do not impact the performance, check only lines with some quantity delivered
if (orderLine.getQtyDelivered().signum() == 0 || orderBL.isSalesOrder(OrderId.ofRepoId(orderLine.getC_Order_ID())))
{
return;
}
final I_C_OrderLine oldOrderLineRecord = InterfaceWrapperHelper.createOld(orderLine, I_C_OrderLine.class);
if (oldOrderLineRecord.getQtyEntered().compareTo(orderLine.getQtyEntered()) != 0 || oldOrderLineRecord.getC_UOM_ID() != orderLine.getC_UOM_ID())
{
validateQtyEntered(orderLine);
}
else
{
throw new AdempiereException(ERR_ORDER_MODIFICATION_NOT_ALLOWED_RECEIPT_EXISTS)
.markAsUserValidationError();
}
}
|
private void validateQtyEntered(@NonNull final I_C_OrderLine orderLine)
{
final Quantity quantityEntered = orderLineBL.convertQtyEnteredToStockUOM(orderLine);
final Quantity quantityDelivered = orderLineBL.getQtyDelivered(OrderAndLineId.of(
OrderId.ofRepoId(orderLine.getC_Order_ID()), OrderLineId.ofRepoId(orderLine.getC_OrderLine_ID())));
if (quantityEntered.compareTo(quantityDelivered) < 0)
{
throw new AdempiereException("@QtyEntered@ < @QtyDelivered@")
.markAsUserValidationError();
}
}
private void updateQtyPacks(final de.metas.handlingunits.model.I_C_OrderLine orderLine)
{
final IHUPackingAware packingAware = new OrderLineHUPackingAware(orderLine);
Services.get(IHUPackingAwareBL.class).setQtyTU(packingAware);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\C_OrderLine.java
| 1
|
请完成以下Java代码
|
public String getName() {
return "enum";
}
@Override
public Object getInformation(String key) {
if ("values".equals(key)) {
return values;
}
return null;
}
@Override
public Object convertFormValueToModelValue(String propertyValue) {
validateValue(propertyValue);
return propertyValue;
}
@Override
public String convertModelValueToFormValue(Object modelValue) {
if (modelValue != null) {
if (!(modelValue instanceof String)) {
|
throw new FlowableIllegalArgumentException("Model value should be a String");
}
validateValue((String) modelValue);
}
return (String) modelValue;
}
protected void validateValue(String value) {
if (value != null) {
if (values != null && !values.containsKey(value)) {
throw new FlowableIllegalArgumentException("Invalid value for enum form property: " + value);
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\form\EnumFormType.java
| 1
|
请完成以下Java代码
|
public ClientRegistration findByRegistrationId(String registrationId) {
OAuth2Client oAuth2Client = oAuth2ClientService.findOAuth2ClientById(TenantId.SYS_TENANT_ID, new OAuth2ClientId(UUID.fromString(registrationId)));
if (oAuth2Client == null) {
return null;
}
return toSpringClientRegistration(oAuth2Client);
}
private ClientRegistration toSpringClientRegistration(OAuth2Client oAuth2Client) {
String registrationId = oAuth2Client.getUuidId().toString();
// NONE is used if we need pkce-based code challenge
ClientAuthenticationMethod authMethod = ClientAuthenticationMethod.NONE;
if (oAuth2Client.getClientAuthenticationMethod().equals("POST")) {
authMethod = ClientAuthenticationMethod.CLIENT_SECRET_POST;
} else if (oAuth2Client.getClientAuthenticationMethod().equals("BASIC")) {
authMethod = ClientAuthenticationMethod.CLIENT_SECRET_BASIC;
}
|
return ClientRegistration.withRegistrationId(registrationId)
.clientName(oAuth2Client.getName())
.clientId(oAuth2Client.getClientId())
.authorizationUri(oAuth2Client.getAuthorizationUri())
.clientSecret(oAuth2Client.getClientSecret())
.tokenUri(oAuth2Client.getAccessTokenUri())
.scope(oAuth2Client.getScope())
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.userInfoUri(oAuth2Client.getUserInfoUri())
.userNameAttributeName(oAuth2Client.getUserNameAttributeName())
.jwkSetUri(oAuth2Client.getJwkSetUri())
.clientAuthenticationMethod(authMethod)
.redirectUri(defaultRedirectUriTemplate)
.build();
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\oauth2\HybridClientRegistrationRepository.java
| 1
|
请完成以下Java代码
|
private static void addParagraphInCenter(Document document) throws IOException, DocumentException {
Paragraph paragraph = new Paragraph("This paragraph will be horizontally centered.");
paragraph.setAlignment(Element.ALIGN_CENTER);
document.add(paragraph);
}
private static void addTableHeader(PdfPTable table) {
Stream.of("column header 1", "column header 2", "column header 3")
.forEach(columnTitle -> {
PdfPCell header = new PdfPCell();
header.setBackgroundColor(BaseColor.LIGHT_GRAY);
header.setBorderWidth(2);
header.setPhrase(new Phrase(columnTitle));
table.addCell(header);
});
}
private static void setAbsoluteColumnWidths(PdfPTable table) throws DocumentException {
table.setTotalWidth(500); // Sets total table width to 500 points
table.setLockedWidth(true);
float[] columnWidths = {100f, 200f, 200f}; // Defines three columns with absolute widths
table.setWidths(columnWidths);
}
private static void setAbsoluteColumnWidthsInTableWidth(PdfPTable table) throws DocumentException {
table.setTotalWidth(new float[] {72f, 144f, 216f}); // First column 1 inch, second 2 inches, third 3 inches
table.setLockedWidth(true);
}
private static void setRelativeColumnWidths(PdfPTable table) throws DocumentException {
// Set column widths (relative)
table.setWidths(new float[] {1, 2, 1});
table.setWidthPercentage(80); // Table width as 80% of page width
}
private static void addRows(PdfPTable table) {
table.addCell("row 1, col 1");
table.addCell("row 1, col 2");
table.addCell("row 1, col 3");
|
}
private static void addCustomRows(PdfPTable table) throws URISyntaxException, BadElementException, IOException {
Path path = Paths.get(ClassLoader.getSystemResource("Java_logo.png").toURI());
Image img = Image.getInstance(path.toAbsolutePath().toString());
img.scalePercent(10);
PdfPCell imageCell = new PdfPCell(img);
table.addCell(imageCell);
PdfPCell horizontalAlignCell = new PdfPCell(new Phrase("row 2, col 2"));
horizontalAlignCell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(horizontalAlignCell);
PdfPCell verticalAlignCell = new PdfPCell(new Phrase("row 2, col 3"));
verticalAlignCell.setVerticalAlignment(Element.ALIGN_BOTTOM);
table.addCell(verticalAlignCell);
}
}
|
repos\tutorials-master\text-processing-libraries-modules\pdf\src\main\java\com\baeldung\pdf\PDFSampleMain.java
| 1
|
请完成以下Java代码
|
protected String doIt()
{
final I_AD_ImpFormat impFormat = getRecord(I_AD_ImpFormat.class);
final I_AD_Table table = tableDAO.retrieveTable(AdTableId.ofRepoId(impFormat.getAD_Table_ID()));
final List<I_AD_Column> columns = tableDAO.retrieveColumnsForTable(table);
final AtomicInteger index = new AtomicInteger(1);
columns.stream().filter(column -> !DisplayType.isLookup(column.getAD_Reference_ID()))
.forEach(column -> {
final I_AD_ImpFormat_Row impRow = createImpFormatRow(impFormat, column, index);
index.incrementAndGet();
addLog("@Created@ @AD_ImpFormat_Row_ID@: {}", impRow);
});
return MSG_OK;
}
private I_AD_ImpFormat_Row createImpFormatRow(@NonNull final I_AD_ImpFormat impFormat, @NonNull final I_AD_Column column, final AtomicInteger index)
{
final I_AD_ImpFormat_Row impRow = newInstance(I_AD_ImpFormat_Row.class);
impRow.setAD_Column_ID(column.getAD_Column_ID());
impRow.setAD_ImpFormat_ID(impFormat.getAD_ImpFormat_ID());
impRow.setName(column.getName());
final int adRefId = column.getAD_Reference_ID();
impRow.setDataType(extractDisplayType(adRefId));
impRow.setSeqNo(index.get());
impRow.setStartNo(index.get());
save(impRow);
return impRow;
}
private String extractDisplayType(final int adRefId)
{
if (DisplayType.isText(adRefId))
|
{
return X_AD_ImpFormat_Row.DATATYPE_String;
}
else if (DisplayType.isNumeric(adRefId))
{
return X_AD_ImpFormat_Row.DATATYPE_Number;
}
else if (DisplayType.isDate(adRefId))
{
return X_AD_ImpFormat_Row.DATATYPE_Date;
}
else
{
return X_AD_ImpFormat_Row.DATATYPE_Constant;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\process\AD_ImpFormat_Row_Create_Based_OnTable.java
| 1
|
请完成以下Java代码
|
public class DefaultReactiveHealthContributorRegistry extends AbstractRegistry<ReactiveHealthContributor, Entry>
implements ReactiveHealthContributorRegistry {
/**
* Create a new empty {@link DefaultReactiveHealthContributorRegistry} instance.
*/
public DefaultReactiveHealthContributorRegistry() {
this(null, null);
}
/**
* Create a new {@link DefaultReactiveHealthContributorRegistry} instance.
* @param nameValidators the name validators to apply
* @param initialRegistrations callback to setup any initial registrations
*/
public DefaultReactiveHealthContributorRegistry(
@Nullable Collection<? extends HealthContributorNameValidator> nameValidators,
@Nullable Consumer<BiConsumer<String, ReactiveHealthContributor>> initialRegistrations) {
super(Entry::new, nameValidators, initialRegistrations);
}
@Override
public @Nullable ReactiveHealthContributor getContributor(String name) {
return super.getContributor(name);
}
@Override
|
public Stream<Entry> stream() {
return super.stream();
}
@Override
public void registerContributor(String name, ReactiveHealthContributor contributor) {
super.registerContributor(name, contributor);
}
@Override
public @Nullable ReactiveHealthContributor unregisterContributor(String name) {
return super.unregisterContributor(name);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\registry\DefaultReactiveHealthContributorRegistry.java
| 1
|
请完成以下Java代码
|
public String getEventName() {
return eventName;
}
public boolean isAsync() {
return async;
}
public void setAsync(boolean async) {
this.async = async;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getActivityId() {
return activityId;
}
public boolean isStartEvent() {
return isStartEvent;
}
public void setStartEvent(boolean isStartEvent) {
this.isStartEvent = isStartEvent;
}
public String getEventType() {
return eventType;
}
public String getConfiguration() {
return configuration;
}
public void setConfiguration(String configuration) {
this.configuration = configuration;
}
public EventSubscriptionEntity prepareEventSubscriptionEntity(ExecutionEntity execution) {
|
EventSubscriptionEntity eventSubscriptionEntity = null;
if ("message".equals(eventType)) {
eventSubscriptionEntity = new MessageEventSubscriptionEntity(execution);
} else if ("signal".equals(eventType)) {
eventSubscriptionEntity = new SignalEventSubscriptionEntity(execution);
} else {
throw new ActivitiIllegalArgumentException("Found event definition of unknown type: " + eventType);
}
eventSubscriptionEntity.setEventName(eventName);
if (activityId != null) {
ActivityImpl activity = execution.getProcessDefinition().findActivity(activityId);
eventSubscriptionEntity.setActivity(activity);
}
if (configuration != null) {
eventSubscriptionEntity.setConfiguration(configuration);
}
return eventSubscriptionEntity;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\EventSubscriptionDeclaration.java
| 1
|
请完成以下Java代码
|
public class MGoalRestriction extends X_PA_GoalRestriction
{
/**
*
*/
private static final long serialVersionUID = 4027980875091517732L;
/**
* Standard Constructor
* @param ctx context
* @param PA_GoalRestriction_ID id
* @param trxName trx
*/
public MGoalRestriction (Properties ctx, int PA_GoalRestriction_ID,
String trxName)
{
super (ctx, PA_GoalRestriction_ID, trxName);
} // MGoalRestriction
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName trx
|
*/
public MGoalRestriction (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MGoalRestriction
/**
* String Representation
* @return info
*/
public String toString ()
{
StringBuffer sb = new StringBuffer ("MGoalRestriction[");
sb.append (get_ID()).append ("-").append (getName()).append ("]");
return sb.toString ();
} // toString
} // MGoalRestriction
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MGoalRestriction.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public TransactionSynchronizationFactory transactionSynchronizationFactory() {
ExpressionEvaluatingTransactionSynchronizationProcessor processor =
new ExpressionEvaluatingTransactionSynchronizationProcessor();
SpelExpressionParser spelParser = new SpelExpressionParser();
processor.setAfterCommitExpression(
spelParser.parseExpression(
"payload.renameTo(new java.io.File(payload.absolutePath + '.PASSED'))"));
processor.setAfterRollbackExpression(
spelParser.parseExpression(
"payload.renameTo(new java.io.File(payload.absolutePath + '.FAILED'))"));
return new DefaultTransactionSynchronizationFactory(processor);
}
@Bean
@Transformer(inputChannel = "inputChannel", outputChannel = "toServiceChannel")
public FileToStringTransformer fileToStringTransformer() {
return new FileToStringTransformer();
}
@ServiceActivator(inputChannel = "toServiceChannel")
public void serviceActivator(String payload) {
jdbcTemplate.update("insert into STUDENT values(?)", payload);
if (payload.toLowerCase().startsWith("fail")) {
log.error("Service failure. Test result: {} ", payload);
throw new RuntimeException("Service failure.");
}
log.info("Service success. Test result: {}", payload);
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
|
.setType(EmbeddedDatabaseType.H2)
.addScript("classpath:table.sql")
.build();
}
@Bean
public DataSourceTransactionManager txManager() {
return new DataSourceTransactionManager(dataSource);
}
public static void main(final String... args) {
final AbstractApplicationContext context = new AnnotationConfigApplicationContext(TxIntegrationConfig.class);
context.registerShutdownHook();
final Scanner scanner = new Scanner(System.in);
System.out.print("Integration flow is running. Type q + <enter> to quit ");
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\tx\TxIntegrationConfig.java
| 2
|
请完成以下Java代码
|
int calculateSum(int[] x) {
int sum = 0;
for (int i = 0; i < 10; i++) {
if (x[i] < 0) {
break;
}
sum += x[i];
}
return sum;
}
<T> T stopExecutionUsingException(T object) {
if (object instanceof Number) {
throw new IllegalArgumentException("Parameter can not be number.");
}
T upperCase = (T) String.valueOf(object)
.toUpperCase(Locale.ENGLISH);
return upperCase;
}
int processLines(String[] lines) {
int statusCode = 0;
parser:
for (String line : lines) {
System.out.println("Processing line: " + line);
if (line.equals("stop")) {
System.out.println("Stopping parsing...");
statusCode = -1;
break parser; // Stop parsing and exit the loop
}
System.out.println("Line processed.");
}
return statusCode;
}
void download(String fileUrl, String destinationPath) throws MalformedURLException, URISyntaxException {
if (fileUrl == null || fileUrl.isEmpty() || destinationPath == null || destinationPath.isEmpty()) {
|
return;
}
// execute downloading
URL url = new URI(fileUrl).toURL();
try (InputStream in = url.openStream(); FileOutputStream out = new FileOutputStream(destinationPath)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-6\src\main\java\com\baeldung\stopexecution\StopExecutionFurtherCode.java
| 1
|
请完成以下Java代码
|
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Product))
return false;
Product product = (Product) o;
if (id != product.id)
return false;
if (memory != product.memory)
return false;
if (!productName.equals(product.productName))
return false;
return description.equals(product.description);
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + productName.hashCode();
result = 31 * result + memory;
result = 31 * result + description.hashCode();
return result;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProductName() {
|
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getMemory() {
return memory;
}
public void setMemory(int memory) {
this.memory = memory;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
repos\tutorials-master\persistence-modules\spring-hibernate-5\src\main\java\com\baeldung\hibernatesearch\model\Product.java
| 1
|
请完成以下Java代码
|
public I_C_Flatrate_Term getWrappedRecord()
{
return delegate;
}
@Override
public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL)
{
return documentLocationBL.toPlainDocumentLocation(this);
}
@Override
public ContractBillLocationAdapter toOldValues()
{
InterfaceWrapperHelper.assertNotOldValues(delegate);
return new ContractBillLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_Flatrate_Term.class));
}
|
public void setFrom(final @NonNull BPartnerLocationAndCaptureId billToLocationId, final @Nullable BPartnerContactId billToContactId)
{
setBill_BPartner_ID(billToLocationId.getBpartnerRepoId());
setBill_Location_ID(billToLocationId.getBPartnerLocationRepoId());
setBill_Location_Value_ID(billToLocationId.getLocationCaptureRepoId());
setBill_User_ID(billToContactId == null ? -1 : billToContactId.getRepoId());
}
public void setFrom(final @NonNull BPartnerLocationAndCaptureId billToLocationId)
{
setBill_BPartner_ID(billToLocationId.getBpartnerRepoId());
setBill_Location_ID(billToLocationId.getBPartnerLocationRepoId());
setBill_Location_Value_ID(billToLocationId.getLocationCaptureRepoId());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\location\adapter\ContractBillLocationAdapter.java
| 1
|
请完成以下Java代码
|
protected void invoke() throws Exception {
varMapping.mapOutputVariables(execution, subInstance);
}
});
}
}
protected void invokeVarMappingDelegation(DelegateInvocation delegation) {
try {
Context.getProcessEngineConfiguration().getDelegateInterceptor().handleInvocation(delegation);
} catch (Exception ex) {
throw new ProcessEngineException(ex);
}
}
protected VariableMap filterVariables(VariableMap variables) {
if (variables != null) {
for (String key : variablesFilter) {
variables.remove(key);
}
}
return variables;
}
@Override
public void completed(ActivityExecution execution) throws Exception {
// only control flow. no sub instance data available
leave(execution);
}
public CallableElement getCallableElement() {
return callableElement;
}
public void setCallableElement(CallableElement callableElement) {
this.callableElement = callableElement;
}
protected String getBusinessKey(ActivityExecution execution) {
return getCallableElement().getBusinessKey(execution);
}
protected VariableMap getInputVariables(ActivityExecution callingExecution) {
return getCallableElement().getInputVariables(callingExecution);
}
|
protected VariableMap getOutputVariables(VariableScope calledElementScope) {
return getCallableElement().getOutputVariables(calledElementScope);
}
protected VariableMap getOutputVariablesLocal(VariableScope calledElementScope) {
return getCallableElement().getOutputVariablesLocal(calledElementScope);
}
protected Integer getVersion(ActivityExecution execution) {
return getCallableElement().getVersion(execution);
}
protected String getDeploymentId(ActivityExecution execution) {
return getCallableElement().getDeploymentId();
}
protected CallableElementBinding getBinding() {
return getCallableElement().getBinding();
}
protected boolean isLatestBinding() {
return getCallableElement().isLatestBinding();
}
protected boolean isDeploymentBinding() {
return getCallableElement().isDeploymentBinding();
}
protected boolean isVersionBinding() {
return getCallableElement().isVersionBinding();
}
protected abstract void startInstance(ActivityExecution execution, VariableMap variables, String businessKey);
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\CallableElementActivityBehavior.java
| 1
|
请完成以下Java代码
|
public void setC_Queue_PackageProcessor_ID (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, Integer.valueOf(C_Queue_PackageProcessor_ID));
}
/** Get WorkPackage Processor.
@return WorkPackage Processor */
@Override
public int getC_Queue_PackageProcessor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_PackageProcessor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Java-Klasse.
@param Classname Java-Klasse */
@Override
public void setClassname (java.lang.String Classname)
{
set_Value (COLUMNNAME_Classname, Classname);
}
/** Get Java-Klasse.
@return Java-Klasse */
@Override
public java.lang.String getClassname ()
{
return (java.lang.String)get_Value(COLUMNNAME_Classname);
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/**
|
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entitäts-Art.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public void setEntityType (java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitäts-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public java.lang.String getEntityType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** Set Interner Name.
@param InternalName
Generally used to give records a name that can be safely referenced from code.
*/
@Override
public void setInternalName (java.lang.String InternalName)
{
set_Value (COLUMNNAME_InternalName, InternalName);
}
/** Get Interner Name.
@return Generally used to give records a name that can be safely referenced from code.
*/
@Override
public java.lang.String getInternalName ()
{
return (java.lang.String)get_Value(COLUMNNAME_InternalName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_PackageProcessor.java
| 1
|
请完成以下Java代码
|
public void setIsSOTrx (boolean IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, Boolean.valueOf(IsSOTrx));
}
/** Get Sales Transaction.
@return This is a Sales Transaction
*/
public boolean isSOTrx ()
{
Object oo = get_Value(COLUMNNAME_IsSOTrx);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Exclude Attribute Set.
@param M_AttributeSetExclude_ID
Exclude the ability to enter Attribute Sets
*/
public void setM_AttributeSetExclude_ID (int M_AttributeSetExclude_ID)
{
if (M_AttributeSetExclude_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_AttributeSetExclude_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSetExclude_ID, Integer.valueOf(M_AttributeSetExclude_ID));
}
/** Get Exclude Attribute Set.
@return Exclude the ability to enter Attribute Sets
*/
public int getM_AttributeSetExclude_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetExclude_ID);
if (ii == null)
return 0;
|
return ii.intValue();
}
public I_M_AttributeSet getM_AttributeSet() throws RuntimeException
{
return (I_M_AttributeSet)MTable.get(getCtx(), I_M_AttributeSet.Table_Name)
.getPO(getM_AttributeSet_ID(), get_TrxName()); }
/** Set Attribute Set.
@param M_AttributeSet_ID
Product Attribute Set
*/
public void setM_AttributeSet_ID (int M_AttributeSet_ID)
{
if (M_AttributeSet_ID < 0)
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, Integer.valueOf(M_AttributeSet_ID));
}
/** Get Attribute Set.
@return Product Attribute Set
*/
public int getM_AttributeSet_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSet_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeSetExclude.java
| 1
|
请完成以下Java代码
|
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
|
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
repos\SpringAll-master\56.Spring-Boot-MongoDB-crud\src\main\java\com\example\mongodb\domain\User.java
| 1
|
请完成以下Java代码
|
public String getDataFormatName() {
return dataFormat.getName();
}
public Attr unwrap() {
return attributeNode;
}
public String name() {
return attributeNode.getLocalName();
}
public String namespace() {
return attributeNode.getNamespaceURI();
}
public String prefix() {
return attributeNode.getPrefix();
}
public boolean hasPrefix(String prefix) {
String attributePrefix = attributeNode.getPrefix();
if(attributePrefix == null) {
return prefix == null;
} else {
return attributePrefix.equals(prefix);
}
}
public boolean hasNamespace(String namespace) {
String attributeNamespace = attributeNode.getNamespaceURI();
if (attributeNamespace == null) {
return namespace == null;
}
else {
return attributeNamespace.equals(namespace);
}
}
public String value() {
return attributeNode.getValue();
}
public SpinXmlAttribute value(String value) {
if (value == null) {
throw LOG.unableToSetAttributeValueToNull(namespace(), name());
}
attributeNode.setValue(value);
return this;
|
}
public SpinXmlElement remove() {
Element ownerElement = attributeNode.getOwnerElement();
ownerElement.removeAttributeNode(attributeNode);
return dataFormat.createElementWrapper(ownerElement);
}
public String toString() {
return value();
}
public void writeToWriter(Writer writer) {
try {
writer.write(toString());
} catch (IOException e) {
throw LOG.unableToWriteAttribute(this, e);
}
}
public <C> C mapTo(Class<C> javaClass) {
DataFormatMapper mapper = dataFormat.getMapper();
return mapper.mapInternalToJava(this, javaClass);
}
public <C> C mapTo(String javaClass) {
DataFormatMapper mapper = dataFormat.getMapper();
return mapper.mapInternalToJava(this, javaClass);
}
}
|
repos\camunda-bpm-platform-master\spin\dataformat-xml-dom\src\main\java\org\camunda\spin\impl\xml\dom\DomXmlAttribute.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<HistoricTaskInstance> findHistoricTaskInstancesAndRelatedEntitiesByQueryCriteria(HistoricTaskInstanceQueryImpl historicTaskInstanceQuery) {
return dataManager.findHistoricTaskInstancesAndRelatedEntitiesByQueryCriteria(historicTaskInstanceQuery);
}
@Override
public List<HistoricTaskInstance> findHistoricTaskInstancesByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findHistoricTaskInstancesByNativeQuery(parameterMap);
}
@Override
public long findHistoricTaskInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findHistoricTaskInstanceCountByNativeQuery(parameterMap);
}
@Override
public void deleteHistoricTaskInstances(HistoricTaskInstanceQueryImpl historicTaskInstanceQuery) {
dataManager.deleteHistoricTaskInstances(historicTaskInstanceQuery);
}
@Override
public void bulkDeleteHistoricTaskInstancesForIds(Collection<String> taskIds) {
dataManager.bulkDeleteHistoricTaskInstancesForIds(taskIds);
}
@Override
public void deleteHistoricTaskInstancesForNonExistingProcessInstances() {
|
dataManager.deleteHistoricTaskInstancesForNonExistingProcessInstances();
}
@Override
public void deleteHistoricTaskInstancesForNonExistingCaseInstances() {
dataManager.deleteHistoricTaskInstancesForNonExistingCaseInstances();
}
public HistoricTaskInstanceDataManager getHistoricTaskInstanceDataManager() {
return dataManager;
}
public void setHistoricTaskInstanceDataManager(HistoricTaskInstanceDataManager historicTaskInstanceDataManager) {
this.dataManager = historicTaskInstanceDataManager;
}
}
|
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\HistoricTaskInstanceEntityManagerImpl.java
| 2
|
请完成以下Java代码
|
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_AD_Image[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Image.
@param AD_Image_ID
Image or Icon
*/
public void setAD_Image_ID (int AD_Image_ID)
{
if (AD_Image_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Image_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Image_ID, Integer.valueOf(AD_Image_ID));
}
/** Get Image.
@return Image or Icon
*/
public int getAD_Image_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Image_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set BinaryData.
@param BinaryData
Binary Data
*/
public void setBinaryData (byte[] BinaryData)
{
set_Value (COLUMNNAME_BinaryData, BinaryData);
}
/** Get BinaryData.
@return Binary Data
*/
public byte[] getBinaryData ()
{
return (byte[])get_Value(COLUMNNAME_BinaryData);
}
/** 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);
}
/** EntityType AD_Reference_ID=389 */
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entity Type.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
public void setEntityType (String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entity Type.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
public String getEntityType ()
{
|
return (String)get_Value(COLUMNNAME_EntityType);
}
/** Set Image URL.
@param ImageURL
URL of image
*/
public void setImageURL (String ImageURL)
{
set_Value (COLUMNNAME_ImageURL, ImageURL);
}
/** Get Image URL.
@return URL of image
*/
public String getImageURL ()
{
return (String)get_Value(COLUMNNAME_ImageURL);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Image.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Employee implements Serializable {
@Id
@GeneratedValue (strategy = GenerationType.SEQUENCE)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "workplace_id")
private Company workplace;
@Column(name = "first_name")
private String firstName;
public Employee() { }
public Employee(Company workplace, String firstName) {
this.workplace = workplace;
this.firstName = firstName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Company getWorkplace() {
return workplace;
}
public void setWorkplace(Company workplace) {
|
this.workplace = workplace;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return Objects.equals(id, employee.id) &&
Objects.equals(workplace, employee.workplace) &&
Objects.equals(firstName, employee.firstName);
}
@Override
public int hashCode() {
return Objects.hash(id, workplace, firstName);
}
}
|
repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\proxy\Employee.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public RecordMessageConverter converter() {
return new JsonMessageConverter();
}
@KafkaListener(id = "fooGroup", topics = "topic1")
public void listen(Foo2 foo) {
logger.info("Received: " + foo);
if (foo.getFoo().startsWith("fail")) {
throw new RuntimeException("failed");
}
this.exec.execute(() -> System.out.println("Hit Enter to terminate..."));
}
@KafkaListener(id = "dltGroup", topics = "topic1-dlt")
public void dltListen(byte[] in) {
logger.info("Received from DLT: " + new String(in));
this.exec.execute(() -> System.out.println("Hit Enter to terminate..."));
}
@Bean
public NewTopic topic() {
|
return new NewTopic("topic1", 1, (short) 1);
}
@Bean
public NewTopic dlt() {
return new NewTopic("topic1-dlt", 1, (short) 1);
}
@Bean
@Profile("default") // Don't run from test(s)
public ApplicationRunner runner() {
return args -> {
System.out.println("Hit Enter to terminate...");
System.in.read();
};
}
}
|
repos\spring-kafka-main\samples\sample-01\src\main\java\com\example\Application.java
| 2
|
请完成以下Java代码
|
protected String readObjectNameFromFields(ValueFields valueFields) {
return valueFields.getTextValue2();
}
public boolean isMutableValue(ObjectValue typedValue) {
return typedValue.isDeserialized();
}
// methods to be implemented by subclasses ////////////
/**
* Returns the type name for the deserialized object.
*
* @param deserializedObject. Guaranteed not to be null
* @return the type name fot the object.
*/
protected abstract String getTypeNameForDeserialized(Object deserializedObject);
/**
* Implementations must return a byte[] representation of the provided object.
* The object is guaranteed not to be null.
*
* @param deserializedObject the object to serialize
* @return the byte array value of the object
* @throws exception in case the object cannot be serialized
*/
protected abstract byte[] serializeToByteArray(Object deserializedObject) throws Exception;
|
protected Object deserializeFromByteArray(byte[] object, ValueFields valueFields) throws Exception {
String objectTypeName = readObjectNameFromFields(valueFields);
return deserializeFromByteArray(object, objectTypeName);
}
/**
* Deserialize the object from a byte array.
*
* @param object the object to deserialize
* @param objectTypeName the type name of the object to deserialize
* @return the deserialized object
* @throws exception in case the object cannot be deserialized
*/
protected abstract Object deserializeFromByteArray(byte[] object, String objectTypeName) throws Exception;
/**
* Return true if the serialization is text based. Return false otherwise
*
*/
protected abstract boolean isSerializationTextBased();
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\serializer\AbstractObjectValueSerializer.java
| 1
|
请完成以下Java代码
|
public List<Item> findItemsByColorAndGrade() {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Item> criteriaQuery = criteriaBuilder.createQuery(Item.class);
Root<Item> itemRoot = criteriaQuery.from(Item.class);
Predicate predicateForBlueColor = criteriaBuilder.equal(itemRoot.get("color"), "blue");
Predicate predicateForRedColor = criteriaBuilder.equal(itemRoot.get("color"), "red");
Predicate predicateForColor = criteriaBuilder.or(predicateForBlueColor, predicateForRedColor);
Predicate predicateForGradeA = criteriaBuilder.equal(itemRoot.get("grade"), "A");
Predicate predicateForGradeB = criteriaBuilder.equal(itemRoot.get("grade"), "B");
Predicate predicateForGrade = criteriaBuilder.or(predicateForGradeA, predicateForGradeB);
// final search filter
Predicate finalPredicate = criteriaBuilder.and(predicateForColor, predicateForGrade);
criteriaQuery.where(finalPredicate);
List<Item> items = entityManager.createQuery(criteriaQuery)
.getResultList();
return items;
}
@Override
public List<Item> findItemByColorOrGrade() {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Item> criteriaQuery = criteriaBuilder.createQuery(Item.class);
Root<Item> itemRoot = criteriaQuery.from(Item.class);
Predicate predicateForBlueColor = criteriaBuilder.equal(itemRoot.get("color"), "red");
|
Predicate predicateForGradeA = criteriaBuilder.equal(itemRoot.get("grade"), "D");
Predicate predicateForBlueColorAndGradeA = criteriaBuilder.and(predicateForBlueColor, predicateForGradeA);
Predicate predicateForRedColor = criteriaBuilder.equal(itemRoot.get("color"), "blue");
Predicate predicateForGradeB = criteriaBuilder.equal(itemRoot.get("grade"), "B");
Predicate predicateForRedColorAndGradeB = criteriaBuilder.and(predicateForRedColor, predicateForGradeB);
// final search filter
Predicate finalPredicate = criteriaBuilder.or(predicateForBlueColorAndGradeA, predicateForRedColorAndGradeB);
criteriaQuery.where(finalPredicate);
List<Item> items = entityManager.createQuery(criteriaQuery)
.getResultList();
return items;
}
}
|
repos\tutorials-master\persistence-modules\java-jpa-2\src\main\java\com\baeldung\jpa\criteria\CustomItemRepositoryImpl.java
| 1
|
请完成以下Java代码
|
public void updateInfoJson(String id, byte[] json) {
ProcessDefinitionInfoEntity processDefinitionInfo = getDbSqlSession().selectById(ProcessDefinitionInfoEntity.class, id);
if (processDefinitionInfo != null) {
ByteArrayRef ref = new ByteArrayRef(processDefinitionInfo.getInfoJsonId());
ref.setValue("json", json);
if (processDefinitionInfo.getInfoJsonId() == null) {
processDefinitionInfo.setInfoJsonId(ref.getId());
updateProcessDefinitionInfo(processDefinitionInfo);
}
}
}
public void deleteInfoJson(ProcessDefinitionInfoEntity processDefinitionInfo) {
if (processDefinitionInfo.getInfoJsonId() != null) {
ByteArrayRef ref = new ByteArrayRef(processDefinitionInfo.getInfoJsonId());
ref.delete();
|
}
}
public ProcessDefinitionInfoEntity findProcessDefinitionInfoById(String id) {
return (ProcessDefinitionInfoEntity) getDbSqlSession().selectOne("selectProcessDefinitionInfo", id);
}
public ProcessDefinitionInfoEntity findProcessDefinitionInfoByProcessDefinitionId(String processDefinitionId) {
return (ProcessDefinitionInfoEntity) getDbSqlSession().selectOne("selectProcessDefinitionInfoByProcessDefinitionId", processDefinitionId);
}
public byte[] findInfoJsonById(String infoJsonId) {
ByteArrayRef ref = new ByteArrayRef(infoJsonId);
return ref.getBytes();
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ProcessDefinitionInfoEntityManager.java
| 1
|
请完成以下Java代码
|
private boolean isApplyClientAndOrgAccess(final String mainTableName)
{
return !I_AD_PInstance_Log.Table_Name.equals(mainTableName);
}
/**
* Return Where clause for Record Access
*
* @return record access where clause or empty
*/
private String getRecordWhere(
final TableNameAndAlias tableNameAndAlias,
final AdTableId adTableId,
final String keyColumnNameFQ,
final Access access)
{
final StringBuilder sqlWhereFinal = new StringBuilder();
//
// Private data record access
final UserId userId = getUserId();
if (!hasAccessToPersonalDataOfOtherUsers())
{
final String sqlWhere = buildPersonalDataRecordAccessSqlWhereClause(adTableId, keyColumnNameFQ, userId);
if (sqlWhereFinal.length() > 0)
{
sqlWhereFinal.append(" AND ");
}
sqlWhereFinal.append(sqlWhere);
}
//
// User/Group record access
{
final String sqlWhere = getUserGroupRecordAccessService().buildUserGroupRecordAccessSqlWhereClause(
tableNameAndAlias.getTableName(),
adTableId,
keyColumnNameFQ,
userId,
getUserGroupIds(),
getRoleId());
if (!Check.isEmpty(sqlWhere))
{
if (sqlWhereFinal.length() > 0)
{
sqlWhereFinal.append(" AND ");
}
sqlWhereFinal.append(sqlWhere);
}
}
//
return sqlWhereFinal.toString();
|
} // getRecordWhere
private String buildPersonalDataRecordAccessSqlWhereClause(
@NonNull final AdTableId adTableId,
@NonNull final String keyColumnNameFQ,
@NonNull final UserId userId)
{
final StringBuilder sql = new StringBuilder(" NOT EXISTS ( SELECT Record_ID FROM " + I_AD_Private_Access.Table_Name
+ " WHERE"
+ " IsActive='Y'"
+ " AND AD_Table_ID=" + adTableId.getRepoId()
+ " AND Record_ID=" + keyColumnNameFQ);
//
// User
sql.append(" AND AD_User_ID <> " + userId.getRepoId());
//
// User Group
final Set<UserGroupId> userGroupIds = getUserGroupIds();
if (!userGroupIds.isEmpty())
{
sql.append(" AND NOT (").append(DB.buildSqlList("AD_UserGroup_ID", userGroupIds)).append(")");
}
//
sql.append(")");
return sql.toString();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\UserRolePermissionsSqlHelpers.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Optional<Pool> getPool() {
return Optional.ofNullable(this.pool);
}
public @NonNull PoolConnectionEndpoint with(@Nullable Pool pool) {
this.pool = pool;
return this;
}
/**
* @inheritDoc
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof PoolConnectionEndpoint)) {
return false;
}
PoolConnectionEndpoint that = (PoolConnectionEndpoint) obj;
return super.equals(that)
&& this.getPool().equals(that.getPool());
}
/**
* @inheritDoc
*/
@Override
public int hashCode() {
int hashValue = super.hashCode();
hashValue = 37 * hashValue + ObjectUtils.nullSafeHashCode(getPool());
return hashValue;
}
/**
* @inheritDoc
*/
|
@Override
public String toString() {
return String.format("ConnectionEndpoint [%1$s] from Pool [%2$s]",
super.toString(), getPool().map(Pool::getName).orElse(""));
}
}
@SuppressWarnings("unused")
protected static class SocketCreationException extends RuntimeException {
protected SocketCreationException() { }
protected SocketCreationException(String message) {
super(message);
}
protected SocketCreationException(Throwable cause) {
super(cause);
}
protected SocketCreationException(String message, Throwable cause) {
super(message, cause);
}
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\ClusterAwareConfiguration.java
| 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.