instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public void setTenantIdLikeIgnoreCase(String tenantIdLikeIgnoreCase) {
this.tenantIdLikeIgnoreCase = tenantIdLikeIgnoreCase;
}
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Boolean getWithoutCaseInstanceParentId() {
return withoutCaseInstanceParentId;
}
public void setWithoutCaseInstanceParentId(Boolean withoutCaseInstanceParentId) {
this.withoutCaseInstanceParentId = withoutCaseInstanceParentId;
} | public Boolean getWithoutCaseInstanceCallbackId() {
return withoutCaseInstanceCallbackId;
}
public void setWithoutCaseInstanceCallbackId(Boolean withoutCaseInstanceCallbackId) {
this.withoutCaseInstanceCallbackId = withoutCaseInstanceCallbackId;
}
public Set<String> getCaseInstanceCallbackIds() {
return caseInstanceCallbackIds;
}
public void setCaseInstanceCallbackIds(Set<String> caseInstanceCallbackIds) {
this.caseInstanceCallbackIds = caseInstanceCallbackIds;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\caze\HistoricCaseInstanceQueryRequest.java | 2 |
请完成以下Java代码 | public void stop(TbActorRef actorRef) {
stop(actorRef.getActorId());
}
@Override
public void stop(TbActorId actorId) {
Set<TbActorId> children = parentChildMap.remove(actorId);
if (children != null) {
for (TbActorId child : children) {
stop(child);
}
}
parentChildMap.values().forEach(parentChildren -> parentChildren.remove(actorId));
TbActorMailbox mailbox = actors.remove(actorId);
if (mailbox != null) {
mailbox.destroy(null);
}
}
@Override
public void stop() { | dispatchers.values().forEach(dispatcher -> {
dispatcher.getExecutor().shutdown();
try {
dispatcher.getExecutor().awaitTermination(3, TimeUnit.SECONDS);
} catch (InterruptedException e) {
log.warn("[{}] Failed to stop dispatcher", dispatcher.getDispatcherId(), e);
}
});
if (scheduler != null) {
scheduler.shutdownNow();
}
actors.clear();
}
} | repos\thingsboard-master\common\actor\src\main\java\org\thingsboard\server\actors\DefaultTbActorSystem.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Persons implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "create_datetime")
/*
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", locale = "zh", timezone = "UTC")
@Type(type="datetime")
*/
private String create_datetime;
@Column(name = "username")
private String username;
@Column(name = "email")
private String email;
@Column(name = "phone")
private String phone;
@Column(name = "sex")
private String sex;
@Column(name = "zone")
private String zone;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCreate_datetime() {
return create_datetime;
}
public void setCreate_datetime(String create_datetime) {
this.create_datetime = create_datetime;
}
public String getUsername() { | return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getZone() {
return zone;
}
public void setZone(String zone) {
this.zone = zone;
}
} | repos\SpringBoot-vue-master\src\main\java\com\boylegu\springboot_vue\entities\Persons.java | 2 |
请完成以下Java代码 | public static final ConstantStringExpression of(final String expressionStr)
{
final ConstantStringExpression cached = CACHE.get(expressionStr);
if (cached != null)
{
return cached;
}
return new ConstantStringExpression(expressionStr);
}
/** @return constant string expression or {@link IStringExpression#NULL} if the expressionStr is null */
public static final IStringExpression ofNullable(final String expressionStr)
{
return expressionStr == null ? IStringExpression.NULL : of(expressionStr);
}
private static final ImmutableMap<String, ConstantStringExpression> CACHE = ImmutableMap.<String, ConstantStringExpression> builder()
.put("", new ConstantStringExpression("")) // this case is totally discouraged, but if it happens, lets not create a lot of instances...
.put(" ", new ConstantStringExpression(" ")) // one space
.put(", ", new ConstantStringExpression(", ")) // one space comma
.put("\n, ", new ConstantStringExpression("\n, "))
.put("\n", new ConstantStringExpression("\n"))
.put("\r\n", new ConstantStringExpression("\r\n"))
.build();
private final String expressionStr;
private ConstantStringExpression(@NonNull final String expressionStr)
{
this.expressionStr = expressionStr;
}
@Override
public String toString()
{
return expressionStr;
}
@Override
public int hashCode()
{
return Objects.hash(expressionStr);
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final ConstantStringExpression other = (ConstantStringExpression)obj;
return Objects.equals(expressionStr, other.expressionStr);
}
@Override
public String getExpressionString()
{
return expressionStr; | }
@Override
public String getFormatedExpressionString()
{
return expressionStr;
}
@Override
public Set<CtxName> getParameters()
{
return ImmutableSet.of();
}
@Override
public String evaluate(final Evaluatee ctx, final boolean ignoreUnparsable)
{
return expressionStr;
}
@Override
public String evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound)
{
return expressionStr;
}
public String getConstantValue()
{
return expressionStr;
}
@Override
public final IStringExpression resolvePartial(final Evaluatee ctx)
{
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\ConstantStringExpression.java | 1 |
请完成以下Java代码 | public boolean isDisjunctive() {
return disjunctive;
}
public List<CompositePermissionCheck> getCompositeChecks() {
return compositeChecks;
}
public List<PermissionCheck> getAtomicChecks() {
return atomicChecks;
}
public void clear() {
compositeChecks.clear();
atomicChecks.clear(); | }
public List<PermissionCheck> getAllPermissionChecks() {
List<PermissionCheck> allChecks = new ArrayList<PermissionCheck>();
allChecks.addAll(atomicChecks);
for (CompositePermissionCheck compositePermissionCheck : compositeChecks) {
allChecks.addAll(compositePermissionCheck.getAllPermissionChecks());
}
return allChecks;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\CompositePermissionCheck.java | 1 |
请完成以下Java代码 | public de.metas.handlingunits.model.I_M_HU_Trx_Line getReversalLine()
{
return get_ValueAsPO(COLUMNNAME_ReversalLine_ID, de.metas.handlingunits.model.I_M_HU_Trx_Line.class);
}
@Override
public void setReversalLine(final de.metas.handlingunits.model.I_M_HU_Trx_Line ReversalLine)
{
set_ValueFromPO(COLUMNNAME_ReversalLine_ID, de.metas.handlingunits.model.I_M_HU_Trx_Line.class, ReversalLine);
}
@Override
public void setReversalLine_ID (final int ReversalLine_ID)
{
if (ReversalLine_ID < 1)
set_Value (COLUMNNAME_ReversalLine_ID, null);
else
set_Value (COLUMNNAME_ReversalLine_ID, ReversalLine_ID);
}
@Override
public int getReversalLine_ID()
{
return get_ValueAsInt(COLUMNNAME_ReversalLine_ID);
}
@Override
public de.metas.handlingunits.model.I_M_HU_Item getVHU_Item()
{
return get_ValueAsPO(COLUMNNAME_VHU_Item_ID, de.metas.handlingunits.model.I_M_HU_Item.class);
}
@Override
public void setVHU_Item(final de.metas.handlingunits.model.I_M_HU_Item VHU_Item)
{
set_ValueFromPO(COLUMNNAME_VHU_Item_ID, de.metas.handlingunits.model.I_M_HU_Item.class, VHU_Item); | }
@Override
public void setVHU_Item_ID (final int VHU_Item_ID)
{
if (VHU_Item_ID < 1)
set_Value (COLUMNNAME_VHU_Item_ID, null);
else
set_Value (COLUMNNAME_VHU_Item_ID, VHU_Item_ID);
}
@Override
public int getVHU_Item_ID()
{
return get_ValueAsInt(COLUMNNAME_VHU_Item_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Trx_Line.java | 1 |
请完成以下Java代码 | protected final <T> IQuery<T> createQuery(final QueryBuildContext<T> queryBuildCtx,
final ISqlQueryFilter sqlFilters,
final IQueryFilter<T> nonSqlFilters)
{
final Properties ctx = queryBuildCtx.getCtx();
final String sqlWhereClause;
final List<Object> sqlParams;
if (sqlFilters != null)
{
sqlWhereClause = sqlFilters.getSql();
sqlParams = sqlFilters.getSqlParams(ctx);
}
else
{
sqlWhereClause = null;
sqlParams = null;
}
final String trxName = queryBuildCtx.getTrxName();
final Class<T> modelClass = queryBuildCtx.getModelClass();
final String modelTableName = queryBuildCtx.getModelTableName();
final IQueryOrderBy queryOrderBy = queryBuildCtx.getQueryOrderBy();
final QueryLimit queryLimit = queryBuildCtx.getQueryLimit();
final PInstanceId queryOnlySelectionId = queryBuildCtx.getQueryOnlySelectionId();
final Map<String, Object> queryOptions = queryBuildCtx.getQueryOptions();
return new TypedSqlQuery<>(ctx, modelClass, modelTableName, sqlWhereClause, trxName)
.setParameters(sqlParams)
.setPostQueryFilter(nonSqlFilters)
.setOrderBy(queryOrderBy)
.setLimit(queryLimit)
.setOnlySelection(queryOnlySelectionId)
.setOptions(queryOptions);
}
@Override
public <T> String getSql(
@NonNull final Properties ctx,
@NonNull final ICompositeQueryFilter<T> filter,
final List<Object> sqlParamsOut)
{
// Make sure given filter does not have nonSQL parts | final IQueryFilter<T> nonSqlFilters = filter.asPartialNonSqlFilterOrNull();
if (nonSqlFilters != null)
{
throw new DBException("Cannot convert filter to SQL because it contains nonSQL parts too: " + filter);
}
final ISqlQueryFilter sqlFilter = filter.asPartialSqlQueryFilter();
final String filterSql = sqlFilter.getSql();
final List<Object> filterSqlParams = sqlFilter.getSqlParams(ctx);
if (!Check.isEmpty(filterSqlParams))
{
// NOTE: we enforce the sqlParamsOut to be not null, only if we really have some parameters to append
Check.assumeNotNull(sqlParamsOut, "sqlParamsOut not null");
sqlParamsOut.addAll(filterSqlParams);
}
return filterSql;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\QueryBuilderDAO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Long getMpsVolume() {
return mpsVolume;
}
/**
* Sets the value of the mpsVolume property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setMpsVolume(Long value) {
this.mpsVolume = value;
}
/**
* Gets the value of the mpsWeight property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getMpsWeight() {
return mpsWeight;
}
/**
* Sets the value of the mpsWeight property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setMpsWeight(Long value) {
this.mpsWeight = value;
}
/**
* Gets the value of the mpsExpectedSendingDate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMpsExpectedSendingDate() {
return mpsExpectedSendingDate;
}
/**
* Sets the value of the mpsExpectedSendingDate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMpsExpectedSendingDate(String value) {
this.mpsExpectedSendingDate = value;
}
/**
* Gets the value of the mpsExpectedSendingTime property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMpsExpectedSendingTime() {
return mpsExpectedSendingTime;
}
/**
* Sets the value of the mpsExpectedSendingTime property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMpsExpectedSendingTime(String value) {
this.mpsExpectedSendingTime = value;
}
/**
* Gets the value of the sender property.
*
* @return
* possible object is
* {@link Address } | *
*/
public Address getSender() {
return sender;
}
/**
* Sets the value of the sender property.
*
* @param value
* allowed object is
* {@link Address }
*
*/
public void setSender(Address value) {
this.sender = value;
}
/**
* Gets the value of the recipient property.
*
* @return
* possible object is
* {@link Address }
*
*/
public Address getRecipient() {
return recipient;
}
/**
* Sets the value of the recipient property.
*
* @param value
* allowed object is
* {@link Address }
*
*/
public void setRecipient(Address value) {
this.recipient = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\GeneralShipmentData.java | 2 |
请完成以下Java代码 | protected String doIt()
{
final I_C_RfQ rfq = getRecord(I_C_RfQ.class);
if (rfq.getC_BPartner_ID() <= 0 || rfq.getC_BPartner_Location_ID() <= 0)
{
throw new AdempiereException("No Business Partner/Location");
}
final I_C_BPartner bp = rfq.getC_BPartner();
final MOrder order = new MOrder(getCtx(), 0, get_TrxName());
order.setIsSOTrx(true);
if (p_C_DocType_ID > 0)
{
orderBL.setDocTypeTargetIdAndUpdateDescription(order, p_C_DocType_ID);
}
else
{
orderBL.setDefaultDocTypeTargetId(order);
}
order.setBPartner(bp);
order.setC_BPartner_Location_ID(rfq.getC_BPartner_Location_ID());
order.setSalesRep_ID(rfq.getSalesRep_ID());
if (rfq.getDateWorkComplete() != null)
{
order.setDatePromised(rfq.getDateWorkComplete());
}
order.save();
for (final I_C_RfQLine line : rfqDAO.retrieveLines(rfq))
{
for (final I_C_RfQLineQty qty : rfqDAO.retrieveLineQtys(line))
{
if (qty.isActive() && qty.isOfferQty())
{
final MOrderLine ol = new MOrderLine(order);
ol.setM_Product_ID(line.getM_Product_ID(), qty.getC_UOM_ID());
ol.setDescription(line.getDescription());
ol.setQty(qty.getQty());
//
BigDecimal price = qty.getOfferAmt();
if (price == null || price.signum() == 0)
{ | price = qty.getBestResponseAmt();
if (price == null || price.signum() == 0)
{
price = BigDecimal.ZERO;
log.warn(" - BestResponse=0 - {}", qty);
}
else
{
BigDecimal margin = qty.getMargin();
if (margin == null || margin.signum() == 0)
{
margin = rfq.getMargin();
}
if (margin != null && margin.signum() != 0)
{
margin = margin.add(Env.ONEHUNDRED);
price = price.multiply(margin)
.divide(Env.ONEHUNDRED, 2, BigDecimal.ROUND_HALF_UP);
}
}
} // price
ol.setPrice(price);
ol.save();
} // Offer Qty
} // All Qtys
} // All Lines
//
rfq.setC_Order(order);
InterfaceWrapperHelper.save(rfq);
return order.getDocumentNo();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\process\C_RfQ_CreateSO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public AuthorizationManagerWebInvocationPrivilegeEvaluator.HttpServletRequestTransformer getObject()
throws Exception {
AuthorizationManagerWebInvocationPrivilegeEvaluator.HttpServletRequestTransformer requestTransformer = this.applicationContext
.getBeanProvider(
AuthorizationManagerWebInvocationPrivilegeEvaluator.HttpServletRequestTransformer.class)
.getIfUnique();
if (requestTransformer != null) {
return requestTransformer;
}
return new PathPatternRequestTransformer();
}
@Override
public Class<?> getObjectType() {
return AuthorizationManagerWebInvocationPrivilegeEvaluator.HttpServletRequestTransformer.class;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
static class RoleVoterBeanFactory extends AbstractGrantedAuthorityDefaultsBeanFactory {
private RoleVoter voter = new RoleVoter();
@Override
public RoleVoter getBean() {
this.voter.setRolePrefix(this.rolePrefix);
return this.voter;
}
}
static class SecurityContextHolderAwareRequestFilterBeanFactory
extends GrantedAuthorityDefaultsParserUtils.AbstractGrantedAuthorityDefaultsBeanFactory {
private SecurityContextHolderAwareRequestFilter filter = new SecurityContextHolderAwareRequestFilter();
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
@Override
public SecurityContextHolderAwareRequestFilter getBean() {
this.filter.setSecurityContextHolderStrategy(this.securityContextHolderStrategy);
this.filter.setRolePrefix(this.rolePrefix);
return this.filter;
}
void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
} | static class SecurityContextHolderStrategyFactory implements FactoryBean<SecurityContextHolderStrategy> {
@Override
public SecurityContextHolderStrategy getObject() throws Exception {
return SecurityContextHolder.getContextHolderStrategy();
}
@Override
public Class<?> getObjectType() {
return SecurityContextHolderStrategy.class;
}
}
static class ObservationRegistryFactory implements FactoryBean<ObservationRegistry> {
@Override
public ObservationRegistry getObject() throws Exception {
return ObservationRegistry.NOOP;
}
@Override
public Class<?> getObjectType() {
return ObservationRegistry.class;
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\HttpConfigurationBuilder.java | 2 |
请完成以下Java代码 | public class ClaimTaskCmd extends NeedsActiveTaskCmd<Void> {
private static final long serialVersionUID = 1L;
protected String userId;
public ClaimTaskCmd(String taskId, String userId) {
super(taskId);
this.userId = userId;
}
protected Void execute(CommandContext commandContext, TaskEntity task) {
if (userId != null) {
task.setClaimTime(commandContext.getProcessEngineConfiguration().getClock().getCurrentTime());
if (task.getAssignee() != null) {
if (!task.getAssignee().equals(userId)) {
// When the task is already claimed by another user, throw
// exception. Otherwise, ignore
// this, post-conditions of method already met.
throw new ActivitiTaskAlreadyClaimedException(task.getId(), task.getAssignee());
}
} else {
commandContext.getTaskEntityManager().changeTaskAssignee(task, userId); | }
} else {
// Task claim time should be null
task.setClaimTime(null);
// Task should be assigned to no one
commandContext.getTaskEntityManager().changeTaskAssignee(task, null);
}
// Add claim time to historic task instance
commandContext.getHistoryManager().recordTaskClaim(task);
return null;
}
@Override
protected String getSuspendedTaskException() {
return "Cannot claim a suspended task";
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\ClaimTaskCmd.java | 1 |
请完成以下Java代码 | public @Nullable Object convert(@Nullable String json) {
if (StringUtils.hasText(json)) {
String objectTypeName = null;
try {
ObjectMapper objectMapper = getObjectMapper();
JsonNode jsonNode = objectMapper.readTree(json);
if (isPojo(jsonNode)) {
return ((POJONode) jsonNode).getPojo();
}
else {
Assert.state(jsonNode.isObject(), () -> String.format("The JSON [%s] must be an object", json));
Assert.state(jsonNode.has(AT_TYPE_FIELD_NAME),
() -> String.format("The JSON object [%1$s] must have an '%2$s' metadata field",
json, AT_TYPE_FIELD_NAME));
objectTypeName = jsonNode.get(AT_TYPE_FIELD_NAME).asText();
Class<?> objectType =
ClassUtils.forName(objectTypeName, Thread.currentThread().getContextClassLoader());
return objectMapper.readValue(json, objectType);
}
}
catch (ClassNotFoundException cause) {
throw new MappingException(String.format("Failed to map JSON [%1$s] to an Object of type [%2$s]",
json, objectTypeName), cause);
}
catch (JsonProcessingException cause) { | throw new DataRetrievalFailureException(String.format("Failed to read JSON [%s]", json), cause);
}
}
return null;
}
/**
* Null-safe method to determine whether the given {@link JsonNode} represents a {@link Object POJO}.
*
* @param jsonNode {@link JsonNode} to evaluate.
* @return a boolean value indicating whether the given {@link JsonNode} represents a {@link Object POJO}.
* @see com.fasterxml.jackson.databind.JsonNode
*/
boolean isPojo(@Nullable JsonNode jsonNode) {
return jsonNode != null
&& (jsonNode instanceof POJONode || jsonNode.isPojo() || JsonNodeType.POJO.equals(jsonNode.getNodeType()));
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\data\json\converter\support\JacksonJsonToObjectConverter.java | 1 |
请完成以下Java代码 | protected IDocument getLegacyDocumentOrNull(
Object documentObj,
boolean throwEx)
{
final Object documentObjToUse;
final POJOWrapper wrapper;
if (documentObj instanceof ITableRecordReference)
{
final Object referencedModel = ((ITableRecordReference)documentObj).getModel(Object.class);
documentObjToUse = referencedModel;
wrapper = POJOWrapper.getWrapper(referencedModel);
}
else
{
wrapper = POJOWrapper.getWrapper(documentObj);
documentObjToUse = documentObj;
}
final Class<?> interfaceClass = wrapper.getInterfaceClass();
if (hasMethod(interfaceClass, String.class, "getDocStatus") | && hasMethod(interfaceClass, String.class, "getDocAction")
// allow for now to consider documents also the ones that don't have DocumentNo; see <code>I_C_Flatrate_Term</code>
// && hasMethod(interfaceClass, String.class, "getDocumentNo")
)
{
final IDocument pojoWrapper = POJOWrapper.create(documentObjToUse, IDocument.class);
return pojoWrapper;
}
if (throwEx)
{
throw new AdempiereException("Cannot extract " + IDocument.class + " from " + documentObj);
}
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\document\engine\impl\PlainDocumentBL.java | 1 |
请完成以下Java代码 | public void learn(Sentence ... sentences)
{
learn(Arrays.asList(sentences));
}
/**
* 训练
* @param corpus 语料库路径
*/
public void train(String corpus)
{
CorpusLoader.walk(corpus, new CorpusLoader.Handler()
{
@Override
public void handle(Document document)
{
List<List<Word>> simpleSentenceList = document.getSimpleSentenceList();
List<List<IWord>> compatibleList = new LinkedList<List<IWord>>();
for (List<Word> wordList : simpleSentenceList)
{ | compatibleList.add(new LinkedList<IWord>(wordList));
}
CommonDictionaryMaker.this.compute(compatibleList);
}
});
}
/**
* 加入到词典中,允许子类自定义过滤等等,这样比较灵活
* @param sentenceList
*/
abstract protected void addToDictionary(List<List<IWord>> sentenceList);
/**
* 角色标注,如果子类要进行label的调整或增加新的首尾等等,可以在此进行
*/
abstract protected void roleTag(List<List<IWord>> sentenceList);
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\CommonDictionaryMaker.java | 1 |
请完成以下Java代码 | public static String formatDate(Date date, String pattern) {
return DateFormatUtils.format(date, pattern);
}
/**
* Format date by 'yyyy-MM-dd' pattern
*
* @param date
* @return
*/
public static String formatByDayPattern(Date date) {
if (date != null) {
return DateFormatUtils.format(date, DAY_PATTERN);
} else {
return null;
}
}
/**
* Format date by 'yyyy-MM-dd HH:mm:ss' pattern
*
* @param date | * @return
*/
public static String formatByDateTimePattern(Date date) {
return DateFormatUtils.format(date, DATETIME_PATTERN);
}
/**
* Get current day using format date by 'yyyy-MM-dd HH:mm:ss' pattern
*
* @return
* @author yebo
*/
public static String getCurrentDayByDayPattern() {
Calendar cal = Calendar.getInstance();
return formatByDayPattern(cal.getTime());
}
} | repos\Spring-Boot-In-Action-master\id-spring-boot-starter\src\main\java\com\baidu\fsg\uid\utils\DateUtils.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<I_C_BPartner_Contact_QuickInput> retrieveContactsByQuickInputId(@NonNull final BPartnerQuickInputId bpartnerQuickInputId)
{
return queryBL
.createQueryBuilder(I_C_BPartner_Contact_QuickInput.class)
.addEqualsFilter(I_C_BPartner_Contact_QuickInput.COLUMNNAME_C_BPartner_QuickInput_ID, bpartnerQuickInputId)
.orderBy(I_C_BPartner_Contact_QuickInput.COLUMNNAME_C_BPartner_Contact_QuickInput_ID)
.create()
.list();
}
public List<I_C_BPartner_Location_QuickInput> retrieveLocationsByQuickInputId(final BPartnerQuickInputId bpartnerQuickInputId)
{
return queryBL
.createQueryBuilder(I_C_BPartner_Location_QuickInput.class)
.addEqualsFilter(I_C_BPartner_Location_QuickInput.COLUMNNAME_C_BPartner_QuickInput_ID, bpartnerQuickInputId)
.orderBy(I_C_BPartner_Location_QuickInput.COLUMNNAME_C_BPartner_Location_QuickInput_ID)
.create()
.list();
}
public List<I_C_BPartner_Location_QuickInput> retrieveBillToLocationsByQuickInputId(final BPartnerQuickInputId bpartnerQuickInputId)
{ | return queryBL
.createQueryBuilder(I_C_BPartner_Location_QuickInput.class)
.addEqualsFilter(I_C_BPartner_Location_QuickInput.COLUMNNAME_C_BPartner_QuickInput_ID, bpartnerQuickInputId)
.orderBy(I_C_BPartner_Location_QuickInput.COLUMNNAME_C_BPartner_Location_QuickInput_ID)
.create()
.list();
}
public List<String> getOtherLocationNames(
final int bpartnerQuickInputRecordId,
final int bpartnerLocationQuickInputIdToExclude)
{
return queryBL
.createQueryBuilder(I_C_BPartner_Location_QuickInput.class)
.addEqualsFilter(I_C_BPartner_Location_QuickInput.COLUMNNAME_C_BPartner_QuickInput_ID, bpartnerQuickInputRecordId)
.addNotEqualsFilter(I_C_BPartner_Location_QuickInput.COLUMNNAME_C_BPartner_Location_QuickInput_ID, bpartnerLocationQuickInputIdToExclude)
.create()
.listDistinct(I_C_BPartner_Location_QuickInput.COLUMNNAME_Name, String.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\quick_input\service\BPartnerQuickInputRepository.java | 2 |
请完成以下Java代码 | public void dispatchEvent(FlowableEvent event) {
commandExecutor.execute(new DispatchEventCommand(event));
}
@Override
public void setProcessInstanceName(String processInstanceId, String name) {
commandExecutor.execute(new SetProcessInstanceNameCmd(processInstanceId, name));
}
@Override
public List<Event> getProcessInstanceEvents(String processInstanceId) {
return commandExecutor.execute(new GetProcessInstanceEventsCmd(processInstanceId));
}
@Override
public ProcessInstanceBuilder createProcessInstanceBuilder() {
return new ProcessInstanceBuilderImpl(this); | }
public ProcessInstance startProcessInstance(ProcessInstanceBuilderImpl processInstanceBuilder) {
if (processInstanceBuilder.getProcessDefinitionId() != null
|| processInstanceBuilder.getProcessDefinitionKey() != null) {
return commandExecutor.execute(new StartProcessInstanceCmd<ProcessInstance>(processInstanceBuilder));
} else if (processInstanceBuilder.getMessageName() != null) {
return commandExecutor.execute(new StartProcessInstanceByMessageCmd(processInstanceBuilder));
} else {
throw new ActivitiIllegalArgumentException(
"No processDefinitionId, processDefinitionKey nor messageName provided");
}
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\RuntimeServiceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public UUID registerForAdoption( String speciesName) {
var species = speciesRepo.findByName(speciesName)
.orElseThrow(() -> new IllegalArgumentException("Unknown Species: " + speciesName));
var pet = new Pet();
pet.setSpecies(species);
pet.setUuid(UUID.randomUUID());
petsRepo.save(pet);
return pet.getUuid();
}
public List<Pet> findPetsForAdoption(String speciesName) {
var species = speciesRepo.findByName(speciesName)
.orElseThrow(() -> new IllegalArgumentException("Unknown Species: " + speciesName));
return petsRepo.findPetsByOwnerNullAndSpecies(species);
}
public Pet adoptPet(UUID petUuid, String ownerName, String petName) {
var newOwner = ownersRepo.findByName(ownerName)
.orElseThrow(() -> new IllegalArgumentException("Unknown owner"));
var pet = petsRepo.findPetByUuid(petUuid)
.orElseThrow(() -> new IllegalArgumentException("Unknown pet"));
if ( pet.getOwner() != null) {
throw new IllegalArgumentException("Pet already adopted");
}
pet.setOwner(newOwner);
pet.setName(petName);
petsRepo.save(pet);
return pet;
}
public Pet returnPet(UUID petUuid) {
var pet = petsRepo.findPetByUuid(petUuid)
.orElseThrow(() -> new IllegalArgumentException("Unknown pet"));
pet.setOwner(null);
petsRepo.save(pet);
return pet;
} | public List<PetHistoryEntry> listPetHistory(UUID petUuid) {
var pet = petsRepo.findPetByUuid(petUuid)
.orElseThrow(() -> new IllegalArgumentException("No pet with UUID '" + petUuid + "' found"));
return petsRepo.findRevisions(pet.getId()).stream()
.map(r -> {
CustomRevisionEntity rev = r.getMetadata().getDelegate();
return new PetHistoryEntry(r.getRequiredRevisionInstant(),
r.getMetadata().getRevisionType(),
r.getEntity().getUuid(),
r.getEntity().getSpecies().getName(),
r.getEntity().getName(),
r.getEntity().getOwner() != null ? r.getEntity().getOwner().getName() : null,
rev.getRemoteHost(),
rev.getRemoteUser());
})
.toList();
}
} | repos\tutorials-master\persistence-modules\spring-data-envers\src\main\java\com\baeldung\envers\customrevision\service\AdoptionService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class SpringBootApacheGeodeDockerClientCacheApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootApacheGeodeDockerClientCacheApplication.class, args);
}
@Bean
@SuppressWarnings("unused")
ApplicationRunner runner(GemFireCache cache, CustomerRepository customerRepository) {
return args -> {
assertClientCacheAndConfigureMappingPdxSerializer(cache);
assertThat(customerRepository.count()).isEqualTo(0);
Customer jonDoe = Customer.newCustomer(1L, "Jon Doe");
log("Saving Customer [%s]...%n", jonDoe);
jonDoe = customerRepository.save(jonDoe);
assertThat(jonDoe).isNotNull();
assertThat(jonDoe.getId()).isEqualTo(1L);
assertThat(jonDoe.getName()).isEqualTo("Jon Doe");
assertThat(customerRepository.count()).isEqualTo(1);
log("Querying for Customer [SELECT * FROM /Customers WHERE name LIKE '%s']...%n", "%Doe");
Customer queriedJonDoe = customerRepository.findByNameLike("%Doe");
assertThat(queriedJonDoe).isEqualTo(jonDoe);
log("Customer was [%s]%n", queriedJonDoe);
};
} | private void assertClientCacheAndConfigureMappingPdxSerializer(GemFireCache cache) {
assertThat(cache).isNotNull();
assertThat(cache.getName())
.isEqualTo(SpringBootApacheGeodeDockerClientCacheApplication.class.getSimpleName());
assertThat(cache.getPdxSerializer()).isInstanceOf(MappingPdxSerializer.class);
MappingPdxSerializer serializer = (MappingPdxSerializer) cache.getPdxSerializer();
serializer.setIncludeTypeFilters(type -> Optional.ofNullable(type)
.map(Class::getPackage)
.map(Package::getName)
.filter(packageName -> packageName.startsWith(this.getClass().getPackage().getName()))
.isPresent());
}
private void log(String message, Object... args) {
System.err.printf(message, args);
System.err.flush();
}
}
// end::class[] | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-docs\src\main\java\org\springframework\geode\docs\example\app\docker\SpringBootApacheGeodeDockerClientCacheApplication.java | 2 |
请完成以下Java代码 | public Long call() throws Exception {
long total = 0L;
for (int i = from; i < to; i++) {
total += numbers[i];
}
return total;
}
}
public long sum(int[] numbers) {
int chunk = numbers.length / nThreads;
int from, to;
List<SumTask> tasks = new ArrayList<SumTask>();
for (int i = 1; i <= nThreads; i++) {
if (i == nThreads) {
from = (i - 1) * chunk;
to = numbers.length;
} else {
from = (i - 1) * chunk;
to = i * chunk;
}
tasks.add(new SumTask(numbers, from, to)); | }
try {
List<Future<Long>> futures = pool.invokeAll(tasks);
long total = 0L;
for (Future<Long> future : futures) {
total += future.get();
}
return total;
} catch (Exception e) {
// ignore
return 0;
}
}
@Override
public void shutdown() {
pool.shutdown();
}
} | repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\benchmark\sum\calc\impl\MultithreadCalculator.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
/**
* AlbertaRole AD_Reference_ID=541322
* Reference name: AlbertaRole
*/
public static final int ALBERTAROLE_AD_Reference_ID=541322;
/** Caregiver = CG */
public static final String ALBERTAROLE_Caregiver = "CG";
/** Caretaker = CT */
public static final String ALBERTAROLE_Caretaker = "CT";
/** General Practitioner = GP */
public static final String ALBERTAROLE_GeneralPractitioner = "GP";
/** Health Insurance = HI */
public static final String ALBERTAROLE_HealthInsurance = "HI";
/** Hostpital = HO */
public static final String ALBERTAROLE_Hostpital = "HO";
/** Main Producer = MP */
public static final String ALBERTAROLE_MainProducer = "MP";
/** Nursing Home = NH */
public static final String ALBERTAROLE_NursingHome = "NH";
/** Nursing Service = NS */
public static final String ALBERTAROLE_NursingService = "NS";
/** Payer = PA */
public static final String ALBERTAROLE_Payer = "PA";
/** Doctor = PD */
public static final String ALBERTAROLE_Doctor = "PD";
/** Pharmacy = PH */
public static final String ALBERTAROLE_Pharmacy = "PH";
/** Preferred Pharmacy = PP */
public static final String ALBERTAROLE_PreferredPharmacy = "PP";
/** Pacient = PT */
public static final String ALBERTAROLE_Pacient = "PT";
@Override
public void setAlbertaRole (final String AlbertaRole)
{
set_Value (COLUMNNAME_AlbertaRole, AlbertaRole); | }
@Override
public String getAlbertaRole()
{
return get_ValueAsString(COLUMNNAME_AlbertaRole);
}
@Override
public void setC_BPartner_AlbertaRole_ID (final int C_BPartner_AlbertaRole_ID)
{
if (C_BPartner_AlbertaRole_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_AlbertaRole_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_AlbertaRole_ID, C_BPartner_AlbertaRole_ID);
}
@Override
public int getC_BPartner_AlbertaRole_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_AlbertaRole_ID);
}
@Override
public void setC_BPartner_ID (final int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_Value (COLUMNNAME_C_BPartner_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_ID, C_BPartner_ID);
}
@Override
public int getC_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_C_BPartner_AlbertaRole.java | 1 |
请完成以下Java代码 | public static String getDbTypeString(DbType dbType){
if(DbType.DB2.equals(dbType)){
return DataBaseConstant.DB_TYPE_DB2;
}else if(DbType.HSQL.equals(dbType)){
return DataBaseConstant.DB_TYPE_HSQL;
}else if(dbTypeIsOracle(dbType)){
return DataBaseConstant.DB_TYPE_ORACLE;
}else if(dbTypeIsSqlServer(dbType)){
return DataBaseConstant.DB_TYPE_SQLSERVER;
}else if(dbTypeIsPostgre(dbType)){
return DataBaseConstant.DB_TYPE_POSTGRESQL;
}
return DataBaseConstant.DB_TYPE_MYSQL;
}
/**
* 根据枚举类 获取数据库方言字符串
* @param dbType
* @return
*/
public static String getDbDialect(DbType dbType){ | return dialectMap.get(dbType.getDb());
}
/**
* 判断数据库类型
*/
public static boolean dbTypeIf(DbType dbType, DbType... correctTypes) {
for (DbType type : correctTypes) {
if (type.equals(dbType)) {
return true;
}
}
return false;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\dynamic\db\DbTypeUtils.java | 1 |
请完成以下Java代码 | public class ProcessesXmlStopProcessEnginesStep extends DeploymentOperationStep {
private final static ContainerIntegrationLogger LOG = ProcessEngineLogger.CONTAINER_INTEGRATION_LOGGER;
public String getName() {
return "Stopping process engines";
}
public void performOperationStep(DeploymentOperation operationContext) {
final PlatformServiceContainer serviceContainer = operationContext.getServiceContainer();
final AbstractProcessApplication processApplication = operationContext.getAttachment(Attachments.PROCESS_APPLICATION);
final JmxManagedProcessApplication deployedProcessApplication = serviceContainer.getService(ServiceTypes.PROCESS_APPLICATION, processApplication.getName());
ensureNotNull("Cannot find process application with name " + processApplication.getName(), "deployedProcessApplication", deployedProcessApplication);
List<ProcessesXml> processesXmls = deployedProcessApplication.getProcessesXmls();
for (ProcessesXml processesXml : processesXmls) {
stopProcessEngines(processesXml.getProcessEngines(), operationContext);
} | }
protected void stopProcessEngines(List<ProcessEngineXml> processEngine, DeploymentOperation operationContext) {
for (ProcessEngineXml parsedProcessEngine : processEngine) {
stopProcessEngine(parsedProcessEngine.getName(), operationContext);
}
}
protected void stopProcessEngine(String processEngineName, DeploymentOperation operationContext) {
final PlatformServiceContainer serviceContainer = operationContext.getServiceContainer();
try {
serviceContainer.stopService(ServiceTypes.PROCESS_ENGINE, processEngineName);
}
catch(Exception e) {
LOG.exceptionWhileStopping("Process Engine", processEngineName, e);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\ProcessesXmlStopProcessEnginesStep.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<UmsResource> listResource(Long roleId) {
return roleDao.getResourceListByRoleId(roleId);
}
@Override
public int allocMenu(Long roleId, List<Long> menuIds) {
//先删除原有关系
UmsRoleMenuRelationExample example=new UmsRoleMenuRelationExample();
example.createCriteria().andRoleIdEqualTo(roleId);
roleMenuRelationMapper.deleteByExample(example);
//批量插入新关系
for (Long menuId : menuIds) {
UmsRoleMenuRelation relation = new UmsRoleMenuRelation();
relation.setRoleId(roleId);
relation.setMenuId(menuId);
roleMenuRelationMapper.insert(relation);
}
return menuIds.size();
} | @Override
public int allocResource(Long roleId, List<Long> resourceIds) {
//先删除原有关系
UmsRoleResourceRelationExample example=new UmsRoleResourceRelationExample();
example.createCriteria().andRoleIdEqualTo(roleId);
roleResourceRelationMapper.deleteByExample(example);
//批量插入新关系
for (Long resourceId : resourceIds) {
UmsRoleResourceRelation relation = new UmsRoleResourceRelation();
relation.setRoleId(roleId);
relation.setResourceId(resourceId);
roleResourceRelationMapper.insert(relation);
}
adminCacheService.delResourceListByRole(roleId);
return resourceIds.size();
}
} | repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\UmsRoleServiceImpl.java | 2 |
请完成以下Java代码 | class ServletInitializerContributor implements
MainSourceCodeCustomizer<TypeDeclaration, CompilationUnit<TypeDeclaration>, SourceCode<TypeDeclaration, CompilationUnit<TypeDeclaration>>> {
private final String packageName;
private final String initializerClassName;
private final ObjectProvider<ServletInitializerCustomizer<?>> servletInitializerCustomizers;
ServletInitializerContributor(String packageName, String initializerClassName,
ObjectProvider<ServletInitializerCustomizer<?>> servletInitializerCustomizers) {
this.packageName = packageName;
this.initializerClassName = initializerClassName;
this.servletInitializerCustomizers = servletInitializerCustomizers;
}
@Override
public void customize(SourceCode<TypeDeclaration, CompilationUnit<TypeDeclaration>> sourceCode) {
CompilationUnit<TypeDeclaration> compilationUnit = sourceCode.createCompilationUnit(this.packageName, | "ServletInitializer");
TypeDeclaration servletInitializer = compilationUnit.createTypeDeclaration("ServletInitializer");
servletInitializer.extend(this.initializerClassName);
customizeServletInitializer(servletInitializer);
}
@SuppressWarnings("unchecked")
private void customizeServletInitializer(TypeDeclaration servletInitializer) {
List<ServletInitializerCustomizer<?>> customizers = this.servletInitializerCustomizers.orderedStream()
.collect(Collectors.toList());
LambdaSafe.callbacks(ServletInitializerCustomizer.class, customizers, servletInitializer)
.invoke((customizer) -> customizer.customize(servletInitializer));
}
} | repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\code\ServletInitializerContributor.java | 1 |
请完成以下Java代码 | public void setDescription (String Description)
{
set_ValueNoCheck (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
public I_Fact_Acct getFact_Acct() throws RuntimeException
{
return (I_Fact_Acct)MTable.get(getCtx(), I_Fact_Acct.Table_Name)
.getPO(getFact_Acct_ID(), get_TrxName()); }
/** Set Accounting Fact.
@param Fact_Acct_ID Accounting Fact */
public void setFact_Acct_ID (int Fact_Acct_ID)
{
if (Fact_Acct_ID < 1)
set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, Integer.valueOf(Fact_Acct_ID));
}
/** Get Accounting Fact.
@return Accounting Fact */
public int getFact_Acct_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Fact_Acct_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Level no.
@param LevelNo Level no */
public void setLevelNo (int LevelNo)
{
set_ValueNoCheck (COLUMNNAME_LevelNo, Integer.valueOf(LevelNo));
}
/** Get Level no.
@return Level no */
public int getLevelNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_LevelNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_ValueNoCheck (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 Quantity.
@param Qty
Quantity
*/
public void setQty (BigDecimal Qty)
{
set_ValueNoCheck (COLUMNNAME_Qty, Qty);
}
/** Get Quantity.
@return Quantity
*/
public BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_T_ReportStatement.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EventLogService
{
private final EventLogsRepository eventLogsRepository;
public EventLogService(@NonNull final EventLogsRepository eventLogsRepository)
{
this.eventLogsRepository = eventLogsRepository;
}
public Event loadEventForReposting(@NonNull final EventLogId eventLogId)
{
return loadEventForReposting(eventLogId, ImmutableList.of());
}
public Event loadEventForReposting(
@NonNull final EventLogId eventLogId,
@NonNull final List<String> handlersToIgnore)
{
final I_AD_EventLog eventLogRecord = loadOutOfTrx(eventLogId, I_AD_EventLog.class);
final String eventString = eventLogRecord.getEventData();
final Event eventFromStoredString = JacksonJsonEventSerializer.instance.fromString(eventString);
final List<String> processedHandlers = Services.get(IQueryBL.class)
.createQueryBuilder(I_AD_EventLog_Entry.class, PlainContextAware.newOutOfTrx())
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_AD_EventLog_Entry.COLUMNNAME_AD_EventLog_ID, eventLogRecord.getAD_EventLog_ID())
.addEqualsFilter(I_AD_EventLog_Entry.COLUMNNAME_Processed, true)
.addNotEqualsFilter(I_AD_EventLog_Entry.COLUMNNAME_Classname, null)
.addNotInArrayFilter(I_AD_EventLog_Entry.COLUMN_Classname, handlersToIgnore)
.create()
.listDistinct(I_AD_EventLog_Entry.COLUMNNAME_Classname, String.class);
return eventFromStoredString.toBuilder()
.putPropertyFromObject(
EventLogUserService.PROPERTY_PROCESSED_BY_HANDLER_CLASS_NAMES,
processedHandlers)
.wasLogged() // the event was logged; otherwise we would not be able to load it
.build();
} | public EventLogId saveEvent(
@NonNull final Event event,
@NonNull final Topic eventBusTopic)
{
final String eventString = JacksonJsonEventSerializer.instance.toString(event);
final I_AD_EventLog eventLogRecord = newInstanceOutOfTrx(I_AD_EventLog.class);
eventLogRecord.setEvent_UUID(event.getUuid().toString());
eventLogRecord.setEventTime(Timestamp.from(event.getWhen()));
eventLogRecord.setEventData(eventString);
eventLogRecord.setEventTopicName(eventBusTopic.getName());
eventLogRecord.setEventTypeName(eventBusTopic.getType().toString());
eventLogRecord.setEventName(event.getEventName());
final TableRecordReference sourceRecordReference = event.getSourceRecordReference();
if (sourceRecordReference != null)
{
eventLogRecord.setAD_Table_ID(sourceRecordReference.getAD_Table_ID());
eventLogRecord.setRecord_ID(sourceRecordReference.getRecord_ID());
}
save(eventLogRecord);
return EventLogId.ofRepoId(eventLogRecord.getAD_EventLog_ID());
}
public void saveEventLogEntries(@NonNull final Collection<EventLogEntry> eventLogEntries)
{
if (eventLogEntries.isEmpty())
{
return;
}
// Save each entry
eventLogsRepository.saveLogs(eventLogEntries);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\log\EventLogService.java | 2 |
请完成以下Java代码 | public void setPolicy(ReferrerPolicy policy) {
Assert.notNull(policy, "policy must not be null");
this.delegate = createDelegate(policy);
}
private static ServerHttpHeadersWriter createDelegate(ReferrerPolicy policy) {
Builder builder = StaticServerHttpHeadersWriter.builder();
builder.header(REFERRER_POLICY, policy.getPolicy());
return builder.build();
}
public enum ReferrerPolicy {
NO_REFERRER("no-referrer"),
NO_REFERRER_WHEN_DOWNGRADE("no-referrer-when-downgrade"),
SAME_ORIGIN("same-origin"),
ORIGIN("origin"),
STRICT_ORIGIN("strict-origin"),
ORIGIN_WHEN_CROSS_ORIGIN("origin-when-cross-origin"),
STRICT_ORIGIN_WHEN_CROSS_ORIGIN("strict-origin-when-cross-origin"),
UNSAFE_URL("unsafe-url");
private static final Map<String, ReferrerPolicy> REFERRER_POLICIES;
static {
Map<String, ReferrerPolicy> referrerPolicies = new HashMap<>(); | for (ReferrerPolicy referrerPolicy : values()) {
referrerPolicies.put(referrerPolicy.getPolicy(), referrerPolicy);
}
REFERRER_POLICIES = Collections.unmodifiableMap(referrerPolicies);
}
private final String policy;
ReferrerPolicy(String policy) {
this.policy = policy;
}
public String getPolicy() {
return this.policy;
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\header\ReferrerPolicyServerHttpHeadersWriter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Page<Article> getArticlesByTag(String tagValue, Pageable pageable) {
return tagService.findByValue(tagValue)
.map(tag -> articleRepository.findAllByContentsTagsContains(tag, pageable))
.orElse(Page.empty());
}
@Override
@Transactional(readOnly = true)
public Optional<Article> getArticleBySlug(String slug) {
return articleRepository.findFirstByContentsTitleSlug(slug);
}
@Transactional
public Article updateArticle(long userId, String slug, ArticleUpdateRequest request) {
return mapIfAllPresent(userFindService.findById(userId), getArticleBySlug(slug),
(user, article) -> user.updateArticle(article, request))
.orElseThrow(NoSuchElementException::new);
}
@Transactional
public Article favoriteArticle(long userId, String articleSlugToFavorite) {
return mapIfAllPresent(
userFindService.findById(userId), getArticleBySlug(articleSlugToFavorite),
User::favoriteArticle)
.orElseThrow(NoSuchElementException::new);
} | @Transactional
public Article unfavoriteArticle(long userId, String articleSlugToUnFavorite) {
return mapIfAllPresent(
userFindService.findById(userId), getArticleBySlug(articleSlugToUnFavorite),
User::unfavoriteArticle)
.orElseThrow(NoSuchElementException::new);
}
@Transactional
public void deleteArticleBySlug(long userId, String slug) {
userFindService.findById(userId)
.ifPresentOrElse(user -> articleRepository.deleteArticleByAuthorAndContentsTitleSlug(user, slug),
() -> {throw new NoSuchElementException();});
}
} | repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\article\ArticleService.java | 2 |
请完成以下Java代码 | public boolean containsContext(HttpServletRequest request) {
for (SecurityContextRepository delegate : this.delegates) {
if (delegate.containsContext(request)) {
return true;
}
}
return false;
}
static final class DelegatingDeferredSecurityContext implements DeferredSecurityContext {
private final DeferredSecurityContext previous;
private final DeferredSecurityContext next;
DelegatingDeferredSecurityContext(DeferredSecurityContext previous, DeferredSecurityContext next) {
this.previous = previous;
this.next = next;
} | @Override
public SecurityContext get() {
SecurityContext securityContext = this.previous.get();
if (!this.previous.isGenerated()) {
return securityContext;
}
return this.next.get();
}
@Override
public boolean isGenerated() {
return this.previous.isGenerated() && this.next.isGenerated();
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\context\DelegatingSecurityContextRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void handlePutRfQsRequest(@NonNull final PutRfQsRequest request)
{
logger.debug("Importing: {}", request);
if (request.isEmpty())
{
return;
}
for (final SyncRfQ syncRfq : request.getSyncRfqs())
{
try
{
rfqImportService.importRfQ(syncRfq);
}
catch (final Exception e)
{
logger.error("Failed importing RfQ: {}", syncRfq, e);
}
}
}
public void handlePutRfQCloseEventsRequest(final PutRfQCloseEventsRequest request)
{
logger.debug("Importing: {}", request); | if (request.isEmpty())
{
return;
}
for (final SyncRfQCloseEvent syncRfQCloseEvent : request.getSyncRfQCloseEvents())
{
try
{
rfqImportService.importRfQCloseEvent(syncRfQCloseEvent);
}
catch (final Exception e)
{
logger.error("Failed importing: {}", syncRfQCloseEvent, e);
}
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\sync\ReceiverFromMetasfreshHandler.java | 2 |
请完成以下Java代码 | protected void injectObjectMapper(ProcessInstanceQueryDto queryParameter) {
queryParameter.setObjectMapper(objectMapper);
}
public void setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
/*
The Command interface should always be implemented as a regular,
or inner class so that invoked commands are correctly counted with Telemetry.
*/
protected class QueryProcessInstancesCmd implements Command<List<ProcessInstanceDto>> {
protected ProcessInstanceQueryDto queryParameter;
protected Integer firstResult;
protected Integer maxResults;
public QueryProcessInstancesCmd(ProcessInstanceQueryDto queryParameter, Integer firstResult, Integer maxResults) {
this.queryParameter = queryParameter;
this.firstResult = firstResult;
this.maxResults = maxResults;
}
@Override
public List<ProcessInstanceDto> execute(CommandContext commandContext) {
injectObjectMapper(queryParameter);
injectEngineConfig(queryParameter);
paginate(queryParameter, firstResult, maxResults);
configureExecutionQuery(queryParameter);
return getQueryService().executeQuery("selectRunningProcessInstancesIncludingIncidents", queryParameter); | }
}
protected class QueryProcessInstancesCountCmd implements Command<CountResultDto> {
protected ProcessInstanceQueryDto queryParameter;
public QueryProcessInstancesCountCmd(ProcessInstanceQueryDto queryParameter) {
this.queryParameter = queryParameter;
}
@Override
public CountResultDto execute(CommandContext commandContext) {
injectEngineConfig(queryParameter);
configureExecutionQuery(queryParameter);
long result = getQueryService().executeQueryRowCount("selectRunningProcessInstancesCount", queryParameter);
return new CountResultDto(result);
}
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\resources\ProcessInstanceRestService.java | 1 |
请完成以下Java代码 | private OrgId getFromOrgId()
{
return Services.get(IWarehouseDAO.class).retrieveOrgIdByLocatorId(getM_Locator_ID());
}
private OrgId getToOrgId()
{
return Services.get(IWarehouseDAO.class).retrieveOrgIdByLocatorId(getM_LocatorTo_ID());
}
public final int getM_LocatorTo_ID()
{
final I_M_MovementLine movementLine = getModel(I_M_MovementLine.class);
return movementLine.getM_LocatorTo_ID();
}
@Value
@Builder
private static class MovementLineCostAmounts
{
AggregatedCostAmount outboundCosts;
AggregatedCostAmount inboundCosts;
}
public final MoveCostsResult getCreateCosts(@NonNull final AcctSchema as)
{
if (isReversalLine())
{
final AggregatedCostAmount outboundCosts = services.createReversalCostDetails(
CostDetailReverseRequest.builder()
.acctSchemaId(as.getId())
.reversalDocumentRef(CostingDocumentRef.ofOutboundMovementLineId(get_ID()))
.initialDocumentRef(CostingDocumentRef.ofOutboundMovementLineId(getReversalLine_ID()))
.date(getDateAcctAsInstant())
.build())
.toAggregatedCostAmount();
final AggregatedCostAmount inboundCosts = services.createReversalCostDetails(
CostDetailReverseRequest.builder()
.acctSchemaId(as.getId())
.reversalDocumentRef(CostingDocumentRef.ofInboundMovementLineId(get_ID()))
.initialDocumentRef(CostingDocumentRef.ofInboundMovementLineId(getReversalLine_ID()))
.date(getDateAcctAsInstant())
.build())
.toAggregatedCostAmount();
return MoveCostsResult.builder()
.outboundCosts(outboundCosts)
.inboundCosts(inboundCosts) | .build();
}
else
{
return services.moveCosts(MoveCostsRequest.builder()
.acctSchemaId(as.getId())
.clientId(getClientId())
.date(getDateAcctAsInstant())
// .costElement(null) // all cost elements
.productId(getProductId())
.attributeSetInstanceId(getAttributeSetInstanceId())
.qtyToMove(getQty())
//
.outboundOrgId(getFromOrgId())
.outboundDocumentRef(CostingDocumentRef.ofOutboundMovementLineId(get_ID()))
//
.inboundOrgId(getToOrgId())
.inboundDocumentRef(CostingDocumentRef.ofInboundMovementLineId(get_ID()))
//
.build());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocLine_Movement.java | 1 |
请完成以下Java代码 | public String getXssProtectionOption() {
return xssProtectionOption;
}
public void setXssProtectionOption(String xssProtectionOption) {
this.xssProtectionOption = xssProtectionOption;
}
public String getXssProtectionValue() {
return xssProtectionValue;
}
public void setXssProtectionValue(String xssProtectionValue) {
this.xssProtectionValue = xssProtectionValue;
}
public boolean isContentSecurityPolicyDisabled() {
return contentSecurityPolicyDisabled;
}
public void setContentSecurityPolicyDisabled(boolean contentSecurityPolicyDisabled) {
this.contentSecurityPolicyDisabled = contentSecurityPolicyDisabled;
}
public String getContentSecurityPolicyValue() {
return contentSecurityPolicyValue;
}
public void setContentSecurityPolicyValue(String contentSecurityPolicyValue) {
this.contentSecurityPolicyValue = contentSecurityPolicyValue;
}
public boolean isContentTypeOptionsDisabled() {
return contentTypeOptionsDisabled;
}
public void setContentTypeOptionsDisabled(boolean contentTypeOptionsDisabled) {
this.contentTypeOptionsDisabled = contentTypeOptionsDisabled;
}
public String getContentTypeOptionsValue() {
return contentTypeOptionsValue;
}
public void setContentTypeOptionsValue(String contentTypeOptionsValue) {
this.contentTypeOptionsValue = contentTypeOptionsValue;
}
public boolean isHstsDisabled() {
return hstsDisabled;
}
public void setHstsDisabled(boolean hstsDisabled) {
this.hstsDisabled = hstsDisabled;
}
public boolean isHstsIncludeSubdomainsDisabled() { | return hstsIncludeSubdomainsDisabled;
}
public void setHstsIncludeSubdomainsDisabled(boolean hstsIncludeSubdomainsDisabled) {
this.hstsIncludeSubdomainsDisabled = hstsIncludeSubdomainsDisabled;
}
public String getHstsValue() {
return hstsValue;
}
public void setHstsValue(String hstsValue) {
this.hstsValue = hstsValue;
}
public String getHstsMaxAge() {
return hstsMaxAge;
}
public void setHstsMaxAge(String hstsMaxAge) {
this.hstsMaxAge = hstsMaxAge;
}
@Override
public String toString() {
StringJoiner joinedString = joinOn(this.getClass())
.add("xssProtectionDisabled=" + xssProtectionDisabled)
.add("xssProtectionOption=" + xssProtectionOption)
.add("xssProtectionValue=" + xssProtectionValue)
.add("contentSecurityPolicyDisabled=" + contentSecurityPolicyDisabled)
.add("contentSecurityPolicyValue=" + contentSecurityPolicyValue)
.add("contentTypeOptionsDisabled=" + contentTypeOptionsDisabled)
.add("contentTypeOptionsValue=" + contentTypeOptionsValue)
.add("hstsDisabled=" + hstsDisabled)
.add("hstsMaxAge=" + hstsMaxAge)
.add("hstsIncludeSubdomainsDisabled=" + hstsIncludeSubdomainsDisabled)
.add("hstsValue=" + hstsValue);
return joinedString.toString();
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\HeaderSecurityProperties.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
/**
* Attributes2 AD_Reference_ID=541333
* Reference name: Attributes2
*/
public static final int ATTRIBUTES2_AD_Reference_ID=541333;
@Override
public void setAttributes2 (final java.lang.String Attributes2)
{
set_Value (COLUMNNAME_Attributes2, Attributes2);
}
@Override
public java.lang.String getAttributes2()
{
return get_ValueAsString(COLUMNNAME_Attributes2);
}
@Override
public void setC_BPartner_Attribute2_ID (final int C_BPartner_Attribute2_ID)
{
if (C_BPartner_Attribute2_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_Attribute2_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_Attribute2_ID, C_BPartner_Attribute2_ID);
}
@Override
public int getC_BPartner_Attribute2_ID() | {
return get_ValueAsInt(COLUMNNAME_C_BPartner_Attribute2_ID);
}
@Override
public void setC_BPartner_ID (final int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, C_BPartner_ID);
}
@Override
public int getC_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Attribute2.java | 1 |
请完成以下Java代码 | public int[] getCheck()
{
return check;
}
public void setCheck(int[] check)
{
this.check = check;
}
public int[] getBase()
{
return base;
}
public void setBase(int[] base)
{ | this.base = base;
}
public int[] getLength()
{
return length;
}
public void setLength(int[] length)
{
this.length = length;
}
public void setSize(int size)
{
this.size = size;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\DoubleArrayTrieInteger.java | 1 |
请完成以下Java代码 | private void loadPointcut(final ModelChange annModelChange, final Method method)
{
try
{
addPointcut(preparePointcut(PointcutType.ModelChange, method)
.timings(extractTimings(annModelChange))
.afterCommit(annModelChange.afterCommit())
.columnNamesToCheckForChanges(annModelChange.ifColumnsChanged())
.ignoreColumnNames(annModelChange.ignoreColumnsChanged())
.onlyIfUIAction(annModelChange.ifUIAction())
.skipIfCopying(annModelChange.skipIfCopying())
.build());
}
catch (final AdempiereException ex)
{
throw ex.setParameter("annotation", annModelChange)
.setParameter("method", method)
.appendParametersToMessage();
}
}
private static int[] extractTimings(final ModelChange annModelChange)
{
if (annModelChange.timings().length > 0 && annModelChange.types().length > 0)
{
throw new AdempiereException("Only `timings` or `types` shall be set, but not both");
}
else if (annModelChange.timings().length > 0)
{
return annModelChange.timings();
}
else if (annModelChange.types().length > 0)
{
return Stream.of(annModelChange.types())
.mapToInt(ModelChangeType::toInt)
.toArray();
}
else
{
throw new AdempiereException("At least `timings` or `types` shall be set");
}
}
private void loadPointcut(final DocValidate annDocValidate, final Method method)
{
addPointcut(preparePointcut(PointcutType.DocValidate, method)
.timings(annDocValidate.timings())
.afterCommit(annDocValidate.afterCommit())
.build());
} | private Pointcut.PointcutBuilder preparePointcut(PointcutType type, final Method method)
{
return Pointcut.builder()
.type(type)
.method(method)
.modelClass(getModelClass());
}
private void addPointcut(@NonNull final Pointcut pointcut)
{
assertModelTableNameAllowed(pointcut.getTableName());
if (!pointcuts.add(pointcut))
{
// shall not happen
final String msg = StringUtils.formatMessage("Pointcut {} was not added because another one was found in the list: {}", pointcut, pointcuts);
//noinspection ThrowableNotThrown
new AdempiereException(msg).throwOrLogSevere(Services.get(IDeveloperModeBL.class).isEnabled(), logger);
}
logger.debug("Loaded {}", pointcut);
}
private PointcutKey mkKey(@NonNull final Pointcut pointcut)
{
return PointcutKey.of(pointcut.getTableName(), pointcut.getType());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\AnnotatedModelInterceptorDescriptorBuilder.java | 1 |
请完成以下Java代码 | public void setLastSalesPrice (java.math.BigDecimal LastSalesPrice)
{
set_Value (COLUMNNAME_LastSalesPrice, LastSalesPrice);
}
/** Get Letzter VK.
@return letzter Verkaufspreis
*/
@Override
public java.math.BigDecimal getLastSalesPrice ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_LastSalesPrice);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
@Override
public org.compiere.model.I_C_Currency getLastSalesPrice_Currency() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_LastSalesPrice_Currency_ID, org.compiere.model.I_C_Currency.class);
}
@Override
public void setLastSalesPrice_Currency(org.compiere.model.I_C_Currency LastSalesPrice_Currency)
{
set_ValueFromPO(COLUMNNAME_LastSalesPrice_Currency_ID, org.compiere.model.I_C_Currency.class, LastSalesPrice_Currency);
}
/** Set Letzter VK Währung.
@param LastSalesPrice_Currency_ID
Letzter Verkaufspreis Währung
*/
@Override
public void setLastSalesPrice_Currency_ID (int LastSalesPrice_Currency_ID)
{
if (LastSalesPrice_Currency_ID < 1)
set_Value (COLUMNNAME_LastSalesPrice_Currency_ID, null);
else
set_Value (COLUMNNAME_LastSalesPrice_Currency_ID, Integer.valueOf(LastSalesPrice_Currency_ID));
}
/** Get Letzter VK Währung.
@return Letzter Verkaufspreis Währung
*/
@Override
public int getLastSalesPrice_Currency_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_LastSalesPrice_Currency_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Letzte Lieferung.
@param LastShipDate Letzte Lieferung */
@Override
public void setLastShipDate (java.sql.Timestamp LastShipDate)
{
set_Value (COLUMNNAME_LastShipDate, LastShipDate);
}
/** Get Letzte Lieferung.
@return Letzte Lieferung */
@Override
public java.sql.Timestamp getLastShipDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_LastShipDate);
}
@Override
public org.compiere.model.I_M_Product getM_Product() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); | }
@Override
public void setM_Product(org.compiere.model.I_M_Product M_Product)
{
set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product);
}
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
@Override
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Product_Stats.java | 1 |
请完成以下Java代码 | public class SecondaryCacheSetting {
/**
* @param expirationSecondTime 设置redis缓存的有效时间,单位秒
* @param preloadSecondTime 设置redis缓存的自动刷新时间,单位秒
*/
public SecondaryCacheSetting(long expirationSecondTime, long preloadSecondTime) {
this.expirationSecondTime = expirationSecondTime;
this.preloadSecondTime = preloadSecondTime;
}
/**
* @param usedFirstCache 是否启用一级缓存,默认true
* @param expirationSecondTime 设置redis缓存的有效时间,单位秒
* @param preloadSecondTime 设置redis缓存的自动刷新时间,单位秒
*/
public SecondaryCacheSetting(boolean usedFirstCache, long expirationSecondTime, long preloadSecondTime) {
this.expirationSecondTime = expirationSecondTime;
this.preloadSecondTime = preloadSecondTime;
this.usedFirstCache = usedFirstCache;
}
/**
* @param expirationSecondTime 设置redis缓存的有效时间,单位秒
* @param preloadSecondTime 设置redis缓存的自动刷新时间,单位秒
* @param forceRefresh 是否使用强制刷新(走数据库),默认false
*/
public SecondaryCacheSetting(long expirationSecondTime, long preloadSecondTime, boolean forceRefresh) {
this.expirationSecondTime = expirationSecondTime;
this.preloadSecondTime = preloadSecondTime;
this.forceRefresh = forceRefresh;
}
/**
* @param expirationSecondTime 设置redis缓存的有效时间,单位秒
* @param preloadSecondTime 设置redis缓存的自动刷新时间,单位秒
* @param usedFirstCache 是否启用一级缓存,默认true
* @param forceRefresh 是否使用强制刷新(走数据库),默认false
*/
public SecondaryCacheSetting(long expirationSecondTime, long preloadSecondTime, boolean usedFirstCache, boolean forceRefresh) {
this.expirationSecondTime = expirationSecondTime;
this.preloadSecondTime = preloadSecondTime;
this.usedFirstCache = usedFirstCache;
this.forceRefresh = forceRefresh;
}
/**
* 缓存有效时间
*/
private long expirationSecondTime;
/**
* 缓存主动在失效前强制刷新缓存的时间
* 单位:秒 | */
private long preloadSecondTime = 0;
/**
* 是否使用二级缓存,默认是true
*/
private boolean usedFirstCache = true;
/**
* 是否使用强刷新(走数据库),默认是false
*/
private boolean forceRefresh = false;
public long getPreloadSecondTime() {
return preloadSecondTime;
}
public long getExpirationSecondTime() {
return expirationSecondTime;
}
public boolean getUsedFirstCache() {
return usedFirstCache;
}
public boolean getForceRefresh() {
return forceRefresh;
}
} | repos\spring-boot-student-master\spring-boot-student-cache-redis-caffeine\src\main\java\com\xiaolyuh\cache\setting\SecondaryCacheSetting.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void update(List<CanalEntry.Column> data, String schemaName, String tableName) {
Document obj = DBConvertUtil.columnToJson(data);
logger.debug("update:{}", obj.toString());
if (obj.containsKey("id")) {
updateData(schemaName, tableName, new BasicDBObject("_id", obj.get("id")), obj);
} else {
logger.info("unknown data structure");
}
}
public void drop(String tableName) {
logger.warn("drop table {} from naive", tableName);
System.out.println("drop table " + tableName + " from naive");
try {
mongoTemplate.dropCollection(tableName.trim());
} catch (Exception e) {
logger.error("drop tableName error "+ tableName, e);
}
}
public void insertData(String schemaName, String tableName, Document obj) {
try {
String path = "/" + schemaName + "/" + tableName + "/" + CanalEntry.EventType.INSERT.getNumber();
mongoTemplate.save(obj,tableName);
} catch (MongoClientException | MongoSocketException clientException) {
//客户端连接异常抛出,阻塞同步,防止mongodb宕机
throw clientException;
} catch (DuplicateKeyException dke) {
//主键冲突异常,跳过
logger.warn("DuplicateKeyException:", dke);
} catch (Exception e) {
logger.error(schemaName, tableName, obj, e);
}
}
public void updateData(String schemaName, String tableName, DBObject query, Document obj) {
String path = "/" + schemaName + "/" + tableName + "/" + CanalEntry.EventType.UPDATE.getNumber();
Document options = new Document(query.toMap());
try {
obj.remove("id");
mongoTemplate.getCollection(tableName).replaceOne(options,obj); | obj.putAll(query.toMap());
} catch (MongoClientException | MongoSocketException clientException) {
//客户端连接异常抛出,阻塞同步,防止mongodb宕机
throw clientException;
} catch (Exception e) {
logger.error(schemaName, tableName, obj, e);
}
}
public void deleteData(String schemaName, String tableName, Document obj) {
String path = "/" + schemaName + "/" + tableName + "/" + CanalEntry.EventType.DELETE.getNumber();
//保存原始数据
try {
if (obj.containsKey("id")) {
obj.put("_id", obj.get("id"));
obj.remove("id");
mongoTemplate.remove(new BasicQuery(obj),tableName);
}
} catch (MongoClientException | MongoSocketException clientException) {
//客户端连接异常抛出,阻塞同步,防止mongodb宕机
throw clientException;
} catch (Exception e) {
logger.error(schemaName, tableName, obj, e);
}
}
} | repos\spring-boot-leaning-master\2.x_data\3-3 使用 canal 将业务数据从 Mysql 同步到 MongoDB\spring-boot-canal-mongodb\src\main\java\com\neo\service\DataService.java | 2 |
请完成以下Java代码 | public GatewayFilter apply(HttpStatus httpStatus, URI uri) {
return apply(new HttpStatusHolder(httpStatus, null), uri, false);
}
public GatewayFilter apply(HttpStatus httpStatus, URI uri, boolean includeRequestParams) {
return apply(new HttpStatusHolder(httpStatus, null), uri, includeRequestParams);
}
public GatewayFilter apply(HttpStatusHolder httpStatus, URI uri) {
return apply(httpStatus, uri, false);
}
public GatewayFilter apply(HttpStatusHolder httpStatus, URI uri, boolean includeRequestParams) {
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
if (!exchange.getResponse().isCommitted()) {
setResponseStatus(exchange, httpStatus);
String location;
if (includeRequestParams) {
location = UriComponentsBuilder.fromUri(uri)
.queryParams(exchange.getRequest().getQueryParams())
.build()
.toUri()
.toString();
}
else {
location = uri.toString();
}
final ServerHttpResponse response = exchange.getResponse();
response.getHeaders().set(HttpHeaders.LOCATION, location);
return response.setComplete();
}
return Mono.empty();
}
@Override
public String toString() {
String status;
if (httpStatus.getHttpStatus() != null) {
status = String.valueOf(httpStatus.getHttpStatus().value());
}
else { | status = httpStatus.getStatus().toString();
}
return filterToStringCreator(RedirectToGatewayFilterFactory.this).append(status, uri)
.append(INCLUDE_REQUEST_PARAMS_KEY, includeRequestParams)
.toString();
}
};
}
public static class Config {
private @Nullable String status;
private @Nullable String url;
boolean includeRequestParams;
public @Nullable String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public @Nullable String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public boolean isIncludeRequestParams() {
return includeRequestParams;
}
public void setIncludeRequestParams(boolean includeRequestParams) {
this.includeRequestParams = includeRequestParams;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RedirectToGatewayFilterFactory.java | 1 |
请完成以下Java代码 | public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((pk == null) ? 0 : pk.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false; | }
if (getClass() != obj.getClass()) {
return false;
}
OrderProduct other = (OrderProduct) obj;
if (pk == null) {
if (other.pk != null) {
return false;
}
} else if (!pk.equals(other.pk)) {
return false;
}
return true;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-angular\src\main\java\com\baeldung\ecommerce\model\OrderProduct.java | 1 |
请完成以下Java代码 | public DefaultSyncHttpGraphQlClientBuilder url(String url) {
this.restClientBuilder.baseUrl(url);
return this;
}
@Override
public DefaultSyncHttpGraphQlClientBuilder url(URI url) {
UriBuilderFactory factory = new DefaultUriBuilderFactory(UriComponentsBuilder.fromUri(url));
this.restClientBuilder.uriBuilderFactory(factory);
return this;
}
@Override
public DefaultSyncHttpGraphQlClientBuilder header(String name, String... values) {
this.restClientBuilder.defaultHeader(name, values);
return this;
}
@Override
public DefaultSyncHttpGraphQlClientBuilder headers(Consumer<HttpHeaders> headersConsumer) {
this.restClientBuilder.defaultHeaders(headersConsumer);
return this;
}
@Override
@SuppressWarnings("removal")
public DefaultSyncHttpGraphQlClientBuilder messageConverters(Consumer<List<HttpMessageConverter<?>>> configurer) {
this.restClientBuilder.messageConverters(configurer);
return this;
}
@Override
public DefaultSyncHttpGraphQlClientBuilder configureMessageConverters(Consumer<HttpMessageConverters.ClientBuilder> configurer) {
this.restClientBuilder.configureMessageConverters(configurer);
return this;
}
@Override
public DefaultSyncHttpGraphQlClientBuilder restClient(Consumer<RestClient.Builder> configurer) {
configurer.accept(this.restClientBuilder);
return this;
}
@Override
@SuppressWarnings("unchecked")
public HttpSyncGraphQlClient build() {
this.restClientBuilder.configureMessageConverters((builder) -> {
builder.registerDefaults().configureMessageConverters((converter) -> {
if (HttpMessageConverterDelegate.isJsonConverter(converter)) {
setJsonConverter((HttpMessageConverter<Object>) converter);
}
});
}); | RestClient restClient = this.restClientBuilder.build();
HttpSyncGraphQlTransport transport = new HttpSyncGraphQlTransport(restClient);
GraphQlClient graphQlClient = super.buildGraphQlClient(transport);
return new DefaultHttpSyncGraphQlClient(graphQlClient, restClient, getBuilderInitializer());
}
/**
* Default {@link HttpSyncGraphQlClient} implementation.
*/
private static class DefaultHttpSyncGraphQlClient
extends AbstractDelegatingGraphQlClient implements HttpSyncGraphQlClient {
private final RestClient restClient;
private final Consumer<AbstractGraphQlClientSyncBuilder<?>> builderInitializer;
DefaultHttpSyncGraphQlClient(
GraphQlClient delegate, RestClient restClient,
Consumer<AbstractGraphQlClientSyncBuilder<?>> builderInitializer) {
super(delegate);
Assert.notNull(restClient, "RestClient is required");
Assert.notNull(builderInitializer, "`builderInitializer` is required");
this.restClient = restClient;
this.builderInitializer = builderInitializer;
}
@Override
public DefaultSyncHttpGraphQlClientBuilder mutate() {
DefaultSyncHttpGraphQlClientBuilder builder = new DefaultSyncHttpGraphQlClientBuilder(this.restClient);
this.builderInitializer.accept(builder);
return builder;
}
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\DefaultSyncHttpGraphQlClientBuilder.java | 1 |
请完成以下Java代码 | protected @Nullable FailureAnalysis analyze(Throwable rootFailure,
MutuallyExclusiveConfigurationPropertiesException cause) {
List<Descriptor> descriptors = new ArrayList<>();
for (String name : cause.getConfiguredNames()) {
List<Descriptor> descriptorsForName = getDescriptors(name);
if (descriptorsForName.isEmpty()) {
return null;
}
descriptors.addAll(descriptorsForName);
}
StringBuilder description = new StringBuilder();
appendDetails(description, cause, descriptors);
return new FailureAnalysis(description.toString(),
"Update your configuration so that only one of the mutually exclusive properties is configured.",
cause);
}
private List<Descriptor> getDescriptors(String propertyName) {
return getPropertySources().filter((source) -> source.containsProperty(propertyName))
.map((source) -> Descriptor.get(source, propertyName))
.toList();
}
private Stream<PropertySource<?>> getPropertySources() {
if (this.environment == null) {
return Stream.empty();
}
return this.environment.getPropertySources()
.stream()
.filter((source) -> !ConfigurationPropertySources.isAttachedConfigurationPropertySource(source));
}
private void appendDetails(StringBuilder message, MutuallyExclusiveConfigurationPropertiesException cause,
List<Descriptor> descriptors) {
descriptors.sort(Comparator.comparing((descriptor) -> descriptor.propertyName));
message.append(String.format("The following configuration properties are mutually exclusive:%n%n"));
sortedStrings(cause.getMutuallyExclusiveNames())
.forEach((name) -> message.append(String.format("\t%s%n", name)));
message.append(String.format("%n"));
message.append(
String.format("However, more than one of those properties has been configured at the same time:%n%n"));
Set<String> configuredDescriptions = sortedStrings(descriptors,
(descriptor) -> String.format("\t%s%s%n", descriptor.propertyName,
(descriptor.origin != null) ? " (originating from '" + descriptor.origin + "')" : ""));
configuredDescriptions.forEach(message::append);
}
private Set<String> sortedStrings(Collection<String> input) {
return sortedStrings(input, Function.identity());
} | private <S> Set<String> sortedStrings(Collection<S> input, Function<S, String> converter) {
TreeSet<String> results = new TreeSet<>();
for (S item : input) {
results.add(converter.apply(item));
}
return results;
}
private static final class Descriptor {
private final String propertyName;
private final @Nullable Origin origin;
private Descriptor(String propertyName, @Nullable Origin origin) {
this.propertyName = propertyName;
this.origin = origin;
}
static Descriptor get(PropertySource<?> source, String propertyName) {
Origin origin = OriginLookup.getOrigin(source, propertyName);
return new Descriptor(propertyName, origin);
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\diagnostics\analyzer\MutuallyExclusiveConfigurationPropertiesFailureAnalyzer.java | 1 |
请完成以下Java代码 | public Map<String, String> getInitParams() {
Map<String, String> initParams = new HashMap<>();
if (StringUtils.isNotBlank(targetOrigin)) {
initParams.put("targetOrigin", targetOrigin);
}
if (denyStatus != null) {
initParams.put("denyStatus", denyStatus.toString());
}
if (StringUtils.isNotBlank(randomClass)) {
initParams.put("randomClass", randomClass);
}
if (!entryPoints.isEmpty()) {
initParams.put("entryPoints", StringUtils.join(entryPoints, ","));
}
if (enableSecureCookie) { // only add param if it's true; default is false
initParams.put("enableSecureCookie", String.valueOf(enableSecureCookie));
}
if (!enableSameSiteCookie) { // only add param if it's false; default is true
initParams.put("enableSameSiteCookie", String.valueOf(enableSameSiteCookie));
}
if (StringUtils.isNotBlank(sameSiteCookieOption)) {
initParams.put("sameSiteCookieOption", sameSiteCookieOption);
} | if (StringUtils.isNotBlank(sameSiteCookieValue)) {
initParams.put("sameSiteCookieValue", sameSiteCookieValue);
}
if (StringUtils.isNotBlank(cookieName)) {
initParams.put("cookieName", cookieName);
}
return initParams;
}
@Override
public String toString() {
return joinOn(this.getClass())
.add("targetOrigin=" + targetOrigin)
.add("denyStatus='" + denyStatus + '\'')
.add("randomClass='" + randomClass + '\'')
.add("entryPoints='" + entryPoints + '\'')
.add("enableSecureCookie='" + enableSecureCookie + '\'')
.add("enableSameSiteCookie='" + enableSameSiteCookie + '\'')
.add("sameSiteCookieOption='" + sameSiteCookieOption + '\'')
.add("sameSiteCookieValue='" + sameSiteCookieValue + '\'')
.add("cookieName='" + cookieName + '\'')
.toString();
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\CsrfProperties.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setQuantity(UnitType value) {
this.quantity = value;
}
/**
* Gets the value of the startDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getStartDate() {
return startDate;
}
/**
* Sets the value of the startDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setStartDate(XMLGregorianCalendar value) {
this.startDate = value;
}
/**
* Gets the value of the endDate property.
*
* @return
* possible object is | * {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getEndDate() {
return endDate;
}
/**
* Sets the value of the endDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setEndDate(XMLGregorianCalendar value) {
this.endDate = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ExtendedPeriodType.java | 2 |
请完成以下Java代码 | default void onUserLogin(int AD_Org_ID, int AD_Role_ID, int AD_User_ID)
{
// does nothing by default
}
/**
* Model Change of a monitored Table. Called after PO.beforeSave/PO.beforeDelete when you called addModelChange for the table
*
* @param model persistent object
*
* @exception Exception if the recipient wishes the change to be not accept.
*/
default void onModelChange(Object model, ModelChangeType changeType) throws Exception
{
// does nothing by default | }
/**
* Validate Document. Called as first step of DocAction.prepareIt or at the end of DocAction.completeIt when you called addDocValidate for the table. Note that totals, etc. may not be correct
* before the prepare stage.
*
* @param model persistent object
*
*/
default void onDocValidate(Object model, DocTimingType timing) throws Exception
{
// does nothing by default
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\IModelInterceptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SendMessageController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
// private KafkaTemplate<String, String> kafkaTemplate;
private KafkaTemplate<String, Message> kafkaTemplate;
// @GetMapping("send/{message}")
// public void send(@PathVariable String message) {
// this.kafkaTemplate.send("test", message);
// ListenableFuture<SendResult<String, String>> future = this.kafkaTemplate.send("test", message);
// future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
// @Override
// public void onSuccess(SendResult<String, String> result) { | // logger.info("成功发送消息:{},offset=[{}]", message, result.getRecordMetadata().offset());
// }
//
// @Override
// public void onFailure(Throwable ex) {
// logger.error("消息:{} 发送失败,原因:{}", message, ex.getMessage());
// }
// });
// }
@GetMapping("send/{message}")
public void sendMessage(@PathVariable String message) {
this.kafkaTemplate.send("test", new Message("mrbird", message));
}
} | repos\SpringAll-master\54.Spring-Boot-Kafka\src\main\java\com\example\demo\controller\SendMessageController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private Resource getIndexHtml(ResourceLoader resourceLoader, String location) {
return resourceLoader.getResource(location + "index.html");
}
private boolean isReadable(Resource resource) {
try {
return resource.exists() && (resource.getURL() != null);
}
catch (Exception ex) {
return false;
}
}
private boolean welcomeTemplateExists(TemplateAvailabilityProviders templateAvailabilityProviders,
ApplicationContext applicationContext) {
return templateAvailabilityProviders.getProvider("index", applicationContext) != null; | }
@Nullable RouterFunction<ServerResponse> createRouterFunction() {
if (this.welcomePage != null && "/**".equals(this.staticPathPattern)) {
return RouterFunctions.route(GET("/").and(accept(MediaType.TEXT_HTML)),
(req) -> ServerResponse.ok().contentType(MediaType.TEXT_HTML).bodyValue(this.welcomePage));
}
else if (this.welcomePageTemplateExists) {
return RouterFunctions.route(GET("/").and(accept(MediaType.TEXT_HTML)),
(req) -> ServerResponse.ok().render("index"));
}
return null;
}
} | repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\autoconfigure\WelcomePageRouterFunctionFactory.java | 2 |
请完成以下Java代码 | private static Dataset<Row> normalizeCustomerDataFromEbay(Dataset<Row> rawDataset) {
Dataset<Row> transformedDF = rawDataset.withColumn("id", concat(rawDataset.col("zoneId"), lit("-"), rawDataset.col("customerId")))
.drop(column("customerId"))
.withColumn("source", lit("ebay"))
.withColumn("city", rawDataset.col("contact.customer_city"))
.drop(column("contact"))
.drop(column("zoneId"))
.withColumn("year", functions.year(col("transaction_date")))
.drop("transaction_date")
.withColumn("firstName", functions.split(column("name"), " ")
.getItem(0))
.withColumn("lastName", functions.split(column("name"), " ")
.getItem(1))
.drop(column("name"));
print(transformedDF);
return transformedDF;
}
private static Dataset<Row> normalizeCustomerDataFromAmazon(Dataset<Row> rawDataset) {
Dataset<Row> transformedDF = rawDataset.withColumn("id", concat(rawDataset.col("zoneId"), lit("-"), rawDataset.col("id")))
.withColumn("source", lit("amazon"))
.withColumnRenamed("CITY", "city")
.withColumnRenamed("PHONE_NO", "contactNo")
.withColumnRenamed("POSTCODE", "postCode")
.withColumnRenamed("FIRST_NAME", "firstName")
.drop(column("MIDDLE_NAME"))
.drop(column("zoneId"))
.withColumnRenamed("LAST_NAME", "lastName")
.withColumn("year", functions.year(col("transaction_date")))
.drop("transaction_date");
print(transformedDF); | return transformedDF;
}
private static Dataset<Row> aggregateYearlySalesByGender(Dataset<Row> dataset) {
Dataset<Row> aggDF = dataset.groupBy(column("year"), column("source"), column("gender"))
.sum("transaction_amount")
.withColumnRenamed("sum(transaction_amount)", "annual_spending")
.orderBy(col("year").asc(), col("annual_spending").desc());
print(aggDF);
return aggDF;
}
private static void print(Dataset<Row> aggDs) {
aggDs.show();
aggDs.printSchema();
}
private void exportData(Dataset<Row> dataset) {
String connectionURL = dbProperties.getProperty("connectionURL");
dataset.write()
.mode(SaveMode.Overwrite)
.jdbc(connectionURL, "customer", dbProperties);
}
} | repos\tutorials-master\apache-spark\src\main\java\com\baeldung\dataframes\CustomerDataAggregationPipeline.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setRsaPublicKey(String rsaPublicKey) {
this.rsaPublicKey = rsaPublicKey;
}
public String getPayWayCode() {
return payWayCode;
}
public void setPayWayCode(String payWayCode) {
this.payWayCode = payWayCode;
}
public String getPayWayName() {
return payWayName;
}
public void setPayWayName(String payWayName) {
this.payWayName = payWayName;
}
public String getPartnerKey() {
return partnerKey;
}
public void setPartnerKey(String partnerKey) {
this.partnerKey = partnerKey;
}
private static final long serialVersionUID = 1L;
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId == null ? null : appId.trim();
}
public String getAppSectet() {
return appSectet;
} | public void setAppSectet(String appSectet) {
this.appSectet = appSectet == null ? null : appSectet.trim();
}
public String getMerchantId() {
return merchantId;
}
public void setMerchantId(String merchantId) {
this.merchantId = merchantId == null ? null : merchantId.trim();
}
public String getAppType() {
return appType;
}
public void setAppType(String appType) {
this.appType = appType == null ? null : appType.trim();
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo == null ? null : userNo.trim();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\entity\RpUserPayInfo.java | 2 |
请完成以下Java代码 | public static void queryUsingJDOQL() {
Query query = pm.newQuery("SELECT FROM com.baeldung.libraries.jdo.query.ProductItem " + "WHERE price < threshold PARAMETERS double threshold");
List<ProductItem> explicitParamResults = (List<ProductItem>) query.execute(10);
query = pm.newQuery("SELECT FROM " + "com.baeldung.libraries.jdo.query.ProductItem WHERE price < :threshold");
query.setParameters("double threshold");
List<ProductItem> explicitParamResults2 = (List<ProductItem>) query.execute(10);
query = pm.newQuery("SELECT FROM " + "com.baeldung.libraries.jdo.query.ProductItem WHERE price < :threshold");
List<ProductItem> implicitParamResults = (List<ProductItem>) query.execute(10);
}
public static void queryUsingTypedJDOQL() {
JDOQLTypedQuery<ProductItem> tq = pm.newJDOQLTypedQuery(ProductItem.class);
QProductItem cand = QProductItem.candidate();
tq = tq.filter(cand.price.lt(10).and(cand.name.startsWith("pro")));
List<ProductItem> results = tq.executeList();
}
public static void queryUsingSQL() {
Query query = pm.newQuery("javax.jdo.query.SQL", "select * from " + "product_item where price < ? and status = ?");
query.setClass(ProductItem.class);
query.setParameters(10, "InStock"); | List<ProductItem> results = query.executeList();
}
public static void queryUsingJPQL() {
Query query = pm.newQuery("JPQL", "select i from " + "com.baeldung.libraries.jdo.query.ProductItem i where i.price < 10" + " and i.status = 'InStock'");
List<ProductItem> results = (List<ProductItem>) query.execute();
}
public static void namedQuery() {
Query<ProductItem> query = pm.newNamedQuery(ProductItem.class, "PriceBelow10");
List<ProductItem> results = query.executeList();
}
} | repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\jdo\query\MyApp.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Stream<I_M_HU_QRCode_Assignment> streamAssignmentForQrIds(@NonNull final ImmutableSet<HUQRCodeRepoId> huQrCodeIds)
{
return queryBL.createQueryBuilder(I_M_HU_QRCode_Assignment.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_M_HU_QRCode_Assignment.COLUMN_M_HU_QRCode_ID, huQrCodeIds)
.create()
.stream();
}
@NonNull
private Stream<I_M_HU_QRCode_Assignment> streamAssignmentForQrAndHuIds(
@NonNull final ImmutableSet<HUQRCodeRepoId> huQrCodeIds,
@NonNull final ImmutableSet<HuId> huIds)
{
return queryBL.createQueryBuilder(I_M_HU_QRCode_Assignment.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_M_HU_QRCode_Assignment.COLUMNNAME_M_HU_QRCode_ID, huQrCodeIds)
.addInArrayFilter(I_M_HU_QRCode_Assignment.COLUMNNAME_M_HU_ID, huIds)
.create()
.stream();
}
private static HUQRCode toHUQRCode(final I_M_HU_QRCode record) | {
return HUQRCode.fromGlobalQRCodeJsonString(record.getRenderedQRCode());
}
public Stream<HUQRCode> streamQRCodesLike(@NonNull final String like)
{
return queryBL.createQueryBuilder(I_M_HU_QRCode.class)
.addOnlyActiveRecordsFilter()
.addStringLikeFilter(I_M_HU_QRCode.COLUMNNAME_RenderedQRCode, like, false)
.orderBy(I_M_HU_QRCode.COLUMNNAME_M_HU_QRCode_ID)
.create()
.stream()
.map(HUQRCodesRepository::toHUQRCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\service\HUQRCodesRepository.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public CaseDefinitionQuery orderByTenantId() {
return orderBy(CaseDefinitionQueryProperty.TENANT_ID);
}
@Override
protected boolean hasExcludingConditions() {
return super.hasExcludingConditions() || CompareUtil.elementIsNotContainedInArray(id, ids);
}
//results ////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
if (isCmmnEnabled(commandContext)) {
checkQueryOk();
return commandContext
.getCaseDefinitionManager()
.findCaseDefinitionCountByQueryCriteria(this);
}
return 0;
}
@Override
public List<CaseDefinition> executeList(CommandContext commandContext, Page page) {
if (isCmmnEnabled(commandContext)) {
checkQueryOk();
return commandContext
.getCaseDefinitionManager()
.findCaseDefinitionsByQueryCriteria(this, page);
}
return Collections.emptyList();
}
@Override
public void checkQueryOk() {
super.checkQueryOk();
// latest() makes only sense when used with key() or keyLike()
if (latest && ( (id != null) || (name != null) || (nameLike != null) || (version != null) || (deploymentId != null) ) ){
throw new NotValidException("Calling latest() can only be used in combination with key(String) and keyLike(String)");
}
}
private boolean isCmmnEnabled(CommandContext commandContext) {
return commandContext
.getProcessEngineConfiguration()
.isCmmnEnabled();
}
// getters ////////////////////////////////////////////
public String getId() {
return id;
}
public String[] getIds() {
return ids;
}
public String getCategory() {
return category;
}
public String getCategoryLike() { | return categoryLike;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String getDeploymentId() {
return deploymentId;
}
public String getKey() {
return key;
}
public String getKeyLike() {
return keyLike;
}
public String getResourceName() {
return resourceName;
}
public String getResourceNameLike() {
return resourceNameLike;
}
public Integer getVersion() {
return version;
}
public boolean isLatest() {
return latest;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\repository\CaseDefinitionQueryImpl.java | 2 |
请完成以下Java代码 | public void setCamundaFollowUpDate(String camundaFollowUpDate) {
camundaFollowUpDateAttribute.setValue(this, camundaFollowUpDate);
}
public String getCamundaFormKey() {
return camundaFormKeyAttribute.getValue(this);
}
public void setCamundaFormKey(String camundaFormKey) {
camundaFormKeyAttribute.setValue(this, camundaFormKey);
}
public String getCamundaPriority() {
return camundaPriorityAttribute.getValue(this);
}
public void setCamundaPriority(String camundaPriority) {
camundaPriorityAttribute.setValue(this, camundaPriority);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(HumanTask.class, CMMN_ELEMENT_HUMAN_TASK)
.namespaceUri(CMMN11_NS)
.extendsType(Task.class)
.instanceProvider(new ModelTypeInstanceProvider<HumanTask>() {
public HumanTask newInstance(ModelTypeInstanceContext instanceContext) {
return new HumanTaskImpl(instanceContext);
}
});
performerRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_PERFORMER_REF)
.idAttributeReference(Role.class)
.build();
/** camunda extensions */
camundaAssigneeAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_ASSIGNEE)
.namespace(CAMUNDA_NS)
.build();
camundaCandidateGroupsAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CANDIDATE_GROUPS)
.namespace(CAMUNDA_NS)
.build();
camundaCandidateUsersAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CANDIDATE_USERS) | .namespace(CAMUNDA_NS)
.build();
camundaDueDateAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DUE_DATE)
.namespace(CAMUNDA_NS)
.build();
camundaFollowUpDateAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_FOLLOW_UP_DATE)
.namespace(CAMUNDA_NS)
.build();
camundaFormKeyAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_FORM_KEY)
.namespace(CAMUNDA_NS)
.build();
camundaPriorityAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_PRIORITY)
.namespace(CAMUNDA_NS)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
planningTableCollection = sequenceBuilder.elementCollection(PlanningTable.class)
.build();
planningTableChild = sequenceBuilder.element(PlanningTable.class)
.minOccurs(0)
.maxOccurs(1)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\HumanTaskImpl.java | 1 |
请完成以下Java代码 | private boolean isInstanceAllowedBasedOnMetadata(ServiceInstance instance) {
if (instancesMetadata.isEmpty()) {
return true;
}
for (Map.Entry<String, String> metadata : instance.getMetadata().entrySet()) {
if (isMapContainsEntry(instancesMetadata, metadata)) {
return true;
}
}
return false;
}
private boolean isInstanceIgnoredBasedOnMetadata(ServiceInstance instance) {
if (ignoredInstancesMetadata.isEmpty()) {
return false;
} | for (Map.Entry<String, String> metadata : instance.getMetadata().entrySet()) {
if (isMapContainsEntry(ignoredInstancesMetadata, metadata)) {
return true;
}
}
return false;
}
private boolean isMapContainsEntry(Map<String, String> map, Map.Entry<String, String> entry) {
String value = map.get(entry.getKey());
return value != null && value.equals(entry.getValue());
}
} | repos\spring-boot-admin-master\spring-boot-admin-server-cloud\src\main\java\de\codecentric\boot\admin\server\cloud\discovery\InstanceDiscoveryListener.java | 1 |
请完成以下Java代码 | public Map<String, Object> getTransientVariables(){
return this.transientVariables;
}
public MapDelegateVariableContainer removeTransientVariable(String key){
this.transientVariables.remove(key);
return this;
}
@Override
public String getTenantId() {
return this.delegate.getTenantId();
}
@Override
public Set<String> getVariableNames() {
if (delegate == null || delegate == VariableContainer.empty()) {
return this.transientVariables.keySet(); | }
if (transientVariables.isEmpty()) {
return delegate.getVariableNames();
}
Set<String> keys = new LinkedHashSet<>(delegate.getVariableNames());
keys.addAll(transientVariables.keySet());
return keys;
}
@Override
public String toString() {
return new StringJoiner(", ", getClass().getSimpleName() + "[", "]")
.add("delegate=" + delegate)
.add("tenantId=" + getTenantId())
.toString();
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\variable\MapDelegateVariableContainer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static class HUItemToGroup
{
@NonNull I_M_HU hu;
@NonNull ProductId productId;
@Nullable QRCodeConfiguration productQrCodeConfiguration;
@NonNull
public HuId getHuId()
{
return HuId.ofRepoId(hu.getM_HU_ID());
}
@NonNull
public Set<AttributeId> getAttributesAssumingGroupingIsEnabled()
{
Check.assume(isGroupingByMatchingAttributesEnabled(), "Assuming grouping by attributes is enabled!");
return productQrCodeConfiguration.getGroupByAttributeIds();
}
public boolean isGroupingByMatchingAttributesEnabled()
{
return productQrCodeConfiguration != null && productQrCodeConfiguration.isGroupingByAttributesEnabled();
} | }
private interface GroupKey {}
@Value
@Builder
private static class TUGroupKey implements GroupKey
{
@NonNull ProductId productId;
@NonNull HuPackingInstructionsId packingInstructionsId;
@NonNull AttributesKey attributesKey;
}
@Value(staticConstructor = "ofHuId")
private static class SingleGroupKey implements GroupKey
{
@NonNull HuId huId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\service\HUQRCodeGenerateForExistingHUsCommand.java | 2 |
请完成以下Java代码 | public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
@Override
public org.compiere.model.I_C_Location getOrg_Location() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_Org_Location_ID, org.compiere.model.I_C_Location.class);
}
@Override
public void setOrg_Location(org.compiere.model.I_C_Location Org_Location)
{
set_ValueFromPO(COLUMNNAME_Org_Location_ID, org.compiere.model.I_C_Location.class, Org_Location);
}
/** Set Org Address.
@param Org_Location_ID
Organization Location/Address
*/
@Override
public void setOrg_Location_ID (int Org_Location_ID)
{
if (Org_Location_ID < 1)
set_ValueNoCheck (COLUMNNAME_Org_Location_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Org_Location_ID, Integer.valueOf(Org_Location_ID));
}
/** Get Org Address.
@return Organization Location/Address
*/
@Override
public int getOrg_Location_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Org_Location_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Telefon.
@param Phone
Beschreibt eine Telefon Nummer
*/
@Override
public void setPhone (java.lang.String Phone)
{
set_ValueNoCheck (COLUMNNAME_Phone, Phone);
}
/** Get Telefon.
@return Beschreibt eine Telefon Nummer
*/
@Override
public java.lang.String getPhone ()
{
return (java.lang.String)get_Value(COLUMNNAME_Phone);
}
/** Set Steuer-ID.
@param TaxID
Tax Identification
*/
@Override
public void setTaxID (java.lang.String TaxID) | {
set_ValueNoCheck (COLUMNNAME_TaxID, TaxID);
}
/** Get Steuer-ID.
@return Tax Identification
*/
@Override
public java.lang.String getTaxID ()
{
return (java.lang.String)get_Value(COLUMNNAME_TaxID);
}
/** Set Titel.
@param Title
Name this entity is referred to as
*/
@Override
public void setTitle (java.lang.String Title)
{
set_ValueNoCheck (COLUMNNAME_Title, Title);
}
/** Get Titel.
@return Name this entity is referred to as
*/
@Override
public java.lang.String getTitle ()
{
return (java.lang.String)get_Value(COLUMNNAME_Title);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponse_v.java | 1 |
请完成以下Java代码 | public void setC_DocType_ID (int C_DocType_ID)
{
if (C_DocType_ID < 0)
set_Value (COLUMNNAME_C_DocType_ID, null);
else
set_Value (COLUMNNAME_C_DocType_ID, Integer.valueOf(C_DocType_ID));
}
/** Get Belegart.
@return Belegart oder Verarbeitungsvorgaben
*/
@Override
public int getC_DocType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_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);
}
/**
* IsDirectPrint AD_Reference_ID=319
* Reference name: _YesNo
*/
public static final int ISDIRECTPRINT_AD_Reference_ID=319;
/** Yes = Y */
public static final String ISDIRECTPRINT_Yes = "Y";
/** No = N */
public static final String ISDIRECTPRINT_No = "N";
/** Set Direct print.
@param IsDirectPrint
Print without dialog
*/
@Override
public void setIsDirectPrint (java.lang.String IsDirectPrint)
{
set_Value (COLUMNNAME_IsDirectPrint, IsDirectPrint);
}
/** Get Direct print.
@return Print without dialog | */
@Override
public java.lang.String getIsDirectPrint ()
{
return (java.lang.String)get_Value(COLUMNNAME_IsDirectPrint);
}
/** Set Letzte Seiten.
@param LastPages Letzte Seiten */
@Override
public void setLastPages (int LastPages)
{
set_Value (COLUMNNAME_LastPages, Integer.valueOf(LastPages));
}
/** Get Letzte Seiten.
@return Letzte Seiten */
@Override
public int getLastPages ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_LastPages);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\adempiere\model\X_AD_PrinterRouting.java | 1 |
请完成以下Java代码 | public void setupCaching()
{
final CacheMgt cacheMgt = CacheMgt.get();
cacheMgt.enableRemoteCacheInvalidationForTableName(I_M_ShippingPackage.Table_Name);
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE, ifColumnsChanged = I_M_ShippingPackage.COLUMNNAME_C_Order_ID)
public void closePackageOnOrderDelete(final I_M_ShippingPackage shippingPackage)
{
final int orderRecordId = shippingPackage.getC_Order_ID();
if (orderRecordId > 0)
{
// nothing to do
return;
}
final PackageId packageId = PackageId.ofRepoId(shippingPackage.getM_Package_ID()); | packageRepo.closeMPackage(packageId);
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE)
public void closePackageOnDelete(final I_M_ShippingPackage shippingPackage)
{
final int orderRecordId = shippingPackage.getC_Order_ID();
if (orderRecordId <= 0)
{
// nothing to do
return;
}
final PackageId mPackageId = PackageId.ofRepoId(shippingPackage.getM_Package_ID());
packageRepo.closeMPackage(mPackageId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipping\model\validator\M_ShippingPackage.java | 1 |
请完成以下Java代码 | public String toString()
{
return displayName;
}
@Override
public int hashCode()
{
return attachmentEntryId.hashCode();
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj instanceof AttachmentEntryItem)
{
final AttachmentEntryItem other = (AttachmentEntryItem)obj;
return attachmentEntryId == other.attachmentEntryId;
}
else
{
return false;
}
}
}
/**************************************************************************
* Graphic Image Panel
*/
class GImage extends JPanel
{
/**
*
*/
private static final long serialVersionUID = 4991225210651641722L;
/**
* Graphic Image
*/
public GImage()
{
super();
} // GImage
/** The Image */
private Image m_image = null;
/**
* Set Image
*
* @param image image
*/
public void setImage(final Image image) | {
m_image = image;
if (m_image == null)
{
return;
}
MediaTracker mt = new MediaTracker(this);
mt.addImage(m_image, 0);
try
{
mt.waitForID(0);
}
catch (Exception e)
{
}
Dimension dim = new Dimension(m_image.getWidth(this), m_image.getHeight(this));
this.setPreferredSize(dim);
} // setImage
/**
* Paint
*
* @param g graphics
*/
@Override
public void paint(final Graphics g)
{
Insets in = getInsets();
if (m_image != null)
{
g.drawImage(m_image, in.left, in.top, this);
}
} // paint
/**
* Update
*
* @param g graphics
*/
@Override
public void update(final Graphics g)
{
paint(g);
} // update
} // GImage
} // Attachment | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\Attachment.java | 1 |
请完成以下Spring Boot application配置 | spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/oauth2?useUnicode=true&characterEnc | oding=utf-8&useSSL=false
username: root
password: root | repos\SpringBootLearning-master (1)\springboot-security-oauth2\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Referrer.
@param Referrer
Referring web address
*/
public void setReferrer (String Referrer)
{
set_Value (COLUMNNAME_Referrer, Referrer);
}
/** Get Referrer.
@return Referring web address
*/
public String getReferrer ()
{
return (String)get_Value(COLUMNNAME_Referrer);
}
/** Set Remote Addr.
@param Remote_Addr
Remote Address
*/
public void setRemote_Addr (String Remote_Addr)
{
set_Value (COLUMNNAME_Remote_Addr, Remote_Addr);
}
/** Get Remote Addr.
@return Remote Address
*/
public String getRemote_Addr ()
{
return (String)get_Value(COLUMNNAME_Remote_Addr);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getRemote_Addr());
}
/** Set Remote Host.
@param Remote_Host
Remote host Info
*/
public void setRemote_Host (String Remote_Host)
{
set_Value (COLUMNNAME_Remote_Host, Remote_Host);
}
/** Get Remote Host.
@return Remote host Info
*/
public String getRemote_Host ()
{
return (String)get_Value(COLUMNNAME_Remote_Host);
}
/** Set User Agent.
@param UserAgent
Browser Used
*/
public void setUserAgent (String UserAgent)
{
set_Value (COLUMNNAME_UserAgent, UserAgent); | }
/** Get User Agent.
@return Browser Used
*/
public String getUserAgent ()
{
return (String)get_Value(COLUMNNAME_UserAgent);
}
public I_W_CounterCount getW_CounterCount() throws RuntimeException
{
return (I_W_CounterCount)MTable.get(getCtx(), I_W_CounterCount.Table_Name)
.getPO(getW_CounterCount_ID(), get_TrxName()); }
/** Set Counter Count.
@param W_CounterCount_ID
Web Counter Count Management
*/
public void setW_CounterCount_ID (int W_CounterCount_ID)
{
if (W_CounterCount_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, Integer.valueOf(W_CounterCount_ID));
}
/** Get Counter Count.
@return Web Counter Count Management
*/
public int getW_CounterCount_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_CounterCount_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Web Counter.
@param W_Counter_ID
Individual Count hit
*/
public void setW_Counter_ID (int W_Counter_ID)
{
if (W_Counter_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_Counter_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_Counter_ID, Integer.valueOf(W_Counter_ID));
}
/** Get Web Counter.
@return Individual Count hit
*/
public int getW_Counter_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_Counter_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_Counter.java | 1 |
请完成以下Java代码 | private VPanelLayoutCallback getLayoutCallback()
{
return VPanelLayoutCallback.forContainer(contentPanel);
}
private void setLayoutCallback(final VPanelLayoutCallback layoutCallback)
{
VPanelLayoutCallback.setup(contentPanel, layoutCallback);
}
public void addIncludedFieldGroup(final VPanelFieldGroup childGroupPanel)
{
// If it's not an included tab we shall share the same layout constraints as the parent.
// This will enforce same minimum widths to all labels and editors of this field group and also to child group panel.
if (!childGroupPanel.isIncludedTab())
{
childGroupPanel.setLayoutCallback(getLayoutCallback());
}
final CC constraints = new CC()
.spanX()
.growX()
.newline();
contentPanel.add(childGroupPanel.getComponent(), constraints);
}
public void addLabelAndEditor(final CLabel fieldLabel, final VEditor fieldEditor, final boolean sameLine)
{
final GridField gridField = fieldEditor.getField();
final GridFieldLayoutConstraints gridFieldConstraints = gridField.getLayoutConstraints();
final boolean longField = gridFieldConstraints != null && gridFieldConstraints.isLongField(); | final JComponent editorComp = swingEditorFactory.getEditorComponent(fieldEditor);
//
// Update layout callback.
final VPanelLayoutCallback layoutCallback = getLayoutCallback();
layoutCallback.updateMinWidthFrom(fieldLabel);
// NOTE: skip if long field because in that case the minimum length shall not influence the other fields.
if (!longField)
{
layoutCallback.updateMinWidthFrom(fieldEditor);
}
//
// Link Label to Field
if (fieldLabel != null)
{
fieldLabel.setLabelFor(editorComp);
fieldLabel.setVerticalAlignment(SwingConstants.TOP);
}
//
// Add label
final CC labelConstraints = layoutFactory.createFieldLabelConstraints(sameLine);
contentPanel.add(fieldLabel, labelConstraints);
//
// Add editor
final CC editorConstraints = layoutFactory.createFieldEditorConstraints(gridFieldConstraints);
contentPanel.add(editorComp, editorConstraints);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\VPanelFieldGroup.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void saveOrderRouting(@NonNull final PPOrderRouting routing) {ppOrderRoutingRepository.save(routing);}
public ImmutableList<I_PP_Order_BOMLine> getOrderBOMLines(@NonNull final PPOrderId ppOrderId) {return ImmutableList.copyOf(ppOrderBOMBL.getOrderBOMLines(ppOrderId));}
@NonNull
public ZonedDateTime getDateStartSchedule(@NonNull final I_PP_Order ppOrder)
{
return InstantAndOrgId.ofTimestamp(ppOrder.getDateStartSchedule(), ppOrder.getAD_Org_ID()).toZonedDateTime(orgDAO::getTimeZone);
}
public PPOrderQuantities getQuantities(@NonNull final I_PP_Order order) {return ppOrderBOMBL.getQuantities(order);}
public OrderBOMLineQuantities getQuantities(@NonNull final I_PP_Order_BOMLine orderBOMLine) {return ppOrderBOMBL.getQuantities(orderBOMLine);}
public ImmutableListMultimap<PPOrderBOMLineId, PPOrderIssueSchedule> getIssueSchedules(@NonNull final PPOrderId ppOrderId)
{
return Multimaps.index(ppOrderIssueScheduleService.getByOrderId(ppOrderId), PPOrderIssueSchedule::getPpOrderBOMLineId);
}
public ImmutableAttributeSet getImmutableAttributeSet(final AttributeSetInstanceId asiId)
{
return asiBL.getImmutableAttributeSetById(asiId);
}
public Optional<HuId> getHuIdByQRCodeIfExists(@NonNull final HUQRCode qrCode)
{
return huQRCodeService.getHuIdByQRCodeIfExists(qrCode);
}
public void assignQRCodeForReceiptHU(@NonNull final HUQRCode qrCode, @NonNull final HuId huId)
{
final boolean ensureSingleAssignment = true;
huQRCodeService.assign(qrCode, huId, ensureSingleAssignment);
}
public HUQRCode getFirstQRCodeByHuId(@NonNull final HuId huId)
{
return huQRCodeService.getFirstQRCodeByHuId(huId);
}
public Quantity getHUCapacity(
@NonNull final HuId huId,
@NonNull final ProductId productId, | @NonNull final I_C_UOM uom)
{
final I_M_HU hu = handlingUnitsBL.getById(huId);
return handlingUnitsBL
.getStorageFactory()
.getStorage(hu)
.getQuantity(productId, uom);
}
@NonNull
public ValidateLocatorInfo getValidateSourceLocatorInfo(final @NonNull PPOrderId ppOrderId)
{
final ImmutableList<LocatorInfo> sourceLocatorList = getSourceLocatorIds(ppOrderId)
.stream()
.map(locatorId -> {
final String caption = getLocatorName(locatorId);
return LocatorInfo.builder()
.id(locatorId)
.caption(caption)
.qrCode(LocatorQRCode.builder()
.locatorId(locatorId)
.caption(caption)
.build())
.build();
})
.collect(ImmutableList.toImmutableList());
return ValidateLocatorInfo.ofSourceLocatorList(sourceLocatorList);
}
@NonNull
public Optional<UomId> getCatchWeightUOMId(@NonNull final ProductId productId)
{
return productBL.getCatchUOMId(productId);
}
@NonNull
private ImmutableSet<LocatorId> getSourceLocatorIds(@NonNull final PPOrderId ppOrderId)
{
final ImmutableSet<HuId> huIds = sourceHUService.getSourceHUIds(ppOrderId);
return handlingUnitsBL.getLocatorIds(huIds);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\ManufacturingJobLoaderAndSaverSupportingServices.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getCodedCharacterEncoding() {
return codedCharacterEncoding;
}
/**
* Sets the value of the codedCharacterEncoding property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCodedCharacterEncoding(String value) {
this.codedCharacterEncoding = value;
}
/**
* Gets the value of the releaseNum property.
*
* @return
* possible object is | * {@link String }
*
*/
public String getReleaseNum() {
return releaseNum;
}
/**
* Sets the value of the releaseNum property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReleaseNum(String value) {
this.releaseNum = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\messaging\header\SyntaxIdentifierType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private static JsonRequestLocationUpsert getBPartnerLocationRequest(@NonNull final WarehouseRow warehouseRow)
{
final JsonRequestLocation location = new JsonRequestLocation();
location.setName(StringUtils.trimBlankToNull(warehouseRow.getName()));
location.setAddress1(StringUtils.trimBlankToNull(warehouseRow.getAddress1()));
location.setPostal(StringUtils.trimBlankToNull(warehouseRow.getPostal()));
location.setCity(StringUtils.trimBlankToNull(warehouseRow.getCity()));
location.setGln(StringUtils.trimBlankToNull(warehouseRow.getGln()));
location.setCountryCode(DEFAULT_COUNTRY_CODE);
return JsonRequestLocationUpsert.builder()
.requestItem(JsonRequestLocationUpsertItem.builder()
.locationIdentifier(ExternalId.ofId(warehouseRow.getWarehouseIdentifier()).toExternalIdentifierString())
.location(location)
.build())
.build();
}
private static boolean hasMissingFields(@NonNull final WarehouseRow warehouseRow) | {
return Check.isBlank(warehouseRow.getWarehouseIdentifier())
|| Check.isBlank(warehouseRow.getName())
|| Check.isBlank(warehouseRow.getWarehouseValue());
}
@NonNull
private static JsonRequestBPartnerUpsert wrapUpsertItem(@NonNull final JsonRequestBPartnerUpsertItem upsertItem)
{
return JsonRequestBPartnerUpsert.builder()
.syncAdvise(SyncAdvise.CREATE_OR_MERGE)
.requestItems(ImmutableList.of(upsertItem))
.build();
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\warehouse\processor\CreateBPartnerUpsertRequestProcessor.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class AuthenticationProviderBeanDefinitionParser implements BeanDefinitionParser {
private static final String ATT_USER_DETAILS_REF = "user-service-ref";
@Override
public BeanDefinition parse(Element element, ParserContext pc) {
RootBeanDefinition authProvider = new RootBeanDefinition(DaoAuthenticationProvider.class);
authProvider.setSource(pc.extractSource(element));
Element passwordEncoderElt = DomUtils.getChildElementByTagName(element, Elements.PASSWORD_ENCODER);
PasswordEncoderParser pep = new PasswordEncoderParser(passwordEncoderElt, pc);
BeanMetadataElement passwordEncoder = pep.getPasswordEncoder();
if (passwordEncoder != null) {
authProvider.getPropertyValues().addPropertyValue("passwordEncoder", passwordEncoder);
}
Element userServiceElt = DomUtils.getChildElementByTagName(element, Elements.USER_SERVICE);
if (userServiceElt == null) {
userServiceElt = DomUtils.getChildElementByTagName(element, Elements.JDBC_USER_SERVICE);
}
if (userServiceElt == null) {
userServiceElt = DomUtils.getChildElementByTagName(element, Elements.LDAP_USER_SERVICE);
}
String ref = element.getAttribute(ATT_USER_DETAILS_REF);
if (StringUtils.hasText(ref)) {
if (userServiceElt != null) {
pc.getReaderContext()
.error("The " + ATT_USER_DETAILS_REF + " attribute cannot be used in combination with child"
+ "elements '" + Elements.USER_SERVICE + "', '" + Elements.JDBC_USER_SERVICE + "' or '"
+ Elements.LDAP_USER_SERVICE + "'", element);
}
ValueHolder userDetailsServiceValueHolder = new ValueHolder(new RuntimeBeanReference(ref)); | userDetailsServiceValueHolder.setName("userDetailsService");
authProvider.getConstructorArgumentValues().addGenericArgumentValue(userDetailsServiceValueHolder);
}
else {
// Use the child elements to create the UserDetailsService
if (userServiceElt != null) {
pc.getDelegate().parseCustomElement(userServiceElt, authProvider);
}
else {
pc.getReaderContext().error("A user-service is required", element);
}
// Pinch the cache-ref from the UserDetailsService element, if set.
String cacheRef = userServiceElt.getAttribute(AbstractUserDetailsServiceBeanDefinitionParser.CACHE_REF);
if (StringUtils.hasText(cacheRef)) {
authProvider.getPropertyValues().addPropertyValue("userCache", new RuntimeBeanReference(cacheRef));
}
}
return authProvider;
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\authentication\AuthenticationProviderBeanDefinitionParser.java | 2 |
请完成以下Java代码 | public void setCamundaId(String camundaId) {
camundaIdAttribute.setValue(this, camundaId);
}
public String getCamundaName() {
return camundaNameAttribute.getValue(this);
}
public void setCamundaName(String camundaName) {
camundaNameAttribute.setValue(this, camundaName);
}
public String getCamundaType() {
return camundaTypeAttribute.getValue(this);
}
public void setCamundaType(String camundaType) {
camundaTypeAttribute.setValue(this, camundaType);
}
public boolean isCamundaRequired() {
return camundaRequiredAttribute.getValue(this);
}
public void setCamundaRequired(boolean isCamundaRequired) {
camundaRequiredAttribute.setValue(this, isCamundaRequired);
}
public boolean isCamundaReadable() {
return camundaReadableAttribute.getValue(this);
}
public void setCamundaReadable(boolean isCamundaReadable) {
camundaReadableAttribute.setValue(this, isCamundaReadable);
}
public boolean isCamundaWriteable() {
return camundaWriteableAttribute.getValue(this);
}
public void setCamundaWriteable(boolean isCamundaWriteable) {
camundaWriteableAttribute.setValue(this, isCamundaWriteable);
}
public String getCamundaVariable() {
return camundaVariableAttribute.getValue(this);
}
public void setCamundaVariable(String camundaVariable) { | camundaVariableAttribute.setValue(this, camundaVariable);
}
public String getCamundaExpression() {
return camundaExpressionAttribute.getValue(this);
}
public void setCamundaExpression(String camundaExpression) {
camundaExpressionAttribute.setValue(this, camundaExpression);
}
public String getCamundaDatePattern() {
return camundaDatePatternAttribute.getValue(this);
}
public void setCamundaDatePattern(String camundaDatePattern) {
camundaDatePatternAttribute.setValue(this, camundaDatePattern);
}
public String getCamundaDefault() {
return camundaDefaultAttribute.getValue(this);
}
public void setCamundaDefault(String camundaDefault) {
camundaDefaultAttribute.setValue(this, camundaDefault);
}
public Collection<CamundaValue> getCamundaValues() {
return camundaValueCollection.get(this);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaFormPropertyImpl.java | 1 |
请完成以下Java代码 | private void setOrderReferences(
@NonNull final JsonResponseShipmentCandidateBuilder candidateBuilder,
@NonNull final ShipmentSchedule shipmentSchedule,
@NonNull final Map<OrderId, I_C_Order> id2Order)
{
final OrderId orderId = shipmentSchedule.getOrderAndLineId() != null
? shipmentSchedule.getOrderAndLineId().getOrderId()
: null;
if (orderId == null)
{
return; // nothing to do
}
final I_C_Order orderRecord = id2Order.get(orderId);
if (orderRecord == null) | {
Loggables.withLogger(logger, Level.WARN).addLog("*** WARNING: No I_C_Order was found in id2Order: {} for orderId: {}!", id2Order, orderId);
return;
}
candidateBuilder.orderDocumentNo(orderRecord.getDocumentNo());
candidateBuilder.poReference(orderRecord.getPOReference());
candidateBuilder.deliveryInfo(orderRecord.getDeliveryInfo());
}
private static class ShipmentCandidateExportException extends AdempiereException
{
public ShipmentCandidateExportException(final String message)
{
super(message);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\shipping\ShipmentCandidateAPIService.java | 1 |
请完成以下Java代码 | public boolean canRegisterOnTiming(@NonNull final TrxEventTiming timing)
{
// any timing is accepted because we are executing directly
return true;
}
private void execute(final RegisterListenerRequest listener)
{
if (!listener.isActive())
{
return; // nothing to do
}
if (!TrxEventTiming.BEFORE_COMMIT.equals(listener.getTiming())
&& !TrxEventTiming.AFTER_COMMIT.equals(listener.getTiming())
&& !TrxEventTiming.AFTER_CLOSE.equals(listener.getTiming()))
{
return; // nothing to do
}
try
{
listener.getHandlingMethod().onTransactionEvent(ITrx.TRX_None);
}
catch (Exception e)
{
throw AdempiereException.wrapIfNeeded(e)
.setParameter("listener", listener)
.appendParametersToMessage();
}
}
@Override | public void fireBeforeCommit(final ITrx trx)
{
throw new UnsupportedOperationException();
}
@Override
public void fireAfterCommit(final ITrx trx)
{
throw new UnsupportedOperationException();
}
@Override
public void fireAfterRollback(final ITrx trx)
{
throw new UnsupportedOperationException();
}
@Override
public void fireAfterClose(ITrx trx)
{
throw new UnsupportedOperationException();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\AutoCommitTrxListenerManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static void cancelPayment(String orderId) {
// Cancel Payment in DB
Payment payment = new Payment();
paymentsDAO.readPayment(orderId, payment);
payment.setStatus(Payment.Status.CANCELED);
paymentsDAO.updatePaymentStatus(payment);
}
private static boolean makePayment(Payment payment) {
if (Objects.equals(payment.getPaymentMethod().getType(), "Credit Card")) {
PaymentDetails details = payment.getPaymentMethod().getDetails();
DateFormat dateFormat= new SimpleDateFormat("MM/yyyy");
Date expiry = new Date();
try {
expiry = dateFormat.parse(details.getExpiry());
} catch (ParseException e) { | payment.setErrorMsg("Invalid expiry date:" + details.getExpiry());
return false;
}
Date today = new Date();
if (today.getTime() > expiry.getTime()) {
payment.setErrorMsg("Expired payment method:" + details.getExpiry());
return false;
}
}
// Ideally an async call would be made with a callback
// But, we're skipping that and assuming payment went through
return true;
}
} | repos\tutorials-master\microservices-modules\saga-pattern\src\main\java\io\orkes\example\saga\service\PaymentService.java | 2 |
请完成以下Java代码 | private int selectNextCity(Ant ant) {
int t = random.nextInt(numberOfCities - currentIndex);
if (random.nextDouble() < randomFactor) {
OptionalInt cityIndex = IntStream.range(0, numberOfCities)
.filter(i -> i == t && !ant.visited(i))
.findFirst();
if (cityIndex.isPresent()) {
return cityIndex.getAsInt();
}
}
calculateProbabilities(ant);
double r = random.nextDouble();
double total = 0;
for (int i = 0; i < numberOfCities; i++) {
total += probabilities[i];
if (total >= r) {
return i;
}
}
throw new RuntimeException("There are no other cities");
}
/**
* Calculate the next city picks probabilites
*/
public void calculateProbabilities(Ant ant) {
int i = ant.trail[currentIndex];
double pheromone = 0.0;
for (int l = 0; l < numberOfCities; l++) {
if (!ant.visited(l)) {
pheromone += Math.pow(trails[i][l], alpha) * Math.pow(1.0 / graph[i][l], beta);
}
}
for (int j = 0; j < numberOfCities; j++) {
if (ant.visited(j)) {
probabilities[j] = 0.0;
} else {
double numerator = Math.pow(trails[i][j], alpha) * Math.pow(1.0 / graph[i][j], beta);
probabilities[j] = numerator / pheromone;
}
}
}
/**
* Update trails that ants used | */
private void updateTrails() {
for (int i = 0; i < numberOfCities; i++) {
for (int j = 0; j < numberOfCities; j++) {
trails[i][j] *= evaporation;
}
}
for (Ant a : ants) {
double contribution = Q / a.trailLength(graph);
for (int i = 0; i < numberOfCities - 1; i++) {
trails[a.trail[i]][a.trail[i + 1]] += contribution;
}
trails[a.trail[numberOfCities - 1]][a.trail[0]] += contribution;
}
}
/**
* Update the best solution
*/
private void updateBest() {
if (bestTourOrder == null) {
bestTourOrder = ants.get(0).trail;
bestTourLength = ants.get(0)
.trailLength(graph);
}
for (Ant a : ants) {
if (a.trailLength(graph) < bestTourLength) {
bestTourLength = a.trailLength(graph);
bestTourOrder = a.trail.clone();
}
}
}
/**
* Clear trails after simulation
*/
private void clearTrails() {
IntStream.range(0, numberOfCities)
.forEach(i -> {
IntStream.range(0, numberOfCities)
.forEach(j -> trails[i][j] = c);
});
}
} | repos\tutorials-master\algorithms-modules\algorithms-genetic\src\main\java\com\baeldung\algorithms\ga\ant_colony\AntColonyOptimization.java | 1 |
请完成以下Java代码 | private List<I_M_Inventory> createInventories(
final WarehouseId warehouseId,
final List<I_M_HU> hus)
{
final I_M_Warehouse warehouse = warehouseDAO.getById(warehouseId);
// Make sure all HUs have ThreadInherited transaction (in order to use caching)
InterfaceWrapperHelper.setThreadInheritedTrxName(hus);
//
// Allocation Source: our HUs
final HUListAllocationSourceDestination husSource = HUListAllocationSourceDestination.of(hus);
husSource.setCreateHUSnapshots(true);
//
// Create and setup context
final IMutableHUContext huContext = huContextFactory.createMutableHUContextForProcessing(PlainContextAware.newWithThreadInheritedTrx());
huContext.setDate(request.getMovementDate());
huContext.getHUPackingMaterialsCollector()
.disable(); // we assume the inventory destination will do that
// Inventory allocation destination
final DocTypeId materialDisposalDocTypeId = getInventoryDocTypeId(warehouse);
final InventoryAllocationDestination inventoryAllocationDestination = new InventoryAllocationDestination(
warehouseId,
materialDisposalDocTypeId,
request.getActivityId(),
request.getDescription());
//
// Create and configure Loader
final HULoader loader = HULoader
.of(husSource, inventoryAllocationDestination)
.setAllowPartialLoads(true);
//
// Unload everything from source (our HUs)
loader.unloadAllFromSource(huContext);
//
final List<I_M_Inventory> inventories = inventoryAllocationDestination.processInventories(request.isCompleteInventory());
if (request.isMoveEmptiesToEmptiesWarehouse())
{
inventoryAllocationDestination.createEmptiesMovementForInventories();
}
// destroy empty hus
{
for (final I_M_HU hu : hus)
{
// Skip it if already destroyed
if (handlingUnitsBL.isDestroyed(hu))
{
continue; | }
handlingUnitsBL.destroyIfEmptyStorage(huContext, hu);
}
}
return inventories;
}
private DocTypeId getInventoryDocTypeId(@NonNull final I_M_Warehouse warehouse)
{
if (request.getInternalUseInventoryDocTypeId() != null)
{
return request.getInternalUseInventoryDocTypeId();
}
return docTypeDAO.getDocTypeId(
DocTypeQuery.builder()
.docBaseType(DocBaseType.MaterialPhysicalInventory)
.docSubType(DocSubType.InternalUseInventory)
.adClientId(warehouse.getAD_Client_ID())
.adOrgId(warehouse.getAD_Org_ID())
.build());
}
private List<I_M_HU> getTopLevelHUs()
{
final List<I_M_HU> hus = request.getHus();
if (hus.isEmpty())
{
throw new AdempiereException("No HUs for internal use inventory");
}
return handlingUnitsBL.getTopLevelHUs(TopLevelHusQuery.builder()
.hus(hus)
.includeAll(false)
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\internaluse\HUInternalUseInventoryProducer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getHostTag() {
return this.hostTag;
}
public void setHostTag(String hostTag) {
this.hostTag = hostTag;
}
public boolean isFloorTimes() {
return this.floorTimes;
}
public void setFloorTimes(boolean floorTimes) {
this.floorTimes = floorTimes;
}
@Override
public Integer getBatchSize() {
return this.batchSize; | }
@Override
public void setBatchSize(Integer batchSize) {
this.batchSize = batchSize;
}
@Override
public Duration getConnectTimeout() {
return this.connectTimeout;
}
@Override
public void setConnectTimeout(Duration connectTimeout) {
this.connectTimeout = connectTimeout;
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\appoptics\AppOpticsProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Optional<Student> findOne(String id) {
return Optional.of(template.findById(Student.class).one(id));
}
public List<Student> findAll() {
return template.findByQuery(Student.class).all();
}
public List<Student> findByFirstName(String firstName) {
return template.findByQuery(Student.class).matching(where("firstName").is(firstName)).all();
}
public List<Student> findByLastName(String lastName) {
return template.findByQuery(Student.class).matching(where("lastName").is(lastName)).all();
} | public void create(Student student) {
student.setCreated(DateTime.now());
template.insertById(Student.class).one(student);
}
public void update(Student student) {
student.setUpdated(DateTime.now());
template.upsertById(Student.class).one(student);
}
public void delete(Student student) {
template.removeById(Student.class).oneEntity(student);
}
} | repos\tutorials-master\persistence-modules\spring-data-couchbase-2\src\main\java\com\baeldung\spring\data\couchbase\service\StudentTemplateService.java | 2 |
请完成以下Java代码 | public void setC_Print_Job_Instructions_ID (int C_Print_Job_Instructions_ID)
{
if (C_Print_Job_Instructions_ID < 1)
set_Value (COLUMNNAME_C_Print_Job_Instructions_ID, null);
else
set_Value (COLUMNNAME_C_Print_Job_Instructions_ID, Integer.valueOf(C_Print_Job_Instructions_ID));
}
@Override
public int getC_Print_Job_Instructions_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Print_Job_Instructions_ID);
}
@Override
public void setC_Print_Package_ID (int C_Print_Package_ID)
{
if (C_Print_Package_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Print_Package_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Print_Package_ID, Integer.valueOf(C_Print_Package_ID));
}
@Override
public int getC_Print_Package_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Print_Package_ID);
}
@Override
public void setPackageInfoCount (int PackageInfoCount)
{
throw new IllegalArgumentException ("PackageInfoCount is virtual column"); }
@Override
public int getPackageInfoCount() | {
return get_ValueAsInt(COLUMNNAME_PackageInfoCount);
}
@Override
public void setPageCount (int PageCount)
{
set_Value (COLUMNNAME_PageCount, Integer.valueOf(PageCount));
}
@Override
public int getPageCount()
{
return get_ValueAsInt(COLUMNNAME_PageCount);
}
@Override
public void setTransactionID (java.lang.String TransactionID)
{
set_Value (COLUMNNAME_TransactionID, TransactionID);
}
@Override
public java.lang.String getTransactionID()
{
return (java.lang.String)get_Value(COLUMNNAME_TransactionID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_Package.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class LoginService {
public static final String LOGIN_IDENTITY_KEY = "XXL_JOB_LOGIN_IDENTITY";
@Resource
private XxlJobUserDao xxlJobUserDao;
private String makeToken(XxlJobUser xxlJobUser){
String tokenJson = JacksonUtil.writeValueAsString(xxlJobUser);
String tokenHex = new BigInteger(tokenJson.getBytes()).toString(16);
return tokenHex;
}
private XxlJobUser parseToken(String tokenHex){
XxlJobUser xxlJobUser = null;
if (tokenHex != null) {
String tokenJson = new String(new BigInteger(tokenHex, 16).toByteArray()); // username_password(md5)
xxlJobUser = JacksonUtil.readValue(tokenJson, XxlJobUser.class);
}
return xxlJobUser;
}
public ReturnT<String> login(HttpServletRequest request, HttpServletResponse response, String username, String password, boolean ifRemember){
// param
if (username==null || username.trim().length()==0 || password==null || password.trim().length()==0){
return new ReturnT<String>(500, I18nUtil.getString("login_param_empty"));
}
// valid passowrd
XxlJobUser xxlJobUser = xxlJobUserDao.loadByUserName(username);
if (xxlJobUser == null) {
return new ReturnT<String>(500, I18nUtil.getString("login_param_unvalid"));
}
String passwordMd5 = DigestUtils.md5DigestAsHex(password.getBytes());
if (!passwordMd5.equals(xxlJobUser.getPassword())) {
return new ReturnT<String>(500, I18nUtil.getString("login_param_unvalid"));
}
String loginToken = makeToken(xxlJobUser);
// do login
CookieUtil.set(response, LOGIN_IDENTITY_KEY, loginToken, ifRemember);
return ReturnT.SUCCESS;
}
/**
* logout
*
* @param request
* @param response
*/
public ReturnT<String> logout(HttpServletRequest request, HttpServletResponse response){
CookieUtil.remove(request, response, LOGIN_IDENTITY_KEY); | return ReturnT.SUCCESS;
}
/**
* logout
*
* @param request
* @return
*/
public XxlJobUser ifLogin(HttpServletRequest request, HttpServletResponse response){
String cookieToken = CookieUtil.getValue(request, LOGIN_IDENTITY_KEY);
if (cookieToken != null) {
XxlJobUser cookieUser = null;
try {
cookieUser = parseToken(cookieToken);
} catch (Exception e) {
logout(request, response);
}
if (cookieUser != null) {
XxlJobUser dbUser = xxlJobUserDao.loadByUserName(cookieUser.getUsername());
if (dbUser != null) {
if (cookieUser.getPassword().equals(dbUser.getPassword())) {
return dbUser;
}
}
}
}
return null;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\service\LoginService.java | 2 |
请完成以下Java代码 | public void setFQDN (String FQDN)
{
set_Value (COLUMNNAME_FQDN, FQDN);
}
/** Get Fully Qualified Domain Name.
@return Fully Qualified Domain Name i.e. www.comdivision.com
*/
public String getFQDN ()
{
return (String)get_Value(COLUMNNAME_FQDN);
}
/** 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());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_WebProject_Domain.java | 1 |
请完成以下Java代码 | public Date getDueDate()
{
return (Date)dueDate.clone();
}
@Override
public Date getGraceDate()
{
if (graceDate == null)
{
return null;
}
return (Date)graceDate.clone();
}
@Override
public int getDaysDue()
{
return daysDue;
}
@Override
public String getTableName()
{
return tableName;
}
@Override
public int getRecordId()
{
return record_id;
}
@Override | public boolean isInDispute()
{
return inDispute;
}
@Override
public String toString()
{
return "DunnableDoc [tableName=" + tableName + ", record_id=" + record_id + ", C_BPartner_ID=" + C_BPartner_ID + ", C_BPatner_Location_ID=" + C_BPatner_Location_ID + ", Contact_ID="
+ Contact_ID + ", C_Currency_ID=" + C_Currency_ID + ", totalAmt=" + totalAmt + ", openAmt=" + openAmt + ", dueDate=" + dueDate + ", graceDate=" + graceDate + ", daysDue=" + daysDue
+ ", inDispute=" + inDispute + "]";
}
@Override
public String getDocumentNo()
{
return documentNo;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunnableDoc.java | 1 |
请完成以下Java代码 | public String getF_ISSTD() {
return F_ISSTD;
}
public void setF_ISSTD(String f_ISSTD) {
F_ISSTD = f_ISSTD;
}
public Timestamp getF_EDITTIME() {
return F_EDITTIME;
}
public void setF_EDITTIME(Timestamp f_EDITTIME) {
F_EDITTIME = f_EDITTIME;
}
public String getF_PLATFORM_ID() {
return F_PLATFORM_ID;
}
public void setF_PLATFORM_ID(String f_PLATFORM_ID) {
F_PLATFORM_ID = f_PLATFORM_ID;
}
public String getF_ISENTERPRISES() { | return F_ISENTERPRISES;
}
public void setF_ISENTERPRISES(String f_ISENTERPRISES) {
F_ISENTERPRISES = f_ISENTERPRISES;
}
public String getF_ISCLEAR() {
return F_ISCLEAR;
}
public void setF_ISCLEAR(String f_ISCLEAR) {
F_ISCLEAR = f_ISCLEAR;
}
public String getF_PARENTID() {
return F_PARENTID;
}
public void setF_PARENTID(String f_PARENTID) {
F_PARENTID = f_PARENTID;
}
} | repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscTollItem.java | 1 |
请完成以下Java代码 | public void fireAfterClose(final I_C_RfQResponse rfqResponse)
{
listeners.onAfterClose(rfqResponse);
}
@Override
public void fireBeforeUnClose(I_C_RfQ rfq)
{
listeners.onBeforeUnClose(rfq);
}
@Override
public void fireAfterUnClose(I_C_RfQ rfq)
{
// TODO Auto-generated method stub | }
@Override
public void fireBeforeUnClose(I_C_RfQResponse rfqResponse)
{
// TODO Auto-generated method stub
}
@Override
public void fireAfterUnClose(I_C_RfQResponse rfqResponse)
{
// TODO Auto-generated method stub
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\event\impl\RfQEventDispacher.java | 1 |
请完成以下Java代码 | public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getKeyword());
}
/** Set Index Stop.
@param K_IndexStop_ID
Keyword not to be indexed
*/
public void setK_IndexStop_ID (int K_IndexStop_ID)
{
if (K_IndexStop_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_IndexStop_ID, null);
else
set_ValueNoCheck (COLUMNNAME_K_IndexStop_ID, Integer.valueOf(K_IndexStop_ID));
}
/** Get Index Stop.
@return Keyword not to be indexed
*/
public int getK_IndexStop_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_IndexStop_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_R_RequestType getR_RequestType() throws RuntimeException
{
return (I_R_RequestType)MTable.get(getCtx(), I_R_RequestType.Table_Name)
.getPO(getR_RequestType_ID(), get_TrxName()); }
/** Set Request Type.
@param R_RequestType_ID | Type of request (e.g. Inquiry, Complaint, ..)
*/
public void setR_RequestType_ID (int R_RequestType_ID)
{
if (R_RequestType_ID < 1)
set_Value (COLUMNNAME_R_RequestType_ID, null);
else
set_Value (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID));
}
/** Get Request Type.
@return Type of request (e.g. Inquiry, Complaint, ..)
*/
public int getR_RequestType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_IndexStop.java | 1 |
请完成以下Java代码 | public EngineResource resource() {
return resource;
}
@Override
public boolean enableSafeXml() {
return cmmnEngineConfiguration.isEnableSafeCmmnXml();
}
@Override
public String xmlEncoding() {
return cmmnEngineConfiguration.getXmlEncoding();
}
@Override
public boolean validateXml() {
// On redeploy, we assume it is validated at the first deploy
return newDeployment && !cmmnEngineConfiguration.isDisableCmmnXmlValidation();
} | @Override
public boolean validateCmmnModel() {
// On redeploy, we assume it is validated at the first deploy
return newDeployment && validateXml();
}
@Override
public CaseValidator caseValidator() {
return cmmnEngineConfiguration.getCaseValidator();
}
}
@Override
public void undeploy(EngineDeployment parentDeployment, boolean cascade) {
// Nothing to do
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\deployer\CmmnDeployer.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;
}
@Override
public org.compiere.model.I_AD_Process getAD_Process() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Process_ID, org.compiere.model.I_AD_Process.class);
}
@Override
public void setAD_Process(org.compiere.model.I_AD_Process AD_Process)
{
set_ValueFromPO(COLUMNNAME_AD_Process_ID, org.compiere.model.I_AD_Process.class, AD_Process);
}
/** Set Prozess.
@param AD_Process_ID
Prozess oder Bericht
*/
@Override
public void setAD_Process_ID (int AD_Process_ID)
{
if (AD_Process_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Process_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Process_ID, Integer.valueOf(AD_Process_ID));
}
/** Get Prozess.
@return Prozess oder Bericht
*/
@Override
public int getAD_Process_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Process_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Process Statistics.
@param AD_Process_Stats_ID Process Statistics */
@Override
public void setAD_Process_Stats_ID (int AD_Process_Stats_ID)
{
if (AD_Process_Stats_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Process_Stats_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Process_Stats_ID, Integer.valueOf(AD_Process_Stats_ID));
}
/** Get Process Statistics.
@return Process Statistics */
@Override
public int getAD_Process_Stats_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Process_Stats_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Statistic Count.
@param Statistic_Count
Internal statistics how often the entity was used
*/
@Override
public void setStatistic_Count (int Statistic_Count)
{
set_Value (COLUMNNAME_Statistic_Count, Integer.valueOf(Statistic_Count));
} | /** Get Statistic Count.
@return Internal statistics how often the entity was used
*/
@Override
public int getStatistic_Count ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Statistic_Count);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Statistic Milliseconds.
@param Statistic_Millis
Internal statistics how many milliseconds a process took
*/
@Override
public void setStatistic_Millis (int Statistic_Millis)
{
set_Value (COLUMNNAME_Statistic_Millis, Integer.valueOf(Statistic_Millis));
}
/** Get Statistic Milliseconds.
@return Internal statistics how many milliseconds a process took
*/
@Override
public int getStatistic_Millis ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Statistic_Millis);
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_AD_Process_Stats.java | 1 |
请完成以下Java代码 | public class DDOrderUserNotificationProducer
{
public static final Topic USER_NOTIFICATIONS_TOPIC = Topic.builder()
.name("de.metas.distribution.UserNotifications")
.type(Type.DISTRIBUTED)
.build();
private static final AdMessageKey MSG_Event_DDOrderGenerated = AdMessageKey.of("EVENT_DD_Order_Generated");
private final transient INotificationBL notificationBL = Services.get(INotificationBL.class);
private DDOrderUserNotificationProducer()
{
}
public static DDOrderUserNotificationProducer newInstance()
{
return new DDOrderUserNotificationProducer();
}
public DDOrderUserNotificationProducer notifyGenerated(final Collection<? extends I_DD_Order> orders)
{
if (orders == null || orders.isEmpty())
{
return this;
}
postNotifications(orders.stream()
.map(this::createUserNotification)
.collect(ImmutableList.toImmutableList()));
return this;
}
public final DDOrderUserNotificationProducer notifyGenerated(@NonNull final I_DD_Order order)
{
notifyGenerated(ImmutableList.of(order));
return this; | }
private UserNotificationRequest createUserNotification(@NonNull final I_DD_Order order)
{
final UserId recipientUserId = getNotificationRecipientUserId(order);
final TableRecordReference orderRef = TableRecordReference.of(order);
return newUserNotificationRequest()
.recipientUserId(recipientUserId)
.contentADMessage(MSG_Event_DDOrderGenerated)
.contentADMessageParam(orderRef)
.targetAction(UserNotificationRequest.TargetRecordAction.of(orderRef))
.build();
}
private UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest()
{
return UserNotificationRequest.builder()
.topic(USER_NOTIFICATIONS_TOPIC);
}
private UserId getNotificationRecipientUserId(final I_DD_Order order)
{
return UserId.ofRepoId(order.getCreatedBy());
}
private void postNotifications(final List<UserNotificationRequest> notifications)
{
notificationBL.sendAfterCommit(notifications);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\event\DDOrderUserNotificationProducer.java | 1 |
请完成以下Java代码 | public String getCallbackId() {
return callbackId;
}
public void setCallbackId(String callbackId) {
this.callbackId = callbackId;
}
public String getCallbackType() {
return callbackType;
}
public void setCallbackType(String callbackType) {
this.callbackType = callbackType;
}
public String getInstanceId() {
return instanceId;
}
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
public String getOldState() {
return oldState; | }
public void setOldState(String oldState) {
this.oldState = oldState;
}
public String getNewState() {
return newState;
}
public void setNewState(String newState) {
this.newState = newState;
}
public Map<String, Object> getAdditionalData() {
return additionalData;
}
public void setAdditionalData(Map<String, Object> additionalData) {
this.additionalData = additionalData;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\callback\CallbackData.java | 1 |
请完成以下Java代码 | public class FileManager {
final static Logger logger = LoggerFactory.getLogger(FileManager.class);
public static void main(String[] args) {
GenericFile file1 = new TextFile("SampleTextFile", "This is a sample text content", "v1.0.0");
logger.info("File Info: \n" + file1.getFileInfo() + "\n");
ImageFile imageFile = new ImageFile("SampleImageFile", 200, 100, new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB).toString()
.getBytes(), "v1.0.0");
logger.info("File Info: \n" + imageFile.getFileInfo());
}
public static ImageFile createImageFile(String name, int height, int width, byte[] content, String version) {
ImageFile imageFile = new ImageFile(name, height, width, content, version);
logger.info("File 2 Info: \n" + imageFile.getFileInfo()); | return imageFile;
}
public static GenericFile createTextFile(String name, String content, String version) {
GenericFile file1 = new TextFile(name, content, version);
logger.info("File 1 Info: \n" + file1.getFileInfo() + "\n");
return file1;
}
public static TextFile createTextFile2(String name, String content, String version) {
TextFile file1 = new TextFile(name, content, version);
logger.info("File 1 Info: \n" + file1.getFileInfo() + "\n");
return file1;
}
} | repos\tutorials-master\core-java-modules\core-java-lang-oop-inheritance-2\src\main\java\com\baeldung\polymorphism\FileManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HelloWorldClient {
private static final Logger log = LoggerFactory.getLogger(HelloWorldClient.class);
// constructor injection not possible
// "Do not use in conjunction with @Autowired or @Inject"
// (see https://github.com/grpc-ecosystem/grpc-spring)
@GrpcClient("hello")
HelloWorldServiceGrpc.HelloWorldServiceStub stub;
@EventListener(ContextRefreshedEvent.class)
void sendRequests() {
// prepare the response callback
final StreamObserver<HelloWorldResponse> responseObserver = new StreamObserver<HelloWorldResponse>() {
@Override
public void onNext(HelloWorldResponse helloWorldResponse) {
log.info("Hello World Response: {}", helloWorldResponse.getGreeting());
}
@Override
public void onError(Throwable throwable) {
log.error("Error occured", throwable);
}
@Override
public void onCompleted() {
log.info("Hello World request finished");
}
};
// connect to the server | final StreamObserver<HelloWorldRequest> request = stub.sayHello(responseObserver);
// send multiple requests (streaming)
Stream.of("Tom", "Julia", "Baeldung", "", "Ralf")
.map(HelloWorldRequest.newBuilder()::setName)
.map(HelloWorldRequest.Builder::build)
.forEach(request::onNext);
request.onCompleted();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-3-grpc\helloworld-grpc-consumer\src\main\java\com\baeldung\helloworld\consumer\HelloWorldClient.java | 2 |
请完成以下Java代码 | public Map<String, VariableInstance> execute(CommandContext commandContext) {
if (taskId == null) {
throw new FlowableIllegalArgumentException("taskId is null");
}
CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext);
TaskEntity task = cmmnEngineConfiguration.getTaskServiceConfiguration().getTaskService().getTask(taskId);
if (task == null) {
throw new FlowableObjectNotFoundException("task " + taskId + " doesn't exist", Task.class);
}
Map<String, VariableInstance> variables = null;
if (variableNames == null) {
if (isLocal) {
variables = task.getVariableInstancesLocal();
} else { | variables = task.getVariableInstances();
}
} else {
if (isLocal) {
variables = task.getVariableInstancesLocal(variableNames, false);
} else {
variables = task.getVariableInstances(variableNames, false);
}
}
return variables;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\GetTaskVariableInstancesCmd.java | 1 |
请完成以下Java代码 | private void registerHints(ReflectionHints hints, @Nullable ClassLoader classLoader) {
hints.registerField(findField(AbstractClientHttpRequestFactoryWrapper.class, "requestFactory"));
registerClientHttpRequestFactoryHints(hints, classLoader,
HttpComponentsClientHttpRequestFactoryBuilder.Classes.HTTP_CLIENTS,
() -> registerReflectionHints(hints, HttpComponentsClientHttpRequestFactory.class));
registerClientHttpRequestFactoryHints(hints, classLoader,
JettyClientHttpRequestFactoryBuilder.Classes.HTTP_CLIENT,
() -> registerReflectionHints(hints, JettyClientHttpRequestFactory.class, long.class));
registerClientHttpRequestFactoryHints(hints, classLoader,
ReactorClientHttpRequestFactoryBuilder.Classes.HTTP_CLIENT,
() -> registerReflectionHints(hints, ReactorClientHttpRequestFactory.class, long.class));
registerClientHttpRequestFactoryHints(hints, classLoader,
JdkClientHttpRequestFactoryBuilder.Classes.HTTP_CLIENT,
() -> registerReflectionHints(hints, JdkClientHttpRequestFactory.class));
hints.registerType(SimpleClientHttpRequestFactory.class, (typeHint) -> {
typeHint.onReachableType(HttpURLConnection.class);
registerReflectionHints(hints, SimpleClientHttpRequestFactory.class);
});
}
private void registerClientHttpRequestFactoryHints(ReflectionHints hints, @Nullable ClassLoader classLoader,
String className, Runnable action) {
hints.registerTypeIfPresent(classLoader, className, (typeHint) -> {
typeHint.onReachableType(TypeReference.of(className));
action.run();
});
}
private void registerReflectionHints(ReflectionHints hints,
Class<? extends ClientHttpRequestFactory> requestFactoryType) {
registerReflectionHints(hints, requestFactoryType, int.class);
}
private void registerReflectionHints(ReflectionHints hints,
Class<? extends ClientHttpRequestFactory> requestFactoryType, Class<?> readTimeoutType) {
registerMethod(hints, requestFactoryType, "setConnectTimeout", int.class);
registerMethod(hints, requestFactoryType, "setConnectTimeout", Duration.class);
registerMethod(hints, requestFactoryType, "setReadTimeout", readTimeoutType); | registerMethod(hints, requestFactoryType, "setReadTimeout", Duration.class);
}
private void registerMethod(ReflectionHints hints, Class<? extends ClientHttpRequestFactory> requestFactoryType,
String methodName, Class<?>... parameterTypes) {
Method method = ReflectionUtils.findMethod(requestFactoryType, methodName, parameterTypes);
if (method != null) {
hints.registerMethod(method, ExecutableMode.INVOKE);
}
}
private Field findField(Class<?> type, String name) {
Field field = ReflectionUtils.findField(type, name);
Assert.state(field != null, () -> "Unable to find field '%s' on %s".formatted(type.getName(), name));
return field;
}
} | repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\ClientHttpRequestFactoryRuntimeHints.java | 1 |
请完成以下Java代码 | public class FieldExport {
public static boolean writeFieldExtensions(List<FieldExtension> fieldExtensions, boolean didWriteExtensionElement, XMLStreamWriter xtw) throws
XMLStreamException {
if (fieldExtensions.size() > 0) {
if (!didWriteExtensionElement) {
xtw.writeStartElement(CmmnXmlConstants.ELEMENT_EXTENSION_ELEMENTS);
didWriteExtensionElement = true;
}
for (FieldExtension fieldExtension : fieldExtensions) {
xtw.writeStartElement(CmmnXmlConstants.FLOWABLE_EXTENSIONS_PREFIX, CmmnXmlConstants.ELEMENT_FIELD, CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE);
xtw.writeAttribute(CmmnXmlConstants.ATTRIBUTE_NAME, fieldExtension.getFieldName());
if (StringUtils.isNotEmpty(fieldExtension.getStringValue())) { | xtw.writeStartElement(CmmnXmlConstants.FLOWABLE_EXTENSIONS_PREFIX, CmmnXmlConstants.ELEMENT_FIELD_STRING, CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE);
xtw.writeCData(fieldExtension.getStringValue());
} else {
xtw.writeStartElement(CmmnXmlConstants.FLOWABLE_EXTENSIONS_PREFIX, CmmnXmlConstants.ATTRIBUTE_FIELD_EXPRESSION, CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE);
xtw.writeCData(fieldExtension.getExpression());
}
xtw.writeEndElement();
xtw.writeEndElement();
}
}
return didWriteExtensionElement;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\export\FieldExport.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean isFavorite(User requester, Article article) {
return articleFavoriteRepository.existsBy(requester, article);
}
/**
* Favorite article.
*
* @param requester user who requested
* @param article article
*/
public void favorite(User requester, Article article) {
if (this.isFavorite(requester, article)) {
throw new IllegalArgumentException("you already favorited this article.");
}
articleFavoriteRepository.save(new ArticleFavorite(requester, article));
}
/**
* Unfavorite article.
*
* @param requester user who requested
* @param article article
*/
public void unfavorite(User requester, Article article) {
if (!this.isFavorite(requester, article)) {
throw new IllegalArgumentException("you already unfavorited this article.");
}
articleFavoriteRepository.deleteBy(requester, article);
}
/**
* Get article details for anonymous users
*
* @param article article | * @return Returns article details
*/
public ArticleDetails getArticleDetails(Article article) {
return articleRepository.findArticleDetails(article);
}
/**
* Get article details for user.
*
* @param requester user who requested
* @param article article
* @return Returns article details
*/
public ArticleDetails getArticleDetails(User requester, Article article) {
return articleRepository.findArticleDetails(requester, article);
}
} | repos\realworld-java21-springboot3-main\module\core\src\main\java\io\zhc1\realworld\service\ArticleService.java | 2 |
请完成以下Java代码 | public class UserAccountInfo {
/**
* 登录人id
*/
private String id;
/**
* 登录人账号
*/
private String username;
/**
* 登录人名字
*/
private String realname;
/**
* 电子邮件 | */
private String email;
/**
* 头像
*/
@SensitiveField
private String avatar;
/**
* 同步工作流引擎1同步0不同步
*/
private Integer activitiSync;
/**
* 电话
*/
@SensitiveField
private String phone;
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\vo\UserAccountInfo.java | 1 |
请完成以下Java代码 | public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
public Set<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<Authority> authorities) {
this.authorities = authorities;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
} | User user = (User) o;
return !(user.getId() == null || getId() == null) && Objects.equals(getId(), user.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated='" + activated + '\'' +
", langKey='" + langKey + '\'' +
", activationKey='" + activationKey + '\'' +
"}";
}
} | repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\domain\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
@ApiModelProperty(example = "123")
public String getCallbackId() {
return callbackId;
}
public void setCallbackId(String callbackId) {
this.callbackId = callbackId;
}
@ApiModelProperty(example = "cmmn-1.1-to-cmmn-1.1-child-case")
public String getCallbackType() {
return callbackType;
}
public void setCallbackType(String callbackType) {
this.callbackType = callbackType;
}
@ApiModelProperty(example = "123") | public String getReferenceId() {
return referenceId;
}
public void setReferenceId(String referenceId) {
this.referenceId = referenceId;
}
@ApiModelProperty(example = "event-to-cmmn-1.1-case")
public String getReferenceType() {
return referenceType;
}
public void setReferenceType(String referenceType) {
this.referenceType = referenceType;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\caze\HistoricCaseInstanceResponse.java | 2 |
请完成以下Java代码 | public int getPA_Ratio_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Ratio_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_R_RequestType getR_RequestType() throws RuntimeException
{
return (I_R_RequestType)MTable.get(getCtx(), I_R_RequestType.Table_Name)
.getPO(getR_RequestType_ID(), get_TrxName()); }
/** Set Request Type.
@param R_RequestType_ID
Type of request (e.g. Inquiry, Complaint, ..)
*/
public void setR_RequestType_ID (int R_RequestType_ID)
{
if (R_RequestType_ID < 1)
set_Value (COLUMNNAME_R_RequestType_ID, null); | else
set_Value (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID));
}
/** Get Request Type.
@return Type of request (e.g. Inquiry, Complaint, ..)
*/
public int getR_RequestType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_Measure.java | 1 |
请完成以下Java代码 | public boolean addAll(Collection<? extends T> c) {
boolean result = false;
for (T o: c) {
result |= add(o);
}
return result;
}
public boolean removeAll(Collection<?> c) {
boolean result = false;
for (Object o: c) {
result |= remove(o);
}
return result;
}
public boolean retainAll(Collection<?> c) {
throw new UnsupportedModelOperationException("retainAll()", "not implemented");
}
public void clear() {
performClearOperation(referenceSourceElement);
}
};
}
protected void performClearOperation(ModelElementInstance referenceSourceElement) {
setReferenceIdentifier(referenceSourceElement, "");
}
@Override
protected void setReferenceIdentifier(ModelElementInstance referenceSourceElement, String referenceIdentifier) {
if (referenceIdentifier != null && !referenceIdentifier.isEmpty()) {
super.setReferenceIdentifier(referenceSourceElement, referenceIdentifier);
} else {
referenceSourceAttribute.removeAttribute(referenceSourceElement);
} | }
/**
* @param referenceSourceElement
* @param o
*/
protected void performRemoveOperation(ModelElementInstance referenceSourceElement, Object o) {
removeReference(referenceSourceElement, (ModelElementInstance) o);
}
protected void performAddOperation(ModelElementInstance referenceSourceElement, T referenceTargetElement) {
String identifier = getReferenceIdentifier(referenceSourceElement);
List<String> references = StringUtil.splitListBySeparator(identifier, separator);
String targetIdentifier = getTargetElementIdentifier(referenceTargetElement);
references.add(targetIdentifier);
identifier = StringUtil.joinList(references, separator);
setReferenceIdentifier(referenceSourceElement, identifier);
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\type\reference\AttributeReferenceCollection.java | 1 |
请完成以下Java代码 | public class FormalExpressionImpl extends ExpressionImpl implements FormalExpression {
protected static Attribute<String> languageAttribute;
protected static AttributeReference<ItemDefinition> evaluatesToTypeRefAttribute;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(FormalExpression.class, BPMN_ELEMENT_FORMAL_EXPRESSION)
.namespaceUri(BPMN20_NS)
.extendsType(Expression.class)
.instanceProvider(new ModelTypeInstanceProvider<FormalExpression>() {
public FormalExpression newInstance(ModelTypeInstanceContext instanceContext) {
return new FormalExpressionImpl(instanceContext);
}
});
languageAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_LANGUAGE)
.build();
evaluatesToTypeRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_EVALUATES_TO_TYPE_REF)
.qNameAttributeReference(ItemDefinition.class)
.build();
typeBuilder.build(); | }
public FormalExpressionImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getLanguage() {
return languageAttribute.getValue(this);
}
public void setLanguage(String language) {
languageAttribute.setValue(this, language);
}
public ItemDefinition getEvaluatesToType() {
return evaluatesToTypeRefAttribute.getReferenceTargetElement(this);
}
public void setEvaluatesToType(ItemDefinition evaluatesToType) {
evaluatesToTypeRefAttribute.setReferenceTargetElement(this, evaluatesToType);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\FormalExpressionImpl.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.