instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | /* package */class HUTrxQuery implements IHUTrxQuery
{
private int M_HU_Trx_Hdr_ID = -1;
private int Exclude_M_HU_Trx_Line_ID = -1;
private int Parent_M_HU_Trx_Line_ID = -1;
private int Ref_HU_Item_ID = -1;
private int AD_Table_ID = -1;
private int Record_ID = -1;
private int M_HU_ID = -1;
@Override
public String toString()
{
return "HUTrxQuery ["
+ "M_HU_Trx_Hdr_ID=" + M_HU_Trx_Hdr_ID
+ ", Exclude_M_HU_Trx_Line_ID=" + Exclude_M_HU_Trx_Line_ID
+ ", Parent_M_HU_Trx_Line_ID=" + Parent_M_HU_Trx_Line_ID
+ ", Ref_HU_Item_ID=" + Ref_HU_Item_ID
+ ", AD_Table_ID/Record_ID=" + AD_Table_ID + "/" + Record_ID
+ "]";
}
@Override
public int getM_HU_Trx_Hdr_ID()
{
return M_HU_Trx_Hdr_ID;
}
@Override
public void setM_HU_Trx_Hdr_ID(final int m_HU_Trx_Hdr_ID)
{
M_HU_Trx_Hdr_ID = m_HU_Trx_Hdr_ID;
}
@Override
public int getExclude_M_HU_Trx_Line_ID()
{
return Exclude_M_HU_Trx_Line_ID;
}
@Override
public void setExclude_M_HU_Trx_Line_ID(final int exclude_M_HU_Trx_Line_ID)
{
Exclude_M_HU_Trx_Line_ID = exclude_M_HU_Trx_Line_ID;
}
@Override
public int getParent_M_HU_Trx_Line_ID()
{
return Parent_M_HU_Trx_Line_ID;
}
@Override
public void setParent_M_HU_Trx_Line_ID(final int parent_M_HU_Trx_Line_ID)
{
Parent_M_HU_Trx_Line_ID = parent_M_HU_Trx_Line_ID;
}
@Override
public void setM_HU_Item_ID(final int Ref_HU_Item_ID)
{
this.Ref_HU_Item_ID = Ref_HU_Item_ID;
}
@Override
public int getM_HU_Item_ID()
{ | return Ref_HU_Item_ID;
}
@Override
public int getAD_Table_ID()
{
return AD_Table_ID;
}
@Override
public void setAD_Table_ID(final int aD_Table_ID)
{
AD_Table_ID = aD_Table_ID;
}
@Override
public int getRecord_ID()
{
return Record_ID;
}
@Override
public void setRecord_ID(final int record_ID)
{
Record_ID = record_ID;
}
@Override
public void setM_HU_ID(int m_hu_ID)
{
M_HU_ID = m_hu_ID;
}
@Override
public int getM_HU_ID()
{
return M_HU_ID;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\hutransaction\impl\HUTrxQuery.java | 1 |
请完成以下Java代码 | public MRPQueryBuilder setPP_Plant_ID(final Integer ppPlantId)
{
this._ppPlantId = ppPlantId;
return this;
}
private Set<Integer> getPP_Plant_IDs_ToUse()
{
int ppPlantId = -1;
if (_ppPlantId != null)
{
ppPlantId = _ppPlantId;
}
if (ppPlantId <= 0)
{
return Collections.emptySet();
}
final Set<Integer> plantIds = new HashSet<>();
plantIds.add(ppPlantId);
plantIds.add(null);
return plantIds;
}
@Override
public MRPQueryBuilder setM_Product_ID(final Integer productId)
{
this._productId = productId;
return this;
}
private int getM_Product_ID_ToUse()
{
if (_productId != null)
{
return _productId;
}
return -1;
}
@Override
public MRPQueryBuilder setTypeMRP(final String typeMRP)
{
this._typeMRP = typeMRP;
return this;
}
public String getTypeMRP()
{
return _typeMRP;
}
@Nullable
public Date getDatePromisedMax()
{
return this._datePromisedMax;
}
@Nullable
public MRPFirmType getMRPFirmType()
{
return this._mrpFirmType;
}
public boolean isQtyNotZero()
{
return false;
}
@Nullable
public Boolean getMRPAvailable()
{
return _mrpAvailable;
}
public boolean isOnlyActiveRecords()
{
return _onlyActiveRecords;
}
@Override | public MRPQueryBuilder setOnlyActiveRecords(final boolean onlyActiveRecords)
{
this._onlyActiveRecords = onlyActiveRecords;
return this;
}
@Override
public MRPQueryBuilder setOrderType(final String orderType)
{
this._orderTypes.clear();
if (orderType != null)
{
this._orderTypes.add(orderType);
}
return this;
}
private Set<String> getOrderTypes()
{
return this._orderTypes;
}
@Override
public MRPQueryBuilder setReferencedModel(final Object referencedModel)
{
this._referencedModel = referencedModel;
return this;
}
public Object getReferencedModel()
{
return this._referencedModel;
}
@Override
public void setPP_Order_BOMLine_Null()
{
this._ppOrderBOMLine_Null = true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\mrp\api\impl\MRPQueryBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class LoginController {
@Autowired
private SystemProperties properties;
@PostMapping("/login")
public Response login(
@NotBlank(message = "{required}") String username,
@NotBlank(message = "{required}") String password, HttpServletRequest request) throws Exception {
username = StringUtils.lowerCase(username);
password = MD5Util.encrypt(username, password);
final String errorMessage = "用户名或密码错误";
User user = SystemUtils.getUser(username);
if (user == null)
throw new SystemException(errorMessage);
if (!StringUtils.equals(user.getPassword(), password))
throw new SystemException(errorMessage);
// 生成 Token
String token = JWTUtil.sign(username, password);
Map<String, Object> userInfo = this.generateUserInfo(token, user);
return new Response().message("认证成功").data(userInfo);
}
/**
* 生成前端需要的用户信息,包括:
* 1. token | * 2. user
*
* @param token token
* @param user 用户信息
* @return UserInfo
*/
private Map<String, Object> generateUserInfo(String token, User user) {
String username = user.getUsername();
Map<String, Object> userInfo = new HashMap<>();
userInfo.put("token", token);
user.setPassword("it's a secret");
userInfo.put("user", user);
return userInfo;
}
} | repos\SpringAll-master\62.Spring-Boot-Shiro-JWT\src\main\java\com\example\demo\controller\LoginController.java | 2 |
请完成以下Java代码 | public int getC_Cycle_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Cycle_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 Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name) | {
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Cycle.java | 1 |
请完成以下Java代码 | public String getRootCauseIncidentActivityId() {
return rootCauseIncidentActivityId;
}
public void setRootCauseIncidentActivityId(String rootCauseIncidentActivityId) {
this.rootCauseIncidentActivityId = rootCauseIncidentActivityId;
}
public String getRootCauseIncidentFailedActivityId() {
return rootCauseIncidentFailedActivityId;
}
public void setRootCauseIncidentFailedActivityId(String rootCauseIncidentFailedActivityId) {
this.rootCauseIncidentFailedActivityId = rootCauseIncidentFailedActivityId;
} | public String getRootCauseIncidentConfiguration() {
return rootCauseIncidentConfiguration;
}
public void setRootCauseIncidentConfiguration(String rootCauseIncidentConfiguration) {
this.rootCauseIncidentConfiguration = rootCauseIncidentConfiguration;
}
public String getRootCauseIncidentMessage() {
return rootCauseIncidentMessage;
}
public void setRootCauseIncidentMessage(String rootCauseIncidentMessage) {
this.rootCauseIncidentMessage = rootCauseIncidentMessage;
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\IncidentDto.java | 1 |
请完成以下Java代码 | protected String buildUrl() {
return String.format("%s/bot%s/sendmessage?chat_id={chat_id}&text={text}&parse_mode={parse_mode}"
+ "&disable_notification={disable_notification}", this.apiUrl, this.authToken);
}
private Map<String, Object> createMessage(InstanceEvent event, Instance instance) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("chat_id", this.chatId);
parameters.put("parse_mode", this.parseMode);
parameters.put("disable_notification", this.disableNotify);
parameters.put("text", createContent(event, instance));
return parameters;
}
@Override
protected String getDefaultMessage() {
return DEFAULT_MESSAGE;
}
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public String getApiUrl() {
return apiUrl;
}
public void setApiUrl(String apiUrl) {
this.apiUrl = apiUrl;
}
@Nullable
public String getChatId() {
return chatId; | }
public void setChatId(@Nullable String chatId) {
this.chatId = chatId;
}
@Nullable
public String getAuthToken() {
return authToken;
}
public void setAuthToken(@Nullable String authToken) {
this.authToken = authToken;
}
public boolean isDisableNotify() {
return disableNotify;
}
public void setDisableNotify(boolean disableNotify) {
this.disableNotify = disableNotify;
}
public String getParseMode() {
return parseMode;
}
public void setParseMode(String parseMode) {
this.parseMode = parseMode;
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\TelegramNotifier.java | 1 |
请完成以下Java代码 | public Integer getFinishOrderCount() {
return finishOrderCount;
}
public void setFinishOrderCount(Integer finishOrderCount) {
this.finishOrderCount = finishOrderCount;
}
public BigDecimal getFinishOrderAmount() {
return finishOrderAmount;
}
public void setFinishOrderAmount(BigDecimal finishOrderAmount) {
this.finishOrderAmount = finishOrderAmount;
} | @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(", name=").append(name);
sb.append(", finishOrderCount=").append(finishOrderCount);
sb.append(", finishOrderAmount=").append(finishOrderAmount);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberTag.java | 1 |
请完成以下Java代码 | public boolean isEligibleForAutoCarrierAdvise(@NonNull final I_M_ShipmentSchedule shipmentSchedule)
{
final EligibleCarrierAdviseRequest request = EligibleCarrierAdviseRequest.of(shipmentSchedule, shipmentScheduleEffectiveBL);
return isEligibleForCarrierAdvise(request.toBuilder().isAuto(true).build());
}
public boolean isNotEligibleForManualCarrierAdvise(@NonNull final ShipmentSchedule shipmentSchedule, final boolean isIncludeCarrierAdviseManual)
{
final EligibleCarrierAdviseRequest request = EligibleCarrierAdviseRequest.of(shipmentSchedule);
return !isEligibleForCarrierAdvise(request.toBuilder().isIncludeCarrierAdviseManual(isIncludeCarrierAdviseManual).build());
}
private boolean isEligibleForCarrierAdvise(@NonNull final EligibleCarrierAdviseRequest request)
{
if (request.getShipperId() == null
|| request.isProcessed()
|| request.isClosed()
|| !request.isActive()
|| request.getQuantityToDeliver().signum() <= 0)
{
return false;
}
final CarrierAdviseStatus carrierAdviseStatus = request.getCarrierAdvisingStatus();
if (request.isAuto)
{ | if (carrierAdviseStatus != null && !carrierAdviseStatus.isEligibleForAutoEnqueue()) {return false;}
}
else
{ // Manual
if (carrierAdviseStatus == null || !carrierAdviseStatus.isEligibleForManualEnqueue()) {return false;}
if (!request.isIncludeCarrierAdviseManual && carrierAdviseStatus.isManual()) {return false;}
}
final ShipmentScheduleId shipmentScheduleId = request.getShipmentScheduleId();
if (shipmentScheduleId == null) {return true;}
return !pickingJobScheduleRepository.anyMatch(PickingJobScheduleQuery.builder().onlyShipmentScheduleId(shipmentScheduleId).build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\ShipmentScheduleService.java | 1 |
请完成以下Spring Boot application配置 | nacos:
# Nacos 配置中心的配置项,对应 NacosConfigProperties 配置类
config:
server-addr: 127.0.0.1:18848 # Nacos 服务器地址
bootstrap:
enable: true # 是否开启 Nacos 配置预加载功能。默认为 false。
log-enable: true # 是否开启 Nacos 支持日志级别的加载时机。默认为 false。
data-id: example # 使用的 Nacos 配置集的 dataId。
type: YAML # 使用的 Na | cos 配置集的配置格式。默认为 PROPERTIES。
group: DEFAULT_GROUP # 使用的 Nacos 配置分组,默认为 DEFAULT_GROUP。
namespace: # 使用的 Nacos 的命名空间,默认为 null。 | repos\SpringBoot-Labs-master\lab-44\lab-44-nacos-config-demo\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | protected Collection<T> getElements() {
return ModelUtil.getModelElementCollection(getDomElement().getChildElements(), getModelInstance());
}
public int size() {
return getElements().size();
}
public boolean isEmpty() {
return getElements().isEmpty();
}
public boolean contains(Object o) {
return getElements().contains(o);
}
public Iterator<T> iterator() {
return (Iterator<T>) getElements().iterator();
}
public Object[] toArray() {
return getElements().toArray();
}
public <T1> T1[] toArray(T1[] a) {
return getElements().toArray(a);
}
public boolean add(T t) {
getDomElement().appendChild(t.getDomElement());
return true;
}
public boolean remove(Object o) {
ModelUtil.ensureInstanceOf(o, BpmnModelElementInstance.class);
return getDomElement().removeChild(((BpmnModelElementInstance) o).getDomElement());
}
public boolean containsAll(Collection<?> c) {
for (Object o : c) {
if (!contains(o)) {
return false; | }
}
return true;
}
public boolean addAll(Collection<? extends T> c) {
for (T element : c) {
add(element);
}
return true;
}
public boolean removeAll(Collection<?> c) {
boolean result = false;
for (Object o : c) {
result |= remove(o);
}
return result;
}
public boolean retainAll(Collection<?> c) {
throw new UnsupportedModelOperationException("retainAll()", "not implemented");
}
public void clear() {
DomElement domElement = getDomElement();
List<DomElement> childElements = domElement.getChildElements();
for (DomElement childElement : childElements) {
domElement.removeChild(childElement);
}
}
};
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaListImpl.java | 1 |
请完成以下Java代码 | public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
TypeDescriptor sourceElementType = sourceType.getElementTypeDescriptor();
if (targetType == null || sourceElementType == null) {
return true;
}
return this.conversionService.canConvert(sourceElementType, targetType)
|| sourceElementType.getType().isAssignableFrom(targetType.getType());
}
@Override
@Contract("!null, _, _ -> !null")
public @Nullable Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (source == null) {
return null;
}
Collection<?> sourceCollection = (Collection<?>) source;
return convert(sourceCollection, sourceType, targetType);
}
private Object convert(Collection<?> source, TypeDescriptor sourceType, TypeDescriptor targetType) { | if (source.isEmpty()) {
return "";
}
return source.stream()
.map((element) -> convertElement(element, sourceType, targetType))
.collect(Collectors.joining(getDelimiter(sourceType)));
}
private CharSequence getDelimiter(TypeDescriptor sourceType) {
Delimiter annotation = sourceType.getAnnotation(Delimiter.class);
return (annotation != null) ? annotation.value() : ",";
}
private String convertElement(Object element, TypeDescriptor sourceType, TypeDescriptor targetType) {
return String
.valueOf(this.conversionService.convert(element, sourceType.elementTypeDescriptor(element), targetType));
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\convert\CollectionToDelimitedStringConverter.java | 1 |
请完成以下Java代码 | public class CaseParameterImpl extends ParameterImpl implements CaseParameter {
protected static AttributeReference<CaseFileItem> bindingRefAttribute;
protected static ChildElement<BindingRefinementExpression> bindingRefinementChild;
public CaseParameterImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public CaseFileItem getBinding() {
return bindingRefAttribute.getReferenceTargetElement(this);
}
public void setBinding(CaseFileItem bindingRef) {
bindingRefAttribute.setReferenceTargetElement(this, bindingRef);
}
public BindingRefinementExpression getBindingRefinement() {
return bindingRefinementChild.getChild(this);
}
public void setBindingRefinement(BindingRefinementExpression bindingRefinement) {
bindingRefinementChild.setChild(this, bindingRefinement);
} | public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CaseParameter.class, CMMN_ELEMENT_CASE_PARAMETER)
.namespaceUri(CMMN11_NS)
.extendsType(Parameter.class)
.instanceProvider(new ModelTypeInstanceProvider<CaseParameter>() {
public CaseParameter newInstance(ModelTypeInstanceContext instanceContext) {
return new CaseParameterImpl(instanceContext);
}
});
bindingRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_BINDING_REF)
.idAttributeReference(CaseFileItem.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
bindingRefinementChild = sequenceBuilder.element(BindingRefinementExpression.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CaseParameterImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setMessageReceivedAt(XMLGregorianCalendar value) {
this.messageReceivedAt = value;
}
/**
* Contains details about the digital signature, which may be applied to an ERPEL message. Deprecated.
*
* @return
* possible object is
* {@link SignatureVerificationType }
*
*/
public SignatureVerificationType getSignatureVerification() {
return signatureVerification;
}
/**
* Sets the value of the signatureVerification property.
*
* @param value
* allowed object is
* {@link SignatureVerificationType }
*
*/
public void setSignatureVerification(SignatureVerificationType value) {
this.signatureVerification = value;
}
/**
* Contains all routing information. May include EDIFACT-specific data.
*
* @return
* possible object is
* {@link InterchangeHeaderType }
*
*/
public InterchangeHeaderType getInterchangeHeader() {
return interchangeHeader;
}
/**
* Sets the value of the interchangeHeader property.
*
* @param value
* allowed object is
* {@link InterchangeHeaderType }
*
*/
public void setInterchangeHeader(InterchangeHeaderType value) {
this.interchangeHeader = value;
}
/**
* The ID represents the unique number of the message.
*
* @return
* possible object is
* {@link String }
*
*/
public String getID() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value | * allowed object is
* {@link String }
*
*/
public void setID(String value) {
this.id = value;
}
/**
* This segment contains references related to the message.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReferences() {
return references;
}
/**
* Sets the value of the references property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReferences(String value) {
this.references = value;
}
/**
* Flag indicating whether the message is a test message or not.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isTestIndicator() {
return testIndicator;
}
/**
* Sets the value of the testIndicator property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setTestIndicator(Boolean value) {
this.testIndicator = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\messaging\header\ErpelBusinessDocumentHeaderType.java | 2 |
请完成以下Java代码 | protected boolean isHistoricDetailVariableInstanceUpdateEntity(HistoricVariableUpdate variableUpdate) {
return variableUpdate instanceof HistoricDetailVariableInstanceUpdateEntity;
}
protected List<String> getByteArrayIds(List<HistoricVariableUpdate> variableUpdates) {
List<String> byteArrayIds = new ArrayList<>();
for (HistoricVariableUpdate variableUpdate : variableUpdates) {
if (isHistoricDetailVariableInstanceUpdateEntity(variableUpdate)) {
HistoricDetailVariableInstanceUpdateEntity entity = (HistoricDetailVariableInstanceUpdateEntity) variableUpdate;
if (shouldFetchValue(entity)) {
String byteArrayId = entity.getByteArrayValueId();
if (byteArrayId != null) {
byteArrayIds.add(byteArrayId);
}
}
}
}
return byteArrayIds;
}
protected void resolveTypedValues(List<HistoricVariableUpdate> variableUpdates) { | for (HistoricVariableUpdate variableUpdate : variableUpdates) {
if (isHistoricDetailVariableInstanceUpdateEntity(variableUpdate)) {
HistoricDetailVariableInstanceUpdateEntity entity = (HistoricDetailVariableInstanceUpdateEntity) variableUpdate;
if (shouldFetchValue(entity)) {
try {
entity.getTypedValue(false);
} catch (Exception t) {
// do not fail if one of the variables fails to load
LOG.exceptionWhileGettingValueForVariable(t);
}
}
}
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\optimize\OptimizeHistoricVariableUpdateQueryCmd.java | 1 |
请完成以下Java代码 | public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public void setProperty(String property) {
this.property = property;
}
public void setOrgValue(String orgValue) {
this.orgValue = orgValue;
}
public void setNewValue(String newValue) {
this.newValue = newValue;
}
public String getEntityType() {
return entityType;
}
public void setEntityType(String entityType) {
this.entityType = entityType;
}
public String getJobId() {
return jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public String getJobDefinitionId() {
return jobDefinitionId;
}
public void setJobDefinitionId(String jobDefinitionId) {
this.jobDefinitionId = jobDefinitionId;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getBatchId() {
return batchId;
}
public void setBatchId(String batchId) {
this.batchId = batchId;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
} | public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public String getExternalTaskId() {
return externalTaskId;
}
public void setExternalTaskId(String externalTaskId) {
this.externalTaskId = externalTaskId;
}
public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[taskId=" + taskId
+ ", deploymentId=" + deploymentId
+ ", processDefinitionKey=" + processDefinitionKey
+ ", jobId=" + jobId
+ ", jobDefinitionId=" + jobDefinitionId
+ ", batchId=" + batchId
+ ", operationId=" + operationId
+ ", operationType=" + operationType
+ ", userId=" + userId
+ ", timestamp=" + timestamp
+ ", property=" + property
+ ", orgValue=" + orgValue
+ ", newValue=" + newValue
+ ", id=" + id
+ ", eventType=" + eventType
+ ", executionId=" + executionId
+ ", processDefinitionId=" + processDefinitionId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", processInstanceId=" + processInstanceId
+ ", externalTaskId=" + externalTaskId
+ ", tenantId=" + tenantId
+ ", entityType=" + entityType
+ ", category=" + category
+ ", annotation=" + annotation
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\UserOperationLogEntryEventEntity.java | 1 |
请完成以下Spring Boot application配置 | spring.datasource.url=jdbc:mysql://localhost:3306/numberdb?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.initialization-mode=always
spring.datasource.platform=mysql
spring.datasource.hikari.connectionTimeout=50000
spring.datasource.hikari.idleTimeout=300000
spring.datasource.hikari.maxLifetime=900000
spring.datasource.hikari.maximumPoolSize=8
spring.datasource.hikari.minimumIdle=8
spring.datasource.hikari.poolName=MyPool
spring.datasource.hikari.connectionTestQuery=select 1 from dual
# disable auto-commit
spring.datasource.hikari.autoCommit=false
# more settings can | be added as spring.datasource.hikari.*
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
logging.level.com.zaxxer.hikari.HikariConfig=DEBUG
logging.level.com.zaxxer.hikari=TRACE
spring.jpa.open-in-view=false
spring.jpa.hibernate.ddl-auto=create | repos\Hibernate-SpringBoot-master\HibernateSpringBootHikariCPPropertiesKickoff\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public void setSalt(String salt) {
this.salt = salt;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
public Set<String> getRoles() { | return roles;
}
public void setRoles(Set<String> roles) {
this.roles = roles;
}
public Set<String> getPerms() {
return perms;
}
public void setPerms(Set<String> perms) {
this.perms = perms;
}
} | repos\spring-boot-quick-master\quick-spring-shiro\src\main\java\com\shiro\entity\User.java | 1 |
请完成以下Java代码 | public class PayPalErrorResponse
{
@JsonProperty("name")
String errorCode;
@JsonProperty("details")
List<Detail> details;
@JsonProperty("message")
String message;
@JsonProperty("debug_id")
String debug_id;
@JsonProperty("links")
List<Link> links;
public static final String ERROR_CODE_UKNOWN = "METASFRESH_UNKNOWN";
public static final String ERROR_CODE_RESOURCE_NOT_FOUND = "RESOURCE_NOT_FOUND";
public boolean isResourceNotFound()
{ | return ERROR_CODE_RESOURCE_NOT_FOUND.equals(getErrorCode());
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
@Data
private static class Detail
{
String issue;
String description;
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
@Data
private static class Link
{
String href;
String rel;
String method;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\client\PayPalErrorResponse.java | 1 |
请完成以下Java代码 | protected Map<String, byte[]> findResources(final ClassLoader processApplicationClassloader, String paResourceRoot, String[] additionalResourceSuffixes) {
return ProcessApplicationScanningUtil.findResources(processApplicationClassloader, paResourceRoot, metaFileUrl, additionalResourceSuffixes);
}
@Override
public void cancelOperationStep(DeploymentOperation operationContext) {
final PlatformServiceContainer serviceContainer = operationContext.getServiceContainer();
final AbstractProcessApplication processApplication = operationContext.getAttachment(Attachments.PROCESS_APPLICATION);
ProcessEngine processEngine = getProcessEngine(serviceContainer, processApplication.getDefaultDeployToEngineName());
// if a registration was performed, remove it.
if (deployment != null && deployment.getProcessApplicationRegistration() != null) {
processEngine.getManagementService().unregisterProcessApplication(deployment.getProcessApplicationRegistration().getDeploymentIds(), true);
}
// delete deployment if we were able to create one AND if
// isDeleteUponUndeploy is set.
if (deployment != null && PropertyHelper.getBooleanProperty(processArchive.getProperties(), ProcessArchiveXml.PROP_IS_DELETE_UPON_UNDEPLOY, false)) {
if (processEngine != null) {
processEngine.getRepositoryService().deleteDeployment(deployment.getId(), true);
}
}
}
protected ProcessEngine getProcessEngine(final PlatformServiceContainer serviceContainer) {
return getProcessEngine(serviceContainer, ProcessEngines.NAME_DEFAULT);
}
protected ProcessEngine getProcessEngine(final PlatformServiceContainer serviceContainer, String defaultDeployToProcessEngineName) { | String processEngineName = processArchive.getProcessEngineName();
if (processEngineName != null) {
ProcessEngine processEngine = serviceContainer.getServiceValue(ServiceTypes.PROCESS_ENGINE, processEngineName);
ensureNotNull("Cannot deploy process archive '" + processArchive.getName() + "' to process engine '" + processEngineName
+ "' no such process engine exists", "processEngine", processEngine);
return processEngine;
} else {
ProcessEngine processEngine = serviceContainer.getServiceValue(ServiceTypes.PROCESS_ENGINE, defaultDeployToProcessEngineName);
ensureNotNull("Cannot deploy process archive '" + processArchive.getName() + "' to default process: no such process engine exists", "processEngine",
processEngine);
return processEngine;
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\DeployProcessArchiveStep.java | 1 |
请完成以下Java代码 | public boolean isEligibleForPicking() {return getQtyInTransit().isLessThan(qtyToMove);}
private Quantity getQtyInTransit()
{
return steps.stream()
.map(DistributionJobStep::getQtyInTransit)
.reduce(Quantity::add)
.orElseGet(qtyToMove::toZero);
}
public boolean isFullyMoved()
{
return !steps.isEmpty() && steps.stream().allMatch(DistributionJobStep::isDroppedToLocator);
}
private static WFActivityStatus computeStatusFromSteps(final @NonNull List<DistributionJobStep> steps)
{
return steps.isEmpty()
? WFActivityStatus.NOT_STARTED
: WFActivityStatus.computeStatusFromLines(steps, DistributionJobStep::getStatus);
}
public DDOrderLineId getDdOrderLineId() {return id.toDDOrderLineId();}
public DistributionJobLine withNewStep(final DistributionJobStep stepToAdd)
{
final ArrayList<DistributionJobStep> changedSteps = new ArrayList<>(this.steps);
boolean added = false;
boolean changed = false;
for (final DistributionJobStep step : steps)
{
if (DistributionJobStepId.equals(step.getId(), stepToAdd.getId()))
{
changedSteps.add(stepToAdd);
added = true;
if (!Objects.equals(step, stepToAdd))
{
changed = true;
}
}
else
{
changedSteps.add(step);
}
}
if (!added)
{ | changedSteps.add(stepToAdd);
changed = true;
}
return changed
? toBuilder().steps(ImmutableList.copyOf(changedSteps)).build()
: this;
}
public DistributionJobLine withChangedSteps(@NonNull final UnaryOperator<DistributionJobStep> stepMapper)
{
final ImmutableList<DistributionJobStep> changedSteps = CollectionUtils.map(steps, stepMapper);
return changedSteps.equals(steps)
? this
: toBuilder().steps(changedSteps).build();
}
public DistributionJobLine removeStep(@NonNull final DistributionJobStepId stepId)
{
final ImmutableList<DistributionJobStep> updatedStepCollection = steps.stream()
.filter(step -> !step.getId().equals(stepId))
.collect(ImmutableList.toImmutableList());
return updatedStepCollection.equals(steps)
? this
: toBuilder().steps(updatedStepCollection).build();
}
@NonNull
public Optional<DistributionJobStep> getStepById(@NonNull final DistributionJobStepId stepId)
{
return getSteps().stream().filter(step -> step.getId().equals(stepId)).findFirst();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\model\DistributionJobLine.java | 1 |
请完成以下Java代码 | public static void registerMapper(String mapperPath, RuntimeHints hints, ClassLoader classLoader) {
ResourceHints resourceHints = hints.resources();
ClassPathResource mapperResource = new ClassPathResource(mapperPath);
resourceHints.registerResource(mapperResource);
ReflectionHints reflectionHints = hints.reflection();
MemberCategory[] memberCategories = MemberCategory.values();
try (InputStream mapperStream = mapperResource.getInputStream()) {
XPathParser parser = createParser(mapperStream);
XNode mapper = parser.evalNode("/mapper");
// The xpath resolving is similar like what MyBatis does in XMLMapperBuilder#parse
for (XNode resultMap : mapper.evalNodes("/mapper/resultMap")) {
String type = resultMap.getStringAttribute("type");
if (type != null) {
reflectionHints.registerType(TypeReference.of(type), memberCategories);
}
}
for (XNode statement : mapper.evalNodes("select|insert|update|delete")) {
String parameterType = statement.getStringAttribute("parameterType");
if (parameterType != null) {
if (parameterType.startsWith("org.flowable") || parameterType.startsWith("java.")) {
reflectionHints.registerType(TypeReference.of(parameterType), memberCategories);
} else if (parameterType.equals("map")) {
reflectionHints.registerType(Map.class, memberCategories);
} | }
String resultType = statement.getStringAttribute("resultType");
if (resultType != null) {
if (resultType.equals("long")) {
reflectionHints.registerType(long.class, memberCategories);
reflectionHints.registerType(Long.class, memberCategories);
} else if (resultType.equals("string")) {
reflectionHints.registerType(String.class, memberCategories);
} else if (resultType.equals("map")) {
reflectionHints.registerType(HashMap.class, memberCategories);
}
}
}
} catch (IOException e) {
throw new UncheckedIOException("Failed to read mapper from " + mapperPath, e);
}
}
protected static XPathParser createParser(InputStream stream) {
return new XPathParser(stream, false, null, new XMLMapperEntityResolver());
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\aot\FlowableMyBatisResourceHintsRegistrar.java | 1 |
请完成以下Java代码 | public void setHeightInCm (final int HeightInCm)
{
set_Value (COLUMNNAME_HeightInCm, HeightInCm);
}
@Override
public int getHeightInCm()
{
return get_ValueAsInt(COLUMNNAME_HeightInCm);
}
@Override
public void setLengthInCm (final int LengthInCm)
{
set_Value (COLUMNNAME_LengthInCm, LengthInCm);
}
@Override
public int getLengthInCm()
{
return get_ValueAsInt(COLUMNNAME_LengthInCm);
}
@Override
public void setM_Package_ID (final int M_Package_ID)
{
if (M_Package_ID < 1)
set_Value (COLUMNNAME_M_Package_ID, null);
else
set_Value (COLUMNNAME_M_Package_ID, M_Package_ID);
}
@Override
public int getM_Package_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Package_ID);
}
@Override
public void setPackageDescription (final @Nullable java.lang.String PackageDescription)
{
set_Value (COLUMNNAME_PackageDescription, PackageDescription);
}
@Override
public java.lang.String getPackageDescription()
{
return get_ValueAsString(COLUMNNAME_PackageDescription);
}
@Override
public void setPdfLabelData (final @Nullable byte[] PdfLabelData)
{
set_Value (COLUMNNAME_PdfLabelData, PdfLabelData);
}
@Override
public byte[] getPdfLabelData() | {
return (byte[])get_Value(COLUMNNAME_PdfLabelData);
}
@Override
public void setTrackingURL (final @Nullable java.lang.String TrackingURL)
{
set_Value (COLUMNNAME_TrackingURL, TrackingURL);
}
@Override
public java.lang.String getTrackingURL()
{
return get_ValueAsString(COLUMNNAME_TrackingURL);
}
@Override
public void setWeightInKg (final BigDecimal WeightInKg)
{
set_Value (COLUMNNAME_WeightInKg, WeightInKg);
}
@Override
public BigDecimal getWeightInKg()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WeightInKg);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setWidthInCm (final int WidthInCm)
{
set_Value (COLUMNNAME_WidthInCm, WidthInCm);
}
@Override
public int getWidthInCm()
{
return get_ValueAsInt(COLUMNNAME_WidthInCm);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_ShipmentOrder_Parcel.java | 1 |
请完成以下Java代码 | public Response index() {
return Response.status(200).header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
.header("Access-Control-Allow-Credentials", "true")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD").entity("").build();
}
@GET
@Path("/getinfo")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Movie movieByImdbId(@QueryParam("imdbId") String imdbId) {
System.out.println("*** Calling getinfo for a given ImdbID***");
if (inventory.containsKey(imdbId)) {
return inventory.get(imdbId);
} else
return null;
}
@POST
@Path("/addmovie")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response addMovie(Movie movie) {
System.out.println("*** Calling addMovie ***");
if (null != inventory.get(movie.getImdbId())) {
return Response.status(Response.Status.NOT_MODIFIED).entity("Movie is Already in the database.").build();
}
inventory.put(movie.getImdbId(), movie);
return Response.status(Response.Status.CREATED).build();
}
@PUT
@Path("/updatemovie")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response updateMovie(Movie movie) {
System.out.println("*** Calling updateMovie ***");
if (null == inventory.get(movie.getImdbId())) {
return Response.status(Response.Status.NOT_MODIFIED) | .entity("Movie is not in the database.\nUnable to Update").build();
}
inventory.put(movie.getImdbId(), movie);
return Response.status(Response.Status.OK).build();
}
@DELETE
@Path("/deletemovie")
public Response deleteMovie(@QueryParam("imdbId") String imdbId) {
System.out.println("*** Calling deleteMovie ***");
if (null == inventory.get(imdbId)) {
return Response.status(Response.Status.NOT_FOUND).entity("Movie is not in the database.\nUnable to Delete")
.build();
}
inventory.remove(imdbId);
return Response.status(Response.Status.OK).build();
}
@GET
@Path("/listmovies")
@Produces({ "application/json" })
public List<Movie> listMovies() {
return inventory.values().stream().collect(Collectors.toCollection(ArrayList::new));
}
} | repos\tutorials-master\web-modules\resteasy\src\main\java\com\baeldung\server\MovieCrudService.java | 1 |
请完成以下Java代码 | public void setType (String obscureType)
{
if (obscureType == null || obscureType.equals("904") || obscureType.equals("944") || obscureType.equals("A44") || obscureType.equals("A04"))
{
m_type = obscureType;
m_obscuredValue = null;
return;
}
throw new IllegalArgumentException ("ObscureType Invalid value - Reference_ID=291 - 904 - 944 - A44 - A04");
} // setType
/**
* Get Obscure Type
* @return type
*/
public String getType ()
{
return m_type;
} // getType
/**
* Get Clear Value
* @return Returns the clear Value.
*/
public String getClearValue ()
{
return m_clearValue;
} // getClearValue
/**
* Set Clear Value
* @param clearValue The clearValue to set.
*/
public void setClearValue (String clearValue)
{
m_clearValue = clearValue;
m_obscuredValue = null;
} // setClearValue
/**
* Get Obscured Value
* @param clearValue The clearValue to set.
* @return Returns the obscuredValue.
*/
public String getObscuredValue (String clearValue)
{
setClearValue(clearValue);
return getObscuredValue();
} // getObscuredValue
/**
* Get Obscured Value
* @return Returns the obscuredValue.
*/ | public String getObscuredValue ()
{
if (m_obscuredValue != null)
return m_obscuredValue;
if (m_clearValue == null || m_clearValue.length() == 0)
return m_clearValue;
//
boolean alpha = m_type.charAt(0) == 'A';
int clearStart = Integer.parseInt(m_type.substring(1,2));
int clearEnd = Integer.parseInt(m_type.substring(2));
//
char[] chars = m_clearValue.toCharArray();
int length = chars.length;
StringBuffer sb = new StringBuffer(length);
for (int i = 0; i < length; i++)
{
char c = chars[i];
if (i < clearStart)
sb.append(c);
else if (i >= length-clearEnd)
sb.append(c);
else
{
if (!alpha && !Character.isDigit(c))
sb.append(c);
else
sb.append('*');
}
}
m_obscuredValue = sb.toString();
return m_obscuredValue;
} // getObscuredValue
/**************************************************************************
* test
* @param args ignored
*/
public static void main (String[] args)
{
System.out.println (Obscure.obscure("1a2b3c4d5e6f7g8h9"));
} // main
} // Obscrure | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\Obscure.java | 1 |
请完成以下Java代码 | private static class RoutingDurationsAndYield
{
private Percent yield = Percent.ONE_HUNDRED;
private Duration queuingTime = Duration.ZERO;
private Duration setupTime = Duration.ZERO;
private Duration durationPerOneUnit = Duration.ZERO;
private Duration waitingTime = Duration.ZERO;
private Duration movingTime = Duration.ZERO;
public void addActivity(final PPRoutingActivity activity)
{
if (!activity.getYield().isZero())
{
yield = yield.multiply(activity.getYield(), 0);
}
queuingTime = queuingTime.plus(activity.getQueuingTime());
setupTime = setupTime.plus(activity.getSetupTime());
waitingTime = waitingTime.plus(activity.getWaitingTime());
movingTime = movingTime.plus(activity.getMovingTime());
// We use node.getDuration() instead of m_routingService.estimateWorkingTime(node) because
// this will be the minimum duration of this node. So even if the node have defined units/cycle
// we consider entire duration of the node.
durationPerOneUnit = durationPerOneUnit.plus(activity.getDurationPerOneUnit());
}
} | @lombok.Value(staticConstructor = "of")
private static class RoutingActivitySegmentCost
{
public static Collector<RoutingActivitySegmentCost, ?, Map<CostElementId, BigDecimal>> groupByCostElementId()
{
return Collectors.groupingBy(RoutingActivitySegmentCost::getCostElementId, sumCostsAsBigDecimal());
}
private static Collector<RoutingActivitySegmentCost, ?, BigDecimal> sumCostsAsBigDecimal()
{
return Collectors.reducing(BigDecimal.ZERO, RoutingActivitySegmentCost::getCostAsBigDecimal, BigDecimal::add);
}
@NonNull
CostAmount cost;
@NonNull
PPRoutingActivityId routingActivityId;
@NonNull
CostElementId costElementId;
public BigDecimal getCostAsBigDecimal()
{
return cost.toBigDecimal();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\RollupWorkflow.java | 1 |
请完成以下Java代码 | public I_M_HU_PI retrievePIDefaultForPicking()
{
return handlingUnitsRepo.retrievePIDefaultForPicking();
}
@Override
public boolean isTUIncludedInLU(@NonNull final I_M_HU tu, @NonNull final I_M_HU expectedLU)
{
final I_M_HU actualLU = getLoadingUnitHU(tu);
return actualLU != null && actualLU.getM_HU_ID() == expectedLU.getM_HU_ID();
}
@Override
public List<I_M_HU> retrieveIncludedHUs(final I_M_HU huId)
{
return handlingUnitsRepo.retrieveIncludedHUs(huId);
}
@Override
@NonNull
public ImmutableSet<LocatorId> getLocatorIds(@NonNull final Collection<HuId> huIds)
{
final List<I_M_HU> hus = handlingUnitsRepo.getByIds(huIds);
final ImmutableSet<Integer> locatorIds = hus
.stream()
.map(I_M_HU::getM_Locator_ID)
.filter(locatorId -> locatorId > 0)
.collect(ImmutableSet.toImmutableSet());
return warehouseBL.getLocatorIdsByRepoId(locatorIds);
}
@Override
public Optional<HuId> getHUIdByValueOrExternalBarcode(@NonNull final ScannedCode scannedCode)
{ | return Optionals.firstPresentOfSuppliers(
() -> getHUIdByValue(scannedCode.getAsString()),
() -> getByExternalBarcode(scannedCode)
);
}
private Optional<HuId> getHUIdByValue(final String value)
{
final HuId huId = HuId.ofHUValueOrNull(value);
return huId != null && existsById(huId) ? Optional.of(huId) : Optional.empty();
}
private Optional<HuId> getByExternalBarcode(@NonNull final ScannedCode scannedCode)
{
return handlingUnitsRepo.createHUQueryBuilder()
.setOnlyActiveHUs(true)
.setOnlyTopLevelHUs()
.addOnlyWithAttribute(AttributeConstants.ATTR_ExternalBarcode, scannedCode.getAsString())
.firstIdOnly();
}
@Override
public Set<HuPackingMaterialId> getHUPackingMaterialIds(@NonNull final HuId huId)
{
return handlingUnitsRepo.retrieveAllItemsNoCache(Collections.singleton(huId))
.stream()
.map(item -> HuPackingMaterialId.ofRepoIdOrNull(item.getM_HU_PackingMaterial_ID()))
.filter(Objects::nonNull)
.collect(Collectors.toSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HandlingUnitsBL.java | 1 |
请完成以下Java代码 | public static WebuiASIEditingInfo readonlyASI(final AttributeSetInstanceId attributeSetInstanceId)
{
final ASIEditingInfo info = ASIEditingInfo.builder()
.type(WindowType.StrictASIAttributes)
.soTrx(SOTrx.SALES)
.attributeSetInstanceId(attributeSetInstanceId)
.build();
return builder(info).build();
}
public static WebuiASIEditingInfo processParameterASI(
final AttributeSetInstanceId attributeSetInstanceId,
final DocumentPath documentPath)
{
final ASIEditingInfo info = ASIEditingInfo.builder()
.type(WindowType.ProcessParameter)
.soTrx(SOTrx.SALES)
.attributeSetInstanceId(attributeSetInstanceId)
.build();
return builder(info)
.contextDocumentPath(documentPath)
.build();
}
@NonNull
WindowType contextWindowType; | DocumentPath contextDocumentPath;
@NonNull
AttributeSetId attributeSetId;
String attributeSetName;
String attributeSetDescription;
@NonNull
AttributeSetInstanceId attributeSetInstanceId;
ProductId productId;
@NonNull
SOTrx soTrx;
String callerTableName;
int callerAdColumnId;
@NonNull
@Singular
ImmutableList<Attribute> attributes;
public ImmutableSet<AttributeId> getAttributeIds()
{
return attributes.stream()
.map(Attribute::getAttributeId)
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pattribute\WebuiASIEditingInfo.java | 1 |
请完成以下Java代码 | public int getAD_ReportView_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_ReportView_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getAD_ReportView_ID()));
}
/** Set Function Column.
@param FunctionColumn
Overwrite Column with Function
*/
public void setFunctionColumn (String FunctionColumn)
{
set_Value (COLUMNNAME_FunctionColumn, FunctionColumn);
}
/** Get Function Column.
@return Overwrite Column with Function
*/
public String getFunctionColumn ()
{ | return (String)get_Value(COLUMNNAME_FunctionColumn);
}
/** Set SQL Group Function.
@param IsGroupFunction
This function will generate a Group By Clause
*/
public void setIsGroupFunction (boolean IsGroupFunction)
{
set_Value (COLUMNNAME_IsGroupFunction, Boolean.valueOf(IsGroupFunction));
}
/** Get SQL Group Function.
@return This function will generate a Group By Clause
*/
public boolean isGroupFunction ()
{
Object oo = get_Value(COLUMNNAME_IsGroupFunction);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ReportView_Col.java | 1 |
请完成以下Java代码 | public VatCodeId getIdByCodeAndOrgId(
@NonNull final String code,
@NonNull final OrgId orgId)
{
return queryBL.createQueryBuilder(I_C_VAT_Code.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_VAT_Code.COLUMNNAME_VATCode, code)
.addInArrayFilter(I_C_VAT_Code.COLUMNNAME_AD_Org_ID, orgId, OrgId.ANY)
.create()
.firstIdOnlyOptional(VatCodeId::ofRepoIdOrNull)
.orElseThrow(() -> new AdempiereException("No C_VAT_Code found for code & org")
.appendParametersToMessage()
.setParameter("OrgId", orgId.getRepoId())
.setParameter("code", code));
}
/**
* @return true if the given {@link I_C_VAT_Code} is matching our request.
*/
private boolean isMatching(final I_C_VAT_Code matching, final VATCodeMatchingRequest request)
{
logger.debug("Matching: {}", matching);
logger.debug("Request: {}", request);
// Match accounting schema
if (matching.getC_AcctSchema_ID() != request.getC_AcctSchema_ID())
{
logger.debug("=> not matching (C_AcctSchema_ID)");
return false;
}
// Match tax
if (matching.getC_Tax_ID() != request.getC_Tax_ID())
{
logger.debug("=> not matching (C_Tax_ID)");
return false;
}
// Match IsSOTrx
final String matchingIsSOTrxStr = matching.getIsSOTrx();
final Boolean matchingIsSOTrx = matchingIsSOTrxStr == null ? null : DisplayType.toBoolean(matchingIsSOTrxStr);
if (matchingIsSOTrx != null && matchingIsSOTrx != request.isSOTrx())
{
logger.debug("=> not matching (IsSOTrx)");
return false;
} | // Match Date
if (!TimeUtil.isBetween(request.getDate(), matching.getValidFrom(), matching.getValidTo()))
{
logger.debug("=> not matching (Date)");
return false;
}
logger.debug("=> matching");
return true;
}
/**
* Retries all active {@link I_C_VAT_Code}s for given C_AcctSchema_ID.
*
* @param acctSchemaId C_AcctSchema_ID
*/
@Cached(cacheName = I_C_VAT_Code.Table_Name + "#by#" + I_C_VAT_Code.COLUMNNAME_C_AcctSchema_ID)
public List<I_C_VAT_Code> retriveVATCodeMatchingsForSchema(@CacheCtx final Properties ctx, final int acctSchemaId)
{
return queryBL
.createQueryBuilder(I_C_VAT_Code.class, ctx, ITrx.TRXNAME_ThreadInherited)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_VAT_Code.COLUMN_C_AcctSchema_ID, acctSchemaId)
//
.orderBy()
.addColumn(I_C_VAT_Code.COLUMNNAME_C_Tax_ID)
.addColumn(I_C_VAT_Code.COLUMN_ValidFrom, Direction.Descending, Nulls.Last)
.addColumn(I_C_VAT_Code.COLUMN_ValidTo, Direction.Descending, Nulls.Last)
.addColumn(I_C_VAT_Code.COLUMN_IsSOTrx, Direction.Ascending, Nulls.Last)
.addColumn(I_C_VAT_Code.COLUMN_C_VAT_Code_ID)
.endOrderBy()
//
.create()
.list();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\vatcode\impl\VATCodeDAO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class LocationUpdateReq extends AbsReq {
/** 收货地址ID */
private String locationId;
/** 详细地址 */
private String location;
/** 收货人姓名 */
private String name;
/** 收货人手机号 */
private String phone;
/** 邮编 */
private String postCode;
public String getLocationId() {
return locationId;
}
public void setLocationId(String locationId) {
this.locationId = locationId;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() { | return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
@Override
public String toString() {
return "LocationUpdateReq{" +
"locationId='" + locationId + '\'' +
", location='" + location + '\'' +
", name='" + name + '\'' +
", phone='" + phone + '\'' +
", postCode='" + postCode + '\'' +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\user\LocationUpdateReq.java | 2 |
请完成以下Java代码 | public final I_M_HU_PI getTU_HU_PI()
{
return _tuPI;
}
@Override
public IHandlingUnitsInfo add(final IHandlingUnitsInfo infoToAdd)
{
if (infoToAdd == null)
{
return this;
}
//
// TU PI
final I_M_HU_PI tuPI = getTU_HU_PI();
// TODO make sure tuPIs are compatible
//
// Qty TU
final int qtyTU = getQtyTU();
final int qtyTU_ToAdd = infoToAdd.getQtyTU(); | final int qtyTU_New = qtyTU + qtyTU_ToAdd;
final boolean isReadWrite = false;
final HUHandlingUnitsInfo infoNew = new HUHandlingUnitsInfo(tuPI, qtyTU_New, isReadWrite);
return infoNew;
}
protected void setQtyTUInner(final int qtyTU)
{
Check.errorIf(!_isQtyWritable, "This instance {} is read-only", this);
_qtyTU = qtyTU;
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\materialtracking\spi\impl\HUHandlingUnitsInfo.java | 1 |
请完成以下Java代码 | public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BPMNMessageImpl that = (BPMNMessageImpl) o;
return (
Objects.equals(getElementId(), that.getElementId()) &&
Objects.equals(messagePayload, that.getMessagePayload())
);
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((messagePayload == null) ? 0 : messagePayload.hashCode());
return result; | }
@Override
public String toString() {
return (
"BPMNMessageImpl{" +
", elementId='" +
getElementId() +
'\'' +
", messagePayload='" +
(messagePayload != null ? messagePayload.toString() : null) +
'\'' +
'}'
);
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\BPMNMessageImpl.java | 1 |
请完成以下Java代码 | /* package */abstract class AbstractHUStorageDAO implements IHUStorageDAO
{
@Override
public final I_C_UOM getC_UOMOrNull(final I_M_HU hu)
{
if (hu == null)
{
//
// Null HU; consider that the UOMType is incompatible
return null;
}
final List<I_M_HU_Storage> storages = retrieveStorages(hu);
return getC_UOMOrNull(storages);
}
@VisibleForTesting
/* package */ final I_C_UOM getC_UOMOrNull(final List<I_M_HU_Storage> storages)
{
if (storages == null || storages.isEmpty())
{
return null;
}
if (storages.size() == 1)
{
return IHUStorageBL.extractUOM(storages.get(0));
}
I_C_UOM foundUOM = null;
String foundUOMType = null;
for (final I_M_HU_Storage storage : storages)
{
//
// Retrieve storage UOM
final I_C_UOM storageUOM = IHUStorageBL.extractUOM(storage);
final String storageUOMType = storageUOM.getUOMType();
if (foundUOM == null)
{
// This is actually the initial (and only) assignment
foundUOM = storageUOM;
foundUOMType = storageUOMType;
continue;
}
if (foundUOM.getC_UOM_ID() == storageUOM.getC_UOM_ID())
{
// each uom is compatible with itself
continue;
}
// Validated for null before with that Check | if (Objects.equals(foundUOMType, storageUOMType))
{
if (Check.isEmpty(storageUOMType, true))
{
// if both UOMs' types are empty/null, then we have to thread them as incompatible; exit loop & return null
return null;
}
// We don't care about it if it's the same UOMType
continue;
}
// Incompatible UOM types encountered; exit loop & return null
return null;
}
return foundUOM;
}
@Override
public final UOMType getC_UOMTypeOrNull(final I_M_HU hu)
{
// FIXME: optimize more!
final List<I_M_HU_Storage> storages = retrieveStorages(hu);
if (storages.isEmpty())
{
//
// TODO hardcoded (quickfix in 07088, skyped with teo - we need a compatible UOM type before storages are created when propagating WeightNet)
return UOMType.Weight;
}
final I_C_UOM uom = getC_UOMOrNull(storages);
if (uom == null)
{
return null;
}
return UOMType.ofNullableCodeOrOther(uom.getUOMType());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\AbstractHUStorageDAO.java | 1 |
请完成以下Java代码 | public class WEBUI_Picking_M_Picking_Candidate_Unprocess extends PickingSlotViewBasedProcess
{
private final PickingCandidateService pickingCandidateService = SpringContextHolder.instance.getBean(PickingCandidateService.class);
@Override
protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (!getSelectedRowIds().isSingleDocumentId())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
final PickingSlotRow pickingSlotRow = getSingleSelectedRow();
if (!pickingSlotRow.isPickedHURow())
{
return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_SELECT_PICKED_HU));
}
if (!pickingSlotRow.isProcessed())
{
return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_NO_PROCESSED_RECORDS));
}
return ProcessPreconditionsResolution.accept();
} | @Override
protected String doIt()
{
final PickingSlotRow rowToProcess = getSingleSelectedRow();
final HuId huId = rowToProcess.getHuId();
pickingCandidateService.unprocessAndRestoreSourceHUsByHUId(huId);
return MSG_OK;
}
@Override
protected void postProcess(final boolean success)
{
if (!success)
{
return;
}
invalidatePickingSlotsView();
invalidatePackablesView();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\process\WEBUI_Picking_M_Picking_Candidate_Unprocess.java | 1 |
请完成以下Java代码 | public int getC_BPartner_Location_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_Location_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Abholung.
@param IsToBeFetched Abholung */
@Override
public void setIsToBeFetched (boolean IsToBeFetched)
{
set_Value (COLUMNNAME_IsToBeFetched, Boolean.valueOf(IsToBeFetched));
}
/** Get Abholung.
@return Abholung */
@Override
public boolean isToBeFetched ()
{
Object oo = get_Value(COLUMNNAME_IsToBeFetched);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public de.metas.tourplanning.model.I_M_TourVersion getM_TourVersion() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_TourVersion_ID, de.metas.tourplanning.model.I_M_TourVersion.class);
}
@Override
public void setM_TourVersion(de.metas.tourplanning.model.I_M_TourVersion M_TourVersion)
{
set_ValueFromPO(COLUMNNAME_M_TourVersion_ID, de.metas.tourplanning.model.I_M_TourVersion.class, M_TourVersion);
}
/** Set Tour Version.
@param M_TourVersion_ID Tour Version */
@Override
public void setM_TourVersion_ID (int M_TourVersion_ID)
{
if (M_TourVersion_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_TourVersion_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_TourVersion_ID, Integer.valueOf(M_TourVersion_ID));
}
/** Get Tour Version.
@return Tour Version */
@Override
public int getM_TourVersion_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_TourVersion_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Tour Version Line.
@param M_TourVersionLine_ID Tour Version Line */
@Override
public void setM_TourVersionLine_ID (int M_TourVersionLine_ID)
{
if (M_TourVersionLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_TourVersionLine_ID, null); | else
set_ValueNoCheck (COLUMNNAME_M_TourVersionLine_ID, Integer.valueOf(M_TourVersionLine_ID));
}
/** Get Tour Version Line.
@return Tour Version Line */
@Override
public int getM_TourVersionLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_TourVersionLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\tourplanning\model\X_M_TourVersionLine.java | 1 |
请完成以下Java代码 | public int compare(EventSubscriptionEntity o1, EventSubscriptionEntity o2) {
return o2.getCreated().compareTo(o1.getCreated());
}
});
for (CompensateEventSubscriptionEntity compensateEventSubscriptionEntity : eventSubscriptions) {
compensateEventSubscriptionEntity.eventReceived(null, async);
}
}
/**
* creates an event scope for the given execution:
*
* create a new event scope execution under the parent of the given execution and move all event subscriptions to that execution.
*
* this allows us to "remember" the event subscriptions after finishing a scope
*/
public static void createEventScopeExecution(ExecutionEntity execution) {
ExecutionEntity eventScope = ScopeUtil.findScopeExecutionForScope(execution, execution.getActivity().getParent());
List<CompensateEventSubscriptionEntity> eventSubscriptions = execution.getCompensateEventSubscriptions();
if (!eventSubscriptions.isEmpty()) {
ExecutionEntity eventScopeExecution = eventScope.createExecution();
eventScopeExecution.setActive(false);
eventScopeExecution.setConcurrent(false);
eventScopeExecution.setEventScope(true);
eventScopeExecution.setActivity(execution.getActivity());
execution.setConcurrent(false);
// copy local variables to eventScopeExecution by value. This way,
// the eventScopeExecution references a 'snapshot' of the local variables
Map<String, Object> variables = execution.getVariablesLocal(); | for (Entry<String, Object> variable : variables.entrySet()) {
eventScopeExecution.setVariableLocal(variable.getKey(), variable.getValue());
}
// set event subscriptions to the event scope execution:
for (CompensateEventSubscriptionEntity eventSubscriptionEntity : eventSubscriptions) {
eventSubscriptionEntity = eventSubscriptionEntity.moveUnder(eventScopeExecution);
}
CompensateEventSubscriptionEntity eventSubscription = CompensateEventSubscriptionEntity.createAndInsert(eventScope);
eventSubscription.setActivity(execution.getActivity());
eventSubscription.setConfiguration(eventScopeExecution.getId());
}
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\helper\ScopeUtil.java | 1 |
请完成以下Java代码 | public boolean isInboundTrx()
{
return !isOutboundTrx();
}
public boolean isOutboundTrx()
{
final Boolean outboundTrx = getDocumentRef().getOutboundTrx();
if (outboundTrx != null)
{
return outboundTrx;
}
else
{
return getQty().signum() < 0;
}
}
public CostAmountAndQtyDetailed getAmtAndQtyDetailed() {return CostAmountAndQtyDetailed.of(amt, qty, amtType);}
public CostAmount computePartialCostAmount(@NonNull final Quantity qty, @NonNull final CurrencyPrecision precision) | {
if (qty.equalsIgnoreSource(this.qty))
{
return amt;
}
else if (qty.isZero())
{
return amt.toZero();
}
else
{
final CostAmount price = amt.divide(this.qty, CurrencyPrecision.ofInt(12));
return price.multiply(qty.toBigDecimal()).roundToPrecisionIfNeeded(precision);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostDetail.java | 1 |
请完成以下Java代码 | private I_M_HU_PI_Item_Product getM_HU_PI_Item_Product()
{
final de.metas.handlingunits.model.I_C_OrderLine huOrderLine = InterfaceWrapperHelper.create(orderLine, de.metas.handlingunits.model.I_C_OrderLine.class);
return huOrderLine.getM_HU_PI_Item_Product();
}
@Override
public I_C_Flatrate_DataEntry getC_Flatrate_DataEntry()
{
return Services.get(IPMMContractsDAO.class).retrieveFlatrateDataEntry(
getC_Flatrate_Term(),
getDate());
}
@Override
public Object getWrappedModel()
{
return orderLine;
}
@Override
public Timestamp getDate()
{
return CoalesceUtil.coalesceSuppliers(
() -> orderLine.getDatePromised(),
() -> orderLine.getC_Order().getDatePromised());
}
@Override
public BigDecimal getQty()
{
return orderLine.getQtyOrdered();
}
@Override
public void setM_PricingSystem_ID(int M_PricingSystem_ID)
{
throw new NotImplementedException(); | }
@Override
public void setM_PriceList_ID(int M_PriceList_ID)
{
throw new NotImplementedException();
}
/**
* Sets a private member variable to the given {@code price}.
*/
@Override
public void setPrice(BigDecimal price)
{
this.price = price;
}
/**
*
* @return the value that was set via {@link #setPrice(BigDecimal)}.
*/
public BigDecimal getPrice()
{
return price;
}
public I_M_AttributeSetInstance getM_AttributeSetInstance()
{
return orderLine.getM_AttributeSetInstance();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\PMMPricingAware_C_OrderLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public GetUserResponse createGetUserResponse() {
return new GetUserResponse();
}
/**
* Create an instance of {@link SayHello }
*
*/
public SayHello createSayHello() {
return new SayHello();
}
/**
* Create an instance of {@link GetUser }
*
*/
public GetUser createGetUser() {
return new GetUser();
}
/**
* Create an instance of {@link SayHelloResponse }
*
*/
public SayHelloResponse createSayHelloResponse() {
return new SayHelloResponse();
}
/**
* Create an instance of {@link User }
*
*/
public User createUser() {
return new User();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetUser }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://model.webservice.xncoding.com/", name = "getUser")
public JAXBElement<GetUser> createGetUser(GetUser value) {
return new JAXBElement<GetUser>(_GetUser_QNAME, GetUser.class, null, value); | }
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetUserResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://model.webservice.xncoding.com/", name = "getUserResponse")
public JAXBElement<GetUserResponse> createGetUserResponse(GetUserResponse value) {
return new JAXBElement<GetUserResponse>(_GetUserResponse_QNAME, GetUserResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link SayHello }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://model.webservice.xncoding.com/", name = "sayHello")
public JAXBElement<SayHello> createSayHello(SayHello value) {
return new JAXBElement<SayHello>(_SayHello_QNAME, SayHello.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link SayHelloResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://model.webservice.xncoding.com/", name = "sayHelloResponse")
public JAXBElement<SayHelloResponse> createSayHelloResponse(SayHelloResponse value) {
return new JAXBElement<SayHelloResponse>(_SayHelloResponse_QNAME, SayHelloResponse.class, null, value);
}
} | repos\SpringBootBucket-master\springboot-cxf\src\main\java\com\xncoding\webservice\client\ObjectFactory.java | 2 |
请完成以下Java代码 | private List<String> getColumnHeaders()
{
final List<String> columnHeaders = new ArrayList<>();
columnHeaders.add("ProductName");
columnHeaders.add("CustomerLabelName");
columnHeaders.add("Additional_produktinfos");
columnHeaders.add("ProductValue");
columnHeaders.add("UPC");
columnHeaders.add("NetWeight");
columnHeaders.add("Country");
columnHeaders.add("ShelfLifeDays");
columnHeaders.add("Warehouse_temperature");
columnHeaders.add("ProductDescription");
columnHeaders.add("M_BOMProduct_ID");
columnHeaders.add("IsPackagingMaterial");
columnHeaders.add("Ingredients");
columnHeaders.add("QtyBatch");
columnHeaders.add("Allergen");
columnHeaders.add("M_Product_Nutrition_ID"); | columnHeaders.add("NutritionQty");
return columnHeaders;
}
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
return ProcessPreconditionsResolution.accept();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\product\process\ExportProductSpecifications.java | 1 |
请完成以下Java代码 | public List<HistoricTaskInstanceReportResult> countByTaskName() {
CommandContext commandContext = Context.getCommandContext();
if(commandContext == null) {
return commandExecutor.execute(new HistoricTaskInstanceCountByNameCmd());
}
else {
return executeCountByTaskName(commandContext);
}
}
protected List<HistoricTaskInstanceReportResult> executeCountByTaskName(CommandContext commandContext) {
return commandContext.getTaskReportManager()
.selectHistoricTaskInstanceCountByTaskNameReport(this);
}
@Override
public List<DurationReportResult> duration(PeriodUnit periodUnit) {
ensureNotNull(NotValidException.class, "periodUnit", periodUnit);
this.durationPeriodUnit = periodUnit;
CommandContext commandContext = Context.getCommandContext();
if(commandContext == null) {
return commandExecutor.execute(new ExecuteDurationCmd());
}
else {
return executeDuration(commandContext);
}
}
protected List<DurationReportResult> executeDuration(CommandContext commandContext) {
return commandContext.getTaskReportManager()
.createHistoricTaskDurationReport(this);
}
public Date getCompletedAfter() {
return completedAfter;
}
public Date getCompletedBefore() {
return completedBefore;
}
@Override | public HistoricTaskInstanceReport completedAfter(Date completedAfter) {
ensureNotNull(NotValidException.class, "completedAfter", completedAfter);
this.completedAfter = completedAfter;
return this;
}
@Override
public HistoricTaskInstanceReport completedBefore(Date completedBefore) {
ensureNotNull(NotValidException.class, "completedBefore", completedBefore);
this.completedBefore = completedBefore;
return this;
}
public TenantCheck getTenantCheck() {
return tenantCheck;
}
public String getReportPeriodUnitName() {
return durationPeriodUnit.name();
}
protected class ExecuteDurationCmd implements Command<List<DurationReportResult>> {
@Override
public List<DurationReportResult> execute(CommandContext commandContext) {
return executeDuration(commandContext);
}
}
protected class HistoricTaskInstanceCountByNameCmd implements Command<List<HistoricTaskInstanceReportResult>> {
@Override
public List<HistoricTaskInstanceReportResult> execute(CommandContext commandContext) {
return executeCountByTaskName(commandContext);
}
}
protected class HistoricTaskInstanceCountByProcessDefinitionKey implements Command<List<HistoricTaskInstanceReportResult>> {
@Override
public List<HistoricTaskInstanceReportResult> execute(CommandContext commandContext) {
return executeCountByProcessDefinitionKey(commandContext);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricTaskInstanceReportImpl.java | 1 |
请完成以下Java代码 | public List<Case> getCases() {
return cases;
}
public void setCases(List<Case> cases) {
this.cases = cases;
}
public List<Process> getProcesses() {
return processes;
}
public void setProcesses(List<Process> processes) {
this.processes = processes;
}
public List<Association> getAssociations() {
return associations;
}
public void setAssociations(List<Association> associations) {
this.associations = associations;
}
public List<TextAnnotation> getTextAnnotations() {
return textAnnotations;
}
public void setTextAnnotations(List<TextAnnotation> textAnnotations) {
this.textAnnotations = textAnnotations;
}
public void addNamespace(String prefix, String uri) {
namespaceMap.put(prefix, uri);
}
public boolean containsNamespacePrefix(String prefix) {
return namespaceMap.containsKey(prefix);
}
public String getNamespace(String prefix) {
return namespaceMap.get(prefix);
}
public Map<String, String> getNamespaces() {
return namespaceMap;
}
public Map<String, List<ExtensionAttribute>> getDefinitionsAttributes() { | return definitionsAttributes;
}
public String getDefinitionsAttributeValue(String namespace, String name) {
List<ExtensionAttribute> attributes = getDefinitionsAttributes().get(name);
if (attributes != null && !attributes.isEmpty()) {
for (ExtensionAttribute attribute : attributes) {
if (namespace.equals(attribute.getNamespace())) {
return attribute.getValue();
}
}
}
return null;
}
public void addDefinitionsAttribute(ExtensionAttribute attribute) {
if (attribute != null && StringUtils.isNotEmpty(attribute.getName())) {
List<ExtensionAttribute> attributeList = null;
if (!this.definitionsAttributes.containsKey(attribute.getName())) {
attributeList = new ArrayList<>();
this.definitionsAttributes.put(attribute.getName(), attributeList);
}
this.definitionsAttributes.get(attribute.getName()).add(attribute);
}
}
public void setDefinitionsAttributes(Map<String, List<ExtensionAttribute>> attributes) {
this.definitionsAttributes = attributes;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\CmmnModel.java | 1 |
请完成以下Java代码 | public org.eevolution.model.I_PP_Product_BOM getPP_Product_BOM() throws RuntimeException
{
return (org.eevolution.model.I_PP_Product_BOM)MTable.get(getCtx(), org.eevolution.model.I_PP_Product_BOM.Table_Name)
.getPO(getPP_Product_BOM_ID(), get_TrxName()); }
/** Set BOM & Formula.
@param PP_Product_BOM_ID
BOM & Formula
*/
public void setPP_Product_BOM_ID (int PP_Product_BOM_ID)
{
if (PP_Product_BOM_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Product_BOM_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Product_BOM_ID, Integer.valueOf(PP_Product_BOM_ID));
}
/** Get BOM & Formula.
@return BOM & Formula
*/
public int getPP_Product_BOM_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PP_Product_BOM_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;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ChangeRequest.java | 1 |
请完成以下Java代码 | public String getDbType()
{
return getProperty(PROP_DB_TYPE, "postgresql");
}
public String getDbHostname()
{
return getProperty(PROP_DB_SERVER, "localhost");
}
public String getDbPort()
{
return getProperty(PROP_DB_PORT, "5432");
}
public String getDbPassword()
{
return getProperty(PROP_DB_PASSWORD,
// Default value is null because in case is not configured we shall use other auth methods
IDatabase.PASSWORD_NA);
}
@Override
public String toString()
{ | final HashMap<Object, Object> result = new HashMap<>(properties);
result.put(PROP_DB_PASSWORD, "******");
return result.toString();
}
public DBConnectionSettings toDBConnectionSettings()
{
return DBConnectionSettings.builder()
.dbHostname(getDbHostname())
.dbPort(getDbPort())
.dbName(getDbName())
.dbUser(getDbUser())
.dbPassword(getDbPassword())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\rollout_migrate\DBConnectionSettingProperties.java | 1 |
请完成以下Java代码 | public class FlatrateUserNotificationsProducer
{
public static final FlatrateUserNotificationsProducer newInstance()
{
return new FlatrateUserNotificationsProducer();
}
private static final transient Logger logger = LogManager.getLogger(FlatrateUserNotificationsProducer.class);
public static final Topic EVENTBUS_TOPIC = Topic.builder()
.name("de.metas.contracts.UserNotifications")
.type(Type.DISTRIBUTED)
.build();
public FlatrateUserNotificationsProducer notifyUser(
final I_C_Flatrate_Term contract,
final UserId recipientUserId,
@NonNull final AdMessageKey message)
{
if (contract == null)
{
return this;
}
try
{
postNotification(createFlatrateTermGeneratedEvent(contract, recipientUserId, message));
}
catch (final Exception ex)
{
logger.warn("Failed creating event for contract {}. Ignored.", contract, ex);
}
return this;
}
private final UserNotificationRequest createFlatrateTermGeneratedEvent(
@NonNull final I_C_Flatrate_Term contract, | final UserId recipientUserId,
@NonNull final AdMessageKey message)
{
if (recipientUserId == null)
{
// nothing to do
return null;
}
final TableRecordReference flatrateTermRef = TableRecordReference.of(contract);
return newUserNotificationRequest()
.recipientUserId(recipientUserId)
.contentADMessage(message)
.targetAction(TargetRecordAction.ofRecordAndWindow(flatrateTermRef, Contracts_Constants.CONTRACTS_WINDOW_ID))
.build();
}
private final UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest()
{
return UserNotificationRequest.builder()
.topic(EVENTBUS_TOPIC);
}
private void postNotification(final UserNotificationRequest notification)
{
Services.get(INotificationBL.class).sendAfterCommit(notification);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\event\FlatrateUserNotificationsProducer.java | 1 |
请完成以下Java代码 | public Task getTask() {
ensureCommandContextNotActive();
return getScopedAssociation().getTask();
}
public void setTask(Task task) {
ensureCommandContextNotActive();
getScopedAssociation().setTask(task);
}
public VariableMap getCachedVariables() {
ensureCommandContextNotActive();
return getScopedAssociation().getCachedVariables();
}
public VariableMap getCachedLocalVariables() { | ensureCommandContextNotActive();
return getScopedAssociation().getCachedVariablesLocal();
}
public void flushVariableCache() {
ensureCommandContextNotActive();
getScopedAssociation().flushVariableCache();
}
protected void ensureCommandContextNotActive() {
if(Context.getCommandContext() != null) {
throw new ProcessEngineCdiException("Cannot work with scoped associations inside command context.");
}
}
} | repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\context\DefaultContextAssociationManager.java | 1 |
请完成以下Java代码 | public SignalEventListenerInstanceQuery caseDefinitionId(String caseDefinitionId) {
innerQuery.caseDefinitionId(caseDefinitionId);
return this;
}
@Override
public SignalEventListenerInstanceQuery elementId(String elementId) {
innerQuery.planItemInstanceElementId(elementId);
return this;
}
@Override
public SignalEventListenerInstanceQuery planItemDefinitionId(String planItemDefinitionId) {
innerQuery.planItemDefinitionId(planItemDefinitionId);
return this;
}
@Override
public SignalEventListenerInstanceQuery name(String name) {
innerQuery.planItemInstanceName(name);
return this;
}
@Override
public SignalEventListenerInstanceQuery stageInstanceId(String stageInstanceId) {
innerQuery.stageInstanceId(stageInstanceId);
return this;
}
@Override
public SignalEventListenerInstanceQuery stateAvailable() {
innerQuery.planItemInstanceStateAvailable();
return this;
}
@Override
public SignalEventListenerInstanceQuery stateSuspended() {
innerQuery.planItemInstanceState(PlanItemInstanceState.SUSPENDED);
return this;
}
@Override
public SignalEventListenerInstanceQuery orderByName() {
innerQuery.orderByName();
return this;
}
@Override
public SignalEventListenerInstanceQuery asc() { | innerQuery.asc();
return this;
}
@Override
public SignalEventListenerInstanceQuery desc() {
innerQuery.desc();
return this;
}
@Override
public SignalEventListenerInstanceQuery orderBy(QueryProperty property) {
innerQuery.orderBy(property);
return this;
}
@Override
public SignalEventListenerInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) {
innerQuery.orderBy(property, nullHandlingOnOrder);
return this;
}
@Override
public long count() {
return innerQuery.count();
}
@Override
public SignalEventListenerInstance singleResult() {
PlanItemInstance instance = innerQuery.singleResult();
return SignalEventListenerInstanceImpl.fromPlanItemInstance(instance);
}
@Override
public List<SignalEventListenerInstance> list() {
return convertPlanItemInstances(innerQuery.list());
}
@Override
public List<SignalEventListenerInstance> listPage(int firstResult, int maxResults) {
return convertPlanItemInstances(innerQuery.listPage(firstResult, maxResults));
}
protected List<SignalEventListenerInstance> convertPlanItemInstances(List<PlanItemInstance> instances) {
if (instances == null) {
return null;
}
return instances.stream().map(SignalEventListenerInstanceImpl::fromPlanItemInstance).collect(Collectors.toList());
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\SignalEventListenerInstanceQueryImpl.java | 1 |
请完成以下Java代码 | default Optional<WindowId> getZoomIntoWindowId()
{
return Optional.empty();
}
@Override
boolean equals(Object obj);
@Override
int hashCode();
LookupDataSourceFetcher getLookupDataSourceFetcher();
boolean isHighVolume();
LookupSource getLookupSourceType();
boolean hasParameters();
boolean isNumericKey();
Set<String> getDependsOnFieldNames();
default Set<String> getDependsOnTableNames()
{
return ImmutableSet.of();
}
default Class<?> getValueClass()
{
return isNumericKey() ? IntegerLookupValue.class : StringLookupValue.class;
}
default int getSearchStringMinLength()
{
return -1;
}
default Optional<Duration> getSearchStartDelay()
{
return Optional.empty(); | }
default <T extends LookupDescriptor> T cast(final Class<T> ignoredLookupDescriptorClass)
{
@SuppressWarnings("unchecked")
final T thisCasted = (T)this;
return thisCasted;
}
default <T extends LookupDescriptor> T castOrNull(final Class<T> lookupDescriptorClass)
{
if (lookupDescriptorClass.isAssignableFrom(getClass()))
{
@SuppressWarnings("unchecked")
final T thisCasted = (T)this;
return thisCasted;
}
return null;
}
default TooltipType getTooltipType()
{
return TooltipType.DEFAULT;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\LookupDescriptor.java | 1 |
请完成以下Java代码 | public int getStart()
{
return this.start;
}
public int getEnd()
{
return this.end;
}
public int size()
{
return end - start + 1;
}
/**
* 是否与另一个区间交叉(有一部分重叠)
* @param other
* @return
*/
public boolean overlapsWith(Interval other)
{
return this.start <= other.getEnd() &&
this.end >= other.getStart();
}
/**
* 区间是否覆盖了这个点
* @param point
* @return
*/
public boolean overlapsWith(int point)
{
return this.start <= point && point <= this.end;
}
@Override
public boolean equals(Object o)
{
if (!(o instanceof Intervalable))
{
return false;
}
Intervalable other = (Intervalable) o;
return this.start == other.getStart() &&
this.end == other.getEnd();
}
@Override
public int hashCode()
{ | return this.start % 100 + this.end % 100;
}
@Override
public int compareTo(Object o)
{
if (!(o instanceof Intervalable))
{
return -1;
}
Intervalable other = (Intervalable) o;
int comparison = this.start - other.getStart();
return comparison != 0 ? comparison : this.end - other.getEnd();
}
@Override
public String toString()
{
return this.start + ":" + this.end;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\algorithm\ahocorasick\interval\Interval.java | 1 |
请完成以下Java代码 | public class PushMessageDTO implements Serializable {
private static final long serialVersionUID = 7431775881170684867L;
/**
* 消息标题
*/
private String title;
/**
* 消息内容
*/
private String content;
/**
* 推送形式:all:全推送 single:单用户推送
*/ | private String pushType;
/**
* 用户名usernameList
*/
List<String> usernames;
/**
* 用户名idList
*/
List<String> userIds;
/**
* 消息附加参数
*/
Map<String,Object> payload;
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\api\dto\PushMessageDTO.java | 1 |
请完成以下Java代码 | public class ConsumerStoppingEvent extends KafkaEvent {
private static final long serialVersionUID = 1L;
private transient final Consumer<?, ?> consumer;
private transient final @Nullable Collection<TopicPartition> partitions;
/**
* Construct an instance with the provided source, consumer and partitions.
* @param source the container instance that generated the event.
* @param container the container or the parent container if the container is a child.
* @param consumer the consumer.
* @param partitions the partitions.
* @since 2.2.1
*/
public ConsumerStoppingEvent(Object source, Object container,
Consumer<?, ?> consumer, @Nullable Collection<TopicPartition> partitions) { | super(source, container);
this.consumer = consumer;
this.partitions = partitions;
}
public Consumer<?, ?> getConsumer() {
return this.consumer;
}
public @Nullable Collection<TopicPartition> getPartitions() {
return this.partitions;
}
@Override
public String toString() {
return "ConsumerStoppingEvent [consumer=" + this.consumer + ", partitions=" + this.partitions + "]";
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\event\ConsumerStoppingEvent.java | 1 |
请完成以下Java代码 | public List<Customer> findAll3() {
String sql = "SELECT * FROM CUSTOMER";
List<Customer> customers = jdbcTemplate.query(
sql,
new BeanPropertyRowMapper(Customer.class));
return customers;
}
public List<Customer> findAll4() {
String sql = "SELECT * FROM CUSTOMER";
return jdbcTemplate.query(
sql,
(rs, rowNum) ->
new Customer(
rs.getLong("id"),
rs.getString("name"),
rs.getInt("age"),
rs.getTimestamp("created_date").toLocalDateTime()
)
);
}
public String findCustomerNameById(Long id) {
String sql = "SELECT NAME FROM CUSTOMER WHERE ID = ?";
return jdbcTemplate.queryForObject(
sql, new Object[]{id}, String.class); | }
public int count() {
String sql = "SELECT COUNT(*) FROM CUSTOMER";
// queryForInt() is Deprecated
// https://www.mkyong.com/spring/jdbctemplate-queryforint-is-deprecated/
//int total = jdbcTemplate.queryForInt(sql);
return jdbcTemplate.queryForObject(sql, Integer.class);
}
} | repos\spring-boot-master\spring-jdbc\src\main\java\com\mkyong\customer\CustomerRepository.java | 1 |
请完成以下Java代码 | private I_C_OrderLine createOrderLine(final PurchaseCandidate candidate)
{
final int flatrateDataEntryId = candidate.getC_Flatrate_DataEntry_ID();
final int huPIItemProductId = candidate.getM_HU_PI_Item_Product_ID();
final Timestamp datePromised = candidate.getDatePromised();
final BigDecimal price = candidate.getPrice();
final I_C_OrderLine orderLine = orderLineBL.createOrderLine(order, I_C_OrderLine.class);
orderLine.setIsMFProcurement(true);
//
// BPartner/Location/Contact
OrderLineDocumentLocationAdapterFactory.locationAdapter(orderLine).setFromOrderHeader(order);
//
// PMM Contract
if (flatrateDataEntryId > 0)
{
orderLine.setC_Flatrate_DataEntry_ID(flatrateDataEntryId);
}
//
// Product/UOM/Handling unit
orderLine.setM_Product_ID(candidate.getM_Product_ID());
orderLine.setC_UOM_ID(candidate.getC_UOM_ID());
if (huPIItemProductId > 0)
{
orderLine.setM_HU_PI_Item_Product_ID(huPIItemProductId);
}
//
// ASI
final IAttributeSetInstanceBL attributeSetInstanceBL = Services.get(IAttributeSetInstanceBL.class);
final AttributeSetInstanceId attributeSetInstanceId = candidate.getAttributeSetInstanceId();
final I_M_AttributeSetInstance contractASI = attributeSetInstanceId.isRegular()
? attributeSetInstanceBL.getById(attributeSetInstanceId)
: null;
final I_M_AttributeSetInstance asi;
if (contractASI != null)
{
asi = attributeSetInstanceBL.copy(contractASI);
} | else
{
asi = null;
}
orderLine.setPMM_Contract_ASI(contractASI);
orderLine.setM_AttributeSetInstance(asi);
//
// Quantities
orderLine.setQtyEntered(BigDecimal.ZERO);
orderLine.setQtyOrdered(BigDecimal.ZERO);
//
// Dates
orderLine.setDatePromised(datePromised);
//
// Pricing
orderLine.setIsManualPrice(true); // go with the candidate's price. e.g. don't reset it to 0 because we have no PL
orderLine.setPriceEntered(price);
orderLine.setPriceActual(price);
//
// BPartner/Location/Contact
return orderLine;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\OrderLineAggregation.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SpringWebConfig implements WebMvcConfigurer { // , ApplicationContextAware {
@Autowired
public SpringWebConfig(SpringResourceTemplateResolver templateResolver) {
super();
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
}
/*
* Dispatcher configuration for serving static resources
*/
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) { | WebMvcConfigurer.super.addResourceHandlers(registry);
registry.addResourceHandler("/images/**")
.addResourceLocations("/images/");
registry.addResourceHandler("/css/**")
.addResourceLocations("/css/");
registry.addResourceHandler("/js/**")
.addResourceLocations("/js/");
}
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.addBasenames("name-analysis");
return messageSource;
}
} | repos\tutorials-master\spring-web-modules\spring-thymeleaf-attributes\accessing-session-attributes\src\main\java\com\baeldung\accesing_session_attributes\web\SpringWebConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Publisher {
@Id
private ObjectId id;
private String name;
public Publisher() {
}
public Publisher(ObjectId id, String name) {
this.id = id;
this.name = name;
}
public ObjectId getId() {
return id;
}
public void setId(ObjectId id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Catalog [id=" + id + ", name=" + name + "]";
}
@Override
public int hashCode() {
final int prime = 31; | int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Publisher other = (Publisher) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
} | repos\tutorials-master\persistence-modules\java-mongodb\src\main\java\com\baeldung\bsontojson\Publisher.java | 2 |
请完成以下Java代码 | protected List<Term> roughSegSentence(char[] sentence)
{
char[] tag = model.tag(sentence);
List<Term> termList = new LinkedList<Term>();
int offset = 0;
for (int i = 0; i < tag.length; offset += 1, ++i)
{
switch (tag[i])
{
case 'b':
{
int begin = offset;
while (tag[i] != 'e')
{
offset += 1;
++i;
if (i == tag.length)
{
break;
}
} | if (i == tag.length)
{
termList.add(new Term(new String(sentence, begin, offset - begin), null));
}
else
termList.add(new Term(new String(sentence, begin, offset - begin + 1), null));
}
break;
default:
{
termList.add(new Term(new String(sentence, offset, 1), null));
}
break;
}
}
return termList;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\HMM\HMMSegment.java | 1 |
请完成以下Java代码 | public SetMultimap<PaymentId, InvoiceId> retrieveInvoiceIdsByPaymentIds(@NonNull final Collection<PaymentId> paymentIds)
{
if (paymentIds.isEmpty())
{
return ImmutableSetMultimap.of();
}
final IQuery<I_C_AllocationHdr> completedAllocations = queryBL.createQueryBuilder(I_C_AllocationHdr.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_C_AllocationHdr.COLUMNNAME_DocStatus, DocStatus.Completed, DocStatus.Closed)
.create();
return queryBL.createQueryBuilder(I_C_AllocationLine.class)
.addOnlyActiveRecordsFilter()
.addNotNull(I_C_AllocationLine.COLUMNNAME_C_Invoice_ID)
.addNotNull(I_C_AllocationLine.COLUMNNAME_C_Payment_ID)
.addInArrayFilter(I_C_AllocationLine.COLUMNNAME_C_Payment_ID, paymentIds)
.addInSubQueryFilter(I_C_AllocationLine.COLUMN_C_AllocationHdr_ID, I_C_AllocationHdr.COLUMN_C_AllocationHdr_ID, completedAllocations)
.create()
.list()
.stream() | .collect(ImmutableSetMultimap.toImmutableSetMultimap(
record -> PaymentId.ofRepoId(record.getC_Payment_ID()),
record -> InvoiceId.ofRepoIdOrNull(record.getC_Invoice_ID())));
}
@Override
public @NonNull I_C_AllocationHdr getById(@NonNull final PaymentAllocationId allocationId)
{
return InterfaceWrapperHelper.load(allocationId, I_C_AllocationHdr.class);
}
@Override
public @NonNull I_C_AllocationLine getLineById(@NonNull final PaymentAllocationLineId lineId)
{
return queryBL.createQueryBuilder(I_C_AllocationLine.class)
.addEqualsFilter(I_C_AllocationLine.COLUMNNAME_C_AllocationHdr_ID, lineId.getHeaderId())
.addEqualsFilter(I_C_AllocationLine.COLUMNNAME_C_AllocationLine_ID, lineId.getRepoId())
.create()
.firstOnlyNotNull();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\allocation\api\impl\AllocationDAO.java | 1 |
请完成以下Java代码 | public class ImageFile extends GenericFile {
private int height;
private int width;
public ImageFile(String name, int height, int width, byte[] content, String version) {
this.setHeight(height);
this.setWidth(width);
this.setContent(content);
this.setName(name);
this.setVersion(version);
this.setExtension(".jpg");
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height; | }
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public String getFileInfo() {
return "Image File Impl";
}
public String read() {
return this.getContent()
.toString();
}
} | repos\tutorials-master\core-java-modules\core-java-lang-oop-inheritance-2\src\main\java\com\baeldung\polymorphism\ImageFile.java | 1 |
请完成以下Java代码 | protected boolean deploymentsDiffer(DeploymentEntity deployment, DeploymentEntity saved) {
if (deploymentBuilder.hasEnforcedAppVersion()) {
return deploymentsDifferWhenEnforcedAppVersionIsSet(saved);
} else if (deploymentBuilder.hasProjectManifestSet()) {
return deploymentsDifferWhenProjectManifestIsSet(deployment, saved);
} else {
return deploymentsDifferDefault(deployment, saved);
}
}
private boolean deploymentsDifferWhenEnforcedAppVersionIsSet(DeploymentEntity saved) {
return !deploymentBuilder.getEnforcedAppVersion().equals(saved.getVersion());
}
private boolean deploymentsDifferWhenProjectManifestIsSet(DeploymentEntity deployment, DeploymentEntity saved) {
return !deployment.getProjectReleaseVersion().equals(saved.getProjectReleaseVersion());
}
private boolean deploymentsDifferDefault(DeploymentEntity deployment, DeploymentEntity saved) {
if (deployment.getResources() == null || saved.getResources() == null) {
return true;
}
Map<String, ResourceEntity> resources = deployment.getResources();
Map<String, ResourceEntity> savedResources = saved.getResources();
for (String resourceName : resources.keySet()) {
ResourceEntity savedResource = savedResources.get(resourceName);
if (savedResource == null) {
return true;
}
if (!savedResource.isGenerated()) {
ResourceEntity resource = resources.get(resourceName);
byte[] bytes = resource.getBytes();
byte[] savedBytes = savedResource.getBytes();
if (!Arrays.equals(bytes, savedBytes)) {
return true;
}
}
}
return false;
} | protected void scheduleProcessDefinitionActivation(CommandContext commandContext, DeploymentEntity deployment) {
for (ProcessDefinitionEntity processDefinitionEntity : deployment.getDeployedArtifacts(
ProcessDefinitionEntity.class
)) {
// If activation date is set, we first suspend all the process
// definition
SuspendProcessDefinitionCmd suspendProcessDefinitionCmd = new SuspendProcessDefinitionCmd(
processDefinitionEntity,
false,
null,
deployment.getTenantId()
);
suspendProcessDefinitionCmd.execute(commandContext);
// And we schedule an activation at the provided date
ActivateProcessDefinitionCmd activateProcessDefinitionCmd = new ActivateProcessDefinitionCmd(
processDefinitionEntity,
false,
deploymentBuilder.getProcessDefinitionsActivationDate(),
deployment.getTenantId()
);
activateProcessDefinitionCmd.execute(commandContext);
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\DeployCmd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public SecurityFilterChain filterChain(HttpSecurity http, MvcRequestMatcher.Builder mvc) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry ->
authorizationManagerRequestMatcherRegistry
.requestMatchers(mvc.pattern("/anonymous*")).anonymous()
.requestMatchers(mvc.pattern("/login*"), mvc.pattern("/invalidSession*"), mvc.pattern("/sessionExpired*"),
mvc.pattern("/foo/**")).permitAll()
.anyRequest().authenticated())
.formLogin(httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.loginPage("/login")
.loginProcessingUrl("/login")
.successHandler(successHandler())
.failureUrl("/login?error=true"))
.logout(httpSecurityLogoutConfigurer -> httpSecurityLogoutConfigurer.deleteCookies("JSESSIONID"))
.rememberMe(httpSecurityRememberMeConfigurer ->
httpSecurityRememberMeConfigurer.key("uniqueAndSecret")
.tokenValiditySeconds(86400))
.sessionManagement(httpSecuritySessionManagementConfigurer ->
httpSecuritySessionManagementConfigurer.sessionFixation()
.migrateSession().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.invalidSessionUrl("/invalidSession")
.maximumSessions(2)
.expiredUrl("/sessionExpired"));
return http.build();
}
private AuthenticationSuccessHandler successHandler() {
return new MySimpleUrlAuthenticationSuccessHandler(); | }
@Bean
public HttpSessionEventPublisher httpSessionEventPublisher() {
return new HttpSessionEventPublisher();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
MvcRequestMatcher.Builder mvc(HandlerMappingIntrospector introspector) {
return new MvcRequestMatcher.Builder(introspector);
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-mvc\src\main\java\com\baeldung\session\security\config\SecSecurityConfig.java | 2 |
请完成以下Java代码 | public void setRevision (final @Nullable java.lang.String Revision)
{
set_Value (COLUMNNAME_Revision, Revision);
}
@Override
public java.lang.String getRevision()
{
return get_ValueAsString(COLUMNNAME_Revision);
}
@Override
public org.compiere.model.I_AD_Sequence getSerialNo_Sequence()
{
return get_ValueAsPO(COLUMNNAME_SerialNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class);
}
@Override
public void setSerialNo_Sequence(final org.compiere.model.I_AD_Sequence SerialNo_Sequence)
{
set_ValueFromPO(COLUMNNAME_SerialNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class, SerialNo_Sequence);
}
@Override
public void setSerialNo_Sequence_ID (final int SerialNo_Sequence_ID)
{
if (SerialNo_Sequence_ID < 1)
set_Value (COLUMNNAME_SerialNo_Sequence_ID, null);
else
set_Value (COLUMNNAME_SerialNo_Sequence_ID, SerialNo_Sequence_ID);
}
@Override
public int getSerialNo_Sequence_ID()
{
return get_ValueAsInt(COLUMNNAME_SerialNo_Sequence_ID);
} | @Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_BOM.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HystrixAspect {
private HystrixCommand.Setter config;
private HystrixCommandProperties.Setter commandProperties;
private HystrixThreadPoolProperties.Setter threadPoolProperties;
@Value("${remoteservice.command.execution.timeout}")
private int executionTimeout;
@Value("${remoteservice.command.sleepwindow}")
private int sleepWindow;
@Value("${remoteservice.command.threadpool.maxsize}")
private int maxThreadCount;
@Value("${remoteservice.command.threadpool.coresize}")
private int coreThreadCount;
@Value("${remoteservice.command.task.queue.size}")
private int queueCount;
@Value("${remoteservice.command.group.key}")
private String groupKey;
@Value("${remoteservice.command.key}")
private String key;
@Around("@annotation(com.baeldung.hystrix.HystrixCircuitBreaker)")
public Object circuitBreakerAround(final ProceedingJoinPoint aJoinPoint) {
return new RemoteServiceCommand(config, aJoinPoint).execute();
}
@PostConstruct
private void setup() {
this.config = HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey));
this.config = config.andCommandKey(HystrixCommandKey.Factory.asKey(key)); | this.commandProperties = HystrixCommandProperties.Setter();
this.commandProperties.withExecutionTimeoutInMilliseconds(executionTimeout);
this.commandProperties.withCircuitBreakerSleepWindowInMilliseconds(sleepWindow);
this.threadPoolProperties = HystrixThreadPoolProperties.Setter();
this.threadPoolProperties.withMaxQueueSize(maxThreadCount).withCoreSize(coreThreadCount).withMaxQueueSize(queueCount);
this.config.andCommandPropertiesDefaults(commandProperties);
this.config.andThreadPoolPropertiesDefaults(threadPoolProperties);
}
private static class RemoteServiceCommand extends HystrixCommand<String> {
private final ProceedingJoinPoint joinPoint;
RemoteServiceCommand(final Setter config, final ProceedingJoinPoint joinPoint) {
super(config);
this.joinPoint = joinPoint;
}
@Override
protected String run() throws Exception {
try {
return (String) joinPoint.proceed();
} catch (final Throwable th) {
throw new Exception(th);
}
}
}
} | repos\tutorials-master\hystrix\src\main\java\com\baeldung\hystrix\HystrixAspect.java | 2 |
请完成以下Java代码 | public I_M_HU current()
{
Check.assume(currentItemSet, "has current item");
return currentItem;
}
public void closeCurrent()
{
currentItemSet = false;
currentItem = null;
}
public boolean hasCurrent()
{
return currentItemSet;
}
public boolean hasNext()
{
final int size = list.size();
if (currentIndex < 0)
{
return size > 0;
}
else
{
return currentIndex + 1 < size;
}
}
public I_M_HU next()
{
// Calculate the next index
final int nextIndex;
if (currentIndex < 0)
{ | nextIndex = 0;
}
else
{
nextIndex = currentIndex + 1;
}
// Make sure the new index is valid
final int size = list.size();
if (nextIndex >= size)
{
throw new NoSuchElementException("index=" + nextIndex + ", size=" + size);
}
// Update status
this.currentIndex = nextIndex;
this.currentItem = list.get(nextIndex);
this.currentItemSet = true;
return currentItem;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\util\HUListCursor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BookstoreService {
private final AuthorRepository authorRepository;
public BookstoreService(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
@Transactional
public void registerAuthor() {
Author a1 = new Author();
a1.setName("Quartis Young");
a1.setGenre("Anthology");
a1.setAge(34);
Author a2 = new Author();
a2.setName("Mark Janel");
a2.setGenre("Anthology");
a2.setAge(23);
Book b1 = new Book();
b1.setIsbn("001");
b1.setTitle("The Beatles Anthology");
Book b2 = new Book();
b2.setIsbn("002");
b2.setTitle("A People's Anthology");
Book b3 = new Book();
b3.setIsbn("003");
b3.setTitle("Anthology Myths");
a1.addBook(b1);
a1.addBook(b2);
a2.addBook(b3); | authorRepository.save(a1);
authorRepository.save(a2);
}
@Transactional
public void updateAuthor() {
Author author = authorRepository.findByName("Mark Janel");
author.setAge(45);
}
@Transactional
public void updateBooks() {
Author author = authorRepository.findByName("Quartis Young");
List<Book> books = author.getBooks();
for (Book book : books) {
book.setIsbn("not available");
}
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootAudit\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | public class LargestSubarraySumZero {
public static int maxLenBruteForce(int[] arr) {
int maxLength = 0;
for (int i = 0; i < arr.length; i++) {
int sum = 0;
for (int j = i; j < arr.length; j++) {
sum += arr[j];
if (sum == 0) {
maxLength = Math.max(maxLength, j - i + 1);
}
}
}
return maxLength;
}
public static int maxLenHashMap(int[] arr) {
HashMap<Integer, Integer> map = new HashMap<>(); | int sum = 0;
int maxLength = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
if (sum == 0) {
maxLength = i + 1;
}
if (map.containsKey(sum)) {
maxLength = Math.max(maxLength, i - map.get(sum));
} else {
map.put(sum, i);
}
}
return maxLength;
}
} | repos\tutorials-master\algorithms-modules\algorithms-numeric\src\main\java\com\baeldung\algorithms\subarraysumzero\LargestSubarraySumZero.java | 1 |
请完成以下Java代码 | public class Password implements CharSequence {
private @Delegate final String password;
private @Getter transient boolean encrypted;
Password() {
this.password = null;
this.encrypted = true;
}
/**
* Creates a new raw {@link Password} for the given source {@link String}.
*
* @param password must not be {@literal null} or empty.
* @return
*/
public static Password raw(String password) {
return new Password(password, false);
}
/**
* Creates a new encrypted {@link Password} for the given {@link String}. Note how this method is package protected so
* that encrypted passwords can only be created by components in this package and not accidentally by clients using the
* type from other packages.
* | * @param password must not be {@literal null} or empty.
* @return
*/
static Password encrypted(String password) {
return new Password(password, true);
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
return encrypted ? password : "********";
}
} | repos\spring-data-examples-main\web\example\src\main\java\example\users\Password.java | 1 |
请完成以下Java代码 | public boolean isLwm2mServer() {
return isLwm2mServer;
}
/**
* Checks whether a given ID represents a valid LwM2M Server (1–65534).
* @param id Short Server ID value.
* @return true if the ID belongs to a standard LwM2M Server.
*/
public static boolean isLwm2mServer(Integer id) {
return id != null && id >= PRIMARY_LWM2M_SERVER.id && id <= LWM2M_SERVER_MAX.id;
}
public static boolean isNotLwm2mServer(Integer id) {
return id == null || id < PRIMARY_LWM2M_SERVER.id || id > LWM2M_SERVER_MAX.id;
}
/**
* Returns a {@link Lwm2mServerIdentifier} instance matching the given ID.
* @param id numeric ID.
* @return corresponding enum constant. | * @throws IllegalArgumentException if no constant matches the given ID.
*/
public static Lwm2mServerIdentifier fromId(Integer id) {
for (Lwm2mServerIdentifier s : values()) {
if (s.id == id) {
return s;
}
}
throw new IllegalArgumentException("Unknown Lwm2mServerIdentifier: " + id);
}
@Override
public String toString() {
return name() + "(" + id + ") - " + description;
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\device\credentials\lwm2m\Lwm2mServerIdentifier.java | 1 |
请完成以下Java代码 | public class GeodbObject
{
final private int geodb_loc_id;
final private String city;
private String city_7bitlc;
final private String zip;
final private double lon;
final private double lat;
private int C_Country_ID = -1;
private String countryName = null;
//
private String stringRepresentation = null;
public GeodbObject(int geodb_loc_id, String city, String zip, double lon, double lat)
{
super();
this.geodb_loc_id = geodb_loc_id;
this.city = city;
this.zip = zip;
this.lon = lon;
this.lat = lat;
}
public int getGeodb_loc_id()
{
return geodb_loc_id;
}
public String getCity()
{
return city;
}
public String getZip()
{
return zip;
}
public double getLon()
{
return lon;
}
public double getLat()
{
return lat;
}
public int getC_Country_ID() {
return C_Country_ID;
}
public void setC_Country_ID(int cCountryID) {
C_Country_ID = cCountryID;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName; | }
public String getCity_7bitlc() {
return city_7bitlc;
}
public void setCity_7bitlc(String city_7bitlc) {
this.city_7bitlc = city_7bitlc;
}
public String getStringRepresentation() {
return stringRepresentation;
}
public void setStringRepresentation(String stringRepresentation) {
this.stringRepresentation = stringRepresentation;
}
@Override
public boolean equals(Object obj)
{
if (! (obj instanceof GeodbObject))
return false;
if (this == obj)
return true;
//
GeodbObject go = (GeodbObject)obj;
return this.geodb_loc_id == go.geodb_loc_id
&& this.zip.equals(go.zip)
;
}
@Override
public String toString()
{
String str = getStringRepresentation();
if (str != null)
return str;
return city+", "+zip+" - "+countryName;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\adempiere\gui\search\GeodbObject.java | 1 |
请完成以下Java代码 | public PurchaseRowId toGroupRowId()
{
if (isGroupRowId())
{
return this;
}
else
{
return groupId(purchaseDemandId);
}
}
public PurchaseRowId toLineRowId()
{
if (isLineRowId())
{
return this;
}
else
{
final boolean readonly = false;
return lineId(purchaseDemandId, vendorId, readonly);
}
} | public boolean isGroupRowId()
{
return type == PurchaseRowType.GROUP;
}
public boolean isLineRowId()
{
return type == PurchaseRowType.LINE;
}
public boolean isAvailabilityRowId()
{
return type == PurchaseRowType.AVAILABILITY_DETAIL;
}
public boolean isAvailableOnVendor()
{
assertRowType(PurchaseRowType.AVAILABILITY_DETAIL);
return getAvailabilityType().equals(Type.AVAILABLE);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseRowId.java | 1 |
请完成以下Java代码 | public static boolean hasPermission(String permission) {
return getSubject() != null && permission != null
&& permission.length() > 0
&& getSubject().isPermitted(permission);
}
/**
* 与hasPermission标签逻辑相反,当前用户没有制定权限时,验证通过。
*
* @param permission 权限名
* @return 拥有权限:true,否则false
*/
public static boolean lacksPermission(String permission) {
return !hasPermission(permission);
}
/**
* 已认证通过的用户,不包含已记住的用户,这是与user标签的区别所在。与notAuthenticated搭配使用
*
* @return 通过身份验证:true,否则false
*/
public static boolean isAuthenticated() {
return getSubject() != null && getSubject().isAuthenticated();
}
/**
* 未认证通过用户,与authenticated标签相对应。与guest标签的区别是,该标签包含已记住用户。。
*
* @return 没有通过身份验证:true,否则false
*/
public static boolean notAuthenticated() {
return !isAuthenticated();
} | /**
* 认证通过或已记住的用户。与guset搭配使用。
*
* @return 用户:true,否则 false
*/
public static boolean isUser() {
return getSubject() != null && getSubject().getPrincipal() != null;
}
/**
* 验证当前用户是否为“访客”,即未认证(包含未记住)的用户。用user搭配使用
*
* @return 访客:true,否则false
*/
public static boolean isGuest() {
return !isUser();
}
/**
* 输出当前用户信息,通常为登录帐号信息。
*
* @return 当前用户信息
*/
public static String principal() {
if (getSubject() != null) {
Object principal = getSubject().getPrincipal();
return principal.toString();
}
return "";
}
} | repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\shiro\ShiroKit.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class ReactiveOAuth2ClientConfigurations {
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(OAuth2ClientProperties.class)
@ConditionalOnOAuth2ClientRegistrationProperties
@ConditionalOnMissingBean(ReactiveClientRegistrationRepository.class)
static class ReactiveClientRegistrationRepositoryConfiguration {
@Bean
InMemoryReactiveClientRegistrationRepository reactiveClientRegistrationRepository(
OAuth2ClientProperties properties) {
List<ClientRegistration> registrations = new ArrayList<>(
new OAuth2ClientPropertiesMapper(properties).asClientRegistrations().values());
return new InMemoryReactiveClientRegistrationRepository(registrations);
} | }
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(ReactiveClientRegistrationRepository.class)
static class ReactiveOAuth2AuthorizedClientServiceConfiguration {
@Bean
@ConditionalOnMissingBean
ReactiveOAuth2AuthorizedClientService reactiveAuthorizedClientService(
ReactiveClientRegistrationRepository clientRegistrationRepository) {
return new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-security-oauth2-client\src\main\java\org\springframework\boot\security\oauth2\client\autoconfigure\reactive\ReactiveOAuth2ClientConfigurations.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class OwnerController {
@Value("${lottery.contract.owner-address}")
private String ownerAddress;
@Autowired
private Web3j web3j;
@Autowired
private LotteryService lotteryService;
@GetMapping("/owner")
public String getAddress() {
return ownerAddress;
}
@GetMapping("/owner/balance") | public Balance getBalance() throws IOException {
EthGetBalance wei = web3j.ethGetBalance(ownerAddress, DefaultBlockParameterName.LATEST).send();
return new Balance(wei.getBalance());
}
@GetMapping("/owner/lottery/players")
public List<String> getPlayers() throws Exception {
return lotteryService.getPlayers(ownerAddress);
}
@GetMapping("/owner/lottery/pickWinner")
public void pickWinner() throws Exception {
lotteryService.pickWinner(ownerAddress);
}
} | repos\springboot-demo-master\Blockchain\src\main\java\com\et\bc\controller\OwnerController.java | 2 |
请完成以下Java代码 | public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0];}
}
};
public static void main(String... args) {
try {
new EmailService("smtp.mailtrap.io", 25, "87ba3d9555fae8", "91cb4379af43ed").sendMail();
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendMail() throws Exception {
Session session = getSession();
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com"));
message.setSubject("Mail Subject");
String msg = "This is my first email using JavaMailer";
message.setContent(getMultipart(msg));
Transport.send(message);
}
public void sendMailToMultipleRecipients() throws Exception {
Session session = getSession();
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com, to1@gmail.com"));
message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("to2@gmail.com, to3@gmail.com"));
message.setSubject("Mail Subject");
String msg = "This is my first email using JavaMailer";
message.setContent(getMultipart(msg));
Transport.send(message);
}
private Multipart getMultipart(String msg) throws Exception {
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(msg, "text/html; charset=utf-8"); | String msgStyled = "This is my <b style='color:red;'>bold-red email</b> using JavaMailer";
MimeBodyPart mimeBodyPartWithStyledText = new MimeBodyPart();
mimeBodyPartWithStyledText.setContent(msgStyled, "text/html; charset=utf-8");
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
attachmentBodyPart.attachFile(getFile());
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
multipart.addBodyPart(mimeBodyPartWithStyledText);
multipart.addBodyPart(attachmentBodyPart);
return multipart;
}
private Session getSession() {
Session session = Session.getInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
return session;
}
private File getFile() throws Exception {
URI uri = this.getClass()
.getClassLoader()
.getResource("attachment.txt")
.toURI();
return new File(uri);
}
} | repos\tutorials-master\core-java-modules\core-java-networking\src\main\java\com\baeldung\mail\EmailService.java | 1 |
请完成以下Java代码 | public static List<Date> getDateRangeList(Date begin, Date end) {
List<Date> dateList = new ArrayList<>();
if (begin == null || end == null) {
return dateList;
}
// 清除时间部分,只比较日期
Calendar beginCal = Calendar.getInstance();
beginCal.setTime(begin);
beginCal.set(Calendar.HOUR_OF_DAY, 0);
beginCal.set(Calendar.MINUTE, 0);
beginCal.set(Calendar.SECOND, 0);
beginCal.set(Calendar.MILLISECOND, 0);
Calendar endCal = Calendar.getInstance();
endCal.setTime(end);
endCal.set(Calendar.HOUR_OF_DAY, 0);
endCal.set(Calendar.MINUTE, 0);
endCal.set(Calendar.SECOND, 0); | endCal.set(Calendar.MILLISECOND, 0);
if (endCal.before(beginCal)) {
return dateList;
}
dateList.add(beginCal.getTime());
while (beginCal.before(endCal)) {
beginCal.add(Calendar.DAY_OF_YEAR, 1);
dateList.add(beginCal.getTime());
}
return dateList;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\DateUtils.java | 1 |
请完成以下Java代码 | class DBConnectionMaker
{
public IDatabase createDb(
@NonNull final DBConnectionSettings settings,
@NonNull final String dbName)
{
final IDatabase db = new SQLDatabase(
settings.getDbType(),
settings.getDbHostname(),
settings.getDbPort(),
dbName,
settings.getDbUser(),
settings.getDbPassword());
return db;
}
/**
* Creates an {@link IDatabase} instance we don't intend to run migration scripts against.
* However, connecting to that DB is possible.
*/
public IDatabase createDummyDatabase(
@NonNull final DBConnectionSettings settings,
@NonNull final String dbName)
{
// return a database that does not check whether our script was applied or not
return new SQLDatabase(
settings.getDbType(),
settings.getDbHostname(),
settings.getDbPort(), | dbName,
settings.getDbUser(),
settings.getDbPassword())
{
// @formatter:off
@Override
public IScriptsRegistry getScriptsRegistry()
{
return new IScriptsRegistry()
{
@Override public void markIgnored(final IScript script) { }
@Override public void markApplied(final IScript script) { }
@Override public boolean isApplied(final IScript script) { return false; }
};
};
// @formatter:on
};
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\rollout_migrate\DBConnectionMaker.java | 1 |
请完成以下Java代码 | public int getFact_Acct_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Fact_Acct_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Zeile Nr..
@param Line
Unique line for this document
*/
@Override
public void setLine (int Line)
{ | set_Value (COLUMNNAME_Line, Integer.valueOf(Line));
}
/** Get Zeile Nr..
@return Unique line for this document
*/
@Override
public int getLine ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Line);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_TaxDeclarationAcct.java | 1 |
请完成以下Java代码 | public class FailureRequestDto extends RequestDto {
protected String errorMessage;
protected String errorDetails;
protected int retries;
protected long retryTimeout;
protected Map<String, TypedValueField> variables;
protected Map<String, TypedValueField> localVariables;
public FailureRequestDto(String workerId, String errorMessage, String errorDetails, int retries, long retryTimeout, Map<String, TypedValueField> variables, Map<String, TypedValueField> localVariables) {
super(workerId);
this.errorMessage = errorMessage;
this.errorDetails = errorDetails;
this.retries = retries;
this.retryTimeout = retryTimeout;
this.variables = variables;
this.localVariables = localVariables;
}
public String getErrorMessage() {
return errorMessage;
}
public String getErrorDetails() {
return errorDetails; | }
public int getRetries() {
return retries;
}
public long getRetryTimeout() {
return retryTimeout;
}
public Map<String, TypedValueField> getVariables() {
return variables;
}
public Map<String, TypedValueField> getLocalVariables() {
return localVariables;
}
} | repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\task\impl\dto\FailureRequestDto.java | 1 |
请完成以下Java代码 | public OrderPaymentReservationCreateResult createPaymentReservationIfNeeded(@NonNull final I_C_Order salesOrder)
{
Check.assume(salesOrder.isSOTrx(), "expected sales order but got purchase order: {}", salesOrder);
final PaymentRule paymentRule = PaymentRule.ofCode(salesOrder.getPaymentRule());
if (!paymentReservationService.isPaymentReservationRequired(paymentRule))
{
return OrderPaymentReservationCreateResult.NOT_NEEDED;
}
//
// Get existing reservation / create a new one
final OrderId salesOrderId = OrderId.ofRepoId(salesOrder.getC_Order_ID());
final PaymentReservation paymentReservation = paymentReservationService
.getBySalesOrderIdNotVoided(salesOrderId)
.orElseGet(() -> createPaymentReservation(salesOrder));
//
// Result based on payment reservation's status
final PaymentReservationStatus paymentReservationStatus = paymentReservation.getStatus();
if (PaymentReservationStatus.COMPLETED.equals(paymentReservationStatus))
{
return OrderPaymentReservationCreateResult.ALREADY_COMPLETED;
}
else if (paymentReservationStatus.isWaitingToComplete())
{
return OrderPaymentReservationCreateResult.WAITING_TO_COMPLETE;
}
else
{
throw new AdempiereException("Invalid payment reservation status: " + paymentReservationStatus)
.setParameter("paymentReservation", paymentReservation)
.setParameter("salesOrderId", salesOrderId);
}
}
private PaymentReservation createPaymentReservation(final I_C_Order salesOrder)
{
final BPartnerContactId payerContactId = ordersService.getBillToContactId(salesOrder); | return paymentReservationService.createReservation(PaymentReservationCreateRequest.builder()
.clientId(ClientId.ofRepoId(salesOrder.getAD_Client_ID()))
.orgId(OrgId.ofRepoId(salesOrder.getAD_Org_ID()))
.amount(extractGrandTotal(salesOrder))
.payerContactId(payerContactId)
.payerEmail(bpartnersRepo.getContactEMail(payerContactId))
.salesOrderId(OrderId.ofRepoId(salesOrder.getC_Order_ID()))
.dateTrx(SystemTime.asLocalDate())
.paymentRule(PaymentRule.ofCode(salesOrder.getPaymentRule()))
.build());
}
private static Money extractGrandTotal(final I_C_Order salesOrder)
{
return Money.of(salesOrder.getGrandTotal(), CurrencyId.ofRepoId(salesOrder.getC_Currency_ID()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\payment_reservation\OrderPaymentReservationService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ObjectFactory {
private final static QName _ErpelMessage_QNAME = new QName("http://erpel.at/schemas/1p0/messaging/message", "ErpelMessage");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: at.erpel.schemas._1p0.messaging.message
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link ErpelMessageType }
*
*/
public ErpelMessageType createErpelMessageType() { | return new ErpelMessageType();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link ErpelMessageType }{@code >}
*
* @param value
* Java instance representing xml element's value.
* @return
* the new instance of {@link JAXBElement }{@code <}{@link ErpelMessageType }{@code >}
*/
@XmlElementDecl(namespace = "http://erpel.at/schemas/1p0/messaging/message", name = "ErpelMessage")
public JAXBElement<ErpelMessageType> createErpelMessage(ErpelMessageType value) {
return new JAXBElement<ErpelMessageType>(_ErpelMessage_QNAME, ErpelMessageType.class, null, value);
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\messaging\message\ObjectFactory.java | 2 |
请完成以下Java代码 | public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* TooltipIconName AD_Reference_ID=540912
* Reference name: TooltipIcon
*/
public static final int TOOLTIPICONNAME_AD_Reference_ID=540912;
/** text = text */
public static final String TOOLTIPICONNAME_Text = "text";
/** Set Tooltip Icon Name.
@param TooltipIconName Tooltip Icon Name */
@Override
public void setTooltipIconName (java.lang.String TooltipIconName)
{
set_Value (COLUMNNAME_TooltipIconName, TooltipIconName);
}
/** Get Tooltip Icon Name.
@return Tooltip Icon Name */
@Override
public java.lang.String getTooltipIconName ()
{
return (java.lang.String)get_Value(COLUMNNAME_TooltipIconName);
}
/**
* Type AD_Reference_ID=540910
* Reference name: Type_AD_UI_ElementField | */
public static final int TYPE_AD_Reference_ID=540910;
/** widget = widget */
public static final String TYPE_Widget = "widget";
/** tooltip = tooltip */
public static final String TYPE_Tooltip = "tooltip";
/** Set Art.
@param Type Art */
@Override
public void setType (java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
/** Get Art.
@return Art */
@Override
public java.lang.String getType ()
{
return (java.lang.String)get_Value(COLUMNNAME_Type);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UI_ElementField.java | 1 |
请完成以下Java代码 | public void setEntityType (java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitäts-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public java.lang.String getEntityType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** Set Sql FROM.
@param FromClause | SQL FROM clause
*/
@Override
public void setFromClause (java.lang.String FromClause)
{
set_Value (COLUMNNAME_FromClause, FromClause);
}
/** Get Sql FROM.
@return SQL FROM clause
*/
@Override
public java.lang.String getFromClause ()
{
return (java.lang.String)get_Value(COLUMNNAME_FromClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_InfoWindow_From.java | 1 |
请完成以下Java代码 | public class MigrationLoader
{
private final transient Logger logger = LogManager.getLogger(getClass());
public void load(Properties ctx)
{
scanClasspath();
scanMetasfreshHome();
}
private void scanClasspath()
{
final String resourceName = "/org/adempiere/migration/Migration.xml";
final InputStream inputStream = getClass().getResourceAsStream(resourceName);
if (inputStream == null)
{
logger.info("Resource name not found: " + resourceName + ". Skip migration.");
return;
}
final XMLLoader loader = new XMLLoader(inputStream);
load(loader);
}
private void scanMetasfreshHome()
{
final File home = new File(Adempiere.getMetasfreshHome() + File.separator + "migration");
if (!home.exists() && !home.isDirectory())
{
logger.warn("No migration directory found (" + home + ")");
return;
}
logger.info("Processing migration files in directory: " + home.getAbsolutePath());
final File[] migrationFiles = home.listFiles(new FilenameFilter()
{
@Override
public boolean accept(final File dir, final String name)
{
return name.endsWith(".xml");
}
});
for (final File migrationFile : migrationFiles)
{
final XMLLoader loader = new XMLLoader(migrationFile.getAbsolutePath());
load(loader);
} | }
private void load(final XMLLoader loader)
{
loader.load(ITrx.TRXNAME_None);
for (Object o : loader.getObjects())
{
if (o instanceof I_AD_Migration)
{
final I_AD_Migration migration = (I_AD_Migration)o;
execute(migration);
}
else
{
logger.warn("Unhandled type " + o + " [SKIP]");
}
}
}
private void execute(I_AD_Migration migration)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(migration);
final int migrationId = migration.getAD_Migration_ID();
final IMigrationExecutorProvider executorProvider = Services.get(IMigrationExecutorProvider.class);
final IMigrationExecutorContext migrationCtx = executorProvider.createInitialContext(ctx);
migrationCtx.setFailOnFirstError(true);
final IMigrationExecutor executor = executorProvider.newMigrationExecutor(migrationCtx, migrationId);
executor.setCommitLevel(IMigrationExecutor.CommitLevel.Batch);
executor.execute(IMigrationExecutor.Action.Apply);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\process\MigrationLoader.java | 1 |
请完成以下Java代码 | protected static <T> T getDefaultValue(MailServerInfo serverInfo, MailServerInfo fallbackServerInfo, Function<MailServerInfo, T> valueProvider) {
T value = null;
if (serverInfo != null) {
value = valueProvider.apply(serverInfo);
}
if (value == null) {
value = valueProvider.apply(fallbackServerInfo);
}
return value;
}
protected static Collection<String> getForceTo(MailServerInfo serverInfo, MailServerInfo fallbackServerInfo) {
String forceTo = null;
if (serverInfo != null) { | forceTo = serverInfo.getMailServerForceTo();
}
if (forceTo == null) {
forceTo = fallbackServerInfo.getMailServerForceTo();
}
if (forceTo == null) {
return Collections.emptyList();
}
return Arrays.stream(forceTo.split(",")).map(String::trim).toList();
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\cfg\mail\FlowableMailClientCreator.java | 1 |
请完成以下Java代码 | public int getC_Project_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Project_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_Recurring getC_Recurring() throws RuntimeException
{
return (I_C_Recurring)MTable.get(getCtx(), I_C_Recurring.Table_Name)
.getPO(getC_Recurring_ID(), get_TrxName()); }
/** Set Recurring.
@param C_Recurring_ID
Recurring Document
*/
public void setC_Recurring_ID (int C_Recurring_ID)
{
if (C_Recurring_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Recurring_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Recurring_ID, Integer.valueOf(C_Recurring_ID));
}
/** Get Recurring.
@return Recurring Document
*/
public int getC_Recurring_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Recurring_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Recurring Run.
@param C_Recurring_Run_ID
Recurring Document Run
*/
public void setC_Recurring_Run_ID (int C_Recurring_Run_ID)
{
if (C_Recurring_Run_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Recurring_Run_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Recurring_Run_ID, Integer.valueOf(C_Recurring_Run_ID));
}
/** Get Recurring Run.
@return Recurring Document Run
*/
public int getC_Recurring_Run_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Recurring_Run_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Document Date.
@param DateDoc
Date of the Document
*/
public void setDateDoc (Timestamp DateDoc)
{
set_Value (COLUMNNAME_DateDoc, DateDoc);
}
/** Get Document Date. | @return Date of the Document
*/
public Timestamp getDateDoc ()
{
return (Timestamp)get_Value(COLUMNNAME_DateDoc);
}
public I_GL_JournalBatch getGL_JournalBatch() throws RuntimeException
{
return (I_GL_JournalBatch)MTable.get(getCtx(), I_GL_JournalBatch.Table_Name)
.getPO(getGL_JournalBatch_ID(), get_TrxName()); }
/** Set Journal Batch.
@param GL_JournalBatch_ID
General Ledger Journal Batch
*/
public void setGL_JournalBatch_ID (int GL_JournalBatch_ID)
{
if (GL_JournalBatch_ID < 1)
set_ValueNoCheck (COLUMNNAME_GL_JournalBatch_ID, null);
else
set_ValueNoCheck (COLUMNNAME_GL_JournalBatch_ID, Integer.valueOf(GL_JournalBatch_ID));
}
/** Get Journal Batch.
@return General Ledger Journal Batch
*/
public int getGL_JournalBatch_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GL_JournalBatch_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_C_Recurring_Run.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class TodoControllerWithSessionAttributes {
@GetMapping("/form")
public String showForm(
Model model,
@ModelAttribute("todos") TodoList todos) {
if (!todos.isEmpty()) {
model.addAttribute("todo", todos.peekLast());
} else {
model.addAttribute("todo", new TodoItem());
}
return "sessionattributesform";
}
@PostMapping("/form")
public RedirectView create(
@ModelAttribute TodoItem todo,
@ModelAttribute("todos") TodoList todos,
RedirectAttributes attributes) {
todo.setCreateDate(LocalDateTime.now()); | todos.add(todo);
attributes.addFlashAttribute("todos", todos);
return new RedirectView("/sessionattributes/todos.html");
}
@GetMapping("/todos.html")
public String list(
Model model,
@ModelAttribute("todos") TodoList todos) {
model.addAttribute("todos", todos);
return "sessionattributestodos";
}
@ModelAttribute("todos")
public TodoList todos() {
return new TodoList();
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-forms-thymeleaf\src\main\java\com\baeldung\sessionattrs\TodoControllerWithSessionAttributes.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class AssetProfileInfo extends EntityInfo {
@Schema(description = "Either URL or Base64 data of the icon. Used in the mobile application to visualize set of asset profiles in the grid view. ")
private final String image;
@Schema(description = "Reference to the dashboard. Used in the mobile application to open the default dashboard when user navigates to asset details.")
private final DashboardId defaultDashboardId;
@Schema(description = "Tenant id.")
private final TenantId tenantId;
@JsonCreator
public AssetProfileInfo(@JsonProperty("id") EntityId id,
@JsonProperty("tenantId") TenantId tenantId,
@JsonProperty("name") String name,
@JsonProperty("image") String image,
@JsonProperty("defaultDashboardId") DashboardId defaultDashboardId) {
super(id, name);
this.tenantId = tenantId;
this.image = image; | this.defaultDashboardId = defaultDashboardId;
}
public AssetProfileInfo(UUID uuid, UUID tenantId, String name, String image, UUID defaultDashboardId) {
super(EntityIdFactory.getByTypeAndUuid(EntityType.ASSET_PROFILE, uuid), name);
this.tenantId = TenantId.fromUUID(tenantId);
this.image = image;
this.defaultDashboardId = defaultDashboardId != null ? new DashboardId(defaultDashboardId) : null;
}
public AssetProfileInfo(AssetProfile profile) {
this(profile.getId(), profile.getTenantId(), profile.getName(), profile.getImage(), profile.getDefaultDashboardId());
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\asset\AssetProfileInfo.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private void getCurrencies(final Exchange exchange)
{
final GetCurrenciesRequest getCurrenciesRequest = exchange.getIn().getBody(GetCurrenciesRequest.class);
if (getCurrenciesRequest == null)
{
throw new RuntimeException("No getCurrenciesRequest provided!");
}
final PInstanceLogger pInstanceLogger = PInstanceLogger.of(processLogger);
final ShopwareClient shopwareClient = ShopwareClient
.of(getCurrenciesRequest.getClientId(), getCurrenciesRequest.getClientSecret(), getCurrenciesRequest.getBaseUrl(), pInstanceLogger);
final JsonCurrencies currencies = shopwareClient.getCurrencies(); | if (CollectionUtils.isEmpty(currencies.getCurrencyList()))
{
throw new RuntimeException("No currencies return from Shopware!");
}
final ImmutableMap<String, String> currencyId2IsoCode = currencies.getCurrencyList().stream()
.collect(ImmutableMap.toImmutableMap(JsonCurrency::getId, JsonCurrency::getIsoCode));
final CurrencyInfoProvider currencyInfoProvider = CurrencyInfoProvider.builder()
.currencyId2IsoCode(currencyId2IsoCode)
.build();
exchange.getIn().setBody(currencyInfoProvider);
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\currency\GetCurrenciesRoute.java | 2 |
请完成以下Java代码 | public static I_C_Order extend(@NonNull final I_C_Order existentOrder)
{
if (I_C_Order.CONTRACTSTATUS_Extended.equals(existentOrder.getContractStatus()))
{
throw new AdempiereException(MSG_EXTEND_CONTRACT_ALREADY_PROLONGED);
}
else
{
final I_C_Order newOrder = InterfaceWrapperHelper.newInstance(I_C_Order.class, existentOrder);
final PO newOrderPO = InterfaceWrapperHelper.getPO(newOrder);
final PO existentOrderPO = InterfaceWrapperHelper.getPO(existentOrder);
PO.copyValues(existentOrderPO, newOrderPO, true);
InterfaceWrapperHelper.save(newOrder);
CopyRecordFactory.getCopyRecordSupport(I_C_Order.Table_Name)
.copyChildren(newOrderPO, existentOrderPO);
newOrder.setDocStatus(DocStatus.Drafted.getCode());
newOrder.setDocAction(X_C_Order.DOCACTION_Complete);
final I_C_Flatrate_Term lastTerm = Services.get(ISubscriptionBL.class).retrieveLastFlatrateTermFromOrder(existentOrder);
if (lastTerm != null)
{
final Timestamp addDays = TimeUtil.addDays(lastTerm.getEndDate(), 1); | newOrder.setDatePromised(addDays);
newOrder.setPreparationDate(addDays);
}
InterfaceWrapperHelper.save(newOrder);
// link the existent order to the new one
existentOrder.setRef_FollowupOrder_ID(newOrder.getC_Order_ID());
InterfaceWrapperHelper.save(existentOrder);
return newOrder;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\impl\subscriptioncommands\ExtendContractOrder.java | 1 |
请完成以下Java代码 | public class JeecgOneToMainUtil {
/**
* 一对多(父子表)数据模型,生成方法
* @param args
*/
public static void main(String[] args) {
//第一步:设置主表配置
MainTableVo mainTable = new MainTableVo();
//表名
mainTable.setTableName("jeecg_order_main");
//实体名
mainTable.setEntityName("GuiTestOrderMain");
//包名
mainTable.setEntityPackage("gui");
//描述
mainTable.setFtlDescription("GUI订单管理");
//第二步:设置子表集合配置
List<SubTableVo> subTables = new ArrayList<SubTableVo>();
//[1].子表一
SubTableVo po = new SubTableVo();
//表名
po.setTableName("jeecg_order_customer");
//实体名
po.setEntityName("GuiTestOrderCustom");
//包名
po.setEntityPackage("gui");
//描述
po.setFtlDescription("客户明细");
//子表外键参数配置
/*说明:
* a) 子表引用主表主键ID作为外键,外键字段必须以_ID结尾;
* b) 主表和子表的外键字段名字,必须相同(除主键ID外);
* c) 多个外键字段,采用逗号分隔;
*/
po.setForeignKeys(new String[]{"order_id"});
subTables.add(po);
//[2].子表二
SubTableVo po2 = new SubTableVo();
//表名
po2.setTableName("jeecg_order_ticket");
//实体名
po2.setEntityName("GuiTestOrderTicket"); | //包名
po2.setEntityPackage("gui");
//描述
po2.setFtlDescription("产品明细");
//子表外键参数配置
/*说明:
* a) 子表引用主表主键ID作为外键,外键字段必须以_ID结尾;
* b) 主表和子表的外键字段名字,必须相同(除主键ID外);
* c) 多个外键字段,采用逗号分隔;
*/
po2.setForeignKeys(new String[]{"order_id"});
subTables.add(po2);
mainTable.setSubTables(subTables);
//第三步:一对多(父子表)数据模型,代码生成
try {
new CodeGenerateOneToMany(mainTable,subTables).generateCodeFile(null);
} catch (Exception e) {
e.printStackTrace();
}
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-start\src\main\java\org\jeecg\codegenerate\JeecgOneToMainUtil.java | 1 |
请完成以下Java代码 | private ExplainedOptional<NameAndGreeting> computeForTwoContacts(
@NonNull final ComputeNameAndGreetingRequest.Contact person1,
@NonNull final ComputeNameAndGreetingRequest.Contact person2,
@NonNull final String adLanguage)
{
final GreetingId greetingId = greetingRepo.getComposite(person1.getGreetingId(), person2.getGreetingId())
.map(Greeting::getId)
.orElse(null);
if (!Objects.equals(person1.getLastName(), person2.getLastName()))
{
final String nameComposite = TranslatableStrings.builder()
.append(person1.getFirstName())
.append(" ")
.append(person1.getLastName())
.append(" ")
.appendADMessage(MSG_And)
.append(" ")
.append(person2.getFirstName())
.append(" ")
.append(person2.getLastName())
.build()
.translate(adLanguage);
return ExplainedOptional.of(NameAndGreeting.builder()
.name(nameComposite)
.greetingId(greetingId) | .build());
}
else
{
final String nameComposite = TranslatableStrings.builder()
.append(person1.getFirstName())
.append(" ")
.appendADMessage(MSG_And)
.append(" ")
.append(person2.getFirstName())
.append(" ")
.append(person1.getLastName())
.build()
.translate(adLanguage);
return ExplainedOptional.of(NameAndGreeting.builder()
.name(nameComposite)
.greetingId(greetingId)
.build());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\name\strategy\MembershipContactBPartnerNameAndGreetingStrategy.java | 1 |
请完成以下Java代码 | public static int[] KnuthMorrisPrattShift(char[] pattern) {
int patternSize = pattern.length;
int[] shift = new int[patternSize];
shift[0] = 1;
int i = 1, j = 0;
while ((i + j) < patternSize) {
if (pattern[i + j] == pattern[j]) {
shift[i + j] = i;
j++;
} else {
if (j == 0)
shift[i] = i + 1;
if (j > 0) {
i = i + shift[j - 1];
j = Math.max(j - shift[j - 1], 0);
} else {
i = i + 1;
j = 0;
}
}
}
return shift;
}
public static int BoyerMooreHorspoolSimpleSearch(char[] pattern, char[] text) {
int patternSize = pattern.length;
int textSize = text.length;
int i = 0, j = 0;
while ((i + patternSize) <= textSize) {
j = patternSize - 1;
while (text[i + j] == pattern[j]) {
j--;
if (j < 0)
return i;
}
i++;
}
return -1;
}
public static int BoyerMooreHorspoolSearch(char[] pattern, char[] text) { | int shift[] = new int[256];
for (int k = 0; k < 256; k++) {
shift[k] = pattern.length;
}
for (int k = 0; k < pattern.length - 1; k++) {
shift[pattern[k]] = pattern.length - 1 - k;
}
int i = 0, j = 0;
while ((i + pattern.length) <= text.length) {
j = pattern.length - 1;
while (text[i + j] == pattern[j]) {
j -= 1;
if (j < 0)
return i;
}
i = i + shift[text[i + pattern.length - 1]];
}
return -1;
}
} | repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\textsearch\TextSearchAlgorithms.java | 1 |
请完成以下Java代码 | public int getC_DirectDebit_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DirectDebit_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Dtafile.
@param Dtafile
Copy of the *.dta stored as plain text
*/
public void setDtafile (String Dtafile)
{
set_Value (COLUMNNAME_Dtafile, Dtafile);
}
/** Get Dtafile.
@return Copy of the *.dta stored as plain text
*/
public String getDtafile ()
{
return (String)get_Value(COLUMNNAME_Dtafile);
}
/** Set IsRemittance.
@param IsRemittance IsRemittance */
public void setIsRemittance (boolean IsRemittance) | {
set_Value (COLUMNNAME_IsRemittance, Boolean.valueOf(IsRemittance));
}
/** Get IsRemittance.
@return IsRemittance */
public boolean isRemittance ()
{
Object oo = get_Value(COLUMNNAME_IsRemittance);
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.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_DirectDebit.java | 1 |
请完成以下Java代码 | public class TaskReportManager extends AbstractManager {
@SuppressWarnings("unchecked")
public List<TaskCountByCandidateGroupResult> createTaskCountByCandidateGroupReport(TaskReportImpl query) {
configureQuery(query);
return getDbEntityManager().selectListWithRawParameter("selectTaskCountByCandidateGroupReportQuery", query, 0, Integer.MAX_VALUE);
}
@SuppressWarnings("unchecked")
public List<HistoricTaskInstanceReportResult> selectHistoricTaskInstanceCountByTaskNameReport(HistoricTaskInstanceReportImpl query) {
configureQuery(query);
return getDbEntityManager().selectListWithRawParameter("selectHistoricTaskInstanceCountByTaskNameReport", query, 0, Integer.MAX_VALUE);
}
@SuppressWarnings("unchecked")
public List<HistoricTaskInstanceReportResult> selectHistoricTaskInstanceCountByProcDefKeyReport(HistoricTaskInstanceReportImpl query) {
configureQuery(query);
return getDbEntityManager().selectListWithRawParameter("selectHistoricTaskInstanceCountByProcDefKeyReport", query, 0, Integer.MAX_VALUE);
} | @SuppressWarnings("unchecked")
public List<DurationReportResult> createHistoricTaskDurationReport(HistoricTaskInstanceReportImpl query) {
configureQuery(query);
return getDbEntityManager().selectListWithRawParameter("selectHistoricTaskInstanceDurationReport", query, 0, Integer.MAX_VALUE);
}
protected void configureQuery(HistoricTaskInstanceReportImpl parameter) {
getAuthorizationManager().checkAuthorization(Permissions.READ_HISTORY, Resources.PROCESS_DEFINITION, Authorization.ANY);
getTenantManager().configureTenantCheck(parameter.getTenantCheck());
}
protected void configureQuery(TaskReportImpl parameter) {
getAuthorizationManager().checkAuthorization(Permissions.READ, Resources.TASK, Authorization.ANY);
getTenantManager().configureTenantCheck(parameter.getTenantCheck());
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TaskReportManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ScopesConfig {
@Bean
@Scope("singleton")
public Person personSingleton() {
return new Person();
}
@Bean
@Scope("prototype")
public Person personPrototype() {
return new Person();
}
@Bean
@RequestScope
public HelloMessageGenerator requestScopedBean() {
return new HelloMessageGenerator();
}
@Bean
@SessionScope
public HelloMessageGenerator sessionScopedBean() { | return new HelloMessageGenerator();
}
@Bean
@ApplicationScope
public HelloMessageGenerator applicationScopedBean() {
return new HelloMessageGenerator();
}
@Bean
@Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator websocketScopedBean() {
return new HelloMessageGenerator();
}
} | repos\tutorials-master\spring-core\src\main\java\com\baeldung\beanscopes\ScopesConfig.java | 2 |
请完成以下Java代码 | public void setCompanyName(final String companyName)
{
this.companyName = companyName;
this.companyNameSet = true;
}
public void setLookupLabel(@Nullable final String lookupLabel)
{
this.lookupLabel = lookupLabel;
this.lookupLabelSet = true;
}
public void setVendor(final Boolean vendor)
{
this.vendor = vendor;
this.vendorSet = true;
}
public void setCustomer(final Boolean customer)
{
this.customer = customer;
this.customerSet = true;
}
public void setParentId(final JsonMetasfreshId parentId)
{
this.parentId = parentId;
this.parentIdSet = true;
}
public void setPhone(final String phone)
{
this.phone = phone;
this.phoneSet = true;
}
public void setLanguage(final String language)
{
this.language = language;
this.languageSet = true;
}
public void setInvoiceRule(final JsonInvoiceRule invoiceRule)
{
this.invoiceRule = invoiceRule;
this.invoiceRuleSet = true;
}
public void setPOInvoiceRule(final JsonInvoiceRule invoiceRule)
{
this.poInvoiceRule = invoiceRule;
this.poInvoiceRuleSet = true;
}
public void setUrl(final String url)
{
this.url = url;
this.urlSet = true; | }
public void setUrl2(final String url2)
{
this.url2 = url2;
this.url2Set = true;
}
public void setUrl3(final String url3)
{
this.url3 = url3;
this.url3Set = true;
}
public void setGroup(final String group)
{
this.group = group;
this.groupSet = true;
}
public void setGlobalId(final String globalId)
{
this.globalId = globalId;
this.globalIdset = true;
}
public void setSyncAdvise(final SyncAdvise syncAdvise)
{
this.syncAdvise = syncAdvise;
this.syncAdviseSet = true;
}
public void setVatId(final String vatId)
{
this.vatId = vatId;
this.vatIdSet = true;
}
public void setMemo(final String memo)
{
this.memo = memo;
this.memoIsSet = true;
}
public void setPriceListId(@Nullable final JsonMetasfreshId priceListId)
{
if (JsonMetasfreshId.toValue(priceListId) != null)
{
this.priceListId = priceListId;
this.priceListIdSet = true;
}
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\request\JsonRequestBPartner.java | 1 |
请完成以下Java代码 | public AppDeploymentEntity findLatestDeploymentByName(String deploymentName) {
return dataManager.findLatestDeploymentByName(deploymentName);
}
@Override
public List<String> getDeploymentResourceNames(String deploymentId) {
return dataManager.getDeploymentResourceNames(deploymentId);
}
@Override
public AppDeploymentQuery createDeploymentQuery() {
return new AppDeploymentQueryImpl(engineConfiguration.getCommandExecutor());
}
@Override
public List<AppDeployment> findDeploymentsByQueryCriteria(AppDeploymentQuery deploymentQuery) {
return dataManager.findDeploymentsByQueryCriteria((AppDeploymentQueryImpl) deploymentQuery); | }
@Override
public long findDeploymentCountByQueryCriteria(AppDeploymentQuery deploymentQuery) {
return dataManager.findDeploymentCountByQueryCriteria((AppDeploymentQueryImpl) deploymentQuery);
}
protected AppResourceEntityManager getAppResourceEntityManager() {
return engineConfiguration.getAppResourceEntityManager();
}
protected AppDefinitionEntityManager getAppDefinitionEntityManager() {
return engineConfiguration.getAppDefinitionEntityManager();
}
} | repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\persistence\entity\AppDeploymentEntityManagerImpl.java | 1 |
请完成以下Java代码 | public class SemaphoreDemo {
public static void main(String[] args) {
// Create a Semaphore with a fixed number of permits
int NUM_PERMITS = 3;
Semaphore semaphore = new Semaphore(NUM_PERMITS);
// Simulate resource access by worker threads
for (int i = 1; i <= 5; i++) {
new Thread(() -> {
try {
// Acquire a permit to access the resource
semaphore.acquire();
System.out.println("Thread " + Thread.currentThread().getId() + " accessing resource.");
// Simulate resource usage
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// Release the permit after resource access is complete | semaphore.release();
}
}).start();
}
// Simulate resetting the Semaphore by releasing additional permits after a delay
try {
Thread.sleep(5000);
// Resetting the semaphore permits to the initial count
semaphore.release(NUM_PERMITS);
System.out.println("Semaphore permits reset to initial count.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} | repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-5\src\main\java\com\baeldung\countdownlatchvssemaphore\SemaphoreDemo.java | 1 |
请完成以下Java代码 | public class C_Invoice_PO_CreateAdjustmentCharge extends JavaProcess implements IProcessPrecondition
{
private final IInvoiceBL invoiceBL = Services.get(IInvoiceBL.class);
public String doIt()
{
final DocBaseAndSubType docBaseAndSubType = DocBaseAndSubType.of(X_C_DocType.DOCBASETYPE_APInvoice, X_C_DocType.DOCSUBTYPE_KreditorenNachbelastung);
final AdjustmentChargeCreateRequest adjustmentChargeCreateRequest = AdjustmentChargeCreateRequest.builder()
.invoiceID(InvoiceId.ofRepoId(getRecord_ID()))
.docBaseAndSubTYpe(docBaseAndSubType)
.isSOTrx(false)
.build();
invoiceBL.adjustmentCharge(adjustmentChargeCreateRequest);
return MSG_OK;
}
@Override | public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
return ProcessPreconditionsResolution.accept();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\invoice\process\C_Invoice_PO_CreateAdjustmentCharge.java | 1 |
请完成以下Java代码 | public Optional<ProductBarcodeFilterData> createDataFromHU(
final @Nullable String barcode,
final @Nullable I_M_HU hu)
{
if (hu == null)
{
return Optional.empty();
}
final ImmutableSet<ProductId> productIds = extractProductIds(hu);
if (productIds.isEmpty())
{
return Optional.empty();
}
final ICompositeQueryFilter<I_M_Packageable_V> filter = queryBL.createCompositeQueryFilter(I_M_Packageable_V.class)
.addInArrayFilter(I_M_Packageable_V.COLUMNNAME_M_Product_ID, productIds);
final WarehouseId warehouseId = IHandlingUnitsBL.extractWarehouseIdOrNull(hu);
if (warehouseId != null)
{
filter.addInArrayFilter(I_M_Packageable_V.COLUMNNAME_M_Warehouse_ID, null, warehouseId);
}
final BPartnerId bpartnerId = IHandlingUnitsBL.extractBPartnerIdOrNull(hu);
if (bpartnerId != null)
{
filter.addEqualsFilter(I_M_Packageable_V.COLUMNNAME_C_BPartner_Customer_ID, bpartnerId);
}
return Optional.of(ProductBarcodeFilterData.builder()
.barcode(barcode) | .huId(HuId.ofRepoId(hu.getM_HU_ID()))
.sqlWhereClause(toSqlAndParams(filter))
.build());
}
private ImmutableSet<ProductId> extractProductIds(@NonNull final I_M_HU hu)
{
final IMutableHUContext huContext = handlingUnitsBL.createMutableHUContext(PlainContextAware.newWithThreadInheritedTrx());
return huContext.getHUStorageFactory()
.getStorage(hu)
.getProductStorages()
.stream()
.map(IHUProductStorage::getProductId)
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\packageable\filters\ProductBarcodeFilterServicesFacade.java | 1 |
请完成以下Java代码 | public class BFSMazeSolver {
private static final int[][] DIRECTIONS = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
public List<Coordinate> solve(Maze maze) {
LinkedList<Coordinate> nextToVisit = new LinkedList<>();
Coordinate start = maze.getEntry();
nextToVisit.add(start);
while (!nextToVisit.isEmpty()) {
Coordinate cur = nextToVisit.remove();
if (!maze.isValidLocation(cur.getX(), cur.getY()) || maze.isExplored(cur.getX(), cur.getY())) {
continue;
}
if (maze.isWall(cur.getX(), cur.getY())) {
maze.setVisited(cur.getX(), cur.getY(), true);
continue;
}
if (maze.isExit(cur.getX(), cur.getY())) {
return backtrackPath(cur);
} | for (int[] direction : DIRECTIONS) {
Coordinate coordinate = new Coordinate(cur.getX() + direction[0], cur.getY() + direction[1], cur);
nextToVisit.add(coordinate);
maze.setVisited(cur.getX(), cur.getY(), true);
}
}
return Collections.emptyList();
}
private List<Coordinate> backtrackPath(Coordinate cur) {
List<Coordinate> path = new ArrayList<>();
Coordinate iter = cur;
while (iter != null) {
path.add(iter);
iter = iter.parent;
}
return path;
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\maze\solver\BFSMazeSolver.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.