instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public class JsonDataEntry extends BasicKvEntry {
private final String value;
public JsonDataEntry(String key, String value) {
super(key);
this.value = value;
}
@Override
public DataType getDataType() {
return DataType.JSON;
}
@Override
public Optional<String> getJsonValue() {
return Optional.ofNullable(value);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof JsonDataEntry)) return false;
if (!super.equals(o)) return false;
JsonDataEntry that = (JsonDataEntry) o;
return Objects.equals(value, that.value); | }
@Override
public Object getValue() {
return value;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), value);
}
@Override
public String toString() {
return "JsonDataEntry{" +
"value=" + value +
"} " + super.toString();
}
@Override
public String getValueAsString() {
return value;
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\kv\JsonDataEntry.java | 1 |
请完成以下Java代码 | public FullName getFullName() {
return fullName;
}
public void setFullName(FullName fullName) {
this.fullName = fullName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public List<String> getHobbies() {
return hobbies;
}
public void setHobbies(List<String> hobbies) {
this.hobbies = hobbies;
}
public Map<String, String> getClothes() {
return clothes;
}
public void setClothes(Map<String, String> clothes) { | this.clothes = clothes;
}
public List<Person> getFriends() {
return friends;
}
public void setFriends(List<Person> friends) {
this.friends = friends;
}
@Override
public String toString() {
StringBuilder str = new StringBuilder("Person [name=" + name + ", fullName=" + fullName + ", age="
+ age + ", birthday=" + birthday + ", hobbies=" + hobbies
+ ", clothes=" + clothes + "]\n");
if (friends != null) {
str.append("Friends:\n");
for (Person f : friends) {
str.append("\t").append(f);
}
}
return str.toString();
}
} | repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\benchmark\json\model\Person.java | 1 |
请完成以下Java代码 | public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
} | public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
} | repos\tutorials-master\json-modules\json-2\src\main\java\com\baeldung\jsonschemageneration\recursive\AuthoredArticle.java | 1 |
请完成以下Java代码 | public class SendEventServiceTask extends ServiceTask {
protected String eventType;
protected String triggerEventType;
protected boolean sendSynchronously;
protected List<IOParameter> eventInParameters = new ArrayList<>();
protected List<IOParameter> eventOutParameters = new ArrayList<>();
public String getEventType() {
return eventType;
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
public String getTriggerEventType() {
return triggerEventType;
}
public void setTriggerEventType(String triggerEventType) {
this.triggerEventType = triggerEventType;
}
public boolean isSendSynchronously() {
return sendSynchronously;
}
public void setSendSynchronously(boolean sendSynchronously) {
this.sendSynchronously = sendSynchronously;
}
public List<IOParameter> getEventInParameters() {
return eventInParameters;
}
public void setEventInParameters(List<IOParameter> eventInParameters) {
this.eventInParameters = eventInParameters;
}
public List<IOParameter> getEventOutParameters() {
return eventOutParameters;
}
public void setEventOutParameters(List<IOParameter> eventOutParameters) {
this.eventOutParameters = eventOutParameters; | }
@Override
public SendEventServiceTask clone() {
SendEventServiceTask clone = new SendEventServiceTask();
clone.setValues(this);
return clone;
}
public void setValues(SendEventServiceTask otherElement) {
super.setValues(otherElement);
setEventType(otherElement.getEventType());
setTriggerEventType(otherElement.getTriggerEventType());
setSendSynchronously(otherElement.isSendSynchronously());
eventInParameters = new ArrayList<>();
if (otherElement.getEventInParameters() != null && !otherElement.getEventInParameters().isEmpty()) {
for (IOParameter parameter : otherElement.getEventInParameters()) {
eventInParameters.add(parameter.clone());
}
}
eventOutParameters = new ArrayList<>();
if (otherElement.getEventOutParameters() != null && !otherElement.getEventOutParameters().isEmpty()) {
for (IOParameter parameter : otherElement.getEventOutParameters()) {
eventOutParameters.add(parameter.clone());
}
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\SendEventServiceTask.java | 1 |
请完成以下Java代码 | public void updateAfterReplacement() {
super.updateAfterReplacement();
Collection<Reference> incomingReferences = getIncomingReferencesByType(SequenceFlow.class);
for (Reference<?> reference : incomingReferences) {
for (ModelElementInstance sourceElement : reference.findReferenceSourceElements(this)) {
String referenceIdentifier = reference.getReferenceIdentifier(sourceElement);
if (referenceIdentifier != null && referenceIdentifier.equals(getId()) && reference instanceof AttributeReference) {
String attributeName = ((AttributeReference) reference).getReferenceSourceAttribute().getAttributeName();
if (attributeName.equals(BPMN_ATTRIBUTE_SOURCE_REF)) {
getOutgoing().add((SequenceFlow) sourceElement);
}
else if (attributeName.equals(BPMN_ATTRIBUTE_TARGET_REF)) {
getIncoming().add((SequenceFlow) sourceElement);
}
}
}
}
}
public Collection<SequenceFlow> getIncoming() {
return incomingCollection.getReferenceTargetElements(this);
}
public Collection<SequenceFlow> getOutgoing() {
return outgoingCollection.getReferenceTargetElements(this);
}
public Query<FlowNode> getPreviousNodes() {
Collection<FlowNode> previousNodes = new HashSet<FlowNode>();
for (SequenceFlow sequenceFlow : getIncoming()) {
previousNodes.add(sequenceFlow.getSource());
}
return new QueryImpl<FlowNode>(previousNodes);
}
public Query<FlowNode> getSucceedingNodes() {
Collection<FlowNode> succeedingNodes = new HashSet<FlowNode>();
for (SequenceFlow sequenceFlow : getOutgoing()) {
succeedingNodes.add(sequenceFlow.getTarget());
}
return new QueryImpl<FlowNode>(succeedingNodes);
}
/** Camunda Attributes */
public boolean isCamundaAsyncBefore() {
return camundaAsyncBefore.getValue(this);
}
public void setCamundaAsyncBefore(boolean isCamundaAsyncBefore) { | camundaAsyncBefore.setValue(this, isCamundaAsyncBefore);
}
public boolean isCamundaAsyncAfter() {
return camundaAsyncAfter.getValue(this);
}
public void setCamundaAsyncAfter(boolean isCamundaAsyncAfter) {
camundaAsyncAfter.setValue(this, isCamundaAsyncAfter);
}
public boolean isCamundaExclusive() {
return camundaExclusive.getValue(this);
}
public void setCamundaExclusive(boolean isCamundaExclusive) {
camundaExclusive.setValue(this, isCamundaExclusive);
}
public String getCamundaJobPriority() {
return camundaJobPriority.getValue(this);
}
public void setCamundaJobPriority(String jobPriority) {
camundaJobPriority.setValue(this, jobPriority);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\FlowNodeImpl.java | 1 |
请完成以下Java代码 | public final class CopyTemplate
{
@Getter @NonNull private final String tableName;
@Getter @Nullable private final String keyColumnName;
@NonNull private final ImmutableMap<String, CopyTemplateColumn> columnsByColumnName;
@Getter @NonNull private final ImmutableList<CopyTemplate> childTemplates;
//
// Child/included template specific properties
@Getter @Nullable private final String linkColumnName;
@Getter @NonNull private final ImmutableList<String> orderByColumnNames;
@Builder
private CopyTemplate(
@NonNull final String tableName,
@Nullable final String keyColumnName,
@NonNull @Singular final ImmutableList<CopyTemplateColumn> columns,
@NonNull @Singular final ImmutableList<CopyTemplate> childTemplates,
//
@Nullable final String linkColumnName,
@NonNull @Singular final ImmutableList<String> orderByColumnNames)
{
this.tableName = tableName;
this.keyColumnName = keyColumnName;
this.childTemplates = childTemplates;
this.linkColumnName = linkColumnName;
this.orderByColumnNames = orderByColumnNames;
this.columnsByColumnName = Maps.uniqueIndex(columns, CopyTemplateColumn::getColumnName);
}
private CopyTemplateColumn getColumn(final String columnName)
{
final CopyTemplateColumn column = columnsByColumnName.get(columnName);
if (column == null) | {
throw new AdempiereException("Column `" + columnName + "` not found in " + this);
}
return column;
}
private Optional<CopyTemplateColumn> getColumnIfExists(final String columnName)
{
return Optional.ofNullable(columnsByColumnName.get(columnName));
}
public ValueToCopyResolved getValueToCopy(@NonNull ValueToCopyResolveContext context)
{
return getColumn(context.getColumnName()).getValueToCopy().resolve(context);
}
public Optional<ValueToCopyType> getValueToCopyType(@NonNull final String columnName)
{
return getColumnIfExists(columnName).map(column -> column.getValueToCopy().getType());
}
public boolean hasChildTableName(@NonNull final String tableName)
{
return childTemplates.stream().anyMatch(childTemplate -> childTemplate.getTableName().equals(tableName));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\copy_with_details\template\CopyTemplate.java | 1 |
请完成以下Java代码 | public static String subscribeMessage(String FromUserName, String ToUserName) {
String message = "Hi!我的小伙伴~欢迎关注人事情报科!\n" +
"\n" +
"快速搜索查看2000万人才简历,点击<a href=\"http://wx.rchezi.com\">【搜索】</a>\n" +
"\n" +
"与HR和猎头加好友交换简历~~点击 <a href=\"http://www.rchezi.com/?from=WeChatGZH\">【交换简历】</a>\n" +
"\n" +
"体验产品,领新手红包,点击<a href=\"http://channel.rchezi.com/download?c=WeChatGZH\">【下载App】</a>\n" +
"\n" +
"更多人事资讯请时刻关注我们哦,定期免费课程大放送~";
return reversalMessage(FromUserName, ToUserName, message);
}
/**
* 封装发送消息对象,封装时,需要将调换发送者和接收者的关系
*
* @param fromUserName
* @param toUserName
* @param Content
*/
public static String reversalMessage(String fromUserName, String toUserName, String Content) {
TextMessage text = new TextMessage();
text.setToUserName(fromUserName);
text.setFromUserName(toUserName);
text.setContent(Content);
text.setCreateTime(new Date().getTime());
text.setMsgType(ReqType.TEXT);
return messageToxml(text);
}
/**
* 封装voice消息对象
*
* @param fromUserName
* @param toUserName | * @param mediaId
* @return
*/
public static String reversalVoiceMessage(String fromUserName, String toUserName, String mediaId) {
VoiceMessage voiceMessage = new VoiceMessage();
voiceMessage.setToUserName(fromUserName);
voiceMessage.setFromUserName(toUserName);
voiceMessage.setVoice(new Voice(mediaId));
voiceMessage.setCreateTime(new Date().getTime());
voiceMessage.setMsgType(ReqType.VOICE);
return messageToxml(voiceMessage);
}
/**
* 判断是否是QQ表情
*
* @param content
* @return
*/
public static boolean isQqFace(String content) {
boolean result = false;
// 判断QQ表情的正则表达式
Matcher m = p.matcher(content);
if (m.matches()) {
result = true;
}
return result;
}
} | repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\api\utils\MessageUtil.java | 1 |
请完成以下Java代码 | public void setC_Order_ID (final int C_Order_ID)
{
if (C_Order_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Order_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Order_ID, C_Order_ID);
}
@Override
public int getC_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Order_ID);
}
@Override
public void setIsNamePrinted (final boolean IsNamePrinted)
{
set_Value (COLUMNNAME_IsNamePrinted, IsNamePrinted);
}
@Override
public boolean isNamePrinted()
{
return get_ValueAsBoolean(COLUMNNAME_IsNamePrinted);
}
@Override
public void setM_Product_Category_ID (final int M_Product_Category_ID)
{
if (M_Product_Category_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_ID, null);
else
set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID);
}
@Override
public int getM_Product_Category_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
} | @Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public org.eevolution.model.I_PP_Product_BOM getPP_Product_BOM()
{
return get_ValueAsPO(COLUMNNAME_PP_Product_BOM_ID, org.eevolution.model.I_PP_Product_BOM.class);
}
@Override
public void setPP_Product_BOM(final org.eevolution.model.I_PP_Product_BOM PP_Product_BOM)
{
set_ValueFromPO(COLUMNNAME_PP_Product_BOM_ID, org.eevolution.model.I_PP_Product_BOM.class, PP_Product_BOM);
}
@Override
public void setPP_Product_BOM_ID (final int PP_Product_BOM_ID)
{
if (PP_Product_BOM_ID < 1)
set_Value (COLUMNNAME_PP_Product_BOM_ID, null);
else
set_Value (COLUMNNAME_PP_Product_BOM_ID, PP_Product_BOM_ID);
}
@Override
public int getPP_Product_BOM_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Product_BOM_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Order_CompensationGroup.java | 1 |
请完成以下Java代码 | public void update(int[] goldIndex, int[] predictIndex, double[] total, int[] timestamp, int current)
{
for (int i = 0; i < goldIndex.length; ++i)
{
if (goldIndex[i] == predictIndex[i])
continue;
else
{
update(goldIndex[i], 1, total, timestamp, current);
if (predictIndex[i] >= 0 && predictIndex[i] < parameter.length)
update(predictIndex[i], -1, total, timestamp, current);
else
{
throw new IllegalArgumentException("更新参数时传入了非法的下标");
}
}
}
}
/**
* 根据答案和预测更新参数
*
* @param featureVector 特征向量
* @param value 更新量
* @param total 权值向量总和
* @param timestamp 每个权值上次更新的时间戳
* @param current 当前时间戳
*/
public void update(Collection<Integer> featureVector, float value, double[] total, int[] timestamp, int current)
{
for (Integer i : featureVector)
update(i, value, total, timestamp, current);
}
/**
* 根据答案和预测更新参数
*
* @param index 特征向量的下标
* @param value 更新量 | * @param total 权值向量总和
* @param timestamp 每个权值上次更新的时间戳
* @param current 当前时间戳
*/
private void update(int index, float value, double[] total, int[] timestamp, int current)
{
int passed = current - timestamp[index];
total[index] += passed * parameter[index];
parameter[index] += value;
timestamp[index] = current;
}
public void average(double[] total, int[] timestamp, int current)
{
for (int i = 0; i < parameter.length; i++)
{
parameter[i] = (float) ((total[i] + (current - timestamp[i]) * parameter[i]) / current);
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\model\AveragedPerceptron.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonQuantity
{
@NonNull BigDecimal value;
@NonNull String uomCode; // ISO or system UOM code, e.g. "PCE"
@NonNull
@JsonCreator
public static JsonQuantity parseString(@NonNull final String string)
{
final List<String> parts = Splitter.on(" ").trimResults().omitEmptyStrings().splitToList(string);
if (parts.size() != 2)
{
throw new RuntimeException("Cannot parse " + string + " to JsonQuantity: expected 2 parts separated by space");
}
try
{
return JsonQuantity.builder()
.value(new BigDecimal(parts.get(0))) | .uomCode(parts.get(1))
.build();
}
catch (final Exception ex)
{
throw new RuntimeException("Cannot parse " + string + " to JsonQuantity", ex);
}
}
@Override
public String toString() {return toJson();}
@JsonValue
public String toJson() {return value + " " + uomCode;}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-delivery\src\main\java\de\metas\common\delivery\v1\json\JsonQuantity.java | 2 |
请完成以下Java代码 | public void close(final Connection conn)
{
if (conn != null)
{
try
{
conn.close();
}
catch (final SQLException e)
{
logger.debug(e.getLocalizedMessage(), e);
}
}
}
public void close(final ResultSet rs, final PreparedStatement pstmt, final Connection conn)
{
close(rs);
close(pstmt);
close(conn);
}
public Set<String> getDBFunctionsMatchingPattern(final String functionNamePattern)
{
ResultSet rs = null;
try
{
final ImmutableSet.Builder<String> result = ImmutableSet.builder();
//
// Fetch database functions
close(rs);
rs = database.getConnection()
.getMetaData()
.getFunctions(database.getDbName(), null, functionNamePattern);
while (rs.next())
{
final String functionName = rs.getString("FUNCTION_NAME");
final String schemaName = rs.getString("FUNCTION_SCHEM");
final String functionNameFQ = schemaName != null ? schemaName + "." + functionName : functionName;
result.add(functionNameFQ);
}
//
// Fetch database procedures
// NOTE: after PostgreSQL 11 this will fetch nothing because our "after_import" routines are functions,
// but we are keeping it for legacy purposes. | // (see org.postgresql.jdbc.PgDatabaseMetaData.getProcedures)
close(rs);
rs = database.getConnection()
.getMetaData()
.getProcedures(database.getDbName(), null, functionNamePattern);
while (rs.next())
{
final String functionName = rs.getString("PROCEDURE_NAME");
final String schemaName = rs.getString("PROCEDURE_SCHEM");
final String functionNameFQ = schemaName != null ? schemaName + "." + functionName : functionName;
result.add(functionNameFQ);
}
return result.build();
}
catch (final SQLException ex)
{
logger.warn("Error while fetching functions for pattern {}. Considering no functions found.", functionNamePattern, ex);
return ImmutableSet.of();
}
finally
{
close(rs);
}
}
@FunctionalInterface
public static interface ResultSetRowLoader<T>
{
T loadRow(ResultSet rs) throws SQLException;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\impl\SQLHelper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static List<TsKvEntry> fromProto(TransportProtos.TbSubUpdateProto proto) {
List<TsKvEntry> result = new ArrayList<>();
for (var p : proto.getDataList()) {
result.addAll(fromTsValueProtoList(p.getKey(), p.getTsValueList()));
}
return result;
}
static ToCoreNotificationMsg toProto(EntityId entityId, List<TsKvEntry> updates) {
return toProto(true, null, entityId, updates);
}
static ToCoreNotificationMsg toProto(String scope, EntityId entityId, List<TsKvEntry> updates) {
return toProto(false, scope, entityId, updates);
}
static ToCoreNotificationMsg toProto(boolean timeSeries, String scope, EntityId entityId, List<TsKvEntry> updates) {
TransportProtos.TbSubUpdateProto.Builder builder = TransportProtos.TbSubUpdateProto.newBuilder();
builder.setEntityIdMSB(entityId.getId().getMostSignificantBits());
builder.setEntityIdLSB(entityId.getId().getLeastSignificantBits());
Map<String, List<TransportProtos.TsValueProto>> data = new TreeMap<>();
for (TsKvEntry tsEntry : updates) {
data.computeIfAbsent(tsEntry.getKey(), k -> new ArrayList<>()).add(toTsValueProto(tsEntry.getTs(), tsEntry));
}
data.forEach((key, value) -> {
TransportProtos.TsValueListProto.Builder dataBuilder = TransportProtos.TsValueListProto.newBuilder();
dataBuilder.setKey(key); | dataBuilder.addAllTsValue(value);
builder.addData(dataBuilder.build());
});
var result = TransportProtos.LocalSubscriptionServiceMsgProto.newBuilder();
if (timeSeries) {
result.setTsUpdate(builder);
} else {
builder.setScope(scope);
result.setAttrUpdate(builder);
}
return ToCoreNotificationMsg.newBuilder().setToLocalSubscriptionServiceMsg(result).build();
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\subscription\TbSubscriptionUtils.java | 2 |
请完成以下Java代码 | public class JCacheCacheMeterBinderProvider implements CacheMeterBinderProvider<JCacheCache> {
private final boolean registerCacheRemovalsAsFunctionCounter;
/**
* Creates a {@code JCacheCacheMeterBinderProvider} that registers cache removals as a
* {@link Gauge}.
*/
public JCacheCacheMeterBinderProvider() {
this(false);
}
/**
* Creates a {@code JCacheCacheMeterBinderProvider} that registers cache removals with
* a meter type that depends on the value of
* {@code registerCacheRemovalsAsFunctionCounter}. When {@code false}, cache removals | * are registered as a {@link Gauge}. When {@code true}, cache removals are registered
* as a {@link FunctionCounter}.
* @param registerCacheRemovalsAsFunctionCounter whether to register removals as a
* gauge or a function counter
* @since 3.4.12
*/
public JCacheCacheMeterBinderProvider(boolean registerCacheRemovalsAsFunctionCounter) {
this.registerCacheRemovalsAsFunctionCounter = registerCacheRemovalsAsFunctionCounter;
}
@Override
public MeterBinder getMeterBinder(JCacheCache cache, Iterable<Tag> tags) {
return new JCacheMetrics<>(cache.getNativeCache(), tags, this.registerCacheRemovalsAsFunctionCounter);
}
} | repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\metrics\JCacheCacheMeterBinderProvider.java | 1 |
请完成以下Java代码 | public class C_PaySelection_RevolutPayment_CSVExport extends JavaProcess implements IProcessPrecondition
{
private final IPaySelectionDAO paySelectionDAO = Services.get(IPaySelectionDAO.class);
private static final AdMessageKey REVOLUT_AVAILABLE_ONLY_FOR_CREDIT_TRANSFER_ERROR = AdMessageKey.of("C_PaySelection_RevolutAvailableOnlyForCreditTransfer");
@Override
@NonNull
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
else if (context.isMoreThanOneSelected())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
else
{
final I_C_PaySelection paySelection = paySelectionDAO.getById(PaySelectionId.ofRepoId(context.getSingleSelectedRecordId()))
.orElseThrow(() -> AdempiereException.newWithPlainMessage("No paySelection found for selected record")
.appendParametersToMessage()
.setParameter("recordId", context.getSingleSelectedRecordId()));
if(!DocStatus.ofNullableCodeOrUnknown(paySelection.getDocStatus()).isCompletedOrClosed())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("C_PaySelection_ID=" + paySelection.getC_PaySelection_ID() + " needs to be completed or closed");
}
if (!paySelection.getPaySelectionTrxType().equals(X_C_PaySelection.PAYSELECTIONTRXTYPE_CreditTransfer))
{
return ProcessPreconditionsResolution.rejectWithInternalReason(msgBL.getTranslatableMsgText(REVOLUT_AVAILABLE_ONLY_FOR_CREDIT_TRANSFER_ERROR));
}
}
return ProcessPreconditionsResolution.accept();
}
@Override | protected String doIt()
{
final RevolutExportService revolutExportService = SpringContextHolder.instance.getBean(RevolutExportService.class);
final PaySelectionService paySelectionService = SpringContextHolder.instance.getBean(PaySelectionService.class);
final I_C_PaySelection paySelection = paySelectionDAO.getById(PaySelectionId.ofRepoId(getRecord_ID()))
.orElseThrow(() -> new AdempiereException("No paySelection found for selected record")
.appendParametersToMessage()
.setParameter("recordId", getRecord_ID()));
final List<RevolutPaymentExport> revolutPaymentExportList = paySelectionService.computeRevolutPaymentExportList(paySelection);
final List<RevolutPaymentExport> savedRevolutPaymentExportList = revolutExportService.saveAll(revolutPaymentExportList);
final PaySelectionId paySelectionId = PaySelectionId.ofRepoId(paySelection.getC_PaySelection_ID());
final ReportResultData reportResultData = revolutExportService.exportToCsv(paySelectionId, savedRevolutPaymentExportList);
paySelection.setLastRevolutExport(Timestamp.from(Instant.now()));
paySelection.setLastRevolutExportBy_ID(getAD_User_ID());
paySelectionDAO.save(paySelection);
getProcessInfo().getResult().setReportData(reportResultData);
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.revolut\src\main\java\de\metas\payment\revolut\process\C_PaySelection_RevolutPayment_CSVExport.java | 1 |
请完成以下Java代码 | public String asString() {
return "spring.rabbit.stream.template.name";
}
}
}
/**
* Default {@link RabbitStreamTemplateObservationConvention} for Rabbit template key values.
*/
public static class DefaultRabbitStreamTemplateObservationConvention
implements RabbitStreamTemplateObservationConvention {
/**
* A singleton instance of the convention.
*/ | public static final DefaultRabbitStreamTemplateObservationConvention INSTANCE =
new DefaultRabbitStreamTemplateObservationConvention();
@Override
public KeyValues getLowCardinalityKeyValues(RabbitStreamMessageSenderContext context) {
return KeyValues.of(RabbitStreamTemplateObservation.TemplateLowCardinalityTags.BEAN_NAME.asString(),
context.getBeanName());
}
@Override
public String getContextualName(RabbitStreamMessageSenderContext context) {
return context.getDestination() + " send";
}
}
} | repos\spring-amqp-main\spring-rabbit-stream\src\main\java\org\springframework\rabbit\stream\micrometer\RabbitStreamTemplateObservation.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Character generateCharacterChatModel(@PathVariable String race) {
return characterService.generateCharacterChatModel(race);
}
@GetMapping("/chat-client/{race}")
public Character generateCharacterChatClient(@PathVariable String race) {
return characterService.generateCharacterChatClient(race);
}
// List of character objects
@GetMapping("/chat-model/list/{amount}")
public List<Character> generateListOfCharactersChatModel(@PathVariable int amount) {
if (amount > 10) {
throw new IllegalArgumentException("Amount must be less than 10");
}
return characterService.generateListOfCharactersChatClient(amount);
}
@GetMapping("/chat-client/list/{amount}")
public List<Character> generateListOfCharactersChatClient(@PathVariable int amount) {
if (amount > 10) {
throw new IllegalArgumentException("Amount must be less than 10");
}
return characterService.generateListOfCharactersChatModel(amount);
}
// Map of character names and biographies
@GetMapping("/chat-model/map/{amount}")
public Map<String, Object> generateListOfCharactersChatModelMap(@PathVariable int amount) {
if (amount > 10) {
throw new IllegalArgumentException("Amount must be less than 10");
}
return characterService.generateMapOfCharactersChatModel(amount);
}
@GetMapping("/chat-client/map/{amount}")
public Map<String, Object> generateListOfCharactersChatClientMap(@PathVariable int amount) {
if (amount > 10) {
throw new IllegalArgumentException("Amount must be less than 10");
} | return characterService.generateMapOfCharactersChatClient(amount);
}
// List of character names
@GetMapping("/chat-model/names/{amount}")
public List<String> generateListOfCharacterNamesChatModel(@PathVariable int amount) {
return characterService.generateListOfCharacterNamesChatModel(amount);
}
@GetMapping("/chat-client/names/{amount}")
public List<String> generateListOfCharacterNamesChatClient(@PathVariable int amount) {
return characterService.generateListOfCharacterNamesChatClient(amount);
}
// Custom converter
@GetMapping("/custom-converter/{amount}")
public Map<String, Character> generateMapOfCharactersCustomConverterGenerics(@PathVariable int amount) {
return characterService.generateMapOfCharactersCustomConverter(amount);
}
@GetMapping("/custom-converter/chat-client/{amount}")
public Map<String, Character> generateMapOfCharactersCustomConverterChatClient(@PathVariable int amount) {
return characterService.generateMapOfCharactersCustomConverterChatClient(amount);
}
} | repos\tutorials-master\spring-ai-modules\spring-ai-3\src\main\java\com\baeldung\springaistructuredoutput\controller\CharacterController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class SysClient implements ISysClient {
private IDeptService deptService;
private IPostService postService;
private IRoleService roleService;
private ITenantService tenantService;
@Override
@GetMapping(API_PREFIX + "/getDept")
public Dept getDept(Long id) {
return deptService.getById(id);
}
@Override
@GetMapping(API_PREFIX + "/getDeptName")
public String getDeptName(Long id) {
return deptService.getById(id).getDeptName();
}
@Override
public String getDeptIds(String tenantId, String deptNames) {
return deptService.getDeptIds(tenantId, deptNames);
}
@Override
public List<String> getDeptNames(String deptIds) {
return deptService.getDeptNames(deptIds);
}
@Override
public String getPostIds(String tenantId, String postNames) {
return postService.getPostIds(tenantId, postNames);
}
@Override
public List<String> getPostNames(String postIds) {
return postService.getPostNames(postIds);
}
@Override
@GetMapping(API_PREFIX + "/getRole")
public Role getRole(Long id) {
return roleService.getById(id);
}
@Override
public String getRoleIds(String tenantId, String roleNames) {
return roleService.getRoleIds(tenantId, roleNames);
} | @Override
@GetMapping(API_PREFIX + "/getRoleName")
public String getRoleName(Long id) {
return roleService.getById(id).getRoleName();
}
@Override
public List<String> getRoleNames(String roleIds) {
return roleService.getRoleNames(roleIds);
}
@Override
@GetMapping(API_PREFIX + "/getRoleAlias")
public String getRoleAlias(Long id) {
return roleService.getById(id).getRoleAlias();
}
@Override
@GetMapping(API_PREFIX + "/tenant")
public R<Tenant> getTenant(Long id) {
return R.data(tenantService.getById(id));
}
@Override
@GetMapping(API_PREFIX + "/tenant-id")
public R<Tenant> getTenant(String tenantId) {
return R.data(tenantService.getByTenantId(tenantId));
}
} | repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\feign\SysClient.java | 2 |
请完成以下Java代码 | public class AuthenticatedReactiveAuthorizationManager<T> implements ReactiveAuthorizationManager<T> {
private AuthenticationTrustResolver authTrustResolver = new AuthenticationTrustResolverImpl();
AuthenticatedReactiveAuthorizationManager() {
}
@Override
public Mono<AuthorizationResult> authorize(Mono<Authentication> authentication, T object) {
return authentication.filter(this::isNotAnonymous)
.map(this::getAuthorizationDecision)
.defaultIfEmpty(new AuthorizationDecision(false));
}
private AuthorizationResult getAuthorizationDecision(Authentication authentication) {
return new AuthorizationDecision(authentication.isAuthenticated());
}
/**
* Verify (via {@link AuthenticationTrustResolver}) that the given authentication is
* not anonymous. | * @param authentication to be checked
* @return <code>true</code> if not anonymous, otherwise <code>false</code>.
*/
private boolean isNotAnonymous(Authentication authentication) {
return !this.authTrustResolver.isAnonymous(authentication);
}
/**
* Gets an instance of {@link AuthenticatedReactiveAuthorizationManager}
* @param <T>
* @return
*/
public static <T> AuthenticatedReactiveAuthorizationManager<T> authenticated() {
return new AuthenticatedReactiveAuthorizationManager<>();
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\AuthenticatedReactiveAuthorizationManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public MongoClient mongoClient() {
return MongoClients.create(mongodbUrl);
}
@Bean
public EmbeddingStore<TextSegment> embeddingStore(MongoClient mongoClient) {
String collectionName = "embeddings";
String indexName = "embedding";
Long maxResultRatio = 10L;
CreateCollectionOptions createCollectionOptions = new CreateCollectionOptions();
Bson filter = null;
IndexMapping indexMapping = IndexMapping.builder()
.dimension(TEXT_EMBEDDING_3_SMALL.dimension())
.metadataFieldNames(new HashSet<>())
.build();
Boolean createIndex = true;
return new MongoDbEmbeddingStore(
mongoClient,
databaseName,
collectionName,
indexName,
maxResultRatio,
createCollectionOptions,
filter,
indexMapping,
createIndex
);
}
@Bean
public EmbeddingModel embeddingModel() {
return OpenAiEmbeddingModel.builder()
.apiKey(apiKey)
.modelName(TEXT_EMBEDDING_3_SMALL) | .build();
}
@Bean
public ContentRetriever contentRetriever(EmbeddingStore<TextSegment> embeddingStore, EmbeddingModel embeddingModel) {
return EmbeddingStoreContentRetriever.builder()
.embeddingStore(embeddingStore)
.embeddingModel(embeddingModel)
.maxResults(10)
.minScore(0.8)
.build();
}
@Bean
public ChatLanguageModel chatModel() {
return OpenAiChatModel.builder()
.apiKey(apiKey)
.modelName("gpt-4o-mini")
.build();
}
@Bean
public ArticleBasedAssistant articleBasedAssistant(ChatLanguageModel chatModel, ContentRetriever contentRetriever) {
return AiServices.builder(ArticleBasedAssistant.class)
.chatLanguageModel(chatModel)
.contentRetriever(contentRetriever)
.build();
}
} | repos\tutorials-master\libraries-llms-2\src\main\java\com\baeldung\chatbot\mongodb\configuration\ChatBotConfiguration.java | 2 |
请完成以下Java代码 | public Builder attributes(Consumer<Map<String, Object>> attributesConsumer) {
if (this.attributes == null) {
this.attributes = new HashMap<>();
}
attributesConsumer.accept(this.attributes);
return this;
}
/**
* Sets an attribute associated to the context.
* @param name the name of the attribute
* @param value the value of the attribute
* @return the {@link Builder}
*/
public Builder attribute(String name, Object value) {
if (this.attributes == null) {
this.attributes = new HashMap<>();
}
this.attributes.put(name, value);
return this;
}
/**
* Builds a new {@link OAuth2AuthorizationContext}.
* @return a {@link OAuth2AuthorizationContext}
*/ | public OAuth2AuthorizationContext build() {
Assert.notNull(this.principal, "principal cannot be null");
OAuth2AuthorizationContext context = new OAuth2AuthorizationContext();
if (this.authorizedClient != null) {
context.clientRegistration = this.authorizedClient.getClientRegistration();
context.authorizedClient = this.authorizedClient;
}
else {
context.clientRegistration = this.clientRegistration;
}
context.principal = this.principal;
context.attributes = Collections.unmodifiableMap(CollectionUtils.isEmpty(this.attributes)
? Collections.emptyMap() : new LinkedHashMap<>(this.attributes));
return context;
}
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\OAuth2AuthorizationContext.java | 1 |
请完成以下Java代码 | public java.sql.Timestamp getPreparationTime_4 ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_PreparationTime_4);
}
/** Set Bereitstellungszeit Fr.
@param PreparationTime_5
Preparation time for Friday
*/
@Override
public void setPreparationTime_5 (java.sql.Timestamp PreparationTime_5)
{
set_Value (COLUMNNAME_PreparationTime_5, PreparationTime_5);
}
/** Get Bereitstellungszeit Fr.
@return Preparation time for Friday
*/
@Override
public java.sql.Timestamp getPreparationTime_5 ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_PreparationTime_5);
}
/** Set Bereitstellungszeit Sa.
@param PreparationTime_6
Preparation time for Saturday
*/
@Override
public void setPreparationTime_6 (java.sql.Timestamp PreparationTime_6)
{
set_Value (COLUMNNAME_PreparationTime_6, PreparationTime_6);
}
/** Get Bereitstellungszeit Sa.
@return Preparation time for Saturday
*/
@Override
public java.sql.Timestamp getPreparationTime_6 ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_PreparationTime_6);
}
/** Set Bereitstellungszeit So.
@param PreparationTime_7
Preparation time for Sunday
*/ | @Override
public void setPreparationTime_7 (java.sql.Timestamp PreparationTime_7)
{
set_Value (COLUMNNAME_PreparationTime_7, PreparationTime_7);
}
/** Get Bereitstellungszeit So.
@return Preparation time for Sunday
*/
@Override
public java.sql.Timestamp getPreparationTime_7 ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_PreparationTime_7);
}
/** Set Gültig ab.
@param ValidFrom
Gültig ab inklusiv (erster Tag)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Gültig ab inklusiv (erster Tag)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\tourplanning\model\X_M_TourVersion.java | 1 |
请完成以下Java代码 | public MessageEventDefinition getMessageEventDefinition() {
return messageEventDefinition;
}
protected ThrowMessage getThrowMessage(DelegateExecution execution) {
return messageExecutionContext.createThrowMessage(execution);
}
protected void dispatchEvent(DelegateExecution execution, ThrowMessage throwMessage) {
Optional.ofNullable(Context.getCommandContext())
.filter(commandContext -> commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled())
.ifPresent(commandContext -> {
String messageName = throwMessage.getName();
String correlationKey = throwMessage.getCorrelationKey().orElse(null);
Object payload = throwMessage.getPayload().orElse(null);
commandContext | .getProcessEngineConfiguration()
.getEventDispatcher()
.dispatchEvent(
ActivitiEventBuilder.createMessageSentEvent(execution, messageName, correlationKey, payload)
);
});
}
public ThrowMessageDelegate getDelegate() {
return delegate;
}
public MessageExecutionContext getMessageExecutionContext() {
return messageExecutionContext;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\AbstractThrowMessageEventActivityBehavior.java | 1 |
请完成以下Java代码 | private String createMnemonic(String text)
{
m_savedMnemonic = 0;
if (text == null)
return text;
int pos = text.indexOf('&');
if (pos != -1) // We have a nemonic
{
char ch = text.charAt(pos+1);
if (ch != ' ') // &_ - is the & character
{
setDisplayedMnemonic(ch);
setSavedMnemonic(ch);
return text.substring(0, pos) + text.substring(pos+1);
}
}
return text;
} // createMnemonic
/**
* Set ReadWrite
* @param rw enabled
*/
public void setReadWrite (boolean rw)
{
this.setEnabled(rw);
} // setReadWrite
/**
* Set Label For
* @param c component
*/
@Override
public void setLabelFor (Component c)
{
//reset old if any
if (getLabelFor() != null && getLabelFor() instanceof JTextComponent)
{
((JTextComponent)getLabelFor()).setFocusAccelerator('\0');
}
super.setLabelFor(c);
if (c.getName() == null)
c.setName(getName());
//workaround for focus accelerator issue | if (c instanceof JTextComponent)
{
if (m_savedMnemonic > 0)
{
((JTextComponent)c).setFocusAccelerator(m_savedMnemonic);
}
}
} // setLabelFor
/**
* @return Returns the savedMnemonic.
*/
public char getSavedMnemonic ()
{
return m_savedMnemonic;
} // getSavedMnemonic
/**
* @param savedMnemonic The savedMnemonic to set.
*/
public void setSavedMnemonic (char savedMnemonic)
{
m_savedMnemonic = savedMnemonic;
} // getSavedMnemonic
} // CLabel | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CLabel.java | 1 |
请完成以下Java代码 | public static void main(String[] args) throws IOException {
//创建一个ServerSocket在端口4700监听客户请求
try (ServerSocket server = new ServerSocket(4700)) {
while (true) {
//使用accept()阻塞等待客户请求,有客户, 请求到来则产生一个Socket对象,并继续执行
Socket socket = server.accept();
ExecutorService executor = Executors.newFixedThreadPool(10);
executor.submit(() -> {
try (//由Socket对象得到输入流,并构造相应的BufferedReader对象
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//由Socket对象得到输出流,并构造PrintWriter对象
PrintWriter os = new PrintWriter(socket.getOutputStream());) {
String line = is.readLine();
while (!"bye".equals(line) && line != null) {
//在标准输出上打印从客户端读入的字符串
System.out.println(Thread.currentThread().getName() + " 收到客户端信息:" + line);
//向客户端输出该字符串
os.println("服务端收到了你的消息:" + line);
//刷新输出流,使Client马上收到该字符串 | os.flush();
line = is.readLine();
}
// 关闭连接
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
});
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
} | repos\spring-boot-student-master\spring-boot-student-netty\src\main\java\com\xiaolyuh\bio\SocketServer.java | 1 |
请完成以下Java代码 | public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
} | public void setRole(String role) {
this.role = role;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
} | repos\E-commerce-project-springBoot-master2\JtProject\src\main\java\com\jtspringproject\JtSpringProject\models\User.java | 1 |
请完成以下Java代码 | public OffsetTime getOffsetTime() {
return offsetTime;
}
public void setOffsetTime(OffsetTime offsetTime) {
this.offsetTime = offsetTime;
}
public Instant getInstant() {
return instant;
}
public void setInstant(Instant instant) {
this.instant = instant;
}
public LocalDateTime getLocalDateTime() {
return localDateTime;
}
public void setLocalDateTime(LocalDateTime localDateTime) {
this.localDateTime = localDateTime;
} | public OffsetDateTime getOffsetDateTime() {
return offsetDateTime;
}
public void setOffsetDateTime(OffsetDateTime offsetDateTime) {
this.offsetDateTime = offsetDateTime;
}
public ZonedDateTime getZonedDateTime() {
return zonedDateTime;
}
public void setZonedDateTime(ZonedDateTime zonedDateTime) {
this.zonedDateTime = zonedDateTime;
}
} | repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\hibernate\pojo\TemporalValues.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PostService implements IPostService {
@Autowired
private PostRepository postRepository;
@Autowired
private IUserService userService;
@Override
public List<Post> getPostsList(int page, int size, String sortDir, String sort) {
PageRequest pageReq
= PageRequest.of(page, size, Sort.Direction.fromString(sortDir), sort);
Page<Post> posts = postRepository.findByUser(userService.getCurrentUser(), pageReq);
return posts.getContent(); | }
@Override
public void updatePost(Post post) {
postRepository.save(post);
}
@Override
public Post createPost(Post post) {
return postRepository.save(post);
}
@Override
public Post getPostById(Long id) {
return postRepository.getReferenceById(id);
}
} | repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\springpagination\service\PostService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ZebraConfigRepository
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final transient IMsgBL msgBL = Services.get(IMsgBL.class);
private static final AdMessageKey MSG_NO_ZEBRA_CONFIG = AdMessageKey.of("WEBUI_NoZebraConfigDefined");
public I_AD_Zebra_Config getById(@NonNull final ZebraConfigId zebraConfigId)
{
return loadOutOfTrx(zebraConfigId.getRepoId(), I_AD_Zebra_Config.class);
}
public ZebraConfigId getDefaultZebraConfigId()
{
final ZebraConfigId defaultZebraConfigId = queryBL
.createQueryBuilderOutOfTrx(I_AD_Zebra_Config.class)
.addEqualsFilter(I_AD_Zebra_Config.COLUMNNAME_IsDefault, true)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient()
.create()
.firstId(ZebraConfigId::ofRepoIdOrNull);
if (defaultZebraConfigId == null)
{
throw new AdempiereException(MSG_NO_ZEBRA_CONFIG);
} | return defaultZebraConfigId;
}
public ZebraConfigId retrieveZebraConfigId(final BPartnerId partnerId, final ZebraConfigId defaultZebraConfigId)
{
final I_C_BP_PrintFormat printFormat = queryBL
.createQueryBuilder(I_C_BP_PrintFormat.class)
.addEqualsFilter(I_C_BP_PrintFormat.COLUMNNAME_C_BPartner_ID, partnerId)
.addNotNull(I_C_BP_PrintFormat.COLUMN_AD_Zebra_Config_ID)
.create()
.firstOnly(I_C_BP_PrintFormat.class);
if (printFormat != null)
{
return ZebraConfigId.ofRepoIdOrNull(printFormat.getAD_Zebra_Config_ID());
}
return defaultZebraConfigId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\ZebraConfigRepository.java | 2 |
请完成以下Spring Boot application配置 | app.datasource.ds1.url=jdbc:mysql://localhost:3306/authorsdb?createDatabaseIfNotExist=true
app.datasource.ds1.username=root
app.datasource.ds1.password=root
app.datasource.ds1.connection-timeout=50000
app.datasource.ds1.idle-timeout=300000
app.datasource.ds1.max-lifetime=900000
app.datasource.ds1.maximum-pool-size=5
app.datasource.ds1.minimum-idle=5
app.datasource.ds1.pool-name=MySqlPoolConnection
app.flyway.ds1.location=classpath:db/migration/mysql
app.datasource.ds2.url=jdbc:postgresql://localhost:5432/postgres?currentSchema=booksdb
app.datasource.ds2.username=postgres
app.datasource.ds2.password=postgres
app.datasource.ds2.connection-timeout=50000
app.datasource.ds2.idle-timeout=300000
app.datasource.ds2.max-lifetime=900000
app.datasource.ds2.maximum-po | ol-size=6
app.datasource.ds2.minimum-idle=6
app.datasource.ds2.pool-name=PostgreSqlConnectionPool
app.flyway.ds2.location=classpath:db/migration/postgresql
app.flyway.ds2.schema=booksdb
spring.flyway.enabled=false
spring.jpa.show-sql=true
logging.level.com.zaxxer.hikari.HikariConfig=DEBUG
logging.level.com.zaxxer.hikari=TRACE | repos\Hibernate-SpringBoot-master\HibernateSpringBootFlywayTwoVendors\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public int getPA_GoalParent_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_GoalParent_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_PA_Measure getPA_Measure() throws RuntimeException
{
return (I_PA_Measure)MTable.get(getCtx(), I_PA_Measure.Table_Name)
.getPO(getPA_Measure_ID(), get_TrxName()); }
/** Set Measure.
@param PA_Measure_ID
Concrete Performance Measurement
*/
public void setPA_Measure_ID (int PA_Measure_ID)
{
if (PA_Measure_ID < 1)
set_Value (COLUMNNAME_PA_Measure_ID, null);
else
set_Value (COLUMNNAME_PA_Measure_ID, Integer.valueOf(PA_Measure_ID));
}
/** Get Measure.
@return Concrete Performance Measurement
*/
public int getPA_Measure_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Measure_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Relative Weight.
@param RelativeWeight
Relative weight of this step (0 = ignored)
*/
public void setRelativeWeight (BigDecimal RelativeWeight) | {
set_Value (COLUMNNAME_RelativeWeight, RelativeWeight);
}
/** Get Relative Weight.
@return Relative weight of this step (0 = ignored)
*/
public BigDecimal getRelativeWeight ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RelativeWeight);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_Goal.java | 1 |
请完成以下Java代码 | public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getResourceType() {
return resourceType;
}
public void setResourceType(String resourceType) {
this.resourceType = resourceType;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPermission() {
return permission;
}
public void setPermission(String permission) {
this.permission = permission;
}
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
} | public String getParentIds() {
return parentIds;
}
public void setParentIds(String parentIds) {
this.parentIds = parentIds;
}
public Boolean getAvailable() {
return available;
}
public void setAvailable(Boolean available) {
this.available = available;
}
public List<SysRole> getRoles() {
return roles;
}
public void setRoles(List<SysRole> roles) {
this.roles = roles;
}
} | repos\springboot-demo-master\shiro\src\main\java\com\et\shiro\entity\SysPermission.java | 1 |
请完成以下Java代码 | public class JsonConverters
{
public JsonPagingDescriptor createJsonPagingDescriptor(@NonNull final QueryResultPage<?> page)
{
final JsonPagingDescriptorBuilder jsonPagingDescriptor = JsonPagingDescriptor.builder()
.pageSize(page.getItems().size())
.resultTimestamp(page.getResultTimestamp().toEpochMilli())
.totalSize(page.getTotalSize());
final PageDescriptor nextPageDescriptor = page.getNextPageDescriptor();
if (nextPageDescriptor != null)
{
jsonPagingDescriptor.nextPage(nextPageDescriptor.getPageIdentifier().getCombinedUid());
}
return jsonPagingDescriptor.build();
}
public JsonExternalId toJsonOrNull(@Nullable final ExternalId externalId)
{
if (externalId == null)
{
return null;
}
return JsonExternalId.of(externalId.getValue());
}
public ExternalId fromJsonOrNull(@Nullable final JsonExternalId jsonExternalId) | {
if (jsonExternalId == null)
{
return null;
}
return ExternalId.of(jsonExternalId.getValue());
}
@NonNull
public JsonAttachmentType toJsonAttachmentType(@NonNull final AttachmentEntryType type)
{
switch (type)
{
case Data:
return JsonAttachmentType.Data;
case URL:
return JsonAttachmentType.URL;
case LocalFileURL:
return JsonAttachmentType.LocalFileURL;
default:
throw new AdempiereException("Unknown AttachmentEntryType")
.appendParametersToMessage()
.setParameter("type", type);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\utils\JsonConverters.java | 1 |
请完成以下Java代码 | public class CompositeReceiptScheduleListener implements IReceiptScheduleListener
{
private final CopyOnWriteArrayList<IReceiptScheduleListener> listeners = new CopyOnWriteArrayList<IReceiptScheduleListener>();
public void addReceiptScheduleListener(final IReceiptScheduleListener listener)
{
Check.assumeNotNull(listener, "listener not null");
listeners.addIfAbsent(listener);
}
@Override
public void onReceiptScheduleAllocReversed(final I_M_ReceiptSchedule_Alloc rsa, final I_M_ReceiptSchedule_Alloc rsaReversal)
{
for (final IReceiptScheduleListener listener : listeners)
{
listener.onReceiptScheduleAllocReversed(rsa, rsaReversal);
}
}
@Override
public void onBeforeClose(I_M_ReceiptSchedule receiptSchedule)
{
for (final IReceiptScheduleListener listener : listeners)
{
listener.onBeforeClose(receiptSchedule);
}
}
@Override
public void onAfterClose(I_M_ReceiptSchedule receiptSchedule)
{
for (final IReceiptScheduleListener listener : listeners)
{ | listener.onAfterClose(receiptSchedule);
}
}
@Override
public void onBeforeReopen(I_M_ReceiptSchedule receiptSchedule)
{
for (final IReceiptScheduleListener listener : listeners)
{
listener.onBeforeReopen(receiptSchedule);
}
}
@Override
public void onAfterReopen(I_M_ReceiptSchedule receiptSchedule)
{
for (final IReceiptScheduleListener listener : listeners)
{
listener.onAfterReopen(receiptSchedule);
}
}
@Override
public String toString()
{
return "CompositeReceiptScheduleListener [listeners=" + listeners + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\spi\impl\CompositeReceiptScheduleListener.java | 1 |
请完成以下Java代码 | protected Class<?> requiredViewClass() {
return MustacheView.class;
}
/**
* Set the {@link Charset} to use.
* @param charset the charset
* @since 4.1.0
*/
public void setCharset(@Nullable Charset charset) {
this.charset = charset;
}
/**
* Set the name of the charset to use.
* @param charset the charset
* @deprecated since 4.1.0 for removal in 4.3.0 in favor of
* {@link #setCharset(Charset)}
*/
@Deprecated(since = "4.1.0", forRemoval = true)
public void setCharset(@Nullable String charset) { | setCharset((charset != null) ? Charset.forName(charset) : null);
}
@Override
protected AbstractUrlBasedView buildView(String viewName) throws Exception {
MustacheView view = (MustacheView) super.buildView(viewName);
view.setCompiler(this.compiler);
view.setCharset(this.charset);
return view;
}
@Override
protected AbstractUrlBasedView instantiateView() {
return (getViewClass() == MustacheView.class) ? new MustacheView() : super.instantiateView();
}
} | repos\spring-boot-main\module\spring-boot-mustache\src\main\java\org\springframework\boot\mustache\servlet\view\MustacheViewResolver.java | 1 |
请完成以下Java代码 | public String toString() {
return (
"ProcessInstance{" +
"id='" +
id +
'\'' +
", name='" +
name +
'\'' +
", processDefinitionId='" +
processDefinitionId +
'\'' +
", processDefinitionKey='" +
processDefinitionKey +
'\'' +
", parentId='" +
parentId +
'\'' +
", initiator='" +
initiator +
'\'' +
", startDate=" +
startDate + | ", completedDate=" +
completedDate +
", businessKey='" +
businessKey +
'\'' +
", status=" +
status +
", processDefinitionVersion='" +
processDefinitionVersion +
'\'' +
", processDefinitionName='" +
processDefinitionName +
'\'' +
'}'
);
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\ProcessInstanceImpl.java | 1 |
请完成以下Java代码 | public void setC_ChargeType_ID (int C_ChargeType_ID)
{
if (C_ChargeType_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_ChargeType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_ChargeType_ID, Integer.valueOf(C_ChargeType_ID));
}
/** Get Charge Type.
@return Charge Type */
public int getC_ChargeType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_ChargeType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name) | {
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ChargeType.java | 1 |
请完成以下Java代码 | private void appendXForwarded(URI uri) {
// Append the legacy headers if they were already added upstream
String host = headers.getFirst("x-forwarded-host");
if (host == null) {
return;
}
host = host + "," + uri.getHost();
headers.set("x-forwarded-host", host);
String proto = headers.getFirst("x-forwarded-proto");
if (proto == null) {
return;
}
proto = proto + "," + uri.getScheme();
headers.set("x-forwarded-proto", proto);
}
private void appendForwarded(URI uri) {
String forwarded = headers.getFirst("forwarded");
if (forwarded != null) {
forwarded = forwarded + ",";
}
else {
forwarded = "";
}
forwarded = forwarded + forwarded(uri, exchange.getRequest().getHeaders().getFirst("host"));
headers.set("forwarded", forwarded);
}
private String forwarded(URI uri, @Nullable String hostHeader) {
if (StringUtils.hasText(hostHeader)) {
return "host=" + hostHeader;
}
if ("http".equals(uri.getScheme())) {
return "host=" + uri.getHost();
}
return String.format("host=%s;proto=%s", uri.getHost(), uri.getScheme());
}
private @Nullable Publisher<?> body() {
Publisher<?> body = this.body;
if (body != null) {
return body;
}
body = getRequestBody();
hasBody = true; // even if it's null
return body;
}
/**
* Search for the request body if it was already deserialized using
* <code>@RequestBody</code>. If it is not found then deserialize it in the same way
* that it would have been for a <code>@RequestBody</code>.
* @return the request body | */
private @Nullable Mono<Object> getRequestBody() {
for (String key : bindingContext.getModel().asMap().keySet()) {
if (key.startsWith(BindingResult.MODEL_KEY_PREFIX)) {
BindingResult result = (BindingResult) bindingContext.getModel().asMap().get(key);
Object target = result.getTarget();
if (target != null) {
return Mono.just(target);
}
}
}
return null;
}
protected static class BodyGrabber {
public Publisher<Object> body(@RequestBody Publisher<Object> body) {
return body;
}
}
protected static class BodySender {
@ResponseBody
public @Nullable Publisher<Object> body() {
return null;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-proxyexchange-webflux\src\main\java\org\springframework\cloud\gateway\webflux\ProxyExchange.java | 1 |
请完成以下Java代码 | public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
public FilterChainProxy getFilterChainProxy() {
return this.filterChainProxy;
}
static class DebugRequestWrapper extends HttpServletRequestWrapper {
private static final Logger logger = new Logger();
DebugRequestWrapper(HttpServletRequest request) {
super(request);
}
@Override
public HttpSession getSession() {
boolean sessionExists = super.getSession(false) != null;
HttpSession session = super.getSession(); | if (!sessionExists) {
DebugRequestWrapper.logger.info("New HTTP session created: " + session.getId(), true);
}
return session;
}
@Override
public HttpSession getSession(boolean create) {
if (!create) {
return super.getSession(create);
}
return getSession();
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\debug\DebugFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static class AsyncContinuationConfiguration implements JobHandlerConfiguration {
protected String atomicOperation;
protected String transitionId;
public String getAtomicOperation() {
return atomicOperation;
}
public void setAtomicOperation(String atomicOperation) {
this.atomicOperation = atomicOperation;
}
public String getTransitionId() {
return transitionId;
}
public void setTransitionId(String transitionId) {
this.transitionId = transitionId;
}
@Override
public String toCanonicalString() {
String configuration = atomicOperation;
if(transitionId != null) { | // store id of selected transition in case this is async after.
// id is not serialized with the execution -> we need to remember it as
// job handler configuration.
configuration += "$" + transitionId;
}
return configuration;
}
}
public void onDelete(AsyncContinuationConfiguration configuration, JobEntity jobEntity) {
// do nothing
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\AsyncContinuationJobHandler.java | 2 |
请完成以下Java代码 | public void setCdtNoteAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.cdtNoteAmt = value;
}
/**
* Gets the value of the taxAmt property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the taxAmt property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTaxAmt().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TaxAmountAndType1 }
*
*
*/
public List<TaxAmountAndType1> getTaxAmt() {
if (taxAmt == null) {
taxAmt = new ArrayList<TaxAmountAndType1>();
}
return this.taxAmt;
}
/**
* Gets the value of the adjstmntAmtAndRsn property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the adjstmntAmtAndRsn property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAdjstmntAmtAndRsn().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DocumentAdjustment1 }
*
*
*/ | public List<DocumentAdjustment1> getAdjstmntAmtAndRsn() {
if (adjstmntAmtAndRsn == null) {
adjstmntAmtAndRsn = new ArrayList<DocumentAdjustment1>();
}
return this.adjstmntAmtAndRsn;
}
/**
* Gets the value of the rmtdAmt property.
*
* @return
* possible object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public ActiveOrHistoricCurrencyAndAmount getRmtdAmt() {
return rmtdAmt;
}
/**
* Sets the value of the rmtdAmt property.
*
* @param value
* allowed object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public void setRmtdAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.rmtdAmt = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\RemittanceAmount2.java | 1 |
请完成以下Java代码 | public void execute() throws BuildException {
if (dir==null) {
throw new BuildException("dir attribute is required with the launch task");
}
if (script==null) {
throw new BuildException("script attribute is required with the launch task");
}
String[] cmd = null;
String executable = getExecutable();
if (args!=null) {
List<String> pieces = new ArrayList<String>();
pieces.add(executable);
StringTokenizer tokenizer = new StringTokenizer("args", " ");
while (tokenizer.hasMoreTokens()) {
pieces.add(tokenizer.nextToken());
}
cmd = pieces.toArray(new String[pieces.size()]);
} else {
cmd = new String[]{executable};
}
LaunchThread.launch(this,cmd,dir,msg);
}
public String getExecutable() {
String os = System.getProperty("os.name").toLowerCase();
String dirPath = dir.getAbsolutePath();
String base = dirPath+FILESEPARATOR+script;
if (exists(base)) {
return base;
}
if (os.indexOf("windows")!=-1) {
if (exists(base+".exe")) {
return base+".exe";
}
if (exists(base+".bat")) {
return base+".bat";
}
} | if (os.indexOf("linux")!=-1 || os.indexOf("mac")!=-1) {
if (exists(base+".sh")) {
return base+".sh";
}
}
throw new BuildException("couldn't find executable for script "+base);
}
public boolean exists(String path) {
File file = new File(path);
return (file.exists());
}
public void setDir(File dir) {
this.dir = dir;
}
public void setScript(String script) {
this.script = script;
}
public void setMsg(String msg) {
this.msg = msg;
}
public void setArgs(String args) {
this.args = args;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ant\LaunchTask.java | 1 |
请完成以下Java代码 | public colgroup setChar(String character)
{
addAttribute("char",character);
return(this);
}
/**
Sets the charoff="" attribute.
@param char_off When present this attribute specifies the offset
of the first occurrence of the alignment character on each line.
*/
public colgroup setCharOff(int char_off)
{
addAttribute("charoff",Integer.toString(char_off));
return(this);
}
/**
Sets the charoff="" attribute.
@param char_off When present this attribute specifies the offset
of the first occurrence of the alignment character on each line.
*/
public colgroup setCharOff(String char_off)
{
addAttribute("charoff",char_off);
return(this);
}
/**
Sets the lang="" and xml:lang="" attributes
@param lang the lang="" and xml:lang="" attributes
*/
public Element setLang(String lang)
{
addAttribute("lang",lang);
addAttribute("xml:lang",lang);
return this;
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public colgroup addElement(String hashcode,Element element)
{
addElementToRegistry(hashcode,element); | return(this);
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public colgroup addElement(String hashcode,String element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public colgroup addElement(Element element)
{
addElementToRegistry(element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public colgroup addElement(String element)
{
addElementToRegistry(element);
return(this);
}
/**
Removes an Element from the element.
@param hashcode the name of the element to be removed.
*/
public colgroup removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\colgroup.java | 1 |
请完成以下Java代码 | private boolean isAggregateHU(final HUEditorRow huRow)
{
final I_M_HU hu = huRow.getM_HU();
return handlingUnitsBL.isAggregateHU(hu);
}
private final IAttributeStorage getAttributeStorage(final IHUContext huContext, final I_M_HU hu)
{
final IAttributeStorageFactory attributeStorageFactory = huContext.getHUAttributeStorageFactory();
final IAttributeStorage attributeStorage = attributeStorageFactory.getAttributeStorage(hu);
return attributeStorage;
}
private final HUTransformService newHUTransformation()
{
return HUTransformService.builder()
.referencedObjects(getContextDocumentLines())
.build(); | }
/**
* @return context document/lines (e.g. the receipt schedules)
*/
private List<TableRecordReference> getContextDocumentLines()
{
if (view == null)
{
return ImmutableList.of();
}
return view.getReferencingDocumentPaths()
.stream()
.map(referencingDocumentPath -> documentCollections.getTableRecordReference(referencingDocumentPath))
.collect(GuavaCollectors.toImmutableList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUIHUCreationWithSerialNumberService.java | 1 |
请完成以下Java代码 | public void setPersonalDataCategory (final @Nullable java.lang.String PersonalDataCategory)
{
set_Value (COLUMNNAME_PersonalDataCategory, PersonalDataCategory);
}
@Override
public java.lang.String getPersonalDataCategory()
{
return get_ValueAsString(COLUMNNAME_PersonalDataCategory);
}
@Override
public void setReadOnlyLogic (final @Nullable java.lang.String ReadOnlyLogic)
{
set_Value (COLUMNNAME_ReadOnlyLogic, ReadOnlyLogic);
}
@Override
public java.lang.String getReadOnlyLogic()
{
return get_ValueAsString(COLUMNNAME_ReadOnlyLogic);
}
@Override
public void setSelectionColumnSeqNo (final int SelectionColumnSeqNo)
{
set_Value (COLUMNNAME_SelectionColumnSeqNo, SelectionColumnSeqNo);
}
@Override
public int getSelectionColumnSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SelectionColumnSeqNo);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setTechnicalNote (final @Nullable java.lang.String TechnicalNote)
{
set_Value (COLUMNNAME_TechnicalNote, TechnicalNote);
}
@Override
public java.lang.String getTechnicalNote()
{
return get_ValueAsString(COLUMNNAME_TechnicalNote);
}
@Override
public void setValueMax (final @Nullable java.lang.String ValueMax)
{
set_Value (COLUMNNAME_ValueMax, ValueMax);
} | @Override
public java.lang.String getValueMax()
{
return get_ValueAsString(COLUMNNAME_ValueMax);
}
@Override
public void setValueMin (final @Nullable java.lang.String ValueMin)
{
set_Value (COLUMNNAME_ValueMin, ValueMin);
}
@Override
public java.lang.String getValueMin()
{
return get_ValueAsString(COLUMNNAME_ValueMin);
}
@Override
public void setVersion (final BigDecimal Version)
{
set_Value (COLUMNNAME_Version, Version);
}
@Override
public BigDecimal getVersion()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Version);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setVFormat (final @Nullable java.lang.String VFormat)
{
set_Value (COLUMNNAME_VFormat, VFormat);
}
@Override
public java.lang.String getVFormat()
{
return get_ValueAsString(COLUMNNAME_VFormat);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Column.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
@Override
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
if (this.groupId != null && userId != null) {
throw new ActivitiException("Cannot assign a userId to a task assignment that already has a groupId");
}
this.userId = userId;
} | @Override
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
if (this.userId != null && groupId != null) {
throw new ActivitiException("Cannot assign a groupId to a task assignment that already has a userId");
}
this.groupId = groupId;
}
@Override
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricIdentityLinkEntity.java | 1 |
请完成以下Java代码 | public void setProcessInfo(ProcessInfo pi)
{
m_pi = pi;
}
public ProcessInfo getProcessInfo()
{
return m_pi;
}
// End
/**
* Start Batch
* @param process
* @return running thread
*/
public Thread startBatch (final Runnable process)
{
Thread worker = new Thread()
{
@Override
public void run()
{
setBusy(true);
process.run();
setBusy(false);
}
};
worker.start();
return worker;
} // startBatch
/**
* @return Returns the AD_Form_ID.
*/
public int getAD_Form_ID ()
{
return p_AD_Form_ID;
} // getAD_Window_ID
public int getWindowNo()
{
return m_WindowNo; | }
/**
* @return Returns the manuBar
*/
public JMenuBar getMenu()
{
return menuBar;
}
public void showFormWindow()
{
if (m_panel instanceof FormPanel2)
{
((FormPanel2)m_panel).showFormWindow(m_WindowNo, this);
}
else
{
AEnv.showCenterScreenOrMaximized(this);
}
}
} // FormFrame | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\FormFrame.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<DeadLetterJobEntity> findJobsByExecutionId(String executionId) {
DbSqlSession dbSqlSession = getDbSqlSession();
// If the execution has been inserted in the same command execution as this query, there can't be any in the database
if (isEntityInserted(dbSqlSession, "execution", executionId)) {
return getListFromCache(deadLetterByExecutionIdMatcher, executionId);
}
return getList(dbSqlSession, "selectDeadLetterJobsByExecutionId", executionId, deadLetterByExecutionIdMatcher, true);
}
@Override
@SuppressWarnings("unchecked")
public List<DeadLetterJobEntity> findJobsByProcessInstanceId(final String processInstanceId) {
return getDbSqlSession().selectList("selectDeadLetterJobsByProcessInstanceId", processInstanceId);
} | @Override
public void updateJobTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().directUpdate("updateDeadLetterJobTenantIdForDeployment", params);
}
@Override
protected IdGenerator getIdGenerator() {
return jobServiceConfiguration.getIdGenerator();
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\data\impl\MybatisDeadLetterJobDataManager.java | 2 |
请完成以下Java代码 | protected Map<String, Object> normalizeProperties() {
Map<String, Object> normalizedProperties = new HashMap<>();
this.properties.forEach(normalizedProperties::put);
return normalizedProperties;
}
protected abstract T doBind();
public T bind() {
validate();
Assert.hasText(this.name, "name may not be empty");
Assert.isTrue(this.properties != null || this.normalizedProperties != null,
"properties and normalizedProperties both may not be null");
if (this.normalizedProperties == null) {
this.normalizedProperties = normalizeProperties(); | }
T bound = doBind();
if (this.eventFunction != null && this.service.publisher != null) {
ApplicationEvent applicationEvent = this.eventFunction.apply(bound, this.normalizedProperties);
this.service.publisher.publishEvent(applicationEvent);
}
return bound;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\support\ConfigurationService.java | 1 |
请完成以下Java代码 | public class ArchiveSetDataHandlerConverter implements Converter<I_AD_Archive, I_AD_Archive>
{
public static final transient ArchiveSetDataHandlerConverter instance = new ArchiveSetDataHandlerConverter();
@Override
public I_AD_Archive convert(final I_AD_Archive tempArchive)
{
checkValid(tempArchive);
// Assume that replication module is saving directly to AD_Archive.BinaryData
final byte[] data = tempArchive.getBinaryData();
final Properties ctx = InterfaceWrapperHelper.getCtx(tempArchive);
final IArchiveStorage fsStorage = Services.get(IArchiveStorageFactory.class).getArchiveStorage(ctx, IArchiveStorageFactory.StorageType.Filesystem);
fsStorage.setBinaryData(tempArchive, data); | InterfaceWrapperHelper.save(tempArchive);
return tempArchive;
}
private void checkValid(final I_AD_Archive tempArchive)
{
final int expectedTableId = MTable.getTable_ID(org.compiere.model.I_AD_Archive.Table_Name);
final int adTableId = tempArchive.getAD_Table_ID();
Check.assume(adTableId == expectedTableId,
"AD_Table_ID shall be {} (AD_Archive) and not {} for {}",
expectedTableId, adTableId, tempArchive);
Check.assume(!tempArchive.isFileSystem(), "Archive {} shall NOT be a filesystem archive", tempArchive);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\rpl\requesthandler\ArchiveSetDataHandlerConverter.java | 1 |
请完成以下Java代码 | public static final void checkSequences(final Properties ctx)
{
final ITableSequenceChecker tableSequenceChecker = Services.get(ISequenceDAO.class).createTableSequenceChecker(ctx);
tableSequenceChecker.setSequenceRangeCheck(true);
tableSequenceChecker.setFailOnFirstError(false);
tableSequenceChecker.run();
checkClientSequences(ctx);
}
/**
* Validate Sequences
*
* @param ctx context
*/
public static void validate(final Properties ctx)
{
try
{
checkSequences(ctx);
}
catch (final Exception e)
{
s_log.error("validate", e);
}
} // validate | /**
* Check/Initialize DocumentNo/Value Sequences for all Clients
*
* @param ctx context
* @param sp server process or null
*/
private static void checkClientSequences(final Properties ctx)
{
final IClientDAO clientDAO = Services.get(IClientDAO.class);
final String trxName = null;
// Sequence for DocumentNo/Value
for (final I_AD_Client client : clientDAO.retrieveAllClients(ctx))
{
if (!client.isActive())
{
continue;
}
MSequence.checkClientSequences(ctx, client.getAD_Client_ID(), trxName);
}
} // checkClientSequences
} // SequenceCheck | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\SequenceCheck.java | 1 |
请完成以下Java代码 | public int getC_PaySchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_C_PaySchedule_ID);
}
@Override
public void setDiscount (final BigDecimal Discount)
{
set_Value (COLUMNNAME_Discount, Discount);
}
@Override
public BigDecimal getDiscount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Discount);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setDiscountDays (final int DiscountDays)
{
set_Value (COLUMNNAME_DiscountDays, DiscountDays);
}
@Override
public int getDiscountDays()
{
return get_ValueAsInt(COLUMNNAME_DiscountDays);
}
@Override
public void setGraceDays (final int GraceDays)
{
set_Value (COLUMNNAME_GraceDays, GraceDays);
}
@Override
public int getGraceDays()
{
return get_ValueAsInt(COLUMNNAME_GraceDays);
}
@Override
public void setIsValid (final boolean IsValid)
{
set_Value (COLUMNNAME_IsValid, IsValid);
}
@Override
public boolean isValid()
{
return get_ValueAsBoolean(COLUMNNAME_IsValid);
}
/**
* NetDay AD_Reference_ID=167
* Reference name: Weekdays
*/
public static final int NETDAY_AD_Reference_ID=167;
/** Sunday = 7 */
public static final String NETDAY_Sunday = "7";
/** Monday = 1 */
public static final String NETDAY_Monday = "1";
/** Tuesday = 2 */
public static final String NETDAY_Tuesday = "2";
/** Wednesday = 3 */
public static final String NETDAY_Wednesday = "3";
/** Thursday = 4 */
public static final String NETDAY_Thursday = "4";
/** Friday = 5 */
public static final String NETDAY_Friday = "5"; | /** Saturday = 6 */
public static final String NETDAY_Saturday = "6";
@Override
public void setNetDay (final @Nullable java.lang.String NetDay)
{
set_Value (COLUMNNAME_NetDay, NetDay);
}
@Override
public java.lang.String getNetDay()
{
return get_ValueAsString(COLUMNNAME_NetDay);
}
@Override
public void setNetDays (final int NetDays)
{
set_Value (COLUMNNAME_NetDays, NetDays);
}
@Override
public int getNetDays()
{
return get_ValueAsInt(COLUMNNAME_NetDays);
}
@Override
public void setPercentage (final BigDecimal Percentage)
{
set_Value (COLUMNNAME_Percentage, Percentage);
}
@Override
public BigDecimal getPercentage()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Percentage);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaySchedule.java | 1 |
请完成以下Java代码 | public final void addNotRetryableExceptions(Class<? extends Exception>... exceptionTypes) {
add(false, exceptionTypes);
notRetryable(Arrays.stream(exceptionTypes));
}
/**
* Subclasses can override this to receive notification of configuration of not
* retryable exceptions.
* @param notRetryable the not retryable exceptions.
* @since 2.9.3
*/
protected void notRetryable(Stream<Class<? extends Exception>> notRetryable) {
}
/**
* Add exception types that can be retried. Call this after {@link #defaultFalse()} to
* specify those exception types that should be classified as true.
* All others will be retried, unless {@link #defaultFalse()} has been called.
* @param exceptionTypes the exception types.
* @since 2.8.4
* @see #removeClassification(Class)
* @see #setClassifications(Map, boolean)
*/
@SafeVarargs
@SuppressWarnings("varargs")
public final void addRetryableExceptions(Class<? extends Exception>... exceptionTypes) {
add(true, exceptionTypes);
}
@SafeVarargs
@SuppressWarnings("varargs")
private void add(boolean classified, Class<? extends Exception>... exceptionTypes) {
Assert.notNull(exceptionTypes, "'exceptionTypes' cannot be null");
Assert.noNullElements(exceptionTypes, "'exceptionTypes' cannot contain nulls");
for (Class<? extends Exception> exceptionType : exceptionTypes) {
Assert.isTrue(Exception.class.isAssignableFrom(exceptionType),
() -> "exceptionType " + exceptionType + " must be an Exception");
this.exceptionMatcher.getEntries().put(exceptionType, classified);
}
}
/**
* Remove an exception type from the configured list. By default, the following
* exceptions will not be retried:
* <ul>
* <li>{@link DeserializationException}</li>
* <li>{@link MessageConversionException}</li>
* <li>{@link ConversionException}</li>
* <li>{@link MethodArgumentResolutionException}</li>
* <li>{@link NoSuchMethodException}</li>
* <li>{@link ClassCastException}</li>
* </ul>
* All others will be retried, unless {@link #defaultFalse()} has been called. | * @param exceptionType the exception type.
* @return the classification of the exception if removal was successful;
* null otherwise.
* @since 2.8.4
* @see #addNotRetryableExceptions(Class...)
* @see #setClassifications(Map, boolean)
*/
@Nullable
public Boolean removeClassification(Class<? extends Exception> exceptionType) {
return this.exceptionMatcher.getEntries().remove(exceptionType);
}
/**
* Extended to provide visibility to the current classified exceptions.
*
* @author Gary Russell
*
*/
@SuppressWarnings("serial")
private static final class ExtendedExceptionMatcher extends ExceptionMatcher {
ExtendedExceptionMatcher(Map<Class<? extends Throwable>, Boolean> typeMap, boolean defaultValue) {
super(typeMap, defaultValue, true);
}
@Override
protected Map<Class<? extends Throwable>, Boolean> getEntries() { // NOSONAR worthless override
return super.getEntries();
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\ExceptionClassifier.java | 1 |
请完成以下Java代码 | public String toString()
{
return "MProductPricing ["
+ pricingCtx
+ ", " + result
+ "]";
}
public void setConvertPriceToContextUOM(boolean convertPriceToContextUOM)
{
pricingCtx.setConvertPriceToContextUOM(convertPriceToContextUOM);
}
public void setReferencedObject(Object referencedObject)
{
pricingCtx.setReferencedObject(referencedObject);
}
// metas: end
public int getC_TaxCategory_ID() | {
return TaxCategoryId.toRepoId(result.getTaxCategoryId());
}
public boolean isManualPrice()
{
return pricingCtx.getManualPriceEnabled().isTrue();
}
public void setManualPrice(boolean manualPrice)
{
pricingCtx.setManualPriceEnabled(manualPrice);
}
public void throwProductNotOnPriceListException()
{
throw new ProductNotOnPriceListException(pricingCtx);
}
} // MProductPrice | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MProductPricing.java | 1 |
请完成以下Java代码 | public void clearTransactions()
{
if (trxAttributesCollector != null)
{
trxAttributesCollector.clearTransactions();
}
}
@Override
public void transferAttributes(@NonNull final IHUAttributeTransferRequest request)
{
logger.trace("Transfering attributes for {}", request);
final IAttributeSet attributesFrom = request.getAttributesFrom();
final IAttributeStorage attributesTo = request.getAttributesTo();
for (final I_M_Attribute attribute : attributesFrom.getAttributes())
{
//
// If "toAttributes" does not support our attribute then skip it
if (!attributesTo.hasAttribute(attribute))
{
logger.trace("Skip transfering attribute {} because target storage does not have it", attribute);
continue;
}
final IHUAttributeTransferStrategy transferFromStrategy = getHUAttributeTransferStrategy(request, attribute);
//
// Only transfer value if the request allows it
if (!transferFromStrategy.isTransferable(request, attribute))
{
logger.trace("Skip transfering attribute {} because transfer strategy says so: {}", attribute, transferFromStrategy);
continue;
}
transferFromStrategy.transferAttribute(request, attribute);
logger.trace("Attribute {} was transfered to target storage", attribute);
}
}
private IHUAttributeTransferStrategy getHUAttributeTransferStrategy(final IHUAttributeTransferRequest request, final I_M_Attribute attribute)
{
final IAttributeSet attributesFrom = request.getAttributesFrom();
if (attributesFrom instanceof IAttributeStorage)
{
return ((IAttributeStorage)attributesFrom).retrieveTransferStrategy(attribute);
}
final IAttributeStorage attributesTo = request.getAttributesTo();
return attributesTo.retrieveTransferStrategy(attribute);
}
@Override
public IAllocationResult createAllocationResult()
{
final List<IHUTransactionAttribute> attributeTrxs = getAndClearTransactions();
if (attributeTrxs.isEmpty())
{
// no transactions, nothing to do | return AllocationUtils.nullResult();
}
return AllocationUtils.createQtyAllocationResult(
BigDecimal.ZERO, // qtyToAllocate
BigDecimal.ZERO, // qtyAllocated
Collections.emptyList(), // trxs
attributeTrxs // attribute transactions
);
}
@Override
public IAllocationResult createAndProcessAllocationResult()
{
final IAllocationResult result = createAllocationResult();
Services.get(IHUTrxBL.class).createTrx(huContext, result);
return result;
}
@Override
public void dispose()
{
// Unregister the listener/collector
if (attributeStorageFactory != null && trxAttributesCollector != null)
{
trxAttributesCollector.dispose();
attributeStorageFactory.removeAttributeStorageListener(trxAttributesCollector);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\HUTransactionAttributeBuilder.java | 1 |
请完成以下Java代码 | protected CostDetailCreateResult createCostForMatchInvoice_MaterialCosts(final CostDetailCreateRequest request)
{
final CurrentCost currentCosts = utils.getCurrentCost(request);
final CostDetailPreviousAmounts previousCosts = CostDetailPreviousAmounts.of(currentCosts);
final CostDetailCreateResult result = utils.createCostDetailRecordWithChangedCosts(request, previousCosts);
currentCosts.addWeightedAverage(request.getAmt(), request.getQty(), utils.getQuantityUOMConverter());
utils.saveCurrentCost(currentCosts);
return result;
}
@Override
protected CostDetailCreateResult createOutboundCostDefaultImpl(final CostDetailCreateRequest request)
{
final boolean isReturnTrx = request.getQty().signum() > 0;
final CurrentCost currentCosts = utils.getCurrentCost(request);
final CostDetailPreviousAmounts previousCosts = CostDetailPreviousAmounts.of(currentCosts);
final CostDetailCreateResult result;
if (isReturnTrx)
{
result = utils.createCostDetailRecordWithChangedCosts(request, previousCosts);
currentCosts.addWeightedAverage(request.getAmt(), request.getQty(), utils.getQuantityUOMConverter());
}
else
{
final CostPrice price = currentCosts.getCostPrice(); | final Quantity qty = utils.convertToUOM(request.getQty(), price.getUomId(), request.getProductId());
final CostAmount amt = price.multiply(qty).roundToPrecisionIfNeeded(currentCosts.getPrecision());
final CostDetailCreateRequest requestEffective = request.withAmount(amt);
result = utils.createCostDetailRecordWithChangedCosts(requestEffective, previousCosts);
currentCosts.addToCurrentQtyAndCumulate(qty, amt);
}
utils.saveCurrentCost(currentCosts);
return result;
}
@Override
public void voidCosts(final CostDetailVoidRequest request)
{
final CurrentCost currentCosts = utils.getCurrentCost(request.getCostSegmentAndElement());
currentCosts.addToCurrentQtyAndCumulate(request.getQty().negate(), request.getAmt().negate(), utils.getQuantityUOMConverter());
utils.saveCurrentCost(currentCosts);
}
@Override
public MoveCostsResult createMovementCosts(@NonNull final MoveCostsRequest request)
{
// TODO Auto-generated method stub
throw new UnsupportedOperationException();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\methods\AverageInvoiceCostingMethodHandler.java | 1 |
请完成以下Java代码 | protected void complete(Object value, PlanItemInstanceEntity planItemInstanceEntity) {
if (resultVariable != null) {
if (storeResultVariableAsTransient) {
planItemInstanceEntity.setTransientVariable(resultVariable, value);
} else {
planItemInstanceEntity.setVariable(resultVariable, value);
}
}
CommandContextUtil.getAgenda().planCompletePlanItemInstanceOperation(planItemInstanceEntity);
}
protected class FutureExpressionCompleteAction implements BiConsumer<Object, Throwable> {
protected final PlanItemInstanceEntity planItemInstanceEntity; | public FutureExpressionCompleteAction(PlanItemInstanceEntity planItemInstanceEntity) {
this.planItemInstanceEntity = planItemInstanceEntity;
}
@Override
public void accept(Object value, Throwable throwable) {
if (throwable == null) {
complete(value, planItemInstanceEntity);
} else {
sneakyThrow(throwable);
}
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\behavior\impl\PlanItemExpressionActivityBehavior.java | 1 |
请完成以下Java代码 | public void setM_Warehouse_ID (final int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID);
}
@Override
public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
@Override
public void setQuantityOnHand (final @Nullable BigDecimal QuantityOnHand)
{
set_ValueNoCheck (COLUMNNAME_QuantityOnHand, QuantityOnHand);
}
@Override
public BigDecimal getQuantityOnHand()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QuantityOnHand);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotal_Qty_Five_Weeks_Ago (final @Nullable BigDecimal Total_Qty_Five_Weeks_Ago)
{
set_ValueNoCheck (COLUMNNAME_Total_Qty_Five_Weeks_Ago, Total_Qty_Five_Weeks_Ago);
}
@Override
public BigDecimal getTotal_Qty_Five_Weeks_Ago()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Total_Qty_Five_Weeks_Ago);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotal_Qty_Four_Weeks_Ago (final @Nullable BigDecimal Total_Qty_Four_Weeks_Ago)
{
set_ValueNoCheck (COLUMNNAME_Total_Qty_Four_Weeks_Ago, Total_Qty_Four_Weeks_Ago);
}
@Override
public BigDecimal getTotal_Qty_Four_Weeks_Ago()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Total_Qty_Four_Weeks_Ago);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotal_Qty_One_Week_Ago (final @Nullable BigDecimal Total_Qty_One_Week_Ago)
{
set_ValueNoCheck (COLUMNNAME_Total_Qty_One_Week_Ago, Total_Qty_One_Week_Ago);
}
@Override
public BigDecimal getTotal_Qty_One_Week_Ago()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Total_Qty_One_Week_Ago);
return bd != null ? bd : BigDecimal.ZERO;
} | @Override
public void setTotal_Qty_Six_Weeks_Ago (final @Nullable BigDecimal Total_Qty_Six_Weeks_Ago)
{
set_ValueNoCheck (COLUMNNAME_Total_Qty_Six_Weeks_Ago, Total_Qty_Six_Weeks_Ago);
}
@Override
public BigDecimal getTotal_Qty_Six_Weeks_Ago()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Total_Qty_Six_Weeks_Ago);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotal_Qty_Three_Weeks_Ago (final @Nullable BigDecimal Total_Qty_Three_Weeks_Ago)
{
set_ValueNoCheck (COLUMNNAME_Total_Qty_Three_Weeks_Ago, Total_Qty_Three_Weeks_Ago);
}
@Override
public BigDecimal getTotal_Qty_Three_Weeks_Ago()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Total_Qty_Three_Weeks_Ago);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotal_Qty_Two_Weeks_Ago (final @Nullable BigDecimal Total_Qty_Two_Weeks_Ago)
{
set_ValueNoCheck (COLUMNNAME_Total_Qty_Two_Weeks_Ago, Total_Qty_Two_Weeks_Ago);
}
@Override
public BigDecimal getTotal_Qty_Two_Weeks_Ago()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Total_Qty_Two_Weeks_Ago);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\replenishment\X_M_Material_Needs_Planner_V.java | 1 |
请完成以下Java代码 | public class AccountData {
private String accountNo;
private String accountStatus;
private Long balance;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createDate;
public String getAccountNo() {
return accountNo;
}
public void setAccountNo(String accountNo) {
this.accountNo = accountNo;
}
public String getAccountStatus() {
return accountStatus;
}
public void setAccountStatus(String accountStatus) {
this.accountStatus = accountStatus;
}
public Long getBalance() {
return balance;
}
public void setBalance(Long balance) {
this.balance = balance; | }
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
} | repos\spring-boot-leaning-master\2.x_data\2-4 MongoDB 支持动态 SQL、分页方案\spring-boot-mongodb-page\src\main\java\com\neo\result\AccountData.java | 1 |
请完成以下Java代码 | public void setAsynchronousLeaveNotExclusive(boolean asynchronousLeaveNotExclusive) {
this.asynchronousLeaveNotExclusive = asynchronousLeaveNotExclusive;
}
public Object getBehavior() {
return behavior;
}
public void setBehavior(Object behavior) {
this.behavior = behavior;
}
public List<SequenceFlow> getIncomingFlows() {
return incomingFlows;
}
public void setIncomingFlows(List<SequenceFlow> incomingFlows) {
this.incomingFlows = incomingFlows;
}
public List<SequenceFlow> getOutgoingFlows() {
return outgoingFlows;
}
public void setOutgoingFlows(List<SequenceFlow> outgoingFlows) {
this.outgoingFlows = outgoingFlows;
} | public void setValues(FlowNode otherNode) {
super.setValues(otherNode);
setAsynchronous(otherNode.isAsynchronous());
setNotExclusive(otherNode.isNotExclusive());
setAsynchronousLeave(otherNode.isAsynchronousLeave());
setAsynchronousLeaveNotExclusive(otherNode.isAsynchronousLeaveNotExclusive());
if (otherNode.getIncomingFlows() != null) {
setIncomingFlows(otherNode.getIncomingFlows()
.stream()
.map(SequenceFlow::clone)
.collect(Collectors.toList()));
}
if (otherNode.getOutgoingFlows() != null) {
setOutgoingFlows(otherNode.getOutgoingFlows()
.stream()
.map(SequenceFlow::clone)
.collect(Collectors.toList()));
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\FlowNode.java | 1 |
请完成以下Java代码 | private void addCommonFormatters(CommonFormatters<LogEvent> commonFormatters) {
commonFormatters.add(CommonStructuredLogFormat.ELASTIC_COMMON_SCHEMA, this::createEcsFormatter);
commonFormatters.add(CommonStructuredLogFormat.GRAYLOG_EXTENDED_LOG_FORMAT, this::createGraylogFormatter);
commonFormatters.add(CommonStructuredLogFormat.LOGSTASH, this::createLogstashFormatter);
}
private ElasticCommonSchemaStructuredLogFormatter createEcsFormatter(Instantiator<?> instantiator) {
Environment environment = instantiator.getArg(Environment.class);
StackTracePrinter stackTracePrinter = instantiator.getArg(StackTracePrinter.class);
ContextPairs contextPairs = instantiator.getArg(ContextPairs.class);
StructuredLoggingJsonMembersCustomizer.Builder<?> jsonMembersCustomizerBuilder = instantiator
.getArg(StructuredLoggingJsonMembersCustomizer.Builder.class);
Assert.state(environment != null, "'environment' must not be null");
Assert.state(contextPairs != null, "'contextPairs' must not be null");
Assert.state(jsonMembersCustomizerBuilder != null, "'jsonMembersCustomizerBuilder' must not be null");
return new ElasticCommonSchemaStructuredLogFormatter(environment, stackTracePrinter, contextPairs,
jsonMembersCustomizerBuilder);
}
private GraylogExtendedLogFormatStructuredLogFormatter createGraylogFormatter(Instantiator<?> instantiator) {
Environment environment = instantiator.getArg(Environment.class);
StackTracePrinter stackTracePrinter = instantiator.getArg(StackTracePrinter.class);
ContextPairs contextPairs = instantiator.getArg(ContextPairs.class);
StructuredLoggingJsonMembersCustomizer<?> jsonMembersCustomizer = instantiator
.getArg(StructuredLoggingJsonMembersCustomizer.class);
Assert.state(environment != null, "'environment' must not be null"); | Assert.state(contextPairs != null, "'contextPairs' must not be null");
return new GraylogExtendedLogFormatStructuredLogFormatter(environment, stackTracePrinter, contextPairs,
jsonMembersCustomizer);
}
private LogstashStructuredLogFormatter createLogstashFormatter(Instantiator<?> instantiator) {
StackTracePrinter stackTracePrinter = instantiator.getArg(StackTracePrinter.class);
ContextPairs contextPairs = instantiator.getArg(ContextPairs.class);
StructuredLoggingJsonMembersCustomizer<?> jsonMembersCustomizer = instantiator
.getArg(StructuredLoggingJsonMembersCustomizer.class);
Assert.state(contextPairs != null, "'contextPairs' must not be null");
return new LogstashStructuredLogFormatter(stackTracePrinter, contextPairs, jsonMembersCustomizer);
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\log4j2\StructuredLogLayout.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Account findByName(String accountName) {
Assert.hasLength(accountName);
return repository.findByName(accountName);
}
/**
* {@inheritDoc}
*/
@Override
public Account create(User user) {
Account existing = repository.findByName(user.getUsername());
Assert.isNull(existing, "account already exists: " + user.getUsername());
authClient.createUser(user);
Saving saving = new Saving();
saving.setAmount(new BigDecimal(0));
saving.setCurrency(Currency.getDefault());
saving.setInterest(new BigDecimal(0));
saving.setDeposit(false);
saving.setCapitalization(false);
Account account = new Account();
account.setName(user.getUsername());
account.setLastSeen(new Date());
account.setSaving(saving);
repository.save(account);
log.info("new account has been created: " + account.getName());
return account;
} | /**
* {@inheritDoc}
*/
@Override
public void saveChanges(String name, Account update) {
Account account = repository.findByName(name);
Assert.notNull(account, "can't find account with name " + name);
account.setIncomes(update.getIncomes());
account.setExpenses(update.getExpenses());
account.setSaving(update.getSaving());
account.setNote(update.getNote());
account.setLastSeen(new Date());
repository.save(account);
log.debug("account {} changes has been saved", name);
statisticsClient.updateStatistics(name, account);
}
} | repos\piggymetrics-master\account-service\src\main\java\com\piggymetrics\account\service\AccountServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class SessionServiceImpl implements SessionService {
@Autowired
private SessionDAO sessionDAO;
@Override
public List<UserOnline> list() {
List<UserOnline> list = new ArrayList<>();
Collection<Session> sessions = sessionDAO.getActiveSessions();
for (Session session : sessions) {
UserOnline userOnline = new UserOnline();
User user = new User();
SimplePrincipalCollection principalCollection = new SimplePrincipalCollection();
if (session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) == null) {
continue;
} else {
principalCollection = (SimplePrincipalCollection) session
.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
user = (User) principalCollection.getPrimaryPrincipal();
userOnline.setUsername(user.getUserName());
userOnline.setUserId(user.getId().toString());
}
userOnline.setId((String) session.getId());
userOnline.setHost(session.getHost());
userOnline.setStartTimestamp(session.getStartTimestamp());
userOnline.setLastAccessTime(session.getLastAccessTime()); | Long timeout = session.getTimeout();
if (timeout == 0l) {
userOnline.setStatus("离线");
} else {
userOnline.setStatus("在线");
}
userOnline.setTimeout(timeout);
list.add(userOnline);
}
return list;
}
@Override
public boolean forceLogout(String sessionId) {
Session session = sessionDAO.readSession(sessionId);
session.setTimeout(0);
return true;
}
} | repos\SpringAll-master\17.Spring-Boot-Shiro-Session\src\main\java\com\springboot\service\impl\SessionServiceImpl.java | 2 |
请完成以下Java代码 | public synchronized void stop() {
if (started) {
started = false;
if (cleanerTask != null) {
cleanerTask.cancel(false);
cleanerTask = null;
}
}
}
/**
* Destroy "cleanup" scheduler.
*/
@Override
public synchronized void destroy() {
started = false;
schedExecutor.shutdownNow();
try {
schedExecutor.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
log.warn("Destroying RedisRegistrationStore was interrupted.", e);
}
}
private class Cleaner implements Runnable {
@Override
public void run() {
try (var connection = connectionFactory.getConnection()) {
Set<byte[]> endpointsExpired = connection.zRangeByScore(EXP_EP, Double.NEGATIVE_INFINITY,
System.currentTimeMillis(), 0, cleanLimit);
for (byte[] endpoint : endpointsExpired) {
byte[] data = connection.get(toEndpointKey(endpoint));
if (data != null && data.length > 0) {
Registration r = deserializeReg(data);
if (!r.isAlive(gracePeriod)) {
Deregistration dereg = removeRegistration(connection, r.getId(), true); | if (dereg != null)
expirationListener.registrationExpired(dereg.getRegistration(), dereg.getObservations());
}
}
}
} catch (Exception e) {
log.warn("Unexpected Exception while registration cleaning", e);
}
}
}
@Override
public void setExpirationListener(ExpirationListener listener) {
expirationListener = listener;
}
public void setExecutor(ScheduledExecutorService executor) {
// TODO should we reuse californium executor ?
}
} | repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\store\TbLwM2mRedisRegistrationStore.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
/** Set Users Group.
@param AD_UserGroup_ID Users Group */
@Override
public void setAD_UserGroup_ID (int AD_UserGroup_ID)
{
if (AD_UserGroup_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_UserGroup_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_UserGroup_ID, Integer.valueOf(AD_UserGroup_ID));
}
/** Get Users Group.
@return Users Group */
@Override
public int getAD_UserGroup_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_UserGroup_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override | public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name Name */
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserGroup.java | 1 |
请完成以下Java代码 | public class ExecutionTreeStringBuilder {
protected ExecutionEntity executionEntity;
public ExecutionTreeStringBuilder(ExecutionEntity executionEntity) {
this.executionEntity = executionEntity;
}
/* See http://stackoverflow.com/questions/4965335/how-to-print-binary-tree-diagram */
@Override
public String toString() {
StringBuilder strb = new StringBuilder();
strb
.append(executionEntity.getId())
.append(" : ")
.append(executionEntity.getActivityId())
.append(", parent id ")
.append(executionEntity.getParentId())
.append("\r\n");
List<? extends ExecutionEntity> children = executionEntity.getExecutions();
if (children != null) {
for (ExecutionEntity childExecution : children) {
internalToString(childExecution, strb, "", true);
}
} | return strb.toString();
}
protected void internalToString(ExecutionEntity execution, StringBuilder strb, String prefix, boolean isTail) {
strb
.append(prefix)
.append(isTail ? "└── " : "├── ")
.append(execution.getId())
.append(" : ")
.append("activityId=" + execution.getActivityId())
.append(", parent id ")
.append(execution.getParentId())
.append(execution.isScope() ? " (scope)" : "")
.append(execution.isMultiInstanceRoot() ? " (multi instance root)" : "")
.append("\r\n");
List<? extends ExecutionEntity> children = executionEntity.getExecutions();
if (children != null) {
for (int i = 0; i < children.size() - 1; i++) {
internalToString(children.get(i), strb, prefix + (isTail ? " " : "│ "), false);
}
if (children.size() > 0) {
internalToString(children.get(children.size() - 1), strb, prefix + (isTail ? " " : "│ "), true);
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\util\ExecutionTreeStringBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
this.sysFormFileService.removeByIds(Arrays.asList(ids.split(",")));
return Result.OK("批量删除成功!");
}
/**
* 通过id查询
*
* @param id
* @return
*/
@AutoLog(value = "表单评论文件-通过id查询")
@Operation(summary = "表单评论文件-通过id查询")
@GetMapping(value = "/queryById")
public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
SysFormFile sysFormFile = sysFormFileService.getById(id);
return Result.OK(sysFormFile);
}
/**
* 导出excel
*
* @param request
* @param sysFormFile
*/
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, SysFormFile sysFormFile) {
return super.exportXls(request, sysFormFile, SysFormFile.class, "表单评论文件"); | }
/**
* 通过excel导入数据
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
return super.importExcel(request, response, SysFormFile.class);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysFormFileController.java | 2 |
请完成以下Java代码 | default LogAccessor logger() {
return new LogAccessor(LogFactory.getLog(getClass()));
}
/**
* Handle the exception for a batch listener. The complete {@link ConsumerRecords}
* from the poll is supplied. Return the members of the batch that should be re-sent to
* the listener. The returned records MUST be in the same order as the original records.
* @param thrownException the exception.
* @param data the consumer records.
* @param consumer the consumer.
* @param container the container.
* @param invokeListener a callback to re-invoke the listener.
* @param <K> the key type.
* @param <V> the value type.
* @return the consumer records, or a subset.
* @since 2.9
*/
default <K, V> ConsumerRecords<K, V> handleBatchAndReturnRemaining(Exception thrownException,
ConsumerRecords<?, ?> data, Consumer<?, ?> consumer, MessageListenerContainer container,
Runnable invokeListener) {
handleBatch(thrownException, data, consumer, container, invokeListener);
return ConsumerRecords.empty();
}
@Override
default int deliveryAttempt(TopicPartitionOffset topicPartitionOffset) {
return 0;
}
/**
* Optional method to clear thread state; will be called just before a consumer
* thread terminates.
*/
default void clearThreadState() {
}
/**
* Return true if the offset should be committed for a handled error (no exception
* thrown).
* @return true to commit.
*/
default boolean isAckAfterHandle() {
return true;
} | /**
* Set to false to prevent the container from committing the offset of a recovered
* record (when the error handler does not itself throw an exception).
* @param ack false to not commit.
*/
default void setAckAfterHandle(boolean ack) {
throw new UnsupportedOperationException("This error handler does not support setting this property");
}
/**
* Called when partitions are assigned.
* @param consumer the consumer.
* @param partitions the newly assigned partitions.
* @param publishPause called to publish a consumer paused event.
* @since 2.8.9
*/
default void onPartitionsAssigned(Consumer<?, ?> consumer, Collection<TopicPartition> partitions,
Runnable publishPause) {
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\CommonErrorHandler.java | 1 |
请完成以下Java代码 | public Mono<Authentication> getAuthentication(Map<String, Object> payload) {
String authorizationValue = getAuthorizationValue(payload);
if (authorizationValue == null) {
return Mono.empty();
}
if (!StringUtils.startsWithIgnoreCase(authorizationValue, "bearer")) {
BearerTokenError error = BearerTokenErrors.invalidRequest("Not a bearer token");
return Mono.error(new OAuth2AuthenticationException(error));
}
Matcher matcher = authorizationPattern.matcher(authorizationValue);
if (!matcher.matches()) {
BearerTokenError error = BearerTokenErrors.invalidToken("Bearer token is malformed");
return Mono.error(new OAuth2AuthenticationException(error));
}
String token = matcher.group("token"); | return Mono.just(new BearerTokenAuthenticationToken(token));
}
private @Nullable String getAuthorizationValue(Map<String, Object> payload) {
String value = (String) payload.get(this.authorizationKey);
if (value != null) {
return value;
}
for (String key : payload.keySet()) {
if (key.equalsIgnoreCase(this.authorizationKey)) {
return (String) payload.get(key);
}
}
return null;
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\server\support\BearerTokenAuthenticationExtractor.java | 1 |
请完成以下Java代码 | public InvoiceId retrievePredecessorSalesContractInvoiceId(final InvoiceId invoiceId)
{
final I_C_Invoice invoice = invoiceDAO.getByIdInTrx(invoiceId);
final Optional<InvoiceId> predecessorInvoice = queryBL.createQueryBuilder(I_C_Invoice.class)
.addEqualsFilter(I_C_Invoice.COLUMNNAME_C_BPartner_ID, invoice.getC_BPartner_ID())
.addNotEqualsFilter(I_C_Invoice.COLUMNNAME_C_Invoice_ID, invoice.getC_Invoice_ID())
.addInArrayFilter(I_C_Invoice.COLUMN_DocStatus, DocStatus.completedOrClosedStatuses())
.orderByDescending(I_C_Invoice.COLUMNNAME_DateInvoiced)
.create()
.idsAsSet(InvoiceId::ofRepoId)
.stream()
.filter(this::isContractSalesInvoice)
.findFirst();
return predecessorInvoice.orElse(null);
}
public InvoiceId retrieveLastSalesContractInvoiceId(final BPartnerId bPartnerId)
{
final Optional<InvoiceId> predecessorInvoice = queryBL.createQueryBuilder(I_C_Invoice.class)
.addEqualsFilter(I_C_Invoice.COLUMNNAME_C_BPartner_ID, bPartnerId.getRepoId())
.addInArrayFilter(I_C_Invoice.COLUMN_DocStatus, DocStatus.completedOrClosedStatuses())
.orderByDescending(I_C_Invoice.COLUMNNAME_DateInvoiced)
.create()
.idsAsSet(InvoiceId::ofRepoId)
.stream()
.filter(this::isContractSalesInvoice)
.findFirst();
return predecessorInvoice.orElse(null);
}
private boolean isSubscriptionInvoiceCandidate(final I_C_Invoice_Candidate invoiceCandidate)
{
final int tableId = invoiceCandidate.getAD_Table_ID();
return getTableId(I_C_Flatrate_Term.class) == tableId;
}
public LocalDate retrieveContractEndDateForInvoiceIdOrNull(@NonNull final InvoiceId invoiceId)
{
final I_C_Invoice invoice = invoiceDAO.getByIdInTrx(invoiceId);
final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(invoice.getAD_Org_ID())); | final List<I_C_InvoiceLine> invoiceLines = invoiceDAO.retrieveLines(invoice);
final List<I_C_Invoice_Candidate> allInvoiceCands = new ArrayList<>();
for (final I_C_InvoiceLine invoiceLine : invoiceLines)
{
final List<I_C_Invoice_Candidate> cands = invoiceCandDAO.retrieveIcForIl(invoiceLine);
allInvoiceCands.addAll(cands);
}
final Optional<I_C_Flatrate_Term> latestTerm = allInvoiceCands.stream()
.filter(this::isSubscriptionInvoiceCandidate)
.map(I_C_Invoice_Candidate::getRecord_ID)
.map(flatrateDAO::getById)
.sorted((contract1, contract2) -> {
final Timestamp contractEndDate1 = CoalesceUtil.coalesce(contract1.getMasterEndDate(), contract1.getEndDate());
final Timestamp contractEndDate2 = CoalesceUtil.coalesce(contract2.getMasterEndDate(), contract2.getEndDate());
if (contractEndDate1.after(contractEndDate2))
{
return -1;
}
return 1;
})
.findFirst();
if (latestTerm == null)
{
return null;
}
return TimeUtil.asLocalDate(
CoalesceUtil.coalesce(latestTerm.get().getMasterEndDate(), latestTerm.get().getEndDate()),
timeZone);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\invoice\ContractInvoiceService.java | 1 |
请完成以下Java代码 | public boolean isInternal() {
return false;
}
@Override
public void onRetransmission() {
}
@Override
public void onResponse(Response response) {
}
@Override
public void onAcknowledgement() {
onAcknowledge.accept(msgId);
}
@Override
public void onReject() {
}
@Override
public void onTimeout() {
if (onTimeout != null) {
onTimeout.accept(msgId);
}
}
@Override
public void onCancel() {
}
@Override
public void onReadyToSend() {
}
@Override
public void onConnecting() {
}
@Override
public void onDtlsRetransmission(int flight) {
}
@Override | public void onSent(boolean retransmission) {
}
@Override
public void onSendError(Throwable error) {
}
@Override
public void onResponseHandlingError(Throwable cause) {
}
@Override
public void onContextEstablished(EndpointContext endpointContext) {
}
@Override
public void onTransferComplete() {
}
} | repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\TbCoapMessageObserver.java | 1 |
请完成以下Java代码 | protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_C_CashBook[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Cash Book.
@param C_CashBook_ID
Cash Book for recording petty cash transactions
*/
public void setC_CashBook_ID (int C_CashBook_ID)
{
if (C_CashBook_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_CashBook_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_CashBook_ID, Integer.valueOf(C_CashBook_ID));
}
/** Get Cash Book.
@return Cash Book for recording petty cash transactions
*/
public int getC_CashBook_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_CashBook_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_Currency getC_Currency() throws RuntimeException
{
return (I_C_Currency)MTable.get(getCtx(), I_C_Currency.Table_Name)
.getPO(getC_Currency_ID(), get_TrxName()); }
/** Set Currency.
@param C_Currency_ID
The Currency for this record
*/
public void setC_Currency_ID (int C_Currency_ID)
{
if (C_Currency_ID < 1)
set_Value (COLUMNNAME_C_Currency_ID, null);
else
set_Value (COLUMNNAME_C_Currency_ID, Integer.valueOf(C_Currency_ID));
}
/** Get Currency.
@return The Currency for this record
*/
public int getC_Currency_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Currency_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 Default.
@param IsDefault
Default value
*/
public void setIsDefault (boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
}
/** Get Default.
@return Default value
*/
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set 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_CashBook.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class RemoteDevToolsAutoConfiguration {
private static final Log logger = LogFactory.getLog(RemoteDevToolsAutoConfiguration.class);
private final DevToolsProperties properties;
RemoteDevToolsAutoConfiguration(DevToolsProperties properties) {
this.properties = properties;
}
@Bean
@ConditionalOnMissingBean
AccessManager remoteDevToolsAccessManager() {
RemoteDevToolsProperties remoteProperties = this.properties.getRemote();
String secret = remoteProperties.getSecret();
Assert.state(secret != null, "'secret' must not be null");
return new HttpHeaderAccessManager(remoteProperties.getSecretHeaderName(), secret);
}
@Bean
HandlerMapper remoteDevToolsHealthCheckHandlerMapper(ServerProperties serverProperties) {
Handler handler = new HttpStatusHandler();
Servlet servlet = serverProperties.getServlet();
String servletContextPath = (servlet.getContextPath() != null) ? servlet.getContextPath() : "";
return new UrlHandlerMapper(servletContextPath + this.properties.getRemote().getContextPath(), handler);
}
@Bean
@ConditionalOnMissingBean
DispatcherFilter remoteDevToolsDispatcherFilter(AccessManager accessManager, Collection<HandlerMapper> mappers) {
Dispatcher dispatcher = new Dispatcher(accessManager, mappers);
return new DispatcherFilter(dispatcher);
}
/** | * Configuration for remote update and restarts.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnBooleanProperty(name = "spring.devtools.remote.restart.enabled", matchIfMissing = true)
static class RemoteRestartConfiguration {
@Bean
@ConditionalOnMissingBean
SourceDirectoryUrlFilter remoteRestartSourceDirectoryUrlFilter() {
return new DefaultSourceDirectoryUrlFilter();
}
@Bean
@ConditionalOnMissingBean
HttpRestartServer remoteRestartHttpRestartServer(SourceDirectoryUrlFilter sourceDirectoryUrlFilter) {
return new HttpRestartServer(sourceDirectoryUrlFilter);
}
@Bean
@ConditionalOnMissingBean(name = "remoteRestartHandlerMapper")
UrlHandlerMapper remoteRestartHandlerMapper(HttpRestartServer server, ServerProperties serverProperties,
DevToolsProperties properties) {
Servlet servlet = serverProperties.getServlet();
RemoteDevToolsProperties remote = properties.getRemote();
String servletContextPath = (servlet.getContextPath() != null) ? servlet.getContextPath() : "";
String url = servletContextPath + remote.getContextPath() + "/restart";
logger.warn(LogMessage.format("Listening for remote restart updates on %s", url));
Handler handler = new HttpRestartServerHandler(server);
return new UrlHandlerMapper(url, handler);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\autoconfigure\RemoteDevToolsAutoConfiguration.java | 2 |
请完成以下Java代码 | public String suffix() {
return this.suffix;
}
public long delay() {
return this.delayMs;
}
/**
* Return the number of partitions the
* retry topics should be created with.
* @return the number of partitions.
* @since 2.7.13
*/
public int numPartitions() {
return this.numPartitions;
}
@Nullable
public Boolean autoStartDltHandler() {
return this.autoStartDltHandler;
}
public Set<Class<? extends Throwable>> usedForExceptions() {
return this.usedForExceptions;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Properties that = (Properties) o;
return this.delayMs == that.delayMs
&& this.maxAttempts == that.maxAttempts
&& this.numPartitions == that.numPartitions
&& this.suffix.equals(that.suffix)
&& this.type == that.type
&& this.dltStrategy == that.dltStrategy
&& this.kafkaOperations.equals(that.kafkaOperations);
}
@Override
public int hashCode() {
return Objects.hash(this.delayMs, this.suffix, this.type, this.maxAttempts, this.numPartitions,
this.dltStrategy, this.kafkaOperations);
} | @Override
public String toString() {
return "Properties{" +
"delayMs=" + this.delayMs +
", suffix='" + this.suffix + '\'' +
", type=" + this.type +
", maxAttempts=" + this.maxAttempts +
", numPartitions=" + this.numPartitions +
", dltStrategy=" + this.dltStrategy +
", kafkaOperations=" + this.kafkaOperations +
", shouldRetryOn=" + this.shouldRetryOn +
", timeout=" + this.timeout +
'}';
}
public boolean isMainEndpoint() {
return Type.MAIN.equals(this.type);
}
}
enum Type {
MAIN,
RETRY,
/**
* A retry topic reused along sequential retries
* with the same back off interval.
*
* @since 3.0.4
*/
REUSABLE_RETRY_TOPIC,
DLT,
NO_OPS
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\DestinationTopic.java | 1 |
请完成以下Java代码 | public void registerProducer(final IDocOutboundProducer producer)
{
outboundProducersLock.lock();
try
{
registerProducer0(producer);
}
finally
{
outboundProducersLock.unlock();
}
}
private void registerProducer0(@NonNull final IDocOutboundProducer producer)
{
final AdTableId tableId = producer.getTableId();
Check.assumeNotNull(tableId, "Producer {} shall have a tableId", producer);
if(outboundProducers.containsKey(tableId))
{
logger.warn("Tried to register producer for tableId {} but it was already registered. This should be checked beforehand.", tableId);
return;
}
producer.init(this);
outboundProducers.put(tableId, producer);
}
@Override
public void unregisterProducerByTableId(@NonNull final AdTableId tableId)
{
outboundProducersLock.lock();
try
{
unregisterProducerByTableId0(tableId);
}
finally
{
outboundProducersLock.unlock();
}
}
private void unregisterProducerByTableId0(@NonNull final AdTableId tableId)
{
final IDocOutboundProducer producer = outboundProducers.get(tableId);
if (producer == null) | {
// no producer was not registered for given config, nothing to unregister
return;
}
producer.destroy(this);
outboundProducers.remove(tableId);
}
private List<IDocOutboundProducer> getProducersList()
{
return new ArrayList<>(outboundProducers.values());
}
@Override
public void createDocOutbound(@NonNull final Object model)
{
for (final IDocOutboundProducer producer : getProducersList())
{
if (!producer.accept(model))
{
continue;
}
producer.createDocOutbound(model);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\api\impl\DocOutboundProducerService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<OAuth2ClientInfo> findTenantOAuth2ClientInfosByIds(
@Parameter(description = "A list of oauth2 ids, separated by comma ','", array = @ArraySchema(schema = @Schema(type = "string")), required = true)
@RequestParam("clientIds") UUID[] clientIds) throws ThingsboardException {
List<OAuth2ClientId> oAuth2ClientIds = getOAuth2ClientIds(clientIds);
return oAuth2ClientService.findOAuth2ClientInfosByIds(getTenantId(), oAuth2ClientIds);
}
@ApiOperation(value = "Get OAuth2 Client by id (getOAuth2ClientById)", notes = SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
@GetMapping(value = "/oauth2/client/{id}")
public OAuth2Client getOAuth2ClientById(@PathVariable UUID id) throws ThingsboardException {
OAuth2ClientId oAuth2ClientId = new OAuth2ClientId(id);
return checkEntityId(oAuth2ClientId, oAuth2ClientService::findOAuth2ClientById, Operation.READ);
}
@ApiOperation(value = "Delete oauth2 client (deleteOauth2Client)",
notes = "Deletes the oauth2 client. Referencing non-existing oauth2 client Id will cause an error." + SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") | @DeleteMapping(value = "/oauth2/client/{id}")
public void deleteOauth2Client(@PathVariable UUID id) throws Exception {
OAuth2ClientId oAuth2ClientId = new OAuth2ClientId(id);
OAuth2Client oAuth2Client = checkOauth2ClientId(oAuth2ClientId, Operation.DELETE);
tbOauth2ClientService.delete(oAuth2Client, getCurrentUser());
}
@ApiOperation(value = "Get OAuth2 log in processing URL (getLoginProcessingUrl)", notes = "Returns the URL enclosed in " +
"double quotes. After successful authentication with OAuth2 provider, it makes a redirect to this path so that the platform can do " +
"further log in processing. This URL may be configured as 'security.oauth2.loginProcessingUrl' property in yml configuration file, or " +
"as 'SECURITY_OAUTH2_LOGIN_PROCESSING_URL' env variable. By default it is '/login/oauth2/code/'" + SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
@GetMapping(value = "/oauth2/loginProcessingUrl")
public String getLoginProcessingUrl() {
return "\"" + oAuth2Configuration.getLoginProcessingUrl() + "\"";
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\OAuth2Controller.java | 2 |
请在Spring Boot框架中完成以下Java代码 | class RetrieveContactRequest
{
public enum ContactType
{
BILL_TO_DEFAULT, SHIP_TO_DEFAULT, SALES_DEFAULT, SUBJECT_MATTER
}
public enum IfNotFound
{
RETURN_DEFAULT_CONTACT, RETURN_NULL
}
@NonNull
BPartnerId bpartnerId;
@Nullable
ContactType contactType;
/**
* If specified, then contacts with this location are preferred, even if a user ad another location is the default bill-to user.
*/
@Nullable
BPartnerLocationId bPartnerLocationId;
/**
* If specified, then only matching contacts are considered
*/
@Default
@NonNull
Predicate<User> filter = user -> true;
/**
* If specified and there are multiple equally good fits, then the first fit according to this comparator is returned.
* If not specified, then the contact whose name comes alphabetically first is returned.
*/
@Default
@NonNull
Comparator<User> comparator = Comparator.comparing(User::getName);
@Default
boolean onlyIfInvoiceEmailEnabled = false;
boolean onlyActive;
@Default
IfNotFound ifNotFound = IfNotFound.RETURN_DEFAULT_CONTACT;
}
CountryId getCountryId(@NonNull BPartnerLocationAndCaptureId bpartnerLocationAndCaptureId);
CountryId getCountryId(@NonNull BPartnerInfo bpartnerInfo);
LocationId getLocationId(@NonNull BPartnerLocationAndCaptureId bpartnerLocationAndCaptureId); | int getFreightCostIdByBPartnerId(BPartnerId bpartnerId);
ShipmentAllocationBestBeforePolicy getBestBeforePolicy(BPartnerId bpartnerId);
Optional<PaymentTermId> getPaymentTermIdForBPartner(BPartnerId bpartnerId, SOTrx soTrx);
boolean isSalesRep(BPartnerId bpartnerId);
void validateSalesRep(@NonNull BPartnerId bPartnerId, @Nullable BPartnerId salesRepId);
void updateFromPreviousLocation(final I_C_BPartner_Location bpLocation);
void updateFromPreviousLocationNoSave(final I_C_BPartner_Location bpLocation);
/**
* extracted logic from legacy code
*/
I_C_BPartner_Location extractShipToLocation(@NonNull I_C_BPartner bp);
@NonNull
Optional<UserId> getDefaultDunningContact(@NonNull final BPartnerId bPartnerId);
/**
* Gets the partner's VAT-ID either from the C_BPArtner or from its C_BPArtner_Location, depending on AD_SysConfig {@value #SYS_CONFIG_IgnorePartnerVATID}.
*/
@NonNull
Optional<VATIdentifier> getVATTaxId(@NonNull BPartnerLocationId bpartnerLocationId);
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\IBPartnerBL.java | 2 |
请完成以下Java代码 | private boolean isModal()
{
if (_modal != null)
{
return _modal;
}
//
// Checks if we shall display the info window as modal.
// We shall make the info window modal if the given windowNo is for a regular window, because else we would have a leak in managed windows (so this window will not be closed on logout).
// This is because in case a windowNo is provided, no new windowNo will be created so the window will not be added to window manager.
// Usually, the case when a windowNo is provided is the case when the info window is opened from a window component (like VEditor action button).
return Env.isRegularWindowNo(getWindowNo());
}
public InfoBuilder setWindowNo(final int windowNo)
{
_windowNo = windowNo;
return this;
}
private int getWindowNo()
{
if (_windowNo != null)
{
return _windowNo;
}
return Env.WINDOW_None;
}
public InfoBuilder setKeyColumn(final String keyColumn)
{
_keyColumn = keyColumn;
return this;
}
private String getKeyColumn()
{
if (_keyColumn != null)
{
return _keyColumn;
}
return getTableName() + "_ID";
}
public InfoBuilder setSearchValue(final String value)
{
_searchValue = value;
return this;
}
public String getSearchValue()
{
return _searchValue;
}
public InfoBuilder setMultiSelection(final boolean multiSelection)
{
_multiSelection = multiSelection;
return this;
}
private boolean isMultiSelection()
{
return _multiSelection;
}
public InfoBuilder setWhereClause(final String whereClause)
{
_whereClause = whereClause;
return this;
}
public String getWhereClause()
{
return _whereClause;
}
public InfoBuilder setAttributes(final Map<String, Object> attributes)
{
_attributes = attributes;
return this;
}
private Map<String, Object> getAttributes()
{
return _attributes;
}
public InfoBuilder setInfoWindow(final I_AD_InfoWindow infoWindow)
{
_infoWindowDef = infoWindow; | if (infoWindow != null)
{
final String tableName = Services.get(IADInfoWindowBL.class).getTableName(infoWindow);
setTableName(tableName);
}
return this;
}
private I_AD_InfoWindow getInfoWindow()
{
if (_infoWindowDef != null)
{
return _infoWindowDef;
}
final String tableName = getTableName();
final I_AD_InfoWindow infoWindowFound = Services.get(IADInfoWindowDAO.class).retrieveInfoWindowByTableName(getCtx(), tableName);
if (infoWindowFound != null && infoWindowFound.isActive())
{
return infoWindowFound;
}
return null;
}
/**
* @param iconName icon name (without size and without file extension).
*/
public InfoBuilder setIconName(final String iconName)
{
if (Check.isEmpty(iconName, true))
{
return setIcon(null);
}
else
{
final Image icon = Images.getImage2(iconName + "16");
return setIcon(icon);
}
}
public InfoBuilder setIcon(final Image icon)
{
this._iconImage = icon;
return this;
}
private Image getIconImage()
{
return _iconImage;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\InfoBuilder.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setContent (final @Nullable java.lang.String Content)
{
set_ValueNoCheck (COLUMNNAME_Content, Content);
}
@Override
public java.lang.String getContent()
{
return get_ValueAsString(COLUMNNAME_Content);
}
/**
* Direction AD_Reference_ID=541551
* Reference name: RabbitMQ_Message_Audit_Direction
*/
public static final int DIRECTION_AD_Reference_ID=541551;
/** In = I */
public static final String DIRECTION_In = "I";
/** Out = O */
public static final String DIRECTION_Out = "O";
@Override
public void setDirection (final java.lang.String Direction)
{
set_ValueNoCheck (COLUMNNAME_Direction, Direction);
}
@Override
public java.lang.String getDirection()
{
return get_ValueAsString(COLUMNNAME_Direction);
}
@Override
public void setEvent_UUID (final @Nullable java.lang.String Event_UUID)
{
set_ValueNoCheck (COLUMNNAME_Event_UUID, Event_UUID);
}
@Override
public java.lang.String getEvent_UUID()
{
return get_ValueAsString(COLUMNNAME_Event_UUID);
}
@Override
public void setHost (final @Nullable java.lang.String Host)
{
set_ValueNoCheck (COLUMNNAME_Host, Host);
} | @Override
public java.lang.String getHost()
{
return get_ValueAsString(COLUMNNAME_Host);
}
@Override
public void setRabbitMQ_Message_Audit_ID (final int RabbitMQ_Message_Audit_ID)
{
if (RabbitMQ_Message_Audit_ID < 1)
set_ValueNoCheck (COLUMNNAME_RabbitMQ_Message_Audit_ID, null);
else
set_ValueNoCheck (COLUMNNAME_RabbitMQ_Message_Audit_ID, RabbitMQ_Message_Audit_ID);
}
@Override
public int getRabbitMQ_Message_Audit_ID()
{
return get_ValueAsInt(COLUMNNAME_RabbitMQ_Message_Audit_ID);
}
@Override
public void setRabbitMQ_QueueName (final @Nullable java.lang.String RabbitMQ_QueueName)
{
set_ValueNoCheck (COLUMNNAME_RabbitMQ_QueueName, RabbitMQ_QueueName);
}
@Override
public java.lang.String getRabbitMQ_QueueName()
{
return get_ValueAsString(COLUMNNAME_RabbitMQ_QueueName);
}
@Override
public void setRelated_Event_UUID (final @Nullable java.lang.String Related_Event_UUID)
{
set_ValueNoCheck (COLUMNNAME_Related_Event_UUID, Related_Event_UUID);
}
@Override
public java.lang.String getRelated_Event_UUID()
{
return get_ValueAsString(COLUMNNAME_Related_Event_UUID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_RabbitMQ_Message_Audit.java | 1 |
请完成以下Java代码 | public Baeldung getWebsite() {
return website;
}
}
public static class Baeldung {
private List<BaeldungArticle> articleList;
public void setArticleList(List<BaeldungArticle> articleList) {
this.articleList = articleList;
}
public List<BaeldungArticle> getArticleList() {
return this.articleList;
}
}
public static class BaeldungArticle {
private String title;
private String content;
public void setTitle(String title) { | this.title = title;
}
public String getTitle() {
return this.title;
}
public void setContent(String content) {
this.content = content;
}
public String getContent() {
return this.content;
}
}
} | repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\sax\SaxParserMain.java | 1 |
请完成以下Java代码 | private OrderLineKey createOrderKeyForOrderLineRecord(@NonNull final I_C_OrderLine orderLineRecord)
{
final ProductDescriptor productDescriptor = productDescriptorFactory.createProductDescriptor(orderLineRecord, AttributesKey.ALL);
final BPartnerId bpartnerId = BPartnerId.ofRepoId(orderLineRecord.getC_BPartner_ID()); // this column is mandatory and always > 0
return new OrderLineKey(
productDescriptor.getProductId(),
productDescriptor.getStorageAttributesKey(),
BPartnerClassifier.specific(bpartnerId));
}
@Value
private static class OrderLineKey
{
int productId;
AttributesKey attributesKey;
BPartnerClassifier bpartner;
private static OrderLineKey forResultGroup(@NonNull final AvailableToPromiseResultGroup resultGroup)
{ | return new OrderLineKey(
resultGroup.getProductId().getRepoId(),
resultGroup.getStorageAttributesKey(),
resultGroup.getBpartner());
}
private OrderLineKey(
final int productId,
@NonNull final AttributesKey attributesKey,
@NonNull final BPartnerClassifier bpartner)
{
this.productId = productId;
this.attributesKey = attributesKey;
this.bpartner = bpartner;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\interceptor\OrderAvailableToPromiseTool.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class DeliveryOrderKey
{
@NonNull ShipperId shipperId;
@NonNull ShipperTransportationId shipperTransportationId;
int fromOrgId;
int deliverToBPartnerId;
int deliverToBPartnerLocationId;
@NonNull LocalDate pickupDate;
@NonNull LocalTime timeFrom;
@NonNull LocalTime timeTo;
@Nullable CarrierProductId carrierProductId;
@Nullable CarrierGoodsTypeId carrierGoodsTypeId;
@Nullable Set<CarrierServiceId> carrierServices;
AsyncBatchId asyncBatchId;
@Builder
public DeliveryOrderKey(
@NonNull final ShipperId shipperId,
@NonNull final ShipperTransportationId shipperTransportationId,
final int fromOrgId,
final int deliverToBPartnerId,
final int deliverToBPartnerLocationId,
@NonNull final LocalDate pickupDate,
@NonNull final LocalTime timeFrom,
@NonNull final LocalTime timeTo,
@Nullable final CarrierProductId carrierProductId,
@Nullable final CarrierGoodsTypeId carrierGoodsTypeId,
@Nullable final Set<CarrierServiceId> carrierServices,
@Nullable final AsyncBatchId asyncBatchId)
{
Check.assume(fromOrgId > 0, "fromOrgId > 0");
Check.assume(deliverToBPartnerId > 0, "deliverToBPartnerId > 0");
Check.assume(deliverToBPartnerLocationId > 0, "deliverToBPartnerLocationId > 0"); | this.shipperId = shipperId;
this.shipperTransportationId = shipperTransportationId;
this.fromOrgId = fromOrgId;
this.deliverToBPartnerId = deliverToBPartnerId;
this.deliverToBPartnerLocationId = deliverToBPartnerLocationId;
this.pickupDate = pickupDate;
this.timeFrom = timeFrom;
this.timeTo = timeTo;
this.carrierProductId = carrierProductId;
this.carrierGoodsTypeId = carrierGoodsTypeId;
this.carrierServices = carrierServices;
this.asyncBatchId = asyncBatchId;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.spi\src\main\java\de\metas\shipper\gateway\spi\DraftDeliveryOrderCreator.java | 2 |
请完成以下Java代码 | public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Character getGender() {
return gender;
} | public void setGender(Character gender) {
this.gender = gender;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public Float getPercentage() {
return percentage;
}
public void setPercentage(Float percentage) {
this.percentage = percentage;
}
} | repos\tutorials-master\spring-web-modules\spring-thymeleaf\src\main\java\com\baeldung\thymeleaf\model\Student.java | 1 |
请完成以下Java代码 | public PInstanceId getOnlyAD_PInstance_ID()
{
return onlyAD_PInstance_ID;
}
@Override
public void setOnlyAD_PInstance_ID(final PInstanceId onlyAD_PInstance_ID)
{
this.onlyAD_PInstance_ID = onlyAD_PInstance_ID;
}
@Override
public int getAD_Client_ID()
{
return AD_Client_ID;
}
@Override
public void setAD_Client_ID(final int aD_Client_ID)
{
AD_Client_ID = aD_Client_ID;
}
@Override
public int getAD_Org_ID()
{
return AD_Org_ID;
}
@Override
public void setAD_Org_ID(final int aD_Org_ID)
{
AD_Org_ID = aD_Org_ID;
}
@Override
public int getAD_User_ID()
{
return AD_User_ID;
}
@Override
public void setAD_User_ID(final int aD_User_ID)
{
AD_User_ID = aD_User_ID;
}
@Override
public int getIgnoreC_Printing_Queue_ID()
{
return ignoreC_Printing_Queue_ID;
}
@Override
public void setIgnoreC_Printing_Queue_ID(final int ignoreC_Printing_Queue_ID)
{
this.ignoreC_Printing_Queue_ID = ignoreC_Printing_Queue_ID;
}
@Override
public int getModelTableId()
{
return modelTableId;
}
@Override
public void setModelTableId(int modelTableId)
{
this.modelTableId = modelTableId;
}
@Override
public int getModelFromRecordId()
{
return modelFromRecordId;
}
@Override
public void setModelFromRecordId(int modelFromRecordId)
{
this.modelFromRecordId = modelFromRecordId;
}
@Override
public int getModelToRecordId()
{
return modelToRecordId;
}
@Override
public void setModelToRecordId(int modelToRecordId)
{
this.modelToRecordId = modelToRecordId;
}
@Override
public ISqlQueryFilter getFilter()
{
return filter; | }
@Override
public void setFilter(ISqlQueryFilter filter)
{
this.filter = filter;
}
@Override
public ISqlQueryFilter getModelFilter()
{
return modelFilter;
}
@Override
public void setModelFilter(ISqlQueryFilter modelFilter)
{
this.modelFilter = modelFilter;
}
@Override
public Access getRequiredAccess()
{
return requiredAccess;
}
@Override
public void setRequiredAccess(final Access requiredAccess)
{
this.requiredAccess = requiredAccess;
}
@Override
public Integer getCopies()
{
return copies;
}
@Override
public void setCopies(int copies)
{
this.copies = copies;
}
@Override
public String getAggregationKey()
{
return aggregationKey;
}
@Override
public void setAggregationKey(final String aggregationKey)
{
this.aggregationKey=aggregationKey;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\PrintingQueueQuery.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void publishProductDeletedEvent(final ProductId productId)
{
final PZN pzn = getPZNByProductId(productId);
final MSV3StockAvailability item = MSV3StockAvailability.builder()
.pzn(pzn.getValueAsLong())
.delete(true)
.build();
final MSV3StockAvailabilityUpdatedEvent event = MSV3StockAvailabilityUpdatedEvent.ofSingle(
item,
eventVersionGenerator.getNextEventVersion());
msv3ServerPeerService.publishStockAvailabilityUpdatedEvent(event);
}
public void publishProductExcludeAddedOrChanged(
final ProductId productId,
@NonNull final BPartnerId newBPartnerId,
final BPartnerId oldBPartnerId)
{
final PZN pzn = getPZNByProductId(productId);
final MSV3ProductExcludesUpdateEventBuilder eventBuilder = MSV3ProductExcludesUpdateEvent.builder();
if (oldBPartnerId != null && !Objects.equals(newBPartnerId, oldBPartnerId))
{
eventBuilder.item(MSV3ProductExclude.builder()
.pzn(pzn)
.bpartnerId(oldBPartnerId.getRepoId())
.delete(true)
.build());
}
eventBuilder.item(MSV3ProductExclude.builder()
.pzn(pzn)
.bpartnerId(newBPartnerId.getRepoId())
.build());
msv3ServerPeerService.publishProductExcludes(eventBuilder.build());
}
public void publishProductExcludeDeleted(final ProductId productId, final BPartnerId... bpartnerIds)
{
final PZN pzn = getPZNByProductId(productId);
final List<MSV3ProductExclude> eventItems = Stream.of(bpartnerIds)
.filter(Objects::nonNull)
.distinct()
.map(bpartnerId -> MSV3ProductExclude.builder() | .pzn(pzn)
.bpartnerId(bpartnerId.getRepoId())
.delete(true)
.build())
.collect(ImmutableList.toImmutableList());
if (eventItems.isEmpty())
{
return;
}
msv3ServerPeerService.publishProductExcludes(MSV3ProductExcludesUpdateEvent.builder()
.items(eventItems)
.build());
}
private int getPublishAllStockAvailabilityBatchSize()
{
return Services
.get(ISysConfigBL.class)
.getIntValue(SYSCONFIG_STOCK_AVAILABILITY_BATCH_SIZE, 500);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java\de\metas\vertical\pharma\msv3\server\peer\metasfresh\services\MSV3StockAvailabilityService.java | 2 |
请完成以下Java代码 | public int deleteById(Integer id) {
return template.update("DELETE FROM users WHERE id = ?", id);
}
public UserDO selectById(Integer id) {
return template.queryForObject("SELECT id, username, password, create_time FROM users WHERE id = ?",
new BeanPropertyRowMapper<>(UserDO.class), // 结果转换成对应的对象
id);
}
public UserDO selectByUsername(String username) {
return template.queryForObject("SELECT id, username, password, create_time FROM users WHERE username = ? LIMIT 1",
new BeanPropertyRowMapper<>(UserDO.class), // 结果转换成对应的对象
username);
} | public List<UserDO> selectByIds(List<Integer> ids) {
// 创建 NamedParameterJdbcTemplate 对象
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(template);
// 拼接参数
Map<String, Object> params = new HashMap<>();
params.put("ids", ids);
// 执行查询
return namedParameterJdbcTemplate.query(
"SELECT id, username, password, create_time FROM users WHERE id IN (:ids)", // 使用 :ids 作为占位服务
params,
new BeanPropertyRowMapper<>(UserDO.class) // 结果转换成对应的对象
);
}
} | repos\SpringBoot-Labs-master\lab-14-spring-jdbc-template\lab-14-jdbctemplate\src\main\java\cn\iocoder\springboot\lab14\jdbctemplate\dao\UserDao.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public org.compiere.model.I_AD_Role getAD_Role()
{
return get_ValueAsPO(COLUMNNAME_AD_Role_ID, org.compiere.model.I_AD_Role.class);
}
@Override
public void setAD_Role(org.compiere.model.I_AD_Role AD_Role)
{
set_ValueFromPO(COLUMNNAME_AD_Role_ID, org.compiere.model.I_AD_Role.class, AD_Role);
}
@Override
public void setAD_Role_ID (int AD_Role_ID)
{
if (AD_Role_ID < 0)
set_Value (COLUMNNAME_AD_Role_ID, null);
else
set_Value (COLUMNNAME_AD_Role_ID, Integer.valueOf(AD_Role_ID));
}
@Override
public int getAD_Role_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Role_ID);
}
@Override
public org.compiere.model.I_AD_Session getAD_Session()
{
return get_ValueAsPO(COLUMNNAME_AD_Session_ID, org.compiere.model.I_AD_Session.class);
}
@Override
public void setAD_Session(org.compiere.model.I_AD_Session AD_Session)
{
set_ValueFromPO(COLUMNNAME_AD_Session_ID, org.compiere.model.I_AD_Session.class, AD_Session);
}
@Override
public void setAD_Session_ID (int AD_Session_ID)
{
if (AD_Session_ID < 1)
set_Value (COLUMNNAME_AD_Session_ID, null);
else
set_Value (COLUMNNAME_AD_Session_ID, Integer.valueOf(AD_Session_ID));
}
@Override
public int getAD_Session_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Session_ID);
}
@Override
public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 0)
set_Value (COLUMNNAME_AD_User_ID, null);
else
set_Value (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID));
}
@Override
public int getAD_User_ID() | {
return get_ValueAsInt(COLUMNNAME_AD_User_ID);
}
@Override
public void setAD_User_Login_ID (int AD_User_Login_ID)
{
if (AD_User_Login_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_User_Login_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_Login_ID, Integer.valueOf(AD_User_Login_ID));
}
@Override
public int getAD_User_Login_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_Login_ID);
}
@Override
public void setHostKey (java.lang.String HostKey)
{
set_Value (COLUMNNAME_HostKey, HostKey);
}
@Override
public java.lang.String getHostKey()
{
return (java.lang.String)get_Value(COLUMNNAME_HostKey);
}
@Override
public void setPassword (java.lang.String Password)
{
set_Value (COLUMNNAME_Password, Password);
}
@Override
public java.lang.String getPassword()
{
return (java.lang.String)get_Value(COLUMNNAME_Password);
}
@Override
public void setUserName (java.lang.String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
@Override
public java.lang.String getUserName()
{
return (java.lang.String)get_Value(COLUMNNAME_UserName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_User_Login.java | 1 |
请完成以下Java代码 | public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Internal.
@param IsInternal
Internal Organization
*/
public void setIsInternal (boolean IsInternal)
{
set_Value (COLUMNNAME_IsInternal, Boolean.valueOf(IsInternal));
}
/** Get Internal.
@return Internal Organization
*/
public boolean isInternal ()
{
Object oo = get_Value(COLUMNNAME_IsInternal);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{ | return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_Seller.java | 1 |
请完成以下Java代码 | public void setCompanyName(final String companyName)
{
this.companyName = companyName;
this.companyNameSet = 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 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;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v1\request\JsonRequestBPartner.java | 1 |
请完成以下Java代码 | public void setLogLevel(String levelName)
{
LogManager.setLevel(levelName);
}
@ManagedOperation
public String getLogLevel()
{
final Level level = LogManager.getLevel();
return level == null ? null : level.toString();
}
@ManagedOperation
public void runFinalization()
{ | System.runFinalization();
}
@ManagedOperation
public void resetLocalCache()
{
CacheMgt.get().reset();
}
@ManagedOperation
public void rotateMigrationScriptFile()
{
MigrationScriptFileLoggerHolder.closeMigrationScriptFiles();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\jmx\Metasfresh.java | 1 |
请完成以下Java代码 | public static boolean validateStringFilenameUsingIO(String filename) throws IOException {
File file = new File(filename);
boolean created = false;
try {
created = file.createNewFile();
return created;
} finally {
if (created) {
file.delete();
}
}
}
public static boolean validateStringFilenameUsingNIO2(String filename) {
Paths.get(filename);
return true;
}
public static boolean validateStringFilenameUsingContains(String filename) {
if (filename == null || filename.isEmpty() || filename.length() > 255) {
return false;
}
return Arrays.stream(getInvalidCharsByOS())
.noneMatch(ch -> filename.contains(ch.toString())); | }
public static boolean validateStringFilenameUsingRegex(String filename) {
if (filename == null) {
return false;
}
return filename.matches(REGEX_PATTERN);
}
private static Character[] getInvalidCharsByOS() {
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("win")) {
return INVALID_WINDOWS_SPECIFIC_CHARS;
} else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) {
return INVALID_UNIX_SPECIFIC_CHARS;
} else {
return new Character[]{};
}
}
} | repos\tutorials-master\core-java-modules\core-java-string-operations-3\src\main\java\com\baeldung\stringfilenamevalidaiton\StringFilenameValidationUtils.java | 1 |
请完成以下Java代码 | public ConditionExpression getCondition() {
return conditionChild.getChild(this);
}
public void setCondition(ConditionExpression condition) {
conditionChild.setChild(this, condition);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ManualActivationRule.class, CMMN_ELEMENT_MANUAL_ACTIVATION_RULE)
.namespaceUri(CMMN11_NS)
.extendsType(CmmnElement.class)
.instanceProvider(new ModelTypeInstanceProvider<ManualActivationRule>() {
public ManualActivationRule newInstance(ModelTypeInstanceContext instanceContext) {
return new ManualActivationRuleImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) | .build();
contextRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_CONTEXT_REF)
.idAttributeReference(CaseFileItem.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
conditionChild = sequenceBuilder.element(ConditionExpression.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\ManualActivationRuleImpl.java | 1 |
请完成以下Java代码 | public static CostCollectorType ofCode(@NonNull final String code)
{
final CostCollectorType type = typesByCode.get(code);
if (type == null)
{
throw new AdempiereException("No " + CostCollectorType.class + " found for code: " + code);
}
return type;
}
private static final ImmutableMap<String, CostCollectorType> typesByCode = Maps.uniqueIndex(Arrays.asList(values()), CostCollectorType::getCode);
public boolean isMaterial(@Nullable final PPOrderBOMLineId orderBOMLineId)
{
return isMaterialReceipt()
|| isAnyComponentIssueOrCoProduct(orderBOMLineId);
}
public boolean isMaterialReceipt()
{
return this == MaterialReceipt;
}
public boolean isMaterialReceiptOrCoProduct()
{
return isMaterialReceipt() || isCoOrByProductReceipt();
}
public boolean isComponentIssue()
{
return this == ComponentIssue;
}
public boolean isAnyComponentIssueOrCoProduct(@Nullable final PPOrderBOMLineId orderBOMLineId)
{
return isAnyComponentIssue(orderBOMLineId)
|| isCoOrByProductReceipt();
}
public boolean isAnyComponentIssue(@Nullable final PPOrderBOMLineId orderBOMLineId)
{
return isComponentIssue()
|| isMaterialMethodChangeVariance(orderBOMLineId);
}
public boolean isActivityControl()
{
return this == ActivityControl;
}
public boolean isVariance()
{
return this == MethodChangeVariance
|| this == UsageVariance
|| this == RateVariance
|| this == MixVariance;
} | public boolean isCoOrByProductReceipt()
{
return this == MixVariance;
}
public boolean isUsageVariance()
{
return this == UsageVariance;
}
public boolean isMaterialUsageVariance(@Nullable final PPOrderBOMLineId orderBOMLineId)
{
return this == UsageVariance && orderBOMLineId != null;
}
public boolean isResourceUsageVariance(@Nullable final PPOrderRoutingActivityId activityId)
{
return this == UsageVariance && activityId != null;
}
public boolean isRateVariance()
{
return this == RateVariance;
}
public boolean isMethodChangeVariance()
{
return this == MethodChangeVariance;
}
public boolean isMaterialMethodChangeVariance(@Nullable final PPOrderBOMLineId orderBOMLineId)
{
return this == MethodChangeVariance && orderBOMLineId != null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\CostCollectorType.java | 1 |
请完成以下Java代码 | public void execute(DelegateExecution execution) {
ExecutionEntity executionEntity = (ExecutionEntity) execution;
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration();
FlowableEventDispatcher eventDispatcher = processEngineConfiguration.getEventDispatcher();
if (eventDispatcher != null && eventDispatcher.isEnabled()) {
eventDispatcher.dispatchEvent(FlowableEventBuilder.createConditionalEvent(FlowableEngineEventType.ACTIVITY_CONDITIONAL_WAITING, executionEntity.getActivityId(),
conditionExpression, conditionLanguage, executionEntity.getId(), executionEntity.getProcessInstanceId(), executionEntity.getProcessDefinitionId()),
processEngineConfiguration.getEngineCfgKey());
}
}
@Override
public void trigger(DelegateExecution execution, String triggerName, Object triggerData) {
CommandContext commandContext = Context.getCommandContext();
ExecutionEntity executionEntity = (ExecutionEntity) execution;
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
boolean result = ConditionUtil.hasTrueCondition(conditionalEventDefinition.getId(), conditionExpression, conditionLanguage, executionEntity); | if (result) {
processEngineConfiguration.getActivityInstanceEntityManager().recordActivityStart(executionEntity);
FlowableEventDispatcher eventDispatcher = processEngineConfiguration.getEventDispatcher();
if (eventDispatcher != null && eventDispatcher.isEnabled()) {
eventDispatcher.dispatchEvent(FlowableEventBuilder.createConditionalEvent(FlowableEngineEventType.ACTIVITY_CONDITIONAL_RECEIVED, executionEntity.getActivityId(),
conditionExpression, conditionLanguage, executionEntity.getId(), executionEntity.getProcessInstanceId(), executionEntity.getProcessDefinitionId()),
processEngineConfiguration.getEngineCfgKey());
}
if (interrupting) {
executeInterruptingBehavior(executionEntity, commandContext);
} else {
executeNonInterruptingBehavior(executionEntity, commandContext);
}
}
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\behavior\BoundaryConditionalEventActivityBehavior.java | 1 |
请完成以下Java代码 | public class HibernateOneIsOwningSide {
private static final Logger LOGGER = LoggerFactory.getLogger(HibernateOneIsOwningSide.class);
public static void main(String[] args) {
CartOIO cart = new CartOIO();
CartOIO cart2 = new CartOIO();
ItemOIO item1 = new ItemOIO(cart);
ItemOIO item2 = new ItemOIO(cart2);
Set<ItemOIO> itemsSet = new HashSet<>();
itemsSet.add(item1);
itemsSet.add(item2);
cart.setItems(itemsSet);
SessionFactory sessionFactory = HibernateAnnotationUtil.getSessionFactory();
Session session = sessionFactory.getCurrentSession();
LOGGER.info("Session created");
Transaction tx;
try {
// start transaction
tx = session.beginTransaction();
// Save the Model object
session.persist(cart);
session.persist(cart2);
session.persist(item1);
session.persist(item2); | // Commit transaction
tx.commit();
session = sessionFactory.getCurrentSession();
tx = session.beginTransaction();
item1 = session.get(ItemOIO.class, 1L);
item2 = session.get(ItemOIO.class, 2L);
tx.commit();
LOGGER.info("item1 ID={}, Foreign Key CartOIO ID={}", item1.getId(), item1.getCartOIO().getId());
LOGGER.info("item2 ID={}, Foreign Key CartOIO ID={}", item2.getId(), item2.getCartOIO().getId());
} catch (Exception e) {
LOGGER.error("Exception occurred", e);
} finally {
if (!sessionFactory.isClosed()) {
LOGGER.info("Closing SessionFactory");
sessionFactory.close();
}
}
}
} | repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\oneToMany\main\HibernateOneIsOwningSide.java | 1 |
请完成以下Java代码 | public class AnnotationGlobalClientInterceptorConfigurer implements GlobalClientInterceptorConfigurer {
private final ApplicationContext applicationContext;
/**
* Creates a new AnnotationGlobalClientInterceptorConfigurer.
*
* @param applicationContext The application context to fetch the {@link GrpcGlobalClientInterceptor} annotated
* {@link ClientInterceptor} beans from.
*/
public AnnotationGlobalClientInterceptorConfigurer(final ApplicationContext applicationContext) {
this.applicationContext = requireNonNull(applicationContext, "applicationContext");
}
/**
* Helper method used to get the {@link GrpcGlobalClientInterceptor} annotated {@link ClientInterceptor}s from the
* application context.
*
* @return A map containing the global interceptor beans. | */
protected Map<String, ClientInterceptor> getClientInterceptorBeans() {
return transformValues(this.applicationContext.getBeansWithAnnotation(GrpcGlobalClientInterceptor.class),
ClientInterceptor.class::cast);
}
@Override
public void configureClientInterceptors(final List<ClientInterceptor> interceptors) {
for (final Entry<String, ClientInterceptor> entry : getClientInterceptorBeans().entrySet()) {
final ClientInterceptor interceptor = entry.getValue();
log.debug("Registering GlobalClientInterceptor: {} ({})", entry.getKey(), interceptor);
interceptors.add(interceptor);
}
}
} | repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\interceptor\AnnotationGlobalClientInterceptorConfigurer.java | 1 |
请完成以下Java代码 | public CasePageTask getCasePageTask() {
return casePageTask;
}
public void setCasePageTask(CasePageTask casePageTask) {
this.casePageTask = casePageTask;
}
public PlanItemInstanceEntity getPlanItemInstanceEntity() {
return planItemInstanceEntity;
}
public void setPlanItemInstanceEntity(PlanItemInstanceEntity planItemInstanceEntity) {
this.planItemInstanceEntity = planItemInstanceEntity;
}
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
}
public String getOwner() { | return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public List<String> getCandidateUsers() {
return candidateUsers;
}
public void setCandidateUsers(List<String> candidateUsers) {
this.candidateUsers = candidateUsers;
}
public List<String> getCandidateGroups() {
return candidateGroups;
}
public void setCandidateGroups(List<String> candidateGroups) {
this.candidateGroups = candidateGroups;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\interceptor\CreateCasePageTaskBeforeContext.java | 1 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("type", layoutType)
.add("columnCount", columnCount)
.add("internalName", internalName)
.add("elements", elementLines.isEmpty() ? null : elementLines)
.toString();
}
public boolean hasElementLines()
{
return !elementLines.isEmpty();
}
public static final class Builder
{
private static final Logger logger = LogManager.getLogger(DocumentLayoutElementGroupDescriptor.Builder.class);
private String internalName;
private LayoutType layoutType;
public Integer columnCount = null;
private final List<DocumentLayoutElementLineDescriptor.Builder> elementLinesBuilders = new ArrayList<>();
private Builder()
{
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("internalName", internalName)
.add("layoutType", layoutType)
.add("elementsLines-count", elementLinesBuilders.size())
.toString();
}
public DocumentLayoutElementGroupDescriptor build()
{
final DocumentLayoutElementGroupDescriptor result = new DocumentLayoutElementGroupDescriptor(this);
logger.trace("Built {} for {}", result, this);
return result;
}
private List<DocumentLayoutElementLineDescriptor> buildElementLines()
{
return elementLinesBuilders
.stream()
.map(elementLinesBuilder -> elementLinesBuilder.build())
.collect(GuavaCollectors.toImmutableList());
} | public Builder setInternalName(final String internalName)
{
this.internalName = internalName;
return this;
}
public Builder setLayoutType(final LayoutType layoutType)
{
this.layoutType = layoutType;
return this;
}
public Builder setLayoutType(final String layoutTypeStr)
{
layoutType = LayoutType.fromNullable(layoutTypeStr);
return this;
}
public Builder setColumnCount(final int columnCount)
{
this.columnCount = CoalesceUtil.firstGreaterThanZero(columnCount, 1);
return this;
}
public Builder addElementLine(@NonNull final DocumentLayoutElementLineDescriptor.Builder elementLineBuilder)
{
elementLinesBuilders.add(elementLineBuilder);
return this;
}
public Builder addElementLines(@NonNull final List<DocumentLayoutElementLineDescriptor.Builder> elementLineBuilders)
{
elementLinesBuilders.addAll(elementLineBuilders);
return this;
}
public boolean hasElementLines()
{
return !elementLinesBuilders.isEmpty();
}
public Stream<DocumentLayoutElementDescriptor.Builder> streamElementBuilders()
{
return elementLinesBuilders.stream().flatMap(DocumentLayoutElementLineDescriptor.Builder::streamElementBuilders);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutElementGroupDescriptor.java | 1 |
请完成以下Spring Boot application配置 | app.datasource.url=jdbc:mysql://localhost:3306/numberdb?createDatabaseIfNotExist=true&useSSL=false
app.datasource.username=root
app.datasource.password=root
app.datasource.initialization-mode=always
app.datasource.platform=mysql
app.datasource.partition-count=3
app.datasource.max-connections-per-partition=5
app.datasource.min-connections-per-partition=1
app.datasource.acquire-increment=5
# enable auto-commit (disabled by default)
app.datasource.auto-commit | =true
# more settings can be added as app.datasource.*
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.open-in-view=false
spring.jpa.hibernate.ddl-auto=none | repos\Hibernate-SpringBoot-master\HibernateSpringBootDataSourceBuilderBoneCPKickoff\src\main\resources\application.properties | 2 |
请在Spring Boot框架中完成以下Java代码 | public class PaySchedule
{
@NonNull PayScheduleId id;
@NonNull Percent percentage;
@NonNull Percent discount;
@Nullable DayOfWeek netDay;
int netDays;
int graceDays;
int discountDays;
public Money calculateDueAmt(@NonNull final Money grandTotal, @NonNull final CurrencyPrecision precision)
{
return grandTotal.multiply(percentage, precision);
} | public LocalDate calculateDueDate(@NonNull final LocalDate dateInvoiced)
{
return dateInvoiced.plusDays(netDays);
}
public Money calculateDiscountAmt(@NonNull final Money dueAmt, @NonNull final CurrencyPrecision precision)
{
return dueAmt.multiply(percentage, precision);
}
public LocalDate calculateDiscountDate(@NonNull final LocalDate dateInvoiced)
{
return dateInvoiced.plusDays(discountDays);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\paymentterm\PaySchedule.java | 2 |
请完成以下Java代码 | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.