instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | private void fireOnRecordCopied(final PO to, final PO from, final CopyTemplate template)
{
onRecordCopied(to, from, template);
recordCopiedListeners.forEach(listener -> listener.onRecordCopied(to, from, template));
}
protected void onRecordCopied(final PO to, final PO from, final CopyTemplate template) {}
private void fireOnRecordAndChildrenCopied(final PO to, final PO from, final CopyTemplate template) {onRecordAndChildrenCopied(to, from, template);}
protected void onRecordAndChildrenCopied(final PO to, final PO from, final CopyTemplate template) {}
private Iterator<Object> retrieveChildPOsForParent(final CopyTemplate childTemplate, final PO parentPO)
{
final IQueryBuilder<Object> queryBuilder = queryBL.createQueryBuilder(childTemplate.getTableName())
.addEqualsFilter(childTemplate.getLinkColumnName(), parentPO.get_ID());
childTemplate.getOrderByColumnNames().forEach(queryBuilder::orderBy);
return queryBuilder
.setOption(IQuery.OPTION_GuaranteedIteratorRequired, false)
.create()
.iterate(Object.class);
}
/**
* @return true if the record shall be copied
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
protected boolean isCopyRecord(final PO fromPO) {return true;}
protected boolean isCopyChildRecord(final CopyTemplate parentTemplate, final PO fromChildPO, final CopyTemplate childTemplate) {return true;}
@Override
public final GeneralCopyRecordSupport setParentLink(@NonNull final PO parentPO, @NonNull final String parentLinkColumnName)
{
this.parentPO = parentPO;
this.parentLinkColumnName = parentLinkColumnName;
return this;
}
@Override
public final GeneralCopyRecordSupport setAdWindowId(final @Nullable AdWindowId adWindowId)
{
this.adWindowId = adWindowId;
return this;
}
@SuppressWarnings("SameParameterValue")
@Nullable
protected final <T> T getParentModel(final Class<T> modelType)
{
return parentPO != null ? InterfaceWrapperHelper.create(parentPO, modelType) : null;
}
private int getParentID()
{
return parentPO != null ? parentPO.get_ID() : -1; | }
/**
* Allows other modules to install customer code to be executed each time a record was copied.
*/
@Override
public final GeneralCopyRecordSupport onRecordCopied(@NonNull final OnRecordCopiedListener listener)
{
if (!recordCopiedListeners.contains(listener))
{
recordCopiedListeners.add(listener);
}
return this;
}
@Override
public final CopyRecordSupport onChildRecordCopied(@NonNull final OnRecordCopiedListener listener)
{
if (!childRecordCopiedListeners.contains(listener))
{
childRecordCopiedListeners.add(listener);
}
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\copy_with_details\GeneralCopyRecordSupport.java | 1 |
请完成以下Java代码 | public boolean isWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public List<String> getTenantIdIn() {
return tenantIdIn;
}
public void setTenantIdIn(List<String> tenantIdIn) {
this.tenantIdIn = tenantIdIn;
}
public boolean isIncludeExtensionProperties() {
return includeExtensionProperties;
}
public void setIncludeExtensionProperties(boolean includeExtensionProperties) {
this.includeExtensionProperties = includeExtensionProperties;
}
public static TopicRequestDto fromTopicSubscription(TopicSubscription topicSubscription, long clientLockDuration) {
Long lockDuration = topicSubscription.getLockDuration();
if (lockDuration == null) {
lockDuration = clientLockDuration;
}
String topicName = topicSubscription.getTopicName();
List<String> variables = topicSubscription.getVariableNames();
String businessKey = topicSubscription.getBusinessKey();
TopicRequestDto topicRequestDto = new TopicRequestDto(topicName, lockDuration, variables, businessKey);
if (topicSubscription.getProcessDefinitionId() != null) {
topicRequestDto.setProcessDefinitionId(topicSubscription.getProcessDefinitionId());
}
if (topicSubscription.getProcessDefinitionIdIn() != null) { | topicRequestDto.setProcessDefinitionIdIn(topicSubscription.getProcessDefinitionIdIn());
}
if (topicSubscription.getProcessDefinitionKey() != null) {
topicRequestDto.setProcessDefinitionKey(topicSubscription.getProcessDefinitionKey());
}
if (topicSubscription.getProcessDefinitionKeyIn() != null) {
topicRequestDto.setProcessDefinitionKeyIn(topicSubscription.getProcessDefinitionKeyIn());
}
if (topicSubscription.isWithoutTenantId()) {
topicRequestDto.setWithoutTenantId(topicSubscription.isWithoutTenantId());
}
if (topicSubscription.getTenantIdIn() != null) {
topicRequestDto.setTenantIdIn(topicSubscription.getTenantIdIn());
}
if(topicSubscription.getProcessDefinitionVersionTag() != null) {
topicRequestDto.setProcessDefinitionVersionTag(topicSubscription.getProcessDefinitionVersionTag());
}
if (topicSubscription.getProcessVariables() != null) {
topicRequestDto.setProcessVariables(topicSubscription.getProcessVariables());
}
if (topicSubscription.isLocalVariables()) {
topicRequestDto.setLocalVariables(topicSubscription.isLocalVariables());
}
if(topicSubscription.isIncludeExtensionProperties()) {
topicRequestDto.setIncludeExtensionProperties(topicSubscription.isIncludeExtensionProperties());
}
return topicRequestDto;
}
} | repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\topic\impl\dto\TopicRequestDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public PmsProductAttribute getItem(Long id) {
return productAttributeMapper.selectByPrimaryKey(id);
}
@Override
public int delete(List<Long> ids) {
//获取分类
PmsProductAttribute pmsProductAttribute = productAttributeMapper.selectByPrimaryKey(ids.get(0));
Integer type = pmsProductAttribute.getType();
PmsProductAttributeCategory pmsProductAttributeCategory = productAttributeCategoryMapper.selectByPrimaryKey(pmsProductAttribute.getProductAttributeCategoryId());
PmsProductAttributeExample example = new PmsProductAttributeExample();
example.createCriteria().andIdIn(ids);
int count = productAttributeMapper.deleteByExample(example);
//删除完成后修改数量
if(type==0){
if(pmsProductAttributeCategory.getAttributeCount()>=count){
pmsProductAttributeCategory.setAttributeCount(pmsProductAttributeCategory.getAttributeCount()-count);
}else{
pmsProductAttributeCategory.setAttributeCount(0);
}
}else if(type==1){ | if(pmsProductAttributeCategory.getParamCount()>=count){
pmsProductAttributeCategory.setParamCount(pmsProductAttributeCategory.getParamCount()-count);
}else{
pmsProductAttributeCategory.setParamCount(0);
}
}
productAttributeCategoryMapper.updateByPrimaryKey(pmsProductAttributeCategory);
return count;
}
@Override
public List<ProductAttrInfo> getProductAttrInfo(Long productCategoryId) {
return productAttributeDao.getProductAttrInfo(productCategoryId);
}
} | repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\PmsProductAttributeServiceImpl.java | 2 |
请完成以下Java代码 | public static ProductWithNoCustomsTariffUserNotificationsProducer newInstance()
{
return new ProductWithNoCustomsTariffUserNotificationsProducer();
}
/**
* Topic used to send notifications about shipments/receipts that were generated/reversed asynchronously
*/
public static final Topic EVENTBUS_TOPIC = Topic.builder()
.name("de.metas.product.UserNotifications")
.type(Type.DISTRIBUTED)
.build();
private static final AdWindowId DEFAULT_WINDOW_Product = AdWindowId.ofRepoId(140); // FIXME: HARDCODED
private ProductWithNoCustomsTariffUserNotificationsProducer()
{
}
public ProductWithNoCustomsTariffUserNotificationsProducer notify(final Collection<ProductId> productIds)
{
if (productIds == null || productIds.isEmpty())
{
return this;
}
postNotifications(productIds.stream()
.map(this::createUserNotification)
.collect(ImmutableList.toImmutableList()));
return this;
}
private UserNotificationRequest createUserNotification(@NonNull final ProductId productId)
{
final IADWindowDAO adWindowDAO = Services.get(IADWindowDAO.class); | final AdWindowId productWindowId = adWindowDAO.getAdWindowId(I_M_Product.Table_Name, SOTrx.SALES, DEFAULT_WINDOW_Product);
final TableRecordReference productRef = toTableRecordRef(productId);
return newUserNotificationRequest()
.recipientUserId(Env.getLoggedUserId())
.contentADMessage(MSG_ProductWithNoCustomsTariff)
.contentADMessageParam(productRef)
.targetAction(TargetRecordAction.ofRecordAndWindow(productRef, productWindowId))
.build();
}
private static TableRecordReference toTableRecordRef(final ProductId productId)
{
return TableRecordReference.of(I_M_Product.Table_Name, productId);
}
private UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest()
{
return UserNotificationRequest.builder()
.topic(EVENTBUS_TOPIC);
}
private void postNotifications(final List<UserNotificationRequest> notifications)
{
Services.get(INotificationBL.class).sendAfterCommit(notifications);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\event\ProductWithNoCustomsTariffUserNotificationsProducer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Rule update(Rule rule) throws IOException {
return ruleService.update(rule);
}
/**
* 新增规则
*
* @return
* @throws IOException
*/
@ResponseBody
@RequestMapping("add")
public Rule add(Rule rule) throws IOException {
return ruleService.insert(rule);
}
/**
* 生成随机数 | *
* @param num
* @return
*/
public String generateRandom(int num) {
String chars = "0123456789";
StringBuffer number = new StringBuffer();
for (int i = 0; i < num; i++) {
int rand = (int) (Math.random() * 10);
number = number.append(chars.charAt(rand));
}
return number.toString();
}
} | repos\spring-boot-student-master\spring-boot-student-drools\src\main\java\com\xiaolyuh\controller\RuleController.java | 2 |
请完成以下Java代码 | private IHUQueryBuilder createHUQuery(@NonNull final OrderLine salesOrderLine)
{
final OrderLineId salesOrderLineId = salesOrderLine.getId();
final HUReservationDocRef reservationDocRef = salesOrderLineId != null ? HUReservationDocRef.ofSalesOrderLineId(salesOrderLineId) : null;
return huReservationService.prepareHUQuery()
.warehouseId(salesOrderLine.getWarehouseId())
.productId(salesOrderLine.getProductId())
.bpartnerId(salesOrderLine.getBPartnerId())
.asiId(salesOrderLine.getAsiId())
.reservedToDocumentOrNotReservedAtAll(reservationDocRef)
.build();
}
public DocumentFilter createDocumentFilterIgnoreAttributes(@NonNull final Packageable packageable)
{
final IHUQueryBuilder huQuery = createHUQueryIgnoreAttributes(packageable); | return HUIdsFilterHelper.createFilter(huQuery);
}
private IHUQueryBuilder createHUQueryIgnoreAttributes(final Packageable packageable)
{
final OrderLineId salesOrderLineId = packageable.getSalesOrderLineIdOrNull();
final HUReservationDocRef reservationDocRef = salesOrderLineId != null ? HUReservationDocRef.ofSalesOrderLineId(salesOrderLineId) : null;
return huReservationService.prepareHUQuery()
.warehouseId(packageable.getWarehouseId())
.productId(packageable.getProductId())
.bpartnerId(packageable.getCustomerId())
.asiId(null) // ignore attributes
.reservedToDocumentOrNotReservedAtAll(reservationDocRef)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\hu\reservation\HUReservationDocumentFilterService.java | 1 |
请完成以下Java代码 | public class UmsMemberMemberTagRelation implements Serializable {
private Long id;
private Long memberId;
private Long tagId;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getMemberId() {
return memberId;
}
public void setMemberId(Long memberId) {
this.memberId = memberId;
} | public Long getTagId() {
return tagId;
}
public void setTagId(Long tagId) {
this.tagId = tagId;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", memberId=").append(memberId);
sb.append(", tagId=").append(tagId);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberMemberTagRelation.java | 1 |
请完成以下Java代码 | public final class StateChangeEvent extends EventObject
{
public static enum StateChangeEventType
{
DATA_REFRESH_ALL, DATA_REFRESH, DATA_NEW, DATA_DELETE, DATA_SAVE, DATA_IGNORE
}
private final StateChangeEventType eventType;
/**
*
* @param source
* @param eventType
*/
public StateChangeEvent(final GridTab source, final StateChangeEventType eventType)
{
super(source);
this.eventType = eventType;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this) | .add("eventType", eventType)
.add("source", source)
.toString();
}
@Override
public GridTab getSource()
{
return (GridTab)super.getSource();
}
/**
*
* @return event type (DATA_*)
*/
public StateChangeEventType getEventType()
{
return eventType;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\StateChangeEvent.java | 1 |
请完成以下Java代码 | public void setTransientVariables(Map<String, Object> transientVariables) {
this.transientVariables = transientVariables;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getOwnerId() {
return ownerId;
}
public void setOwnerId(String ownerId) {
this.ownerId = ownerId;
}
public String getAssigneeId() {
return assigneeId;
}
public void setAssigneeId(String assigneeId) {
this.assigneeId = assigneeId;
}
public String getInitiatorVariableName() { | return initiatorVariableName;
}
public void setInitiatorVariableName(String initiatorVariableName) {
this.initiatorVariableName = initiatorVariableName;
}
public String getOverrideDefinitionTenantId() {
return overrideDefinitionTenantId;
}
public void setOverrideDefinitionTenantId(String overrideDefinitionTenantId) {
this.overrideDefinitionTenantId = overrideDefinitionTenantId;
}
public String getPredefinedCaseInstanceId() {
return predefinedCaseInstanceId;
}
public void setPredefinedCaseInstanceId(String predefinedCaseInstanceId) {
this.predefinedCaseInstanceId = predefinedCaseInstanceId;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\interceptor\StartCaseInstanceBeforeContext.java | 1 |
请完成以下Java代码 | public DocumentLayoutDescriptor getLayout()
{
return layout;
}
public ViewLayout getViewLayout(final JSONViewDataType viewDataType)
{
switch (viewDataType)
{
case grid:
{
return layout.getGridViewLayout();
}
case list:
{
return layout.getSideListViewLayout();
}
default:
{
throw new IllegalArgumentException("Invalid viewDataType: " + viewDataType);
}
}
}
public DocumentEntityDescriptor getEntityDescriptor()
{
return entityDescriptor;
}
@Override
public ETag getETag()
{
return eTag;
}
//
public static final class Builder
{
private DocumentLayoutDescriptor layout;
private DocumentEntityDescriptor entityDescriptor;
private Builder() | {
}
public DocumentDescriptor build()
{
return new DocumentDescriptor(this);
}
public Builder setLayout(final DocumentLayoutDescriptor layout)
{
this.layout = layout;
return this;
}
public Builder setEntityDescriptor(final DocumentEntityDescriptor entityDescriptor)
{
this.entityDescriptor = entityDescriptor;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentDescriptor.java | 1 |
请完成以下Java代码 | public void notify(DelegateTask delegateTask) {
if (script == null) {
throw new IllegalArgumentException("The field 'script' should be set on the TaskListener");
}
if (language == null) {
throw new IllegalArgumentException("The field 'language' should be set on the TaskListener");
}
ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines();
Object result = scriptingEngines.evaluate(script.getExpressionText(), language.getExpressionText(), delegateTask, autoStoreVariables);
if (resultVariable != null) {
delegateTask.setVariable(resultVariable.getExpressionText(), result);
}
}
public void setScript(Expression script) {
this.script = script; | }
public void setLanguage(Expression language) {
this.language = language;
}
public void setResultVariable(Expression resultVariable) {
this.resultVariable = resultVariable;
}
public void setAutoStoreVariables(boolean autoStoreVariables) {
this.autoStoreVariables = autoStoreVariables;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\listener\ScriptTaskListener.java | 1 |
请完成以下Java代码 | public @Nullable Tag getParent() {
return this.parent;
}
@Override
public void setParent(Tag parent) {
this.parent = parent;
}
public @Nullable String getVar() {
return this.var;
}
public void setVar(String var) {
this.var = var;
}
@Override
public void release() {
this.parent = null;
this.id = null;
}
@Override
public void setPageContext(PageContext pageContext) {
this.pageContext = pageContext;
}
@Override
protected ServletRequest getRequest() {
return this.pageContext.getRequest();
}
@Override
protected ServletResponse getResponse() {
return this.pageContext.getResponse();
}
@Override
protected ServletContext getServletContext() {
return this.pageContext.getServletContext();
}
private final class PageContextVariableLookupEvaluationContext implements EvaluationContext {
private EvaluationContext delegate;
private PageContextVariableLookupEvaluationContext(EvaluationContext delegate) {
this.delegate = delegate;
}
@Override
public TypedValue getRootObject() {
return this.delegate.getRootObject();
}
@Override
public List<ConstructorResolver> getConstructorResolvers() {
return this.delegate.getConstructorResolvers();
}
@Override
public List<MethodResolver> getMethodResolvers() {
return this.delegate.getMethodResolvers();
}
@Override
public List<PropertyAccessor> getPropertyAccessors() {
return this.delegate.getPropertyAccessors();
}
@Override
public TypeLocator getTypeLocator() {
return this.delegate.getTypeLocator();
}
@Override | public TypeConverter getTypeConverter() {
return this.delegate.getTypeConverter();
}
@Override
public TypeComparator getTypeComparator() {
return this.delegate.getTypeComparator();
}
@Override
public OperatorOverloader getOperatorOverloader() {
return this.delegate.getOperatorOverloader();
}
@Override
public @Nullable BeanResolver getBeanResolver() {
return this.delegate.getBeanResolver();
}
@Override
public void setVariable(String name, @Nullable Object value) {
this.delegate.setVariable(name, value);
}
@Override
public Object lookupVariable(String name) {
Object result = this.delegate.lookupVariable(name);
if (result == null) {
result = JspAuthorizeTag.this.pageContext.findAttribute(name);
}
return result;
}
}
} | repos\spring-security-main\taglibs\src\main\java\org\springframework\security\taglibs\authz\JspAuthorizeTag.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static class Contact
{
@Nullable
GreetingId greetingId;
@Nullable
String firstName;
@Nullable
String lastName;
int seqNo;
boolean isDefaultContact;
boolean isMembershipContact;
}
@Singular @NonNull ImmutableList<Contact> contacts; | public Optional<Contact> getPrimaryContact()
{
final List<Contact> contactsOrderedPrimaryFirst = getContactsOrderedPrimaryFirst();
return !contactsOrderedPrimaryFirst.isEmpty()
? Optional.of(contactsOrderedPrimaryFirst.get(0))
: Optional.empty();
}
public List<Contact> getContactsOrderedPrimaryFirst()
{
return contacts.stream()
.sorted(Comparator.<Contact, Integer>comparing(contact -> contact.isDefaultContact() ? 0 : 1)
.thenComparing(Contact::getSeqNo))
.collect(ImmutableList.toImmutableList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\name\strategy\ComputeNameAndGreetingRequest.java | 2 |
请完成以下Java代码 | public Builder displayName(final AdMessageKey displayName)
{
return displayName(TranslatableStrings.adMessage(displayName));
}
public ITranslatableString getDisplayName()
{
return displayName;
}
public Builder lookupDescriptor(@NonNull final Optional<LookupDescriptor> lookupDescriptor)
{
this.lookupDescriptor = lookupDescriptor;
return this;
} | public Builder lookupDescriptor(@Nullable final LookupDescriptor lookupDescriptor)
{
return lookupDescriptor(Optional.ofNullable(lookupDescriptor));
}
public Builder lookupDescriptor(@NonNull final UnaryOperator<LookupDescriptor> mapper)
{
if (this.lookupDescriptor!= null) // don't replace with isPresent() since it could be null at this point
{
return lookupDescriptor(this.lookupDescriptor.map(mapper));
}
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\DocumentFilterParamDescriptor.java | 1 |
请完成以下Java代码 | public String getElementVariable() {
return elementVariable;
}
public void setElementVariable(String elementVariable) {
this.elementVariable = elementVariable;
}
public String getElementIndexVariable() {
return elementIndexVariable;
}
public void setElementIndexVariable(String elementIndexVariable) {
this.elementIndexVariable = elementIndexVariable;
}
public boolean isSequential() {
return sequential;
}
public void setSequential(boolean sequential) {
this.sequential = sequential;
}
public boolean isNoWaitStatesAsyncLeave() {
return noWaitStatesAsyncLeave;
}
public void setNoWaitStatesAsyncLeave(boolean noWaitStatesAsyncLeave) {
this.noWaitStatesAsyncLeave = noWaitStatesAsyncLeave;
}
public VariableAggregationDefinitions getAggregations() {
return aggregations;
}
public void setAggregations(VariableAggregationDefinitions aggregations) {
this.aggregations = aggregations;
}
public void addAggregation(VariableAggregationDefinition aggregation) {
if (this.aggregations == null) {
this.aggregations = new VariableAggregationDefinitions(); | }
this.aggregations.getAggregations().add(aggregation);
}
@Override
public MultiInstanceLoopCharacteristics clone() {
MultiInstanceLoopCharacteristics clone = new MultiInstanceLoopCharacteristics();
clone.setValues(this);
return clone;
}
public void setValues(MultiInstanceLoopCharacteristics otherLoopCharacteristics) {
super.setValues(otherLoopCharacteristics);
setInputDataItem(otherLoopCharacteristics.getInputDataItem());
setCollectionString(otherLoopCharacteristics.getCollectionString());
if (otherLoopCharacteristics.getHandler() != null) {
setHandler(otherLoopCharacteristics.getHandler().clone());
}
setLoopCardinality(otherLoopCharacteristics.getLoopCardinality());
setCompletionCondition(otherLoopCharacteristics.getCompletionCondition());
setElementVariable(otherLoopCharacteristics.getElementVariable());
setElementIndexVariable(otherLoopCharacteristics.getElementIndexVariable());
setSequential(otherLoopCharacteristics.isSequential());
setNoWaitStatesAsyncLeave(otherLoopCharacteristics.isNoWaitStatesAsyncLeave());
if (otherLoopCharacteristics.getAggregations() != null) {
setAggregations(otherLoopCharacteristics.getAggregations().clone());
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\MultiInstanceLoopCharacteristics.java | 1 |
请完成以下Java代码 | public class InstantWrapper {
Clock clock;
private InstantWrapper() {
this.clock = Clock.systemDefaultZone();
}
private InstantWrapper(ZonedDateTime zonedDateTime) {
this.clock = Clock.fixed(zonedDateTime.toInstant(), zonedDateTime.getZone());
}
private InstantWrapper(LocalDateTime localDateTime) {
this.clock = Clock.fixed(localDateTime.toInstant(ZoneOffset.UTC), ZoneOffset.UTC);
}
public static InstantWrapper of() { | return new InstantWrapper();
}
public static InstantWrapper of(ZonedDateTime zonedDateTime) {
return new InstantWrapper(zonedDateTime);
}
public static InstantWrapper of(LocalDateTime localDateTime) {
return new InstantWrapper(localDateTime);
}
public Instant instant() {
return clock.instant();
}
} | repos\tutorials-master\core-java-modules\core-java-17\src\main\java\com\baeldung\instantsource\InstantWrapper.java | 1 |
请完成以下Java代码 | private <T extends Serializable> Class<T> classIdTypeFrom(ResultSet resultSet) throws SQLException {
return classIdTypeFrom(resultSet.getString(DEFAULT_CLASS_ID_TYPE_COLUMN_NAME));
}
private <T extends Serializable> Class<T> classIdTypeFrom(String className) {
if (className == null) {
return null;
}
try {
return (Class) Class.forName(className);
}
catch (ClassNotFoundException ex) {
log.debug("Unable to find class id type on classpath", ex);
return null;
}
}
private <T> boolean canConvertFromStringTo(Class<T> targetType) {
return this.conversionService.canConvert(String.class, targetType);
}
private <T extends Serializable> T convertFromStringTo(String identifier, Class<T> targetType) {
return this.conversionService.convert(identifier, targetType);
}
/**
* Converts to a {@link Long}, attempting to use the {@link ConversionService} if
* available.
* @param identifier The identifier
* @return Long version of the identifier
* @throws NumberFormatException if the string cannot be parsed to a long.
* @throws org.springframework.core.convert.ConversionException if a conversion
* exception occurred
* @throws IllegalArgumentException if targetType is null
*/
private Long convertToLong(Serializable identifier) {
if (this.conversionService.canConvert(identifier.getClass(), Long.class)) {
return this.conversionService.convert(identifier, Long.class);
}
return Long.valueOf(identifier.toString());
}
private boolean isString(Serializable object) {
return object.getClass().isAssignableFrom(String.class);
} | void setConversionService(ConversionService conversionService) {
Assert.notNull(conversionService, "conversionService must not be null");
this.conversionService = conversionService;
}
private static class StringToLongConverter implements Converter<String, Long> {
@Override
public Long convert(String identifierAsString) {
if (identifierAsString == null) {
throw new ConversionFailedException(TypeDescriptor.valueOf(String.class),
TypeDescriptor.valueOf(Long.class), null, null);
}
return Long.parseLong(identifierAsString);
}
}
private static class StringToUUIDConverter implements Converter<String, UUID> {
@Override
public UUID convert(String identifierAsString) {
if (identifierAsString == null) {
throw new ConversionFailedException(TypeDescriptor.valueOf(String.class),
TypeDescriptor.valueOf(UUID.class), null, null);
}
return UUID.fromString(identifierAsString);
}
}
} | repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\jdbc\AclClassIdUtils.java | 1 |
请完成以下Java代码 | public void setT_Date (final @Nullable java.sql.Timestamp T_Date)
{
set_Value (COLUMNNAME_T_Date, T_Date);
}
@Override
public java.sql.Timestamp getT_Date()
{
return get_ValueAsTimestamp(COLUMNNAME_T_Date);
}
@Override
public void setT_DateTime (final @Nullable java.sql.Timestamp T_DateTime)
{
set_Value (COLUMNNAME_T_DateTime, T_DateTime);
}
@Override
public java.sql.Timestamp getT_DateTime()
{
return get_ValueAsTimestamp(COLUMNNAME_T_DateTime);
}
@Override
public void setT_Integer (final int T_Integer)
{
set_Value (COLUMNNAME_T_Integer, T_Integer);
}
@Override
public int getT_Integer()
{
return get_ValueAsInt(COLUMNNAME_T_Integer);
}
@Override
public void setT_Number (final @Nullable BigDecimal T_Number)
{
set_Value (COLUMNNAME_T_Number, T_Number);
}
@Override
public BigDecimal getT_Number()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_T_Number);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override | public void setT_Qty (final @Nullable BigDecimal T_Qty)
{
set_Value (COLUMNNAME_T_Qty, T_Qty);
}
@Override
public BigDecimal getT_Qty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_T_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setT_Time (final @Nullable java.sql.Timestamp T_Time)
{
set_Value (COLUMNNAME_T_Time, T_Time);
}
@Override
public java.sql.Timestamp getT_Time()
{
return get_ValueAsTimestamp(COLUMNNAME_T_Time);
}
@Override
public void setTest_ID (final int Test_ID)
{
if (Test_ID < 1)
set_ValueNoCheck (COLUMNNAME_Test_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Test_ID, Test_ID);
}
@Override
public int getTest_ID()
{
return get_ValueAsInt(COLUMNNAME_Test_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Test.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ShipperTransportationReportAdvisor implements DocumentReportAdvisor
{
private final IShipperTransportationDAO shipperTransportationDAO = Services.get(IShipperTransportationDAO.class);
@NonNull
private final DocumentReportAdvisorUtil util;
@Override
public @NonNull String getHandledTableName()
{
return I_M_ShipperTransportation.Table_Name;
}
@Override
public StandardDocumentReportType getStandardDocumentReportType()
{
return StandardDocumentReportType.SHIPPER_TRANSPORTATION;
}
@Override
public @NonNull DocumentReportInfo getDocumentReportInfo(
@NonNull final TableRecordReference recordRef,
@Nullable final PrintFormatId adPrintFormatToUseId, final AdProcessId reportProcessIdToUse)
{
final ShipperTransportationId shipperTransportationId = recordRef.getIdAssumingTableName(I_M_ShipperTransportation.Table_Name, ShipperTransportationId::ofRepoId);
final I_M_ShipperTransportation shipperTransportation = shipperTransportationDAO.getById(shipperTransportationId);
final BPartnerId shipperPartnerId = BPartnerId.ofRepoId(shipperTransportation.getShipper_BPartner_ID());
final I_C_BPartner shipperPartner = util.getBPartnerById(shipperPartnerId);
final DocTypeId docTypeId = DocTypeId.ofRepoId(shipperTransportation.getC_DocType_ID());
final I_C_DocType docType = util.getDocTypeById(docTypeId); | final Language language = util.getBPartnerLanguage(shipperPartner).orElse(null);
final BPPrintFormatQuery bpPrintFormatQuery = BPPrintFormatQuery.builder()
.adTableId(recordRef.getAdTableId())
.bpartnerId(shipperPartnerId)
.bPartnerLocationId(BPartnerLocationId.ofRepoId(shipperPartnerId, shipperTransportation.getShipper_Location_ID()))
.docTypeId(docTypeId)
.onlyCopiesGreaterZero(true)
.build();
return DocumentReportInfo.builder()
.recordRef(recordRef)
.reportProcessId(reportProcessIdToUse)
.copies(util.getDocumentCopies(docType, bpPrintFormatQuery))
.documentNo(shipperTransportation.getDocumentNo())
.bpartnerId(shipperPartnerId)
.docTypeId(docTypeId)
.language(language)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipping\ShipperTransportationReportAdvisor.java | 2 |
请完成以下Java代码 | protected boolean isLeapYear(int year) {
return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
}
protected int getLastDayOfMonth(int monthNum, int year) {
switch (monthNum) {
case 1:
return 31;
case 2:
return (isLeapYear(year)) ? 29 : 28;
case 3:
return 31;
case 4:
return 30;
case 5:
return 31;
case 6:
return 30;
case 7:
return 31;
case 8:
return 31;
case 9:
return 30;
case 10:
return 31;
case 11:
return 30;
case 12: | return 31;
default:
throw new IllegalArgumentException("Illegal month number: "
+ monthNum);
}
}
private void readObject(java.io.ObjectInputStream stream)
throws java.io.IOException, ClassNotFoundException {
stream.defaultReadObject();
try {
buildExpression(cronExpression);
} catch (Exception ignore) {
} // never happens
}
@Override
@Deprecated
public Object clone() {
return new CronExpression(this);
}
}
class ValueSet {
public int value;
public int pos;
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\cron\CronExpression.java | 1 |
请完成以下Java代码 | public boolean isEnabled() {
return false;
}
@Override
public void apply(Builder builder) {
throw new IllegalStateException("AutoTimer is disabled");
}
};
/**
* Return if the auto-timer is enabled and metrics should be recorded.
* @return if the auto-timer is enabled
*/
default boolean isEnabled() {
return true;
}
/**
* Factory method to create a new {@link Builder Timer.Builder} with auto-timer
* settings {@link #apply(Timer.Builder) applied}.
* @param name the name of the timer
* @return a new builder instance with auto-settings applied
*/
default Timer.Builder builder(String name) {
return builder(() -> Timer.builder(name));
}
/**
* Factory method to create a new {@link Builder Timer.Builder} with auto-timer
* settings {@link #apply(Timer.Builder) applied}.
* @param supplier the builder supplier
* @return a new builder instance with auto-settings applied | */
default Timer.Builder builder(Supplier<Timer.Builder> supplier) {
Timer.Builder builder = supplier.get();
apply(builder);
return builder;
}
/**
* Called to apply any auto-timer settings to the given {@link Builder Timer.Builder}.
* @param builder the builder to apply settings to
*/
void apply(Timer.Builder builder);
static void apply(@Nullable AutoTimer autoTimer, String metricName, Set<Timed> annotations,
Consumer<Timer.Builder> action) {
if (!CollectionUtils.isEmpty(annotations)) {
for (Timed annotation : annotations) {
action.accept(Timer.builder(annotation, metricName));
}
}
else {
if (autoTimer != null && autoTimer.isEnabled()) {
action.accept(autoTimer.builder(metricName));
}
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-data-commons\src\main\java\org\springframework\boot\data\metrics\AutoTimer.java | 1 |
请完成以下Java代码 | private CompositeSqlLookupFilter getFilters()
{
return filtersBuilder.getOrBuild();
}
private static boolean computeIsHighVolume(@NonNull final ReferenceId diplayType)
{
final int displayTypeInt = diplayType.getRepoId();
return DisplayType.TableDir != displayTypeInt && DisplayType.Table != displayTypeInt && DisplayType.List != displayTypeInt && DisplayType.Button != displayTypeInt;
}
/**
* Advice the lookup to show all records on which current user has at least read only access
*/
public SqlLookupDescriptorFactory setReadOnlyAccess()
{
this.requiredAccess = Access.READ;
return this;
}
private Access getRequiredAccess(@NonNull final TableName tableName)
{
if (requiredAccess != null)
{
return requiredAccess;
} | // AD_Client_ID/AD_Org_ID (security fields): shall display only those entries on which current user has read-write access
if (I_AD_Client.Table_Name.equals(tableName.getAsString())
|| I_AD_Org.Table_Name.equals(tableName.getAsString()))
{
return Access.WRITE;
}
// Default: all entries on which current user has at least readonly access
return Access.READ;
}
SqlLookupDescriptorFactory addValidationRules(final Collection<IValidationRule> validationRules)
{
this.filtersBuilder.addFilter(validationRules, null);
return this;
}
SqlLookupDescriptorFactory setPageLength(final Integer pageLength)
{
this.pageLength = pageLength;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlLookupDescriptorFactory.java | 1 |
请完成以下Java代码 | public void init()
{
// nothing to do here
}
@Override
public Properties getContext()
{
return ctxProxy;
}
private final Properties getActualContext()
{
final Properties temporaryCtx = temporaryCtxHolder.get();
if (temporaryCtx != null)
{
return temporaryCtx;
}
return rootCtx;
}
@Override
public IAutoCloseable switchContext(final Properties ctx)
{
Check.assumeNotNull(ctx, "ctx not null");
// If we were asked to set the context proxy (the one which we are returning everytime),
// then it's better to do nothing because this could end in a StackOverflowException.
if (ctx == ctxProxy)
{
return NullAutoCloseable.instance;
}
final Properties previousTempCtx = temporaryCtxHolder.get();
temporaryCtxHolder.set(ctx);
return new IAutoCloseable() | {
private boolean closed = false;
@Override
public void close()
{
if (closed)
{
return;
}
if (previousTempCtx != null)
{
temporaryCtxHolder.set(previousTempCtx);
}
else
{
temporaryCtxHolder.remove();
}
closed = true;
}
};
}
@Override
public void reset()
{
temporaryCtxHolder.remove();
rootCtx.clear();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\context\SwingContextProvider.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getProcessDefinitionId() {
return this.processDefId;
}
@Override
public String getScopeId() {
return this.scopeId;
}
@Override
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
@Override
public String getSubScopeId() {
return subScopeId;
}
@Override
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
@Override
public String getScopeType() {
return this.scopeType;
}
@Override
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
@Override
public String getScopeDefinitionId() {
return this.scopeDefinitionId;
}
@Override
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("IdentityLinkEntity[id=").append(id);
sb.append(", type=").append(type);
if (userId != null) { | sb.append(", userId=").append(userId);
}
if (groupId != null) {
sb.append(", groupId=").append(groupId);
}
if (taskId != null) {
sb.append(", taskId=").append(taskId);
}
if (processInstanceId != null) {
sb.append(", processInstanceId=").append(processInstanceId);
}
if (processDefId != null) {
sb.append(", processDefId=").append(processDefId);
}
if (scopeId != null) {
sb.append(", scopeId=").append(scopeId);
}
if (scopeType != null) {
sb.append(", scopeType=").append(scopeType);
}
if (scopeDefinitionId != null) {
sb.append(", scopeDefinitionId=").append(scopeDefinitionId);
}
sb.append("]");
return sb.toString();
}
} | repos\flowable-engine-main\modules\flowable-identitylink-service\src\main\java\org\flowable\identitylink\service\impl\persistence\entity\IdentityLinkEntityImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public final String getDocumentNo()
{
if (!Check.isEmpty(documentNo, true))
{
return documentNo;
}
final TableRecordReference reference = getReference();
if (reference != null)
{
return "<" + reference.getRecord_ID() + ">";
}
return "?";
}
@Override
public CurrencyId getCurrencyId()
{
return amountToAllocateInitial.getCurrencyId();
}
@Override
public void addAllocatedAmt(@NonNull final Money allocatedAmtToAdd)
{
allocatedAmt = allocatedAmt.add(allocatedAmtToAdd);
amountToAllocate = amountToAllocate.subtract(allocatedAmtToAdd);
}
@Override
public LocalDate getDate()
{
return dateTrx;
}
@Override
public boolean isFullyAllocated()
{
return getAmountToAllocate().signum() == 0;
} | private Money getOpenAmtRemaining()
{
final Money totalAllocated = allocatedAmt;
return openAmtInitial.subtract(totalAllocated);
}
@Override
public Money calculateProjectedOverUnderAmt(@NonNull final Money amountToAllocate)
{
return getOpenAmtRemaining().subtract(amountToAllocate);
}
@Override
public boolean canPay(@NonNull final PayableDocument payable)
{
return true;
}
@Override
public Money getPaymentDiscountAmt()
{
return amountToAllocate.toZero();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\service\PaymentDocument.java | 2 |
请完成以下Java代码 | public long longValue() {
return sum();
}
/**
* Returns the {@link #sum} as an {@code int} after a narrowing
* primitive conversion.
*/
public int intValue() {
return (int)sum();
}
/**
* Returns the {@link #sum} as a {@code float}
* after a widening primitive conversion.
*/
public float floatValue() {
return (float)sum();
}
/**
* Returns the {@link #sum} as a {@code double} after a widening
* primitive conversion.
*/
public double doubleValue() {
return (double)sum();
}
/**
* Serialization proxy, used to avoid reference to the non-public
* Striped64 superclass in serialized forms.
* @serial include
*/
private static class SerializationProxy implements Serializable {
private static final long serialVersionUID = 7249069246863182397L;
/**
* The current value returned by sum().
* @serial
*/
private final long value;
SerializationProxy(LongAdder a) {
value = a.sum();
}
/** | * Return a {@code LongAdder} object with initial state
* held by this proxy.
*
* @return a {@code LongAdder} object with initial state
* held by this proxy.
*/
private Object readResolve() {
LongAdder a = new LongAdder();
a.base = value;
return a;
}
}
/**
* Returns a
* <a href="../../../../serialized-form.html#java.util.concurrent.atomic.LongAdder.SerializationProxy">
* SerializationProxy</a>
* representing the state of this instance.
*
* @return a {@link SerializationProxy}
* representing the state of this instance
*/
private Object writeReplace() {
return new SerializationProxy(this);
}
/**
* @param s the stream
* @throws java.io.InvalidObjectException always
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.InvalidObjectException {
throw new java.io.InvalidObjectException("Proxy required");
}
} | repos\tutorials-master\jmh\src\main\java\com\baeldung\falsesharing\LongAdder.java | 1 |
请完成以下Java代码 | public FormDefinition getFormDefinition() {
return formDefinition;
}
public void setFormDefinition(FormDefinition formDefinition) {
this.formDefinition = formDefinition;
}
public Expression getFormKey() {
return formDefinition.getFormKey();
}
public void setFormKey(Expression formKey) {
this.formDefinition.setFormKey(formKey);
}
public Expression getCamundaFormDefinitionKey() {
return formDefinition.getCamundaFormDefinitionKey();
} | public String getCamundaFormDefinitionBinding() {
return formDefinition.getCamundaFormDefinitionBinding();
}
public Expression getCamundaFormDefinitionVersion() {
return formDefinition.getCamundaFormDefinitionVersion();
}
// helper methods ///////////////////////////////////////////////////////////
protected void populateAllTaskListeners() {
// reset allTaskListeners to build it from zero
allTaskListeners = new HashMap<>();
// ensure builtinTaskListeners are executed before regular taskListeners
CollectionUtil.mergeMapsOfLists(allTaskListeners, builtinTaskListeners);
CollectionUtil.mergeMapsOfLists(allTaskListeners, taskListeners);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\task\TaskDefinition.java | 1 |
请完成以下Java代码 | public static Object convertValueToFieldType(
@Nullable final Object value,
@NonNull final DataEntryField field)
{
if (value == null)
{
return null;
}
final Class<?> typeClass = field.getType().getClazz();
if (typeClass.isInstance(value))
{
return value;
}
else if (Integer.class.equals(typeClass))
{
final Integer valueConv = NumberUtils.asInteger(value, null);
if (valueConv == null)
{
throw new AdempiereException("Failed converting `" + value + "` " + value.getClass() + " to " + Integer.class);
}
return valueConv;
}
else if (BigDecimal.class.equals(typeClass))
{
final BigDecimal valueConv = NumberUtils.asBigDecimal(value, null);
if (valueConv == null)
{
throw new AdempiereException("Failed converting `" + value + "` " + value.getClass() + " to " + BigDecimal.class);
}
return valueConv;
}
else if (String.class.equals(typeClass))
{
return value.toString();
}
else if (Boolean.class.equals(typeClass))
{
final Boolean valueConv = StringUtils.toBoolean(value, null);
if (valueConv == null)
{
throw new AdempiereException("Failed converting `" + value + "` " + value.getClass() + " to " + Boolean.class);
}
return valueConv;
}
else if (LocalDate.class.equals(typeClass))
{
return TimeUtil.asLocalDate(value);
}
else if (DataEntryListValueId.class.equals(typeClass))
{
return convertValueToListValueId(value, field);
}
else
{
throw new AdempiereException("Cannot convert `" + value + "` from " + value.getClass() + " to " + typeClass);
}
}
@Nullable
private static DataEntryListValueId convertValueToListValueId(
@Nullable final Object value,
@NonNull final DataEntryField field) | {
if (value == null)
{
return null;
}
//
// Match by ID
final Integer valueInt = NumberUtils.asIntegerOrNull(value);
if (valueInt != null)
{
final DataEntryListValueId id = DataEntryListValueId.ofRepoIdOrNull(valueInt);
if (id != null)
{
final DataEntryListValue matchedListValue = field.getFirstListValueMatching(listValue -> id.equals(listValue.getId()))
.orElse(null);
if (matchedListValue != null)
{
return matchedListValue.getId();
}
}
}
//
// Match by Name
{
final String captionStr = value.toString().trim();
if (captionStr.isEmpty())
{
return null;
}
final DataEntryListValue matchedListValue = field.getFirstListValueMatching(listValue -> listValue.isNameMatching(captionStr))
.orElse(null);
if (matchedListValue != null)
{
return matchedListValue.getId();
}
}
//
// Fail
throw new AdempiereException("No list value found for `" + value + "`");
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\data\DataEntryRecordField.java | 1 |
请完成以下Java代码 | private void doShutdown(GracefulShutdownCallback callback, CountDownLatch shutdownUnderway) {
try {
List<Connector> connectors = getConnectors();
connectors.forEach(this::close);
shutdownUnderway.countDown();
awaitInactiveOrAborted();
if (this.aborted) {
logger.info("Graceful shutdown aborted with one or more requests still active");
callback.shutdownComplete(GracefulShutdownResult.REQUESTS_ACTIVE);
}
else {
logger.info("Graceful shutdown complete");
callback.shutdownComplete(GracefulShutdownResult.IDLE);
}
}
finally {
shutdownUnderway.countDown();
}
}
private List<Connector> getConnectors() {
List<Connector> connectors = new ArrayList<>();
for (Service service : this.tomcat.getServer().findServices()) {
Collections.addAll(connectors, service.findConnectors());
}
return connectors;
}
private void close(Connector connector) {
connector.pause();
connector.getProtocolHandler().closeServerSocketGraceful();
}
private void awaitInactiveOrAborted() {
try {
for (Container host : this.tomcat.getEngine().findChildren()) {
for (Container context : host.findChildren()) {
while (!this.aborted && isActive(context)) {
Thread.sleep(50);
}
}
}
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
} | private boolean isActive(Container context) {
try {
if (((StandardContext) context).getInProgressAsyncCount() > 0) {
return true;
}
for (Container wrapper : context.findChildren()) {
if (((StandardWrapper) wrapper).getCountAllocated() > 0) {
return true;
}
}
return false;
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
}
void abort() {
this.aborted = true;
}
} | repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\GracefulShutdown.java | 1 |
请完成以下Java代码 | public class UseSwitchToConvertPhoneNumberInWordsToNumber {
public static String convertPhoneNumberInWordsToNumber(String phoneNumberInWord) {
StringBuilder output = new StringBuilder();
Integer currentMultiplier = null;
String[] words = phoneNumberInWord.split(" ");
for (String word : words) {
Integer multiplier = getWordAsMultiplier(word);
if (multiplier != null) {
if (currentMultiplier != null) {
throw new IllegalArgumentException("Cannot have consecutive multipliers, at: " + word);
}
currentMultiplier = multiplier;
} else {
output.append(getWordAsDigit(word).repeat(currentMultiplier != null ? currentMultiplier : 1));
currentMultiplier = null;
}
}
return output.toString();
}
public static Integer getWordAsMultiplier(String word) {
switch (word) {
case "double":
return 2;
case "triple":
return 3;
case "quadruple":
return 4;
default:
return null;
}
}
public static String getWordAsDigit(String word) {
switch (word) {
case "zero":
return "0"; | case "one":
return "1";
case "two":
return "2";
case "three":
return "3";
case "four":
return "4";
case "five":
return "5";
case "six":
return "6";
case "seven":
return "7";
case "eight":
return "8";
case "nine":
return "9";
default:
throw new IllegalArgumentException("Invalid word: " + word);
}
}
} | repos\tutorials-master\core-java-modules\core-java-numbers-7\src\main\java\com\baeldung\convertphonenumberinwordstonumber\UseSwitchToConvertPhoneNumberInWordsToNumber.java | 1 |
请完成以下Java代码 | public class X_M_Picking_Job_Schedule extends org.compiere.model.PO implements I_M_Picking_Job_Schedule, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 1754908611L;
/** Standard Constructor */
public X_M_Picking_Job_Schedule (final Properties ctx, final int M_Picking_Job_Schedule_ID, @Nullable final String trxName)
{
super (ctx, M_Picking_Job_Schedule_ID, trxName);
}
/** Load Constructor */
public X_M_Picking_Job_Schedule (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_UOM_ID (final int C_UOM_ID)
{
if (C_UOM_ID < 1)
set_Value (COLUMNNAME_C_UOM_ID, null);
else
set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID);
}
@Override
public int getC_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_C_UOM_ID);
}
@Override
public void setC_Workplace_ID (final int C_Workplace_ID)
{
if (C_Workplace_ID < 1)
set_Value (COLUMNNAME_C_Workplace_ID, null);
else
set_Value (COLUMNNAME_C_Workplace_ID, C_Workplace_ID);
}
@Override
public int getC_Workplace_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Workplace_ID);
}
@Override
public void setM_Picking_Job_Schedule_ID (final int M_Picking_Job_Schedule_ID)
{
if (M_Picking_Job_Schedule_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Picking_Job_Schedule_ID, null); | else
set_ValueNoCheck (COLUMNNAME_M_Picking_Job_Schedule_ID, M_Picking_Job_Schedule_ID);
}
@Override
public int getM_Picking_Job_Schedule_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Picking_Job_Schedule_ID);
}
@Override
public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID)
{
if (M_ShipmentSchedule_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID);
}
@Override
public int getM_ShipmentSchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setQtyToPick (final BigDecimal QtyToPick)
{
set_Value (COLUMNNAME_QtyToPick, QtyToPick);
}
@Override
public BigDecimal getQtyToPick()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_Picking_Job_Schedule.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Result<Long> deleteApi(Long id) {
if (id == null) {
return Result.ofFail(-1, "id can't be null");
}
ApiDefinitionEntity oldEntity = repository.findById(id);
if (oldEntity == null) {
return Result.ofSuccess(null);
}
try {
repository.delete(id);
} catch (Throwable throwable) {
logger.error("delete gateway api error:", throwable);
return Result.ofThrowable(-1, throwable);
}
if (!publishApis(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) {
logger.warn("publish gateway apis fail after delete");
}
return Result.ofSuccess(id); | }
private boolean publishApis(String app, String ip, Integer port) {
List<ApiDefinitionEntity> apis = repository.findAllByApp(app);
try {
apiPublisher.publish(app, apis);
//延迟加载
delayTime();
return true;
} catch (Exception e) {
logger.error("publish api error!");
e.printStackTrace();
return false;
}
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\gateway\GatewayApiController.java | 2 |
请完成以下Java代码 | public C_Aggregation_Builder setAD_Table_ID(final int adTableId)
{
this.adTableId = adTableId;
return this;
}
public C_Aggregation_Builder setAD_Table_ID(final String tableName)
{
this.adTableId = Services.get(IADTableDAO.class).retrieveTableId(tableName);
return this;
}
public C_Aggregation_Builder setIsDefault(final boolean isDefault)
{
this.isDefault = isDefault;
return this;
}
public C_Aggregation_Builder setIsDefaultSO(final boolean isDefaultSO)
{
this.isDefaultSO = isDefaultSO;
return this;
}
public C_Aggregation_Builder setIsDefaultPO(final boolean isDefaultPO)
{
this.isDefaultPO = isDefaultPO;
return this;
} | public C_Aggregation_Builder setAggregationUsageLevel(final String aggregationUsageLevel)
{
this.aggregationUsageLevel = aggregationUsageLevel;
return this;
}
public C_AggregationItem_Builder newItem()
{
if (adTableId <= 0)
{
throw new AdempiereException("Before creating a new item, a adTableId needs to be set to the builder")
.appendParametersToMessage()
.setParameter("C_Aggregation_Builder", this);
}
final C_AggregationItem_Builder itemBuilder = new C_AggregationItem_Builder(this, AdTableId.ofRepoId(adTableId));
itemBuilders.add(itemBuilder);
return itemBuilder;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\model\C_Aggregation_Builder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private MaterialDescriptorQuery createMaterialDescriptorQuery(@NonNull final StockChangedEvent event)
{
final ProductDescriptor productDescriptor = event.getProductDescriptor();
final DateAndSeqNo timeRangeEnd = DateAndSeqNo.builder()
.date(computeDate(event))
.operator(Operator.INCLUSIVE).build();
return MaterialDescriptorQuery.builder()
.timeRangeEnd(timeRangeEnd)
.productId(productDescriptor.getProductId())
.storageAttributesKey(productDescriptor.getStorageAttributesKey())
.warehouseId(event.getWarehouseId())
.build();
}
private MaterialDescriptorBuilder createMaterialDescriptorBuilder(@NonNull final StockChangedEvent event)
{
final ProductDescriptor productDescriptor = event.getProductDescriptor();
final Instant date = computeDate(event);
return MaterialDescriptor.builder()
.date(date)
.productDescriptor(productDescriptor)
.customerId(null)
.warehouseId(event.getWarehouseId());
}
private TransactionDetail createStockChangeDetail(@NonNull final StockChangedEvent event)
{
final StockChangeDetails stockChangeDetails = event.getStockChangeDetails();
final ProductDescriptor productDescriptor = event.getProductDescriptor(); | return TransactionDetail.builder()
.attributeSetInstanceId(productDescriptor.getAttributeSetInstanceId())
.complete(true)
.quantity(event.getQtyOnHand().subtract(event.getQtyOnHandOld()))
.resetStockPInstanceId(stockChangeDetails.getResetStockPInstanceId())
.stockId(stockChangeDetails.getStockId())
.storageAttributesKey(productDescriptor.getStorageAttributesKey())
.transactionId(stockChangeDetails.getTransactionId())
.transactionDate(computeDate(event))
.complete(true)
.build();
}
private Instant computeDate(@NonNull final StockChangedEvent event)
{
return CoalesceUtil.coalesceSuppliers(
event::getChangeDate,
SystemTime::asInstant);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\StockChangedEventHandler.java | 2 |
请在Spring Boot框架中完成以下Java代码 | class KafkaStreamsAnnotationDrivenConfiguration {
private final KafkaProperties properties;
KafkaStreamsAnnotationDrivenConfiguration(KafkaProperties properties) {
this.properties = properties;
}
@ConditionalOnMissingBean
@Bean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME)
KafkaStreamsConfiguration defaultKafkaStreamsConfig(Environment environment,
KafkaConnectionDetails connectionDetails) {
Map<String, Object> properties = this.properties.buildStreamsProperties();
applyKafkaConnectionDetailsForStreams(properties, connectionDetails);
if (this.properties.getStreams().getApplicationId() == null) {
String applicationName = environment.getProperty("spring.application.name");
if (applicationName == null) {
throw new InvalidConfigurationPropertyValueException("spring.kafka.streams.application-id", null,
"This property is mandatory and fallback 'spring.application.name' is not set either.");
}
properties.put(StreamsConfig.APPLICATION_ID_CONFIG, applicationName);
}
return new KafkaStreamsConfiguration(properties);
}
@Bean
StreamsBuilderFactoryBeanConfigurer kafkaPropertiesStreamsBuilderFactoryBeanConfigurer() {
return new KafkaPropertiesStreamsBuilderFactoryBeanConfigurer(this.properties);
}
private void applyKafkaConnectionDetailsForStreams(Map<String, Object> properties, | KafkaConnectionDetails connectionDetails) {
KafkaConnectionDetails.Configuration streams = connectionDetails.getStreams();
properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, streams.getBootstrapServers());
KafkaAutoConfiguration.applySecurityProtocol(properties, streams.getSecurityProtocol());
KafkaAutoConfiguration.applySslBundle(properties, streams.getSslBundle());
}
static class KafkaPropertiesStreamsBuilderFactoryBeanConfigurer implements StreamsBuilderFactoryBeanConfigurer {
private final KafkaProperties properties;
KafkaPropertiesStreamsBuilderFactoryBeanConfigurer(KafkaProperties properties) {
this.properties = properties;
}
@Override
public void configure(StreamsBuilderFactoryBean factoryBean) {
factoryBean.setAutoStartup(this.properties.getStreams().isAutoStartup());
KafkaProperties.Cleanup cleanup = this.properties.getStreams().getCleanup();
CleanupConfig cleanupConfig = new CleanupConfig(cleanup.isOnStartup(), cleanup.isOnShutdown());
factoryBean.setCleanupConfig(cleanupConfig);
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-kafka\src\main\java\org\springframework\boot\kafka\autoconfigure\KafkaStreamsAnnotationDrivenConfiguration.java | 2 |
请完成以下Java代码 | public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Redo.
@param Redo Redo */
@Override
public void setRedo (java.lang.String Redo)
{
set_Value (COLUMNNAME_Redo, Redo);
}
/** Get Redo.
@return Redo */
@Override
public java.lang.String getRedo ()
{
return (java.lang.String)get_Value(COLUMNNAME_Redo);
}
/** Set Transaktion.
@param TrxName
Name of the transaction
*/
@Override
public void setTrxName (java.lang.String TrxName)
{
set_ValueNoCheck (COLUMNNAME_TrxName, TrxName);
} | /** Get Transaktion.
@return Name of the transaction
*/
@Override
public java.lang.String getTrxName ()
{
return (java.lang.String)get_Value(COLUMNNAME_TrxName);
}
/** Set Undo.
@param Undo Undo */
@Override
public void setUndo (java.lang.String Undo)
{
set_Value (COLUMNNAME_Undo, Undo);
}
/** Get Undo.
@return Undo */
@Override
public java.lang.String getUndo ()
{
return (java.lang.String)get_Value(COLUMNNAME_Undo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ChangeLog.java | 1 |
请完成以下Java代码 | public SuspensionState getSuspensionState() {
return suspensionState;
}
public void setSuspensionState(SuspensionState suspensionState) {
this.suspensionState = suspensionState;
}
public String getIncidentId() {
return incidentId;
}
public String getIncidentType() {
return incidentType;
}
public String getIncidentMessage() {
return incidentMessage;
}
public String getIncidentMessageLike() {
return incidentMessageLike;
}
public String getVersionTag() {
return versionTag;
}
public boolean isStartableInTasklist() {
return isStartableInTasklist;
}
public boolean isNotStartableInTasklist() {
return isNotStartableInTasklist;
}
public boolean isStartablePermissionCheck() {
return startablePermissionCheck;
}
public void setProcessDefinitionCreatePermissionChecks(List<PermissionCheck> processDefinitionCreatePermissionChecks) {
this.processDefinitionCreatePermissionChecks = processDefinitionCreatePermissionChecks; | }
public List<PermissionCheck> getProcessDefinitionCreatePermissionChecks() {
return processDefinitionCreatePermissionChecks;
}
public boolean isShouldJoinDeploymentTable() {
return shouldJoinDeploymentTable;
}
public void addProcessDefinitionCreatePermissionCheck(CompositePermissionCheck processDefinitionCreatePermissionCheck) {
processDefinitionCreatePermissionChecks.addAll(processDefinitionCreatePermissionCheck.getAllPermissionChecks());
}
public List<String> getCandidateGroups() {
if (cachedCandidateGroups != null) {
return cachedCandidateGroups;
}
if(authorizationUserId != null) {
List<Group> groups = Context.getCommandContext()
.getReadOnlyIdentityProvider()
.createGroupQuery()
.groupMember(authorizationUserId)
.list();
cachedCandidateGroups = groups.stream().map(Group::getId).collect(Collectors.toList());
}
return cachedCandidateGroups;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessDefinitionQueryImpl.java | 1 |
请完成以下Java代码 | public JsonHUAttributeCodeAndValues toJsonHUAttributeCodeAndValues()
{
final JsonHUAttributeCodeAndValues result = new JsonHUAttributeCodeAndValues();
for (final JsonHUAttribute attribute : list)
{
result.putAttribute(attribute.getCode(), attribute.getValue());
}
return result;
}
public static JsonHUAttributes ofJsonHUAttributeCodeAndValues(@NonNull JsonHUAttributeCodeAndValues attributeCodeAndValues)
{
final ArrayList<JsonHUAttribute> list = new ArrayList<>();
for (final Map.Entry<String, Object> attributeCodeAndValue : attributeCodeAndValues.getAttributes().entrySet())
{
list.add(JsonHUAttribute.builder()
.code(attributeCodeAndValue.getKey())
.caption(attributeCodeAndValue.getKey())
.value(attributeCodeAndValue.getValue())
.build());
} | return JsonHUAttributes.builder().list(list).build();
}
public JsonHUAttributes retainOnlyAttributesInOrder(@NonNull final List<String> codes)
{
final ArrayList<JsonHUAttribute> filteredList = new ArrayList<>();
final ImmutableListMultimap<String, JsonHUAttribute> attributesByCode = Multimaps.index(list, JsonHUAttribute::getCode);
for (String code : codes)
{
filteredList.addAll(attributesByCode.get(code));
}
return builder().list(filteredList).build();
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-manufacturing\src\main\java\de\metas\common\handlingunits\JsonHUAttributes.java | 1 |
请完成以下Java代码 | public boolean isWithoutDueDate() {
return withoutDueDate;
}
public SuspensionState getSuspensionState() {
return suspensionState;
}
public boolean isIncludeTaskLocalVariables() {
return includeTaskLocalVariables;
}
public boolean isIncludeProcessVariables() {
return includeProcessVariables;
}
public boolean isBothCandidateAndAssigned() {
return bothCandidateAndAssigned;
}
public String getNameLikeIgnoreCase() {
return nameLikeIgnoreCase;
}
public String getDescriptionLikeIgnoreCase() {
return descriptionLikeIgnoreCase;
} | public String getAssigneeLikeIgnoreCase() {
return assigneeLikeIgnoreCase;
}
public String getOwnerLikeIgnoreCase() {
return ownerLikeIgnoreCase;
}
public String getProcessInstanceBusinessKeyLikeIgnoreCase() {
return processInstanceBusinessKeyLikeIgnoreCase;
}
public String getProcessDefinitionKeyLikeIgnoreCase() {
return processDefinitionKeyLikeIgnoreCase;
}
public String getLocale() {
return locale;
}
public boolean isOrActive() {
return orActive;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\TaskQueryImpl.java | 1 |
请完成以下Java代码 | public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ModelApiResponse _apiResponse = (ModelApiResponse) o;
return Objects.equals(this.code, _apiResponse.code) &&
Objects.equals(this.type, _apiResponse.type) &&
Objects.equals(this.message, _apiResponse.message);
}
@Override
public int hashCode() {
return Objects.hash(code, type, message);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ModelApiResponse {\n");
sb.append(" code: ").append(toIndentedString(code)).append("\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n"); | sb.append(" message: ").append(toIndentedString(message)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\tutorials-master\spring-swagger-codegen-modules\spring-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\model\ModelApiResponse.java | 1 |
请完成以下Java代码 | public FrontendPrinterData toFrontendPrinterData()
{
return queuesMap.values()
.stream()
.map(PrinterQueue::toFrontendPrinterData)
.collect(GuavaCollectors.collectUsingListAccumulator(FrontendPrinterData::of));
}
}
@RequiredArgsConstructor
private static class PrinterQueue
{
@NonNull private final HardwarePrinter printer;
@NonNull private final ArrayList<PrintingDataAndSegment> segments = new ArrayList<>();
public void add(
@NonNull PrintingData printingData,
@NonNull PrintingSegment segment)
{
Check.assumeEquals(this.printer, segment.getPrinter(), "Expected segment printer to match: {}, expected={}", segment, printer);
segments.add(PrintingDataAndSegment.of(printingData, segment));
}
public FrontendPrinterDataItem toFrontendPrinterData()
{
return FrontendPrinterDataItem.builder()
.printer(printer)
.filename(suggestFilename())
.data(toByteArray())
.build();
}
private byte[] toByteArray()
{
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (final PrintingDataToPDFWriter pdfWriter = new PrintingDataToPDFWriter(baos))
{
for (PrintingDataAndSegment printingDataAndSegment : segments)
{
pdfWriter.addArchivePartToPDF(printingDataAndSegment.getPrintingData(), printingDataAndSegment.getSegment());
}
}
return baos.toByteArray();
} | private String suggestFilename()
{
final ImmutableSet<String> filenames = segments.stream()
.map(PrintingDataAndSegment::getDocumentFileName)
.collect(ImmutableSet.toImmutableSet());
return filenames.size() == 1 ? filenames.iterator().next() : "report.pdf";
}
}
@Value(staticConstructor = "of")
private static class PrintingDataAndSegment
{
@NonNull PrintingData printingData;
@NonNull PrintingSegment segment;
public String getDocumentFileName()
{
return printingData.getDocumentFileName();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\frontend\FrontendPrinter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable ThrottlerType getType() {
return this.type;
}
public void setType(@Nullable ThrottlerType type) {
this.type = type;
}
public @Nullable Integer getMaxQueueSize() {
return this.maxQueueSize;
}
public void setMaxQueueSize(@Nullable Integer maxQueueSize) {
this.maxQueueSize = maxQueueSize;
}
public @Nullable Integer getMaxConcurrentRequests() {
return this.maxConcurrentRequests;
}
public void setMaxConcurrentRequests(@Nullable Integer maxConcurrentRequests) {
this.maxConcurrentRequests = maxConcurrentRequests;
}
public @Nullable Integer getMaxRequestsPerSecond() {
return this.maxRequestsPerSecond;
}
public void setMaxRequestsPerSecond(@Nullable Integer maxRequestsPerSecond) {
this.maxRequestsPerSecond = maxRequestsPerSecond;
}
public @Nullable Duration getDrainInterval() {
return this.drainInterval;
}
public void setDrainInterval(@Nullable Duration drainInterval) {
this.drainInterval = drainInterval;
}
}
/**
* Name of the algorithm used to compress protocol frames.
*/
public enum Compression {
/**
* Requires 'net.jpountz.lz4:lz4'.
*/
LZ4,
/**
* Requires org.xerial.snappy:snappy-java.
*/ | SNAPPY,
/**
* No compression.
*/
NONE
}
public enum ThrottlerType {
/**
* Limit the number of requests that can be executed in parallel.
*/
CONCURRENCY_LIMITING("ConcurrencyLimitingRequestThrottler"),
/**
* Limits the request rate per second.
*/
RATE_LIMITING("RateLimitingRequestThrottler"),
/**
* No request throttling.
*/
NONE("PassThroughRequestThrottler");
private final String type;
ThrottlerType(String type) {
this.type = type;
}
public String type() {
return this.type;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-cassandra\src\main\java\org\springframework\boot\cassandra\autoconfigure\CassandraProperties.java | 2 |
请完成以下Java代码 | public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String getNameLikeIgnoreCase() {
return nameLikeIgnoreCase;
}
public String getKey() {
return key;
}
public String getKeyLike() {
return keyLike;
}
public String getKeyLikeIgnoreCase() {
return keyLikeIgnoreCase;
}
public String getCategory() {
return category;
}
public String getCategoryLike() {
return categoryLike;
}
public String getResourceName() {
return resourceName;
}
public String getResourceNameLike() {
return resourceNameLike;
} | public String getCategoryNotEquals() {
return categoryNotEquals;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\EventDefinitionQueryImpl.java | 1 |
请完成以下Java代码 | public Map<String, CommandDto> getCommands() {
return commands;
}
public void setCommands(Map<String, CommandDto> commands) {
this.commands = commands;
}
public Map<String, MetricDto> getMetrics() {
return metrics;
}
public void setMetrics(Map<String, MetricDto> metrics) {
this.metrics = metrics;
}
public JdkDto getJdk() {
return jdk;
}
public void setJdk(JdkDto jdk) {
this.jdk = jdk;
}
public Set<String> getCamundaIntegration() {
return camundaIntegration;
}
public void setCamundaIntegration(Set<String> camundaIntegration) {
this.camundaIntegration = camundaIntegration;
}
public LicenseKeyDataDto getLicenseKey() {
return licenseKey;
}
public void setLicenseKey(LicenseKeyDataDto licenseKey) {
this.licenseKey = licenseKey;
}
public Set<String> getWebapps() {
return webapps;
}
public void setWebapps(Set<String> webapps) {
this.webapps = webapps;
}
public Date getDataCollectionStartDate() {
return dataCollectionStartDate; | }
public void setDataCollectionStartDate(Date dataCollectionStartDate) {
this.dataCollectionStartDate = dataCollectionStartDate;
}
public static InternalsDto fromEngineDto(Internals other) {
LicenseKeyData licenseKey = other.getLicenseKey();
InternalsDto dto = new InternalsDto(
DatabaseDto.fromEngineDto(other.getDatabase()),
ApplicationServerDto.fromEngineDto(other.getApplicationServer()),
licenseKey != null ? LicenseKeyDataDto.fromEngineDto(licenseKey) : null,
JdkDto.fromEngineDto(other.getJdk()));
dto.dataCollectionStartDate = other.getDataCollectionStartDate();
dto.commands = new HashMap<>();
other.getCommands().forEach((name, command) -> dto.commands.put(name, new CommandDto(command.getCount())));
dto.metrics = new HashMap<>();
other.getMetrics().forEach((name, metric) -> dto.metrics.put(name, new MetricDto(metric.getCount())));
dto.setWebapps(other.getWebapps());
dto.setCamundaIntegration(other.getCamundaIntegration());
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\telemetry\InternalsDto.java | 1 |
请完成以下Java代码 | public String toString() {
return this.string;
}
private String buildString(String name, @Nullable String tag, @Nullable String digest) {
StringBuilder string = new StringBuilder(name);
if (tag != null) {
string.append(":").append(tag);
}
if (digest != null) {
string.append("@").append(digest);
}
return string.toString();
}
/**
* Create a new {@link ImageReference} from the given value. The following value forms
* can be used:
* <ul>
* <li>{@code name} (maps to {@code docker.io/library/name})</li>
* <li>{@code domain/name}</li>
* <li>{@code domain:port/name}</li>
* <li>{@code domain:port/name:tag}</li>
* <li>{@code domain:port/name@digest}</li>
* </ul>
* @param value the value to parse
* @return an {@link ImageReference} instance
*/
public static ImageReference of(String value) {
Assert.hasText(value, "'value' must not be null");
String domain = ImageName.parseDomain(value);
String path = (domain != null) ? value.substring(domain.length() + 1) : value;
String digest = null;
int digestSplit = path.indexOf("@");
if (digestSplit != -1) {
String remainder = path.substring(digestSplit + 1);
Matcher matcher = Regex.DIGEST.matcher(remainder);
if (matcher.find()) {
digest = remainder.substring(0, matcher.end());
remainder = remainder.substring(matcher.end());
path = path.substring(0, digestSplit) + remainder; | }
}
String tag = null;
int tagSplit = path.lastIndexOf(":");
if (tagSplit != -1) {
String remainder = path.substring(tagSplit + 1);
Matcher matcher = Regex.TAG.matcher(remainder);
if (matcher.find()) {
tag = remainder.substring(0, matcher.end());
remainder = remainder.substring(matcher.end());
path = path.substring(0, tagSplit) + remainder;
}
}
Assert.isTrue(Regex.PATH.matcher(path).matches(),
() -> "'value' path must contain an image reference in the form "
+ "'[domainHost:port/][path/]name[:tag][@digest] "
+ "(with 'path' and 'name' containing only [a-z0-9][.][_][-]) [" + value + "]");
ImageName name = new ImageName(domain, path);
return new ImageReference(name, tag, digest);
}
} | repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\core\ImageReference.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void remove(EntityId profileId, EntityId entityId) {
lock.writeLock().lock();
try {
// Remove from allEntities
removeSafely(allEntities, profileId, entityId);
} finally {
lock.writeLock().unlock();
}
}
public void add(EntityId profileId, EntityId entityId) {
lock.writeLock().lock();
try {
if (EntityType.DEVICE.equals(profileId.getEntityType()) || EntityType.ASSET.equals(profileId.getEntityType())) {
throw new RuntimeException("Entity type '" + profileId.getEntityType() + "' is not a profileId.");
}
allEntities.computeIfAbsent(profileId, k -> new HashSet<>()).add(entityId);
} finally {
lock.writeLock().unlock();
}
}
public void update(EntityId oldProfileId, EntityId newProfileId, EntityId entityId) { | remove(oldProfileId, entityId);
add(newProfileId, entityId);
}
public Collection<EntityId> getEntityIdsByProfileId(EntityId profileId) {
lock.readLock().lock();
try {
var entities = allEntities.getOrDefault(profileId, Collections.emptySet());
List<EntityId> result = new ArrayList<>(entities.size());
result.addAll(entities);
return result;
} finally {
lock.readLock().unlock();
}
}
private void removeSafely(Map<EntityId, Set<EntityId>> map, EntityId profileId, EntityId entityId) {
var set = map.get(profileId);
if (set != null) {
set.remove(entityId);
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\cf\cache\TenantEntityProfileCache.java | 2 |
请完成以下Java代码 | public class Calculator implements CalculatorMBean {
private Integer a = 0;
private Integer b = 0;
@Override
public Integer sum() {
return a + b;
}
@Override
public Integer getA() {
return a;
} | @Override
public void setA(Integer a) {
this.a = a;
}
@Override
public Integer getB() {
return b;
}
@Override
public void setB(Integer b) {
this.b = b;
}
} | repos\tutorials-master\core-java-modules\core-java-perf-2\src\main\java\com\baeldung\jmxshell\bean\Calculator.java | 1 |
请完成以下Java代码 | public class MutableFeatureMap extends FeatureMap
{
public Map<String, Integer> featureIdMap;
// TreeMap 5136
// Bin 2712
// DAT minutes
// trie4j 3411
public MutableFeatureMap(TagSet tagSet)
{
super(tagSet, true);
featureIdMap = new TreeMap<String, Integer>();
addTransitionFeatures(tagSet);
}
private void addTransitionFeatures(TagSet tagSet)
{
for (int i = 0; i < tagSet.size(); i++)
{
idOf("BL=" + tagSet.stringOf(i));
}
idOf("BL=_BL_");
}
public MutableFeatureMap(TagSet tagSet, Map<String, Integer> featureIdMap)
{
super(tagSet);
this.featureIdMap = featureIdMap;
addTransitionFeatures(tagSet);
}
@Override
public Set<Map.Entry<String, Integer>> entrySet()
{
return featureIdMap.entrySet();
}
@Override
public int idOf(String string)
{
Integer id = featureIdMap.get(string);
if (id == null)
{
id = featureIdMap.size();
featureIdMap.put(string, id);
} | return id;
}
public int size()
{
return featureIdMap.size();
}
public Set<String> featureSet()
{
return featureIdMap.keySet();
}
@Override
public int[] allLabels()
{
return tagSet.allTags();
}
@Override
public int bosTag()
{
return tagSet.size();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\feature\MutableFeatureMap.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getAccessKey() {
return accessKey;
}
public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public String getNameSrvAddr() {
return nameSrvAddr;
}
public void setNameSrvAddr(String nameSrvAddr) {
this.nameSrvAddr = nameSrvAddr;
}
public String getTestTopic() {
return testTopic;
}
public void setTestTopic(String testTopic) {
this.testTopic = testTopic;
}
public String getTestGroupId() { | return testGroupId;
}
public void setTestGroupId(String testGroupId) {
this.testGroupId = testGroupId;
}
public String getTestTag() {
return testTag;
}
public void setTestTag(String testTag) {
this.testTag = testTag;
}
} | repos\springBoot-master\springboot-rocketmq-ali\src\main\java\cn\abel\queue\config\ALiMqConfig.java | 2 |
请完成以下Java代码 | public void setUsing(String using) {
this.using = using;
}
public String getUsingdate() {
return usingdate;
}
public void setUsingdate(String usingdate) {
this.usingdate = usingdate;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public String getEnd() {
return end;
}
public void setEnd(String end) {
this.end = end;
}
public String getQrcantonid() {
return qrcantonid;
}
public void setQrcantonid(String qrcantonid) {
this.qrcantonid = qrcantonid;
} | public String getDeclare() {
return declare;
}
public void setDeclare(String declare) {
this.declare = declare;
}
public String getDeclareisend() {
return declareisend;
}
public void setDeclareisend(String declareisend) {
this.declareisend = declareisend;
}
} | repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\canton\Canton.java | 1 |
请完成以下Java代码 | public Row4<Integer, String, String, Integer> fieldsRow() {
return (Row4) super.fieldsRow();
}
@Override
public Row4<Integer, String, String, Integer> valuesRow() {
return (Row4) super.valuesRow();
}
@Override
public Field<Integer> field1() {
return Article.ARTICLE.ID;
}
@Override
public Field<String> field2() {
return Article.ARTICLE.TITLE;
}
@Override
public Field<String> field3() {
return Article.ARTICLE.DESCRIPTION;
}
@Override
public Field<Integer> field4() {
return Article.ARTICLE.AUTHOR_ID;
}
@Override
public Integer component1() {
return getId();
}
@Override
public String component2() {
return getTitle();
}
@Override
public String component3() {
return getDescription();
}
@Override
public Integer component4() {
return getAuthorId();
}
@Override
public Integer value1() {
return getId();
}
@Override
public String value2() {
return getTitle();
}
@Override
public String value3() {
return getDescription();
}
@Override
public Integer value4() {
return getAuthorId();
}
@Override
public ArticleRecord value1(Integer value) { | setId(value);
return this;
}
@Override
public ArticleRecord value2(String value) {
setTitle(value);
return this;
}
@Override
public ArticleRecord value3(String value) {
setDescription(value);
return this;
}
@Override
public ArticleRecord value4(Integer value) {
setAuthorId(value);
return this;
}
@Override
public ArticleRecord values(Integer value1, String value2, String value3, Integer value4) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached ArticleRecord
*/
public ArticleRecord() {
super(Article.ARTICLE);
}
/**
* Create a detached, initialised ArticleRecord
*/
public ArticleRecord(Integer id, String title, String description, Integer authorId) {
super(Article.ARTICLE);
set(0, id);
set(1, title);
set(2, description);
set(3, authorId);
}
} | repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\model\tables\records\ArticleRecord.java | 1 |
请完成以下Java代码 | public String getName() {
return this.name;
}
}
/**
* The direction of createTime.
*/
public enum Direction {
ASC, DESC;
public String asString() {
return super.name().toLowerCase();
}
}
/**
* Static Class that encapsulates an ordering property with a field and its direction.
*/
public static class OrderingProperty {
protected SortingField field;
protected Direction direction;
/**
* Static factory method to create {@link OrderingProperty} out of a field and its corresponding {@link Direction}.
*/
public static OrderingProperty of(SortingField field, Direction direction) {
OrderingProperty result = new OrderingProperty();
result.setField(field);
result.setDirection(direction);
return result;
} | public void setField(SortingField field) {
this.field = field;
}
public SortingField getField() {
return this.field;
}
public void setDirection(Direction direction) {
this.direction = direction;
}
public Direction getDirection() {
return this.direction;
}
}
} | repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\task\OrderingConfig.java | 1 |
请完成以下Java代码 | private static void transformIntoList() {
Integer[] anArray = new Integer[] {1, 2, 3, 4, 5};
// Naïve implementation
List<Integer> aList = new ArrayList<>(); // We create an empty list
for (int element : anArray) {
// We iterate over array's elements and add them to the list
aList.add(element);
}
// Pretty implementation
aList = Arrays.asList(anArray);
// Drawbacks
try {
aList.remove(0);
} catch (UnsupportedOperationException e) {
System.out.println(e.getMessage());
}
try {
aList.add(6);
} catch (UnsupportedOperationException e) {
System.out.println(e.getMessage());
}
int[] anotherArray = new int[] {1, 2, 3, 4, 5};
// List<Integer> anotherList = Arrays.asList(anotherArray);
}
private static void transformIntoStream() {
int[] anArray = new int[] {1, 2, 3, 4, 5};
IntStream aStream = Arrays.stream(anArray);
Integer[] anotherArray = new Integer[] {1, 2, 3, 4, 5};
Stream<Integer> anotherStream = Arrays.stream(anotherArray, 2, 4);
}
private static void sort() {
int[] anArray = new int[] {5, 2, 1, 4, 8};
Arrays.sort(anArray); // anArray is now {1, 2, 4, 5, 8}
Integer[] anotherArray = new Integer[] {5, 2, 1, 4, 8};
Arrays.sort(anotherArray); // anArray is now {1, 2, 4, 5, 8}
String[] yetAnotherArray = new String[] {"A", "E", "Z", "B", "C"};
Arrays.sort(yetAnotherArray, 1, 3, Comparator.comparing(String::toString).reversed()); // yetAnotherArray is now {"A", "Z", "E", "B", "C"}
}
private static void search() {
int[] anArray = new int[] {5, 2, 1, 4, 8};
for (int i = 0; i < anArray.length; i++) {
if (anArray[i] == 4) {
System.out.println("Found at index " + i);
break;
} | }
Arrays.sort(anArray);
int index = Arrays.binarySearch(anArray, 4);
System.out.println("Found at index " + index);
}
private static void merge() {
int[] anArray = new int[] {5, 2, 1, 4, 8};
int[] anotherArray = new int[] {10, 4, 9, 11, 2};
int[] resultArray = new int[anArray.length + anotherArray.length];
for (int i = 0; i < resultArray.length; i++) {
resultArray[i] = (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]);
}
for (int element : resultArray) {
System.out.println(element);
}
Arrays.setAll(resultArray, i -> (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]));
for (int element : resultArray) {
System.out.println(element);
}
}
} | repos\tutorials-master\core-java-modules\core-java-arrays-guides\src\main\java\com\baeldung\array\ArrayReferenceGuide.java | 1 |
请完成以下Java代码 | public class RuleEngineOriginatedNotificationInfo implements RuleOriginatedNotificationInfo {
private EntityId msgOriginator;
private CustomerId msgCustomerId;
private String msgType;
private Map<String, String> msgMetadata;
private Map<String, String> msgData;
@Override
public Map<String, String> getTemplateData() {
Map<String, String> templateData = new HashMap<>();
templateData.putAll(msgMetadata);
templateData.putAll(msgData);
templateData.put("originatorType", msgOriginator.getEntityType().getNormalName());
templateData.put("originatorId", msgOriginator.getId().toString());
templateData.put("msgType", msgType); | templateData.put("customerId", msgCustomerId != null ? msgCustomerId.getId().toString() : "");
return templateData;
}
@Override
public EntityId getStateEntityId() {
return msgOriginator;
}
@Override
public CustomerId getAffectedCustomerId() {
return msgCustomerId;
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\notification\info\RuleEngineOriginatedNotificationInfo.java | 1 |
请完成以下Java代码 | public List<IdentityLinkEntity> findIdentityLinkByTaskUserGroupAndType(
String taskId,
String userId,
String groupId,
String type
) {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("taskId", taskId);
parameters.put("userId", userId);
parameters.put("groupId", groupId);
parameters.put("type", type);
return getDbSqlSession().selectList("selectIdentityLinkByTaskUserGroupAndType", parameters);
}
@Override
@SuppressWarnings("unchecked")
public List<IdentityLinkEntity> findIdentityLinkByProcessInstanceUserGroupAndType(
String processInstanceId,
String userId,
String groupId,
String type
) {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("processInstanceId", processInstanceId);
parameters.put("userId", userId);
parameters.put("groupId", groupId);
parameters.put("type", type); | return getDbSqlSession().selectList("selectIdentityLinkByProcessInstanceUserGroupAndType", parameters);
}
@Override
@SuppressWarnings("unchecked")
public List<IdentityLinkEntity> findIdentityLinkByProcessDefinitionUserAndGroup(
String processDefinitionId,
String userId,
String groupId
) {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("processDefinitionId", processDefinitionId);
parameters.put("userId", userId);
parameters.put("groupId", groupId);
return getDbSqlSession().selectList("selectIdentityLinkByProcessDefinitionUserAndGroup", parameters);
}
@Override
public void deleteIdentityLinksByProcDef(String processDefId) {
getDbSqlSession().delete("deleteIdentityLinkByProcDef", processDefId, IdentityLinkEntityImpl.class);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisIdentityLinkDataManager.java | 1 |
请完成以下Java代码 | public class User implements Serializable {
@MvcBinding
@Null
private String id;
@MvcBinding
@NotNull
@Size(min = 1, message = "Name cannot be blank")
@FormParam("name")
private String name;
@MvcBinding
@Min(value = 18, message = "The minimum age of the user should be 18 years")
@FormParam("age")
private int age;
@MvcBinding
@Email(message = "The email cannot be blank and should be in a valid format")
@Size(min=3, message = "Email cannot be empty")
@FormParam("email")
private String email;
@MvcBinding
@Null
@FormParam("phone")
private String phone;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
} | repos\tutorials-master\web-modules\jakarta-ee\src\main\java\com\baeldung\eclipse\krazo\User.java | 1 |
请完成以下Java代码 | public void parseEventBasedGateway(Element eventBasedGwElement, ScopeImpl scope, ActivityImpl activity) {
addStartEventListener(activity);
addEndEventListener(activity);
}
@Override
public void parseTransaction(Element transactionElement, ScopeImpl scope, ActivityImpl activity) {
addStartEventListener(activity);
addEndEventListener(activity);
}
@Override
public void parseCompensateEventDefinition(Element compensateEventDefinition, ActivityImpl compensationActivity) {
}
@Override
public void parseIntermediateThrowEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) {
addStartEventListener(activity);
addEndEventListener(activity);
}
@Override
public void parseIntermediateCatchEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) {
addStartEventListener(activity);
addEndEventListener(activity);
}
@Override
public void parseBoundaryEvent(Element boundaryEventElement, ScopeImpl scopeElement, ActivityImpl activity) {
addStartEventListener(activity);
addEndEventListener(activity);
}
@Override
public void parseIntermediateMessageCatchEventDefinition(Element messageEventDefinition, ActivityImpl nestedActivity) {
}
@Override | public void parseBoundaryMessageEventDefinition(Element element, boolean interrupting, ActivityImpl messageActivity) {
}
@Override
public void parseBoundaryEscalationEventDefinition(Element escalationEventDefinition, boolean interrupting, ActivityImpl boundaryEventActivity) {
}
@Override
public void parseBoundaryConditionalEventDefinition(Element element, boolean interrupting, ActivityImpl conditionalActivity) {
}
@Override
public void parseIntermediateConditionalEventDefinition(Element conditionalEventDefinition, ActivityImpl conditionalActivity) {
}
public void parseConditionalStartEventForEventSubprocess(Element element, ActivityImpl conditionalActivity, boolean interrupting) {
}
@Override
public void parseIoMapping(Element extensionElements, ActivityImpl activity, IoMapping inputOutput) {
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\event\ProcessApplicationEventParseListener.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void populateCategories() {
TopCategory tc1 = new TopCategory();
tc1.setName("TOP_CATEGORY_1");
TopCategory tc2 = new TopCategory();
tc2.setName("TOP_CATEGORY_2");
MiddleCategory mc1 = new MiddleCategory();
mc1.setName("MIDDLE_CATEGORY_1");
MiddleCategory mc2 = new MiddleCategory();
mc2.setName("MIDDLE_CATEGORY_2");
MiddleCategory mc3 = new MiddleCategory();
mc3.setName("MIDDLE_CATEGORY_3");
BottomCategory bc1 = new BottomCategory();
bc1.setName("BOTTOM_CATEGORY_1");
BottomCategory bc2 = new BottomCategory();
bc2.setName("BOTTOM_CATEGORY_2");
BottomCategory bc3 = new BottomCategory();
bc3.setName("BOTTOM_CATEGORY_3");
BottomCategory bc4 = new BottomCategory();
bc4.setName("BOTTOM_CATEGORY_4");
BottomCategory bc5 = new BottomCategory();
bc5.setName("BOTTOM_CATEGORY_5");
tc1.addMiddleCategory(mc1);
tc1.addMiddleCategory(mc2);
tc2.addMiddleCategory(mc3); | mc1.addBottomCategory(bc1);
mc1.addBottomCategory(bc2);
mc1.addBottomCategory(bc3);
mc2.addBottomCategory(bc4);
mc3.addBottomCategory(bc5);
dao.persist(tc1);
dao.persist(tc2);
}
public List<CategoryDto> fetchCategories() {
return dao.fetchCategories();
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoSqlResultSetMapping\src\main\java\com\app\service\CategoryService.java | 2 |
请完成以下Java代码 | public int getDLM_Partition_Config_Line_ID()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Partition_Config_Line_ID);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Table getDLM_Referencing_Table() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_DLM_Referencing_Table_ID, org.compiere.model.I_AD_Table.class);
}
@Override
public void setDLM_Referencing_Table(final org.compiere.model.I_AD_Table DLM_Referencing_Table)
{
set_ValueFromPO(COLUMNNAME_DLM_Referencing_Table_ID, org.compiere.model.I_AD_Table.class, DLM_Referencing_Table);
}
/**
* Set Referenzierende Tabelle.
*
* @param DLM_Referencing_Table_ID Referenzierende Tabelle
*/
@Override
public void setDLM_Referencing_Table_ID(final int DLM_Referencing_Table_ID)
{
if (DLM_Referencing_Table_ID < 1)
{
set_Value(COLUMNNAME_DLM_Referencing_Table_ID, null);
}
else
{
set_Value(COLUMNNAME_DLM_Referencing_Table_ID, Integer.valueOf(DLM_Referencing_Table_ID));
}
}
/**
* Get Referenzierende Tabelle.
*
* @return Referenzierende Tabelle
*/
@Override
public int getDLM_Referencing_Table_ID()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Referencing_Table_ID);
if (ii == null)
{
return 0;
} | return ii.intValue();
}
/**
* Set DLM aktiviert.
*
* @param IsDLM
* Die Datensätze einer Tabelle mit aktiviertem DLM können vom System unterschiedlichen DLM-Levels zugeordnet werden
*/
@Override
public void setIsDLM(final boolean IsDLM)
{
throw new IllegalArgumentException("IsDLM is virtual column");
}
/**
* Get DLM aktiviert.
*
* @return Die Datensätze einer Tabelle mit aktiviertem DLM können vom System unterschiedlichen DLM-Levels zugeordnet werden
*/
@Override
public boolean isDLM()
{
final Object oo = get_Value(COLUMNNAME_IsDLM);
if (oo != null)
{
if (oo instanceof Boolean)
{
return ((Boolean)oo).booleanValue();
}
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition_Config_Line.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Boolean isArchived() {
return archived;
}
public void setArchived(Boolean archived) {
this.archived = archived;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InsuranceContractQuantity insuranceContractQuantity = (InsuranceContractQuantity) o;
return Objects.equals(this.pcn, insuranceContractQuantity.pcn) &&
Objects.equals(this.quantity, insuranceContractQuantity.quantity) &&
Objects.equals(this.unit, insuranceContractQuantity.unit) &&
Objects.equals(this.archived, insuranceContractQuantity.archived);
}
@Override
public int hashCode() {
return Objects.hash(pcn, quantity, unit, archived); | }
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class InsuranceContractQuantity {\n");
sb.append(" pcn: ").append(toIndentedString(pcn)).append("\n");
sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n");
sb.append(" unit: ").append(toIndentedString(unit)).append("\n");
sb.append(" archived: ").append(toIndentedString(archived)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\InsuranceContractQuantity.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ConfigTreeConfigDataResource extends ConfigDataResource {
private final Path path;
ConfigTreeConfigDataResource(String path) {
Assert.notNull(path, "'path' must not be null");
this.path = Paths.get(path).toAbsolutePath();
}
ConfigTreeConfigDataResource(Path path) {
Assert.notNull(path, "'path' must not be null");
this.path = path.toAbsolutePath();
}
Path getPath() {
return this.path;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true; | }
if (obj == null || getClass() != obj.getClass()) {
return false;
}
ConfigTreeConfigDataResource other = (ConfigTreeConfigDataResource) obj;
return Objects.equals(this.path, other.path);
}
@Override
public int hashCode() {
return this.path.hashCode();
}
@Override
public String toString() {
return "config tree [" + this.path + "]";
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigTreeConfigDataResource.java | 2 |
请完成以下Java代码 | public final class AggregationKey
{
public static final AggregationKey NULL = new AggregationKey();
@Nullable private final String keyString;
private final IStringExpression keyStringExpr;
@Nullable @Getter
private final AggregationId aggregationId;
public AggregationKey(final ArrayKey key, final AggregationId aggregationId)
{
this(key == null ? null : key.toString(), aggregationId);
}
public AggregationKey(@Nullable final String keyString)
{
this(keyString, null);
}
public AggregationKey(@Nullable final String keyString, @Nullable final AggregationId aggregationId)
{
this.keyString = keyString;
keyStringExpr = Services.get(IExpressionFactory.class).compile(keyString, IStringExpression.class);
this.aggregationId = aggregationId;
}
/**
* Null ctor
*/
private AggregationKey()
{
this.keyString = null;
this.keyStringExpr = NullStringExpression.instance;
this.aggregationId = null;
}
@Override
@Deprecated
public String toString()
{
return getAggregationKeyString();
} | public String getAggregationKeyString()
{
return keyString;
}
public AggregationKey parse(final Evaluatee ctx)
{
final String keyStringNew = keyStringExpr.evaluate(ctx, OnVariableNotFound.Preserve);
return new AggregationKey(keyStringNew, aggregationId);
}
public AggregationKey append(final String keyPart)
{
Check.assumeNotEmpty(keyPart, "keyPart is not empty");
final String keyStringNew = this.keyString + ArrayKey.SEPARATOR + keyPart;
return new AggregationKey(keyStringNew, aggregationId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\api\AggregationKey.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DefaultRepositoryTagsProvider implements RepositoryTagsProvider {
private static final Tag EXCEPTION_NONE = Tag.of("exception", "None");
@Override
public Iterable<Tag> repositoryTags(RepositoryMethodInvocation invocation) {
Tags tags = Tags.empty();
tags = and(tags, invocation.getRepositoryInterface(), "repository", this::getSimpleClassName);
tags = and(tags, invocation.getMethod(), "method", Method::getName);
RepositoryMethodInvocationResult result = invocation.getResult();
if (result != null) {
tags = and(tags, result.getState(), "state", State::name);
tags = and(tags, result.getError(), "exception", this::getExceptionName, EXCEPTION_NONE);
}
return tags;
}
private <T> Tags and(Tags tags, @Nullable T instance, String key, Function<T, String> value) {
return and(tags, instance, key, value, null);
}
private <T> Tags and(Tags tags, @Nullable T instance, String key, Function<T, String> value, | @Nullable Tag fallback) {
if (instance != null) {
return tags.and(key, value.apply(instance));
}
return (fallback != null) ? tags.and(fallback) : tags;
}
private String getExceptionName(Throwable error) {
return getSimpleClassName(error.getClass());
}
private String getSimpleClassName(Class<?> type) {
String simpleName = type.getSimpleName();
return (!StringUtils.hasText(simpleName)) ? type.getName() : simpleName;
}
} | repos\spring-boot-4.0.1\module\spring-boot-data-commons\src\main\java\org\springframework\boot\data\metrics\DefaultRepositoryTagsProvider.java | 2 |
请完成以下Java代码 | public DocumentIdsSelection getDocumentIdsToInvalidate(final TableRecordReferenceSet recordRefs)
{
return DocumentIdsSelection.EMPTY;
}
@Override
public void invalidateAll()
{
// nothing
}
@Override
public void patchRow(
final RowEditingContext ctx,
final List<JSONDocumentChangedEvent> fieldChangeRequests)
{
final ShipmentCandidateRowUserChangeRequest userChanges = toUserChangeRequest(fieldChangeRequests);
changeRow(ctx.getRowId(), row -> row.withChanges(userChanges));
}
private static ShipmentCandidateRowUserChangeRequest toUserChangeRequest(@NonNull final List<JSONDocumentChangedEvent> fieldChangeRequests)
{
Check.assumeNotEmpty(fieldChangeRequests, "fieldChangeRequests is not empty");
final ShipmentCandidateRowUserChangeRequestBuilder builder = ShipmentCandidateRowUserChangeRequest.builder();
for (final JSONDocumentChangedEvent fieldChangeRequest : fieldChangeRequests)
{
final String fieldName = fieldChangeRequest.getPath();
if (ShipmentCandidateRow.FIELD_qtyToDeliverUserEntered.equals(fieldName))
{
builder.qtyToDeliverUserEntered(fieldChangeRequest.getValueAsBigDecimal());
}
else if (ShipmentCandidateRow.FIELD_qtyToDeliverCatchOverride.equals(fieldName))
{
builder.qtyToDeliverCatchOverride(fieldChangeRequest.getValueAsBigDecimal());
}
else if (ShipmentCandidateRow.FIELD_asi.equals(fieldName))
{
builder.asi(fieldChangeRequest.getValueAsIntegerLookupValue());
}
}
return builder.build(); | }
private void changeRow(
@NonNull final DocumentId rowId,
@NonNull final UnaryOperator<ShipmentCandidateRow> mapper)
{
if (!rowIds.contains(rowId))
{
throw new EntityNotFoundException(rowId.toJson());
}
rowsById.compute(rowId, (key, oldRow) -> {
if (oldRow == null)
{
throw new EntityNotFoundException(rowId.toJson());
}
return mapper.apply(oldRow);
});
}
Optional<ShipmentScheduleUserChangeRequestsList> createShipmentScheduleUserChangeRequestsList()
{
final ImmutableList<ShipmentScheduleUserChangeRequest> userChanges = rowsById.values()
.stream()
.map(row -> row.createShipmentScheduleUserChangeRequest().orElse(null))
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList());
return !userChanges.isEmpty()
? Optional.of(ShipmentScheduleUserChangeRequestsList.of(userChanges))
: Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\shipment_candidates_editor\ShipmentCandidateRows.java | 1 |
请完成以下Java代码 | public class HelloV2ActivitiesImpl implements HelloV2Activities {
private static final Logger log = LoggerFactory.getLogger(HelloV2ActivitiesImpl.class);
@Override
public String sayHello(String person) {
var info = Activity.getExecutionContext().getInfo();
log.info("Saying hello to {}, workflowId={}, attempt={}", person,
info.getWorkflowId(),
info.getAttempt());
return "Step1 - OK";
}
@Override
public String sayGoodbye(String person) { | var info = Activity.getExecutionContext().getInfo();
log.info("Saying goodbye to {}, workflowId={}, attempt={}", person,
info.getWorkflowId(),
info.getAttempt());
if ( info.getAttempt() == 1 ) {
throw new IllegalStateException("Simulating task failure");
}
else {
return "Step2 - OK";
}
}
} | repos\tutorials-master\saas-modules\temporal\src\main\java\com\baeldung\temporal\workflows\hellov2\activities\HelloV2ActivitiesImpl.java | 1 |
请完成以下Java代码 | default String retrieveOrgValue(final int adOrgId)
{
return retrieveOrgValue(OrgId.ofRepoIdOrNull(adOrgId));
}
@NonNull
default String retrieveOrgValue(@Nullable final OrgId adOrgId)
{
if (adOrgId == null)
{
return "?";
}
else if (adOrgId.isAny())
{
//return "*";
return "0"; // "*" is the name of the "any" org, but it's org-value is 0
}
else
{
final I_AD_Org orgRecord = getById(adOrgId);
return orgRecord != null ? orgRecord.getValue() : "<" + adOrgId.getRepoId() + ">";
}
}
List<I_AD_Org> getByIds(Set<OrgId> orgIds);
List<I_AD_Org> getAllActiveOrgs();
OrgInfo createOrUpdateOrgInfo(OrgInfoUpdateRequest request);
OrgInfo getOrgInfoById(OrgId adOrgId);
OrgInfo getOrgInfoByIdInTrx(OrgId adOrgId);
WarehouseId getOrgWarehouseId(OrgId orgId);
WarehouseId getOrgPOWarehouseId(OrgId orgId);
WarehouseId getOrgDropshipWarehouseId(OrgId orgId);
/** | * Search for the organization when the value is known
*
* @return AD_Org Object if the organization was found, null otherwise.
*/
I_AD_Org retrieveOrganizationByValue(Properties ctx, String value);
List<I_AD_Org> retrieveClientOrgs(Properties ctx, int adClientId);
default List<I_AD_Org> retrieveClientOrgs(final int adClientId)
{
return retrieveClientOrgs(Env.getCtx(), adClientId);
}
/** @return organization's time zone or system time zone; never returns null */
ZoneId getTimeZone(OrgId orgId);
/**
* @return true if the given org falls under the european One-Stop-Shop (OSS) regulations
*/
boolean isEUOneStopShop(@NonNull OrgId orgId);
UserGroupId getSupplierApprovalExpirationNotifyUserGroupID(OrgId ofRepoId);
UserGroupId getPartnerCreatedFromAnotherOrgNotifyUserGroupID(OrgId orgId);
String getOrgName(@NonNull OrgId orgId);
boolean isAutoInvoiceFlatrateTerm(OrgId orgId);
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\IOrgDAO.java | 1 |
请完成以下Java代码 | public class Role extends BaseEntity implements Serializable {
@Id
@Column(name = "role_id")
@NotNull(groups = {Update.class})
@GeneratedValue(strategy = GenerationType.IDENTITY)
@ApiModelProperty(value = "ID", hidden = true)
private Long id;
@JSONField(serialize = false)
@ManyToMany(mappedBy = "roles")
@ApiModelProperty(value = "用户", hidden = true)
private Set<User> users;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "sys_roles_menus",
joinColumns = {@JoinColumn(name = "role_id",referencedColumnName = "role_id")},
inverseJoinColumns = {@JoinColumn(name = "menu_id",referencedColumnName = "menu_id")})
@ApiModelProperty(value = "菜单", hidden = true)
private Set<Menu> menus;
@ManyToMany
@JoinTable(name = "sys_roles_depts",
joinColumns = {@JoinColumn(name = "role_id",referencedColumnName = "role_id")},
inverseJoinColumns = {@JoinColumn(name = "dept_id",referencedColumnName = "dept_id")})
@ApiModelProperty(value = "部门", hidden = true)
private Set<Dept> depts;
@NotBlank
@ApiModelProperty(value = "名称", hidden = true)
private String name;
@ApiModelProperty(value = "数据权限,全部 、 本级 、 自定义")
private String dataScope = DataScopeEnum.THIS_LEVEL.getValue();
@Column(name = "level")
@ApiModelProperty(value = "级别,数值越小,级别越大")
private Integer level = 3; | @ApiModelProperty(value = "描述")
private String description;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Role role = (Role) o;
return Objects.equals(id, role.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\domain\Role.java | 1 |
请完成以下Java代码 | public long getUser_id() {
return user_id;
}
public void setUser_id(long user_id) {
this.user_id = user_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() { | return password;
}
public void setPassword(String password) {
this.password = password;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-sockets\src\main\java\com\baeldung\springsecuredsockets\domain\User.java | 1 |
请完成以下Java代码 | public class C_OrderLine_ShipmentSchedule
{
final ITrxManager trxManager = Services.get(ITrxManager.class);
/**
* Moved code here from <code>InOutCandidateValidator.orderLineChange()</code>.
* @param ol
*/
@ModelChange(timings = { ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_AFTER_DELETE })
public void invalidateShipmentSchedules(final I_C_OrderLine ol)
{
// if the line is not yet processed, there is no point to trigger shipment schedule invalidation
if (!ol.isProcessed())
{
return; | }
// if it's not a sales order, there is no point to trigger invalidation
if (!ol.getC_Order().isSOTrx())
{
return;
}
trxManager.runAfterCommit(() -> {
final IShipmentScheduleInvalidateBL shipmentScheduleInvalidateBL = Services.get(IShipmentScheduleInvalidateBL.class);
shipmentScheduleInvalidateBL.invalidateJustForOrderLine(ol);
shipmentScheduleInvalidateBL.notifySegmentChangedForOrderLine(ol);
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\modelvalidator\C_OrderLine_ShipmentSchedule.java | 1 |
请完成以下Java代码 | public void modifiers(int modifiers) {
this.modifiers = modifiers;
}
/**
* Return the modifiers.
* @return the modifiers
*/
public int getModifiers() {
return this.modifiers;
}
/**
* Adds the given field declaration.
* @param fieldDeclaration the field declaration
*/
public void addFieldDeclaration(JavaFieldDeclaration fieldDeclaration) {
this.fieldDeclarations.add(fieldDeclaration);
}
/**
* Returns the field declarations.
* @return the field declarations
*/
public List<JavaFieldDeclaration> getFieldDeclarations() { | return this.fieldDeclarations;
}
/**
* Adds the given method declaration.
* @param methodDeclaration the method declaration
*/
public void addMethodDeclaration(JavaMethodDeclaration methodDeclaration) {
this.methodDeclarations.add(methodDeclaration);
}
/**
* Returns the method declarations.
* @return the method declarations
*/
public List<JavaMethodDeclaration> getMethodDeclarations() {
return this.methodDeclarations;
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\java\JavaTypeDeclaration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public JAXBElement<EDIExpDesadvPackItemType> createEDIExpDesadvPackItem(EDIExpDesadvPackItemType value) {
return new JAXBElement<EDIExpDesadvPackItemType>(_EDIExpDesadvPackItem_QNAME, EDIExpDesadvPackItemType.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link EDIExpDesadvPackType }{@code >}
*
* @param value
* Java instance representing xml element's value.
* @return
* the new instance of {@link JAXBElement }{@code <}{@link EDIExpDesadvPackType }{@code >}
*/
@XmlElementDecl(namespace = "", name = "EDI_Exp_Desadv_Pack")
public JAXBElement<EDIExpDesadvPackType> createEDIExpDesadvPack(EDIExpDesadvPackType value) {
return new JAXBElement<EDIExpDesadvPackType>(_EDIExpDesadvPack_QNAME, EDIExpDesadvPackType.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link EDIExpDesadvLineWithNoPackType }{@code >}
*
* @param value
* Java instance representing xml element's value. | * @return
* the new instance of {@link JAXBElement }{@code <}{@link EDIExpDesadvLineWithNoPackType }{@code >}
*/
@XmlElementDecl(namespace = "", name = "EDI_Exp_DesadvLineWithNoPack")
public JAXBElement<EDIExpDesadvLineWithNoPackType> createEDIExpDesadvLineWithNoPack(EDIExpDesadvLineWithNoPackType value) {
return new JAXBElement<EDIExpDesadvLineWithNoPackType>(_EDIExpDesadvLineWithNoPack_QNAME, EDIExpDesadvLineWithNoPackType.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link EDIReplicationTrxUpdateType }{@code >}
*
* @param value
* Java instance representing xml element's value.
* @return
* the new instance of {@link JAXBElement }{@code <}{@link EDIReplicationTrxUpdateType }{@code >}
*/
@XmlElementDecl(namespace = "", name = "EDI_ReplicationTrx_Update")
public JAXBElement<EDIReplicationTrxUpdateType> createEDIReplicationTrxUpdate(EDIReplicationTrxUpdateType value) {
return new JAXBElement<EDIReplicationTrxUpdateType>(_EDIReplicationTrxUpdate_QNAME, EDIReplicationTrxUpdateType.class, null, value);
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\ObjectFactory.java | 2 |
请完成以下Java代码 | public final class HUAttributeTransferRequestBuilder implements IHUAttributeTransferRequestBuilder
{
private final IHUContext huContext;
private ProductId productId = null;
private BigDecimal qty = null;
private I_C_UOM uom = null;
private IHUStorage huStorageFrom = null;
private IHUStorage huStorageTo = null;
private IAttributeSet attributeStorageFrom = null;
private IAttributeStorage attributeStorageTo = null;
private BigDecimal qtyUnloaded = null;
/**
* Virtual HU attributes transfer
*/
private boolean vhuTransfer = false;
public HUAttributeTransferRequestBuilder(final IHUContext huContext)
{
super();
this.huContext = huContext;
}
/**
* Create request in give {@link IHUContext} for (product, qty, UOM) and between given {@link IProductStorage}s and {@link IAttributeStorage}s
*
* @return request
*/
@Override
public IHUAttributeTransferRequest create()
{
return new HUAttributeTransferRequest(huContext,
productId, qty, uom,
attributeStorageFrom, attributeStorageTo,
huStorageFrom, huStorageTo,
qtyUnloaded,
vhuTransfer);
}
@Override
public IHUAttributeTransferRequestBuilder setProductId(final ProductId productId)
{
this.productId = productId;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setQty(final BigDecimal qty)
{
this.qty = qty;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setUOM(final I_C_UOM uom)
{
this.uom = uom;
return this;
}
@Override | public IHUAttributeTransferRequestBuilder setQuantity(final Quantity quantity)
{
qty = quantity.toBigDecimal();
uom = quantity.getUOM();
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setAttributeStorageFrom(final IAttributeSet attributeStorageFrom)
{
this.attributeStorageFrom = attributeStorageFrom;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setAttributeStorageTo(final IAttributeStorage attributeStorageTo)
{
this.attributeStorageTo = attributeStorageTo;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setHUStorageFrom(final IHUStorage huStorageFrom)
{
this.huStorageFrom = huStorageFrom;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setHUStorageTo(final IHUStorage huStorageTo)
{
this.huStorageTo = huStorageTo;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setQtyUnloaded(final BigDecimal qtyUnloaded)
{
this.qtyUnloaded = qtyUnloaded;
return this;
}
@Override
public IHUAttributeTransferRequestBuilder setVHUTransfer(final boolean vhuTransfer)
{
this.vhuTransfer = vhuTransfer;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\strategy\impl\HUAttributeTransferRequestBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CalculatorService extends AbstractCacheableService {
@Cacheable(value = "Factorials", keyGenerator = "resultKeyGenerator")
public ResultHolder factorial(int number) {
this.cacheMiss.set(true);
Assert.isTrue(number >= 0L,
String.format("Number [%d] must be greater than equal to 0", number));
simulateLatency();
if (number <= 2) {
return ResultHolder.of(number, Operator.FACTORIAL, number == 2 ? 2 : 1);
}
int operand = number;
int result = number;
while (--number > 1) {
result *= number;
} | return ResultHolder.of(operand, Operator.FACTORIAL, result);
}
@Cacheable(value = "SquareRoots", keyGenerator = "resultKeyGenerator")
public ResultHolder sqrt(int number) {
this.cacheMiss.set(true);
Assert.isTrue(number >= 0,
String.format("Number [%d] must be greater than equal to 0", number));
simulateLatency();
int result = Double.valueOf(Math.sqrt(number)).intValue();
return ResultHolder.of(number, Operator.SQUARE_ROOT, result);
}
}
// end::class[] | repos\spring-boot-data-geode-main\spring-geode-samples\caching\inline\src\main\java\example\app\caching\inline\service\CalculatorService.java | 2 |
请完成以下Java代码 | public int getC_POSKeyLayout_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_POSKeyLayout_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name); | }
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** POSKeyLayoutType AD_Reference_ID=53351 */
public static final int POSKEYLAYOUTTYPE_AD_Reference_ID=53351;
/** Keyboard = K */
public static final String POSKEYLAYOUTTYPE_Keyboard = "K";
/** Numberpad = N */
public static final String POSKEYLAYOUTTYPE_Numberpad = "N";
/** Product = P */
public static final String POSKEYLAYOUTTYPE_Product = "P";
/** Set POS Key Layout Type.
@param POSKeyLayoutType
The type of Key Layout
*/
public void setPOSKeyLayoutType (String POSKeyLayoutType)
{
set_Value (COLUMNNAME_POSKeyLayoutType, POSKeyLayoutType);
}
/** Get POS Key Layout Type.
@return The type of Key Layout
*/
public String getPOSKeyLayoutType ()
{
return (String)get_Value(COLUMNNAME_POSKeyLayoutType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_POSKeyLayout.java | 1 |
请完成以下Java代码 | public RegulatoryReportingType1Code getDbtCdtRptgInd() {
return dbtCdtRptgInd;
}
/**
* Sets the value of the dbtCdtRptgInd property.
*
* @param value
* allowed object is
* {@link RegulatoryReportingType1Code }
*
*/
public void setDbtCdtRptgInd(RegulatoryReportingType1Code value) {
this.dbtCdtRptgInd = value;
}
/**
* Gets the value of the authrty property.
*
* @return
* possible object is
* {@link RegulatoryAuthority2 }
*
*/
public RegulatoryAuthority2 getAuthrty() {
return authrty;
}
/**
* Sets the value of the authrty property.
*
* @param value
* allowed object is
* {@link RegulatoryAuthority2 }
*
*/
public void setAuthrty(RegulatoryAuthority2 value) {
this.authrty = value;
} | /**
* Gets the value of the dtls property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the dtls property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDtls().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link StructuredRegulatoryReporting3 }
*
*
*/
public List<StructuredRegulatoryReporting3> getDtls() {
if (dtls == null) {
dtls = new ArrayList<StructuredRegulatoryReporting3>();
}
return this.dtls;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\RegulatoryReporting3.java | 1 |
请完成以下Java代码 | public CustomPropertiesResolver createClassDelegateCustomPropertiesResolver(FlowableListener listener) {
return classDelegateFactory.create(listener.getCustomPropertiesResolverImplementation(), null);
}
@Override
public CustomPropertiesResolver createExpressionCustomPropertiesResolver(FlowableListener listener) {
return new ExpressionCustomPropertiesResolver(expressionManager.createExpression(listener.getCustomPropertiesResolverImplementation()));
}
@Override
public CustomPropertiesResolver createDelegateExpressionCustomPropertiesResolver(FlowableListener listener) {
return new DelegateExpressionCustomPropertiesResolver(expressionManager.createExpression(listener.getCustomPropertiesResolverImplementation()));
}
/**
* @param entityType
* the name of the entity | * @return
* @throws FlowableIllegalArgumentException
* when the given entity type is not found
*/
protected Class<?> getEntityType(String entityType) {
if (entityType != null) {
Class<?> entityClass = ENTITY_MAPPING.get(entityType.trim());
if (entityClass == null) {
throw new FlowableIllegalArgumentException("Unsupported entity-type for a FlowableEventListener: " + entityType);
}
return entityClass;
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\parser\factory\DefaultListenerFactory.java | 1 |
请完成以下Java代码 | public Vector divideToSelf(int n)
{
for (int i = 0; i < elementArray.length; i++)
{
elementArray[i] = elementArray[i] / n;
}
return this;
}
public Vector divideToSelf(float f)
{
for (int i = 0; i < elementArray.length; i++)
{
elementArray[i] = elementArray[i] / f;
}
return this;
}
/**
* 自身归一化 | *
* @return
*/
public Vector normalize()
{
divideToSelf(norm());
return this;
}
public float[] getElementArray()
{
return elementArray;
}
public void setElementArray(float[] elementArray)
{
this.elementArray = elementArray;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\Vector.java | 1 |
请完成以下Java代码 | public static void revertLevels(String methodName, LevelsContainer container) {
LOGGER.info("++++++++++++++++++++++++++++ "
+ "Restoring log level setting for test " + methodName);
container.oldCatLevels.forEach((key, value) -> {
if (!key.contains("BrokerRunning")) {
((Logger) LogManager.getLogger(key)).setLevel(value);
}
});
// container.oldLbLevels.forEach((key, value) ->
// ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(key)).setLevel(value));
}
public static class LevelsContainer {
private final Map<Class<?>, Level> oldLevels; | private final Map<String, Level> oldCatLevels;
private final Map<String, ch.qos.logback.classic.Level> oldLbLevels;
public LevelsContainer(Map<Class<?>, Level> oldLevels, Map<String, Level> oldCatLevels,
Map<String, ch.qos.logback.classic.Level> oldLbLevels) {
this.oldLevels = oldLevels;
this.oldCatLevels = oldCatLevels;
this.oldLbLevels = oldLbLevels;
}
}
} | repos\spring-amqp-main\spring-rabbit-junit\src\main\java\org\springframework\amqp\rabbit\junit\JUnitUtils.java | 1 |
请完成以下Java代码 | public void setM_MovementLineConfirm_ID (int M_MovementLineConfirm_ID)
{
if (M_MovementLineConfirm_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_MovementLineConfirm_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_MovementLineConfirm_ID, Integer.valueOf(M_MovementLineConfirm_ID));
}
/** Get Move Line Confirm.
@return Inventory Move Line Confirmation
*/
public int getM_MovementLineConfirm_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_MovementLineConfirm_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_MovementLine getM_MovementLine() throws RuntimeException
{
return (I_M_MovementLine)MTable.get(getCtx(), I_M_MovementLine.Table_Name)
.getPO(getM_MovementLine_ID(), get_TrxName()); }
/** Set Move Line.
@param M_MovementLine_ID
Inventory Move document Line
*/
public void setM_MovementLine_ID (int M_MovementLine_ID)
{
if (M_MovementLine_ID < 1)
set_Value (COLUMNNAME_M_MovementLine_ID, null);
else
set_Value (COLUMNNAME_M_MovementLine_ID, Integer.valueOf(M_MovementLine_ID));
}
/** Get Move Line.
@return Inventory Move document Line
*/
public int getM_MovementLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_MovementLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Scrapped Quantity.
@param ScrappedQty
The Quantity scrapped due to QA issues | */
public void setScrappedQty (BigDecimal ScrappedQty)
{
set_Value (COLUMNNAME_ScrappedQty, ScrappedQty);
}
/** Get Scrapped Quantity.
@return The Quantity scrapped due to QA issues
*/
public BigDecimal getScrappedQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Target Quantity.
@param TargetQty
Target Movement Quantity
*/
public void setTargetQty (BigDecimal TargetQty)
{
set_Value (COLUMNNAME_TargetQty, TargetQty);
}
/** Get Target Quantity.
@return Target Movement Quantity
*/
public BigDecimal getTargetQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TargetQty);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_MovementLineConfirm.java | 1 |
请完成以下Java代码 | public final boolean isOldValues()
{
return useOldValues;
}
public static final boolean isOldValues(final Object model)
{
final DocumentInterfaceWrapper wrapper = getWrapper(model);
return wrapper == null ? false : wrapper.isOldValues();
}
@Override
public Set<String> getColumnNames()
{
return document.getFieldNames();
}
@Override
public int getColumnIndex(final String columnName)
{
throw new UnsupportedOperationException("DocumentInterfaceWrapper has no supported for column indexes");
}
@Override
public boolean isVirtualColumn(final String columnName)
{
final IDocumentFieldView field = document.getFieldViewOrNull(columnName);
return field != null && field.isReadonlyVirtualField();
}
@Override
public boolean isKeyColumnName(final String columnName)
{
final IDocumentFieldView field = document.getFieldViewOrNull(columnName);
return field != null && field.isKey();
}
@Override
public boolean isCalculated(final String columnName)
{
final IDocumentFieldView field = document.getFieldViewOrNull(columnName);
return field != null && field.isCalculated(); | }
@Override
public boolean setValueNoCheck(final String columnName, final Object value)
{
return setValue(columnName, value);
}
@Override
public void setValueFromPO(final String idColumnName, final Class<?> parameterType, final Object value)
{
// TODO: implement
throw new UnsupportedOperationException();
}
@Override
public boolean invokeEquals(final Object[] methodArgs)
{
// TODO: implement
throw new UnsupportedOperationException();
}
@Override
public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception
{
// TODO: implement
throw new UnsupportedOperationException();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentInterfaceWrapper.java | 1 |
请完成以下Java代码 | public I_M_HU_PI getM_LU_HU_PI()
{
return null; // no LU
}
@Override
public I_M_HU_PI getM_TU_HU_PI()
{
final I_M_HU_PI tuPI = Services.get(IHandlingUnitsBL.class).getEffectivePI(aggregatedTU);
if(tuPI == null)
{
new HUException("Invalid aggregated TU. Effective PI could not be fetched; aggregatedTU=" + aggregatedTU).throwIfDeveloperModeOrLogWarningElse(logger);
return null;
}
return tuPI;
}
@Override
public boolean isInfiniteQtyTUsPerLU()
{
return false;
}
@Override
public BigDecimal getQtyTUsPerLU()
{
final I_M_HU_Item parentHUItem = aggregatedTU.getM_HU_Item_Parent();
if (parentHUItem == null)
{
// note: shall not happen because we assume the aggregatedTU is really an aggregated TU.
new HUException("Invalid aggregated TU. Parent item is null; aggregatedTU=" + aggregatedTU).throwIfDeveloperModeOrLogWarningElse(logger);
return null;
}
return parentHUItem.getQty();
}
@Override
public boolean isInfiniteQtyCUsPerTU()
{
return false; | }
@Override
public BigDecimal getQtyCUsPerTU()
{
final IHUProductStorage huProductStorage = getHUProductStorage();
if (huProductStorage == null)
{
return null;
}
final BigDecimal qtyTUsPerLU = getQtyTUsPerLU();
if (qtyTUsPerLU == null || qtyTUsPerLU.signum() == 0)
{
return null;
}
final BigDecimal qtyCUTotal = huProductStorage.getQty().toBigDecimal();
final BigDecimal qtyCUsPerTU = qtyCUTotal.divide(qtyTUsPerLU, 0, RoundingMode.HALF_UP);
return qtyCUsPerTU;
}
@Override
public I_C_UOM getQtyCUsPerTU_UOM()
{
final IHUProductStorage huProductStorage = getHUProductStorage();
if (huProductStorage == null)
{
return null;
}
return huProductStorage.getC_UOM();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\util\AggregatedTUPackingInfo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class FinishedGoodsReceiveLine
{
@NonNull FinishedGoodsReceiveLineId id;
@NonNull ProductId productId;
@NonNull ITranslatableString productName;
@NonNull String productValue;
@NonNull ImmutableAttributeSet attributes;
@NonNull Quantity qtyToReceive;
@NonNull Quantity qtyReceived;
@Nullable PPOrderBOMLineId coProductBOMLineId;
@Nullable ReceivingTarget receivingTarget;
@Nullable UomId catchWeightUOMId;
@NonNull WFActivityStatus status;
@Builder(toBuilder = true)
private FinishedGoodsReceiveLine(
@NonNull final ProductId productId,
@NonNull final ITranslatableString productName,
@NonNull final String productValue,
@NonNull final ImmutableAttributeSet attributes,
@NonNull final Quantity qtyToReceive,
@NonNull final Quantity qtyReceived,
@Nullable final PPOrderBOMLineId coProductBOMLineId,
@Nullable final ReceivingTarget receivingTarget,
@Nullable final UomId catchWeightUOMId)
{
this.productId = productId;
this.productName = productName;
this.productValue = productValue;
this.attributes = attributes;
this.qtyToReceive = qtyToReceive;
this.qtyReceived = qtyReceived;
this.coProductBOMLineId = coProductBOMLineId;
this.receivingTarget = receivingTarget;
this.id = coProductBOMLineId == null
? FinishedGoodsReceiveLineId.FINISHED_GOODS
: FinishedGoodsReceiveLineId.ofCOProductBOMLineId(coProductBOMLineId);
this.catchWeightUOMId = catchWeightUOMId;
this.status = computeStatus(qtyToReceive, qtyReceived);
}
private static WFActivityStatus computeStatus(
@NonNull final Quantity qtyToReceive,
@NonNull final Quantity qtyReceived)
{
if (qtyReceived.isZero())
{
return WFActivityStatus.NOT_STARTED;
} | final Quantity qtyToReceiveRemaining = qtyToReceive.subtract(qtyReceived);
return qtyToReceiveRemaining.signum() != 0 ? WFActivityStatus.IN_PROGRESS : WFActivityStatus.COMPLETED;
}
public FinishedGoodsReceiveLine withReceivingTarget(@Nullable final ReceivingTarget receivingTarget)
{
return !Objects.equals(this.receivingTarget, receivingTarget)
? toBuilder().receivingTarget(receivingTarget).build()
: this;
}
public FinishedGoodsReceiveLine withQtyReceived(@NonNull final Quantity qtyReceived)
{
return !Objects.equals(this.qtyReceived, qtyReceived)
? toBuilder().qtyReceived(qtyReceived).build()
: this;
}
@NonNull
public ITranslatableString getProductValueAndProductName()
{
final TranslatableStringBuilder message = TranslatableStrings.builder()
.append(getProductValue())
.append(" ")
.append(getProductName());
return message.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\model\FinishedGoodsReceiveLine.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void generator(GenConfig genConfig, List<ColumnInfo> columns) {
if (genConfig.getId() == null) {
throw new BadRequestException(CONFIG_MESSAGE);
}
try {
GenUtil.generatorCode(columns, genConfig);
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new BadRequestException("生成失败,请手动处理已生成的文件");
}
}
@Override
public ResponseEntity<Object> preview(GenConfig genConfig, List<ColumnInfo> columns) {
if (genConfig.getId() == null) {
throw new BadRequestException(CONFIG_MESSAGE);
}
List<Map<String, Object>> genList = GenUtil.preview(columns, genConfig);
return new ResponseEntity<>(genList, HttpStatus.OK);
} | @Override
public void download(GenConfig genConfig, List<ColumnInfo> columns, HttpServletRequest request, HttpServletResponse response) {
if (genConfig.getId() == null) {
throw new BadRequestException(CONFIG_MESSAGE);
}
try {
File file = new File(GenUtil.download(columns, genConfig));
String zipPath = file.getPath() + ".zip";
ZipUtil.zip(file.getPath(), zipPath);
FileUtil.downloadFile(request, response, new File(zipPath), true);
} catch (IOException e) {
throw new BadRequestException("打包失败");
}
}
} | repos\eladmin-master\eladmin-generator\src\main\java\me\zhengjie\service\impl\GeneratorServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static void main(String[] args) {
SpringApplication.run(AnnotationApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
// Start the clock
long start = System.currentTimeMillis();
//kick of multiple, asynchronous lookups
CompletableFuture <User> page1 = githubLookupService.findUser("PivotalSoftware");
CompletableFuture < User > page2 = githubLookupService.findUser("CloudFoundry");
CompletableFuture < User > page3 = githubLookupService.findUser("Spring-Projects"); | CompletableFuture < User > page4 = githubLookupService.findUser("Hamdambek");
// Wait until they are all done
CompletableFuture.allOf(page1, page2, page3, page4).join();
// Print results, including elapsed time
logger.info("Elapsed time: " + (System.currentTimeMillis() - start));
logger.info("--> " + page1.get());
logger.info("--> " + page2.get());
logger.info("--> " + page3.get());
logger.info("--> " + page4.get());
}
} | repos\Spring-Boot-Advanced-Projects-main\Springboot-Annotation-LookService\src\main\java\spring\annotation\AnnotationApplication.java | 2 |
请完成以下Java代码 | public PurchaseRow createGroupRow(
@NonNull final PurchaseDemand demand,
@NonNull final List<PurchaseRow> rows)
{
return PurchaseRow.groupRowBuilder()
.lookups(lookups)
.demand(demand)
.qtyAvailableToPromise(getQtyAvailableToPromise(demand))
.includedRows(rows)
.build();
}
private Quantity getQtyAvailableToPromise(final PurchaseDemand demand)
{
final ProductId productId = demand.getProductId();
final AttributesKey attributesKey = AttributesKeys
.createAttributesKeyFromASIStorageAttributes(demand.getAttributeSetInstanceId())
.orElse(AttributesKey.ALL);
final AvailableToPromiseQuery query = AvailableToPromiseQuery.builder()
.productId(productId.getRepoId())
.date(demand.getSalesPreparationDate())
.storageAttributesKeyPattern(AttributesKeyPatternsUtil.ofAttributeKey(attributesKey))
.build();
final BigDecimal qtyAvailableToPromise = availableToPromiseRepository.retrieveAvailableStockQtySum(query);
final I_C_UOM uom = productsBL.getStockUOM(productId);
return Quantity.of(qtyAvailableToPromise, uom);
}
@Builder(builderMethodName = "availabilityDetailSuccessBuilder", builderClassName = "AvailabilityDetailSuccessBuilder")
private PurchaseRow buildRowFromFromAvailabilityResult(
@NonNull final PurchaseRow lineRow, | @NonNull final AvailabilityResult availabilityResult)
{
return PurchaseRow.availabilityDetailSuccessBuilder()
.lineRow(lineRow)
.availabilityResult(availabilityResult)
.build();
}
@Builder(builderMethodName = "availabilityDetailErrorBuilder", builderClassName = "AvailabilityDetailErrorBuilder")
private PurchaseRow buildRowFromFromThrowable(
@NonNull final PurchaseRow lineRow,
@NonNull final Throwable throwable)
{
return PurchaseRow.availabilityDetailErrorBuilder()
.lineRow(lineRow)
.throwable(throwable)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseRowFactory.java | 1 |
请完成以下Java代码 | private List<RelatedDocuments> retrieveZoomTargets(final IZoomSource source)
{
if (source == null)
{
return ImmutableList.of(); // guard against NPE
}
// in Swing this is not needed because we have the Posted button
SpringContextHolder.instance.getBean(FactAcctRelatedDocumentsProvider.class).disable();
final RelatedDocumentsFactory relatedDocumentsFactory = SpringContextHolder.instance.getBean(RelatedDocumentsFactory.class);
final RelatedDocumentsPermissions permissions = RelatedDocumentsPermissionsFactory.ofRolePermissions(Env.getUserRolePermissions());
return relatedDocumentsFactory.retrieveRelatedDocuments(source, permissions);
}
private void launch(final RelatedDocuments relatedDocuments)
{
final AdWindowId adWindowId = relatedDocuments.getAdWindowId();
final MQuery query = relatedDocuments.getQuery();
logger.info("AD_Window_ID={} - {}", adWindowId, query);
AWindow frame = new AWindow();
if (!frame.initWindow(adWindowId, query))
{ | return;
}
AEnv.addToWindowManager(frame);
if (Ini.isPropertyBool(Ini.P_OPEN_WINDOW_MAXIMIZED))
{
AEnv.showMaximized(frame);
}
else
{
AEnv.showCenterScreen(frame);
}
frame = null;
} // launchZoom
} // AZoom | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\AZoomAcross.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class VisitorService implements Visitable {
private final BookRepository bookRepository;
private final List<Visitor> visitors;
private final Map<Class<? extends Visitor>, Visitor> visitorsMap = new HashMap<>();
public VisitorService(BookRepository bookRepository, List<Visitor> visitors) {
this.bookRepository = bookRepository;
this.visitors = visitors;
}
@PostConstruct
public void init() {
visitors.forEach((visitor) -> {
visitorsMap.put(visitor.getClass(), visitor);
});
}
@Override
public void accept(Class<? extends Visitor> clazzVisitor) {
List<Book> allBooks = bookRepository.findAll();
if (!allBooks.isEmpty()) {
Visitor currentVisitor = visitorsMap.get(clazzVisitor);
for (Book book : allBooks) {
ClazzName clazzName = ClazzName.valueOf(book.getClass().getSimpleName()); | switch (clazzName) {
case Ebook:
currentVisitor.visit((Ebook) book);
break;
case Paperback:
currentVisitor.visit((Paperback) book);
break;
default:
throw new IllegalArgumentException("Unkown book type!");
}
}
}
}
enum ClazzName {
Ebook, Paperback
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootJoinedAndVisitor\src\main\java\com\bookstore\service\VisitorService.java | 2 |
请完成以下Java代码 | public List<Job> findTimerJobsByQueryCriteria(TimerJobQueryImpl jobQuery, Page page) {
final String query = "selectTimerJobByQueryCriteria";
return getDbSqlSession().selectList(query, jobQuery, page);
}
@SuppressWarnings("unchecked")
public List<Job> findTimerJobsByTypeAndProcessDefinitionKeyNoTenantId(String jobHandlerType, String processDefinitionKey) {
Map<String, String> params = new HashMap<>(2);
params.put("handlerType", jobHandlerType);
params.put("processDefinitionKey", processDefinitionKey);
return getDbSqlSession().selectList("selectTimerJobByTypeAndProcessDefinitionKeyNoTenantId", params);
}
@SuppressWarnings("unchecked")
public List<Job> findTimerJobsByTypeAndProcessDefinitionKeyAndTenantId(String jobHandlerType, String processDefinitionKey, String tenantId) {
Map<String, String> params = new HashMap<>(3);
params.put("handlerType", jobHandlerType);
params.put("processDefinitionKey", processDefinitionKey);
params.put("tenantId", tenantId);
return getDbSqlSession().selectList("selectTimerJobByTypeAndProcessDefinitionKeyAndTenantId", params);
}
@SuppressWarnings("unchecked")
public List<Job> findTimerJobsByTypeAndProcessDefinitionId(String jobHandlerType, String processDefinitionId) {
Map<String, String> params = new HashMap<>(2); | params.put("handlerType", jobHandlerType);
params.put("processDefinitionId", processDefinitionId);
return getDbSqlSession().selectList("selectTimerJobByTypeAndProcessDefinitionId", params);
}
public long findTimerJobCountByQueryCriteria(TimerJobQueryImpl jobQuery) {
return (Long) getDbSqlSession().selectOne("selectTimerJobCountByQueryCriteria", jobQuery);
}
public void updateTimerJobTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().update("updateTimerJobTenantIdForDeployment", params);
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TimerJobEntityManager.java | 1 |
请完成以下Java代码 | public class IdentityInfoEntity implements DbEntity, HasDbRevision, Account, Serializable {
private static final long serialVersionUID = 1L;
public static final String TYPE_USERACCOUNT = "account";
public static final String TYPE_USERINFO = "userinfo";
protected String id;
protected int revision;
protected String type;
protected String userId;
protected String key;
protected String value;
protected String password;
protected byte[] passwordBytes;
protected String parentId;
protected Map<String, String> details;
public Object getPersistentState() {
Map<String, Object> persistentState = new HashMap<String, Object>();
persistentState.put("value", value);
persistentState.put("password", passwordBytes);
return persistentState;
}
public int getRevisionNext() {
return revision+1;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getRevision() {
return revision;
}
public void setRevision(int revision) {
this.revision = revision;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value; | }
public void setValue(String value) {
this.value = value;
}
public byte[] getPasswordBytes() {
return passwordBytes;
}
public void setPasswordBytes(byte[] passwordBytes) {
this.passwordBytes = passwordBytes;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return key;
}
public String getUsername() {
return value;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public Map<String, String> getDetails() {
return details;
}
public void setDetails(Map<String, String> details) {
this.details = details;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", revision=" + revision
+ ", type=" + type
+ ", userId=" + userId
+ ", key=" + key
+ ", value=" + value
+ ", password=" + password
+ ", parentId=" + parentId
+ ", details=" + details
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\IdentityInfoEntity.java | 1 |
请完成以下Java代码 | public final class OAuth2AuthorizationExchange implements Serializable {
@Serial
private static final long serialVersionUID = 620L;
private final OAuth2AuthorizationRequest authorizationRequest;
private final OAuth2AuthorizationResponse authorizationResponse;
/**
* Constructs a new {@code OAuth2AuthorizationExchange} with the provided
* Authorization Request and Authorization Response.
* @param authorizationRequest the {@link OAuth2AuthorizationRequest Authorization
* Request}
* @param authorizationResponse the {@link OAuth2AuthorizationResponse Authorization
* Response}
*/
public OAuth2AuthorizationExchange(OAuth2AuthorizationRequest authorizationRequest,
OAuth2AuthorizationResponse authorizationResponse) {
Assert.notNull(authorizationRequest, "authorizationRequest cannot be null");
Assert.notNull(authorizationResponse, "authorizationResponse cannot be null");
this.authorizationRequest = authorizationRequest;
this.authorizationResponse = authorizationResponse;
} | /**
* Returns the {@link OAuth2AuthorizationRequest Authorization Request}.
* @return the {@link OAuth2AuthorizationRequest}
*/
public OAuth2AuthorizationRequest getAuthorizationRequest() {
return this.authorizationRequest;
}
/**
* Returns the {@link OAuth2AuthorizationResponse Authorization Response}.
* @return the {@link OAuth2AuthorizationResponse}
*/
public OAuth2AuthorizationResponse getAuthorizationResponse() {
return this.authorizationResponse;
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\endpoint\OAuth2AuthorizationExchange.java | 1 |
请完成以下Java代码 | private static SQLRowLoader createSQLRowLoader(final @NonNull KPI kpi)
{
final KPIChartType chartType = kpi.getChartType();
if (KPIChartType.URLs.equals(chartType))
{
return new URLsSQLRowLoader(kpi.getFields());
}
else
{
return new ValueAndUomSQLRowLoader(kpi.getFields());
}
}
public KPIDataResult retrieveData()
{
final Stopwatch duration = Stopwatch.createStarted();
logger.trace("Loading data for {}", timeRange);
final KPIDataResult.Builder data = KPIDataResult.builder()
.range(timeRange);
final String sql = createSelectSql();
logger.trace("Running SQL: {}", sql);
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_ThreadInherited);
rs = pstmt.executeQuery();
while (rs.next())
{
rowLoader.loadRowToResult(data, rs);
}
}
catch (final SQLException ex)
{
throw new DBException(ex, sql);
}
finally
{
DB.close(rs, pstmt);
}
return data
.datasetsComputeDuration(duration.elapsed())
.build();
}
private String createSelectSql()
{
final Evaluatee evalCtx = createEvaluationContext();
String sql = datasource
.getSqlSelect()
.evaluate(evalCtx, IExpressionEvaluator.OnVariableNotFound.Preserve);
if (datasource.isApplySecuritySettings())
{
sql = permissionsProvider.addAccessSQL(sql, datasource.getSourceTableName(), context);
}
return sql;
} | private Evaluatee createEvaluationContext()
{
return Evaluatees.mapBuilder()
.put("MainFromMillis", DB.TO_DATE(timeRange.getFrom()))
.put("MainToMillis", DB.TO_DATE(timeRange.getTo()))
.put("FromMillis", DB.TO_DATE(timeRange.getFrom()))
.put("ToMillis", DB.TO_DATE(timeRange.getTo()))
.put(KPIDataContext.CTXNAME_AD_User_ID, UserId.toRepoId(context.getUserId()))
.put(KPIDataContext.CTXNAME_AD_Role_ID, RoleId.toRepoId(context.getRoleId()))
.put(KPIDataContext.CTXNAME_AD_Client_ID, ClientId.toRepoId(context.getClientId()))
.put(KPIDataContext.CTXNAME_AD_Org_ID, OrgId.toRepoId(context.getOrgId()))
.put("#Date", DB.TO_DATE(SystemTime.asZonedDateTime()))
.build();
}
public KPIZoomIntoDetailsInfo getKPIZoomIntoDetailsInfo()
{
final String sqlWhereClause = datasource
.getSqlDetailsWhereClause()
.evaluate(createEvaluationContext(), IExpressionEvaluator.OnVariableNotFound.Fail);
return KPIZoomIntoDetailsInfo.builder()
.filterCaption(kpiCaption)
.targetWindowId(datasource.getTargetWindowId())
.tableName(datasource.getSourceTableName())
.sqlWhereClause(sqlWhereClause)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\sql\SQLKPIDataLoader.java | 1 |
请完成以下Java代码 | protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_A_RegistrationProduct[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_A_RegistrationAttribute getA_RegistrationAttribute() throws RuntimeException
{
return (I_A_RegistrationAttribute)MTable.get(getCtx(), I_A_RegistrationAttribute.Table_Name)
.getPO(getA_RegistrationAttribute_ID(), get_TrxName()); }
/** Set Registration Attribute.
@param A_RegistrationAttribute_ID
Asset Registration Attribute
*/
public void setA_RegistrationAttribute_ID (int A_RegistrationAttribute_ID)
{
if (A_RegistrationAttribute_ID < 1)
set_ValueNoCheck (COLUMNNAME_A_RegistrationAttribute_ID, null);
else
set_ValueNoCheck (COLUMNNAME_A_RegistrationAttribute_ID, Integer.valueOf(A_RegistrationAttribute_ID));
}
/** Get Registration Attribute.
@return Asset Registration Attribute
*/
public int getA_RegistrationAttribute_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_RegistrationAttribute_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
public I_M_Product getM_Product() throws RuntimeException | {
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_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_A_RegistrationProduct.java | 1 |
请完成以下Java代码 | public ExceptionDto fromException(Throwable e) {
ExceptionDto exceptionDto;
if (e instanceof MigratingProcessInstanceValidationException) {
exceptionDto = MigratingProcessInstanceValidationExceptionDto.from((MigratingProcessInstanceValidationException)e);
} else if (e instanceof MigrationPlanValidationException) {
exceptionDto = MigrationPlanValidationExceptionDto.from((MigrationPlanValidationException)e);
} else if (e instanceof AuthorizationException) {
exceptionDto = AuthorizationExceptionDto.fromException((AuthorizationException)e);
} else if (e instanceof ParseException){
exceptionDto = ParseExceptionDto.fromException((ParseException) e);
} else {
exceptionDto = ExceptionDto.fromException(e);
}
provideExceptionCode(e, exceptionDto);
return exceptionDto;
}
public Response.Status getStatus(Throwable exception) {
Response.Status responseStatus = Response.Status.INTERNAL_SERVER_ERROR;
if (exception instanceof ProcessEngineException) {
responseStatus = getStatus((ProcessEngineException)exception);
}
else if (exception instanceof RestException) {
responseStatus = getStatus((RestException) exception);
}
else if (exception instanceof WebApplicationException) {
//we need to check this, as otherwise the logic for processing WebApplicationException will be overridden
final int statusCode = ((WebApplicationException) exception).getResponse().getStatus();
responseStatus = Response.Status.fromStatusCode(statusCode);
} | return responseStatus;
}
public Response.Status getStatus(ProcessEngineException exception) {
Response.Status responseStatus = Response.Status.INTERNAL_SERVER_ERROR;
// provide custom handling of authorization exception
if (exception instanceof AuthorizationException) {
responseStatus = Response.Status.FORBIDDEN;
}
else if (exception instanceof MigrationPlanValidationException
|| exception instanceof MigratingProcessInstanceValidationException
|| exception instanceof BadUserRequestException
|| exception instanceof ParseException) {
responseStatus = Response.Status.BAD_REQUEST;
}
return responseStatus;
}
public Response.Status getStatus(RestException exception) {
if (exception.getStatus() != null) {
return exception.getStatus();
}
return Response.Status.INTERNAL_SERVER_ERROR;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\exception\ExceptionHandlerHelper.java | 1 |
请完成以下Java代码 | private Step step() {
return stepBuilderFactory.get("step")
.listener(myStepExecutionListener)
.<String, String>chunk(2)
.faultTolerant()
.listener(myChunkListener)
.reader(reader())
.listener(myItemReaderListener)
.processor(processor())
.listener(myItemProcessListener)
.writer(list -> list.forEach(System.out::println))
.listener(myItemWriterListener)
.build();
}
private ItemReader<String> reader() {
List<String> data = Arrays.asList("java", "c++", "javascript", "python");
return new simpleReader(data);
}
private ItemProcessor<String, String> processor() {
return item -> item + " language"; | }
}
class simpleReader implements ItemReader<String> {
private Iterator<String> iterator;
public simpleReader(List<String> data) {
this.iterator = data.iterator();
}
@Override
public String read() {
return iterator.hasNext() ? iterator.next() : null;
}
} | repos\SpringAll-master\71.spring-batch-listener\src\main\java\cc\mrbird\batch\job\ListenerTestJobDemo.java | 1 |
请完成以下Java代码 | public boolean contains(S element) {
if (isEmpty()) {
return false;
}
Node<S> current = head;
while (current != null) {
if (Objects.equals(element, current.element))
return true;
current = current.next;
}
return false;
}
private boolean isLastNode(Node<S> node) {
return tail == node; | }
private boolean isFistNode(Node<S> node) {
return head == node;
}
public static class Node<T> {
private T element;
private Node<T> next;
public Node(T element) {
this.element = element;
}
}
} | repos\tutorials-master\core-java-modules\core-java-collections-list-7\src\main\java\com\baeldung\linkedlistremove\SinglyLinkedList.java | 1 |
请完成以下Java代码 | public class MethodInvocationBenchmark {
@Benchmark
@Fork(value = 1, warmups = 1)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public void directCall() {
directCall(new Person("John", "Doe", 50));
}
@Benchmark
@Fork(value = 1, warmups = 1)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
public void reflectiveCall() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
reflectiveCall(new Person("John", "Doe", 50));
}
private void directCall(Person person) { | person.getFirstName();
person.getLastName();
person.getAge();
}
private void reflectiveCall(Person person) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method getFirstNameMethod = Person.class.getMethod("getFirstName");
getFirstNameMethod.invoke(person);
Method getLastNameMethod = Person.class.getMethod("getLastName");
getLastNameMethod.invoke(person);
Method getAgeMethod = Person.class.getMethod("getAge");
getAgeMethod.invoke(person);
}
} | repos\tutorials-master\core-java-modules\core-java-reflection-3\src\main\java\com\baeldung\reflection\disadvantages\performance\MethodInvocationBenchmark.java | 1 |
请完成以下Java代码 | public String getSourceProcessDefinitionId() {
return sourceProcessDefinitionId;
}
public void setSourceProcessDefinitionId(String sourceProcessDefinitionId) {
this.sourceProcessDefinitionId = sourceProcessDefinitionId;
}
public String getTargetProcessDefinitionId() {
return targetProcessDefinitionId;
}
public void setTargetProcessDefinitionId(String targetProcessDefinitionId) {
this.targetProcessDefinitionId = targetProcessDefinitionId;
} | public String getMigrationMessage() {
return migrationMessage;
}
public void setMigrationMessage(String migrationMessage) {
this.migrationMessage = migrationMessage;
}
public String getMigrationStacktrace() {
return migrationStacktrace;
}
public void setMigrationStacktrace(String migrationStacktrace) {
this.migrationStacktrace = migrationStacktrace;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\migration\ProcessInstanceBatchMigrationPartResult.java | 1 |
请完成以下Java代码 | public ITrxConstraints setOnlyAllowedTrxNamePrefixes(boolean onlyAllowedTrxNamePrefixes)
{
this.onlyAllowedTrxNamePrefixes = onlyAllowedTrxNamePrefixes;
return this;
}
@Override
public ITrxConstraints addAllowedTrxNamePrefix(final String trxNamePrefix)
{
allowedTrxNamePrefixes.add(trxNamePrefix);
return this;
}
@Override
public ITrxConstraints removeAllowedTrxNamePrefix(final String trxNamePrefix)
{
allowedTrxNamePrefixes.remove(trxNamePrefix);
return this;
}
@Override
public Set<String> getAllowedTrxNamePrefixes()
{
return allowedTrxNamePrefixesRO;
}
@Override
public boolean isAllowTrxAfterThreadEnd()
{
return allowTrxAfterThreadEnd;
}
@Override
public void reset()
{
setActive(DEFAULT_ACTIVE);
setAllowTrxAfterThreadEnd(DEFAULT_ALLOW_TRX_AFTER_TREAD_END);
setMaxSavepoints(DEFAULT_MAX_SAVEPOINTS); | setMaxTrx(DEFAULT_MAX_TRX);
setTrxTimeoutSecs(DEFAULT_TRX_TIMEOUT_SECS, DEFAULT_TRX_TIMEOUT_LOG_ONLY);
setOnlyAllowedTrxNamePrefixes(DEFAULT_ONLY_ALLOWED_TRXNAME_PREFIXES);
allowedTrxNamePrefixes.clear();
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("TrxConstraints[");
sb.append("active=" + this.active);
sb.append(", allowedTrxNamePrefixes=" + getAllowedTrxNamePrefixes());
sb.append(", allowTrxAfterThreadEnd=" + isAllowTrxAfterThreadEnd());
sb.append(", maxSavepoints=" + getMaxSavepoints());
sb.append(", maxTrx=" + getMaxTrx());
sb.append(", onlyAllowedTrxNamePrefixes=" + isOnlyAllowedTrxNamePrefixes());
sb.append(", trxTimeoutLogOnly=" + isTrxTimeoutLogOnly());
sb.append(", trxTimeoutSecs=" + getTrxTimeoutSecs());
sb.append("]");
return sb.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\trxConstraints\api\impl\TrxConstraints.java | 1 |
请完成以下Java代码 | public AstFunction createFunction(String name, int index, AstParameters parameters, boolean varargs, FlowableExpressionParser parser) {
Method method = functionMethod();
int parametersCardinality = parameters.getCardinality();
int methodParameterCount = method.getParameterCount();
if (method.isVarArgs() || parametersCardinality < methodParameterCount) {
// If the method is a varargs or the number of parameters is less than the defined in the method
// then create an identifier for the variableContainer
// and analyze the parameters
List<AstNode> newParameters = new ArrayList<>(parametersCardinality + 1);
newParameters.add(parser.createIdentifier(variableScopeName));
if (methodParameterCount >= 1) {
// If the first parameter is an identifier we have to convert it to a text node
// We want to allow writing variables:get(varName) where varName is without quotes
newParameters.add(createVariableNameNode(parameters.getChild(0)));
for (int i = 1; i < parametersCardinality; i++) {
// the rest of the parameters should be treated as is
newParameters.add(parameters.getChild(i));
}
} | return new AstFunction(name, index, new AstParameters(newParameters), varargs);
} else {
// If the resolved parameters are of the same size as the current method then nothing to do
return new AstFunction(name, index, parameters, varargs);
}
}
protected AstNode createVariableNameNode(AstNode variableNode) {
if (variableNode instanceof AstIdentifier) {
return new AstText(((AstIdentifier) variableNode).getName());
} else {
return variableNode;
}
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\el\function\AbstractFlowableVariableExpressionFunction.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class AiModelImportService extends BaseEntityImportService<AiModelId, AiModel, EntityExportData<AiModel>> {
private final AiModelService aiModelService;
@Override
protected void setOwner(
TenantId tenantId,
AiModel model,
BaseEntityImportService<AiModelId, AiModel, EntityExportData<AiModel>>.IdProvider idProvider
) {
model.setTenantId(tenantId);
}
@Override
protected AiModel prepare(
EntitiesImportCtx ctx,
AiModel model,
AiModel oldModel,
EntityExportData<AiModel> exportData,
BaseEntityImportService<AiModelId, AiModel, EntityExportData<AiModel>>.IdProvider idProvider
) {
return model;
}
@Override
protected AiModel deepCopy(AiModel model) { | return new AiModel(model);
}
@Override
protected AiModel saveOrUpdate(
EntitiesImportCtx ctx,
AiModel model,
EntityExportData<AiModel> exportData,
BaseEntityImportService<AiModelId, AiModel, EntityExportData<AiModel>>.IdProvider idProvider,
CompareResult compareResult
) {
return aiModelService.save(model);
}
@Override
public EntityType getEntityType() {
return EntityType.AI_MODEL;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\AiModelImportService.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.