instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public CardEntry1 getCardTx() {
return cardTx;
}
/**
* Sets the value of the cardTx property.
*
* @param value
* allowed object is
* {@link CardEntry1 }
*
*/
public void setCardTx(CardEntry1 value) {
this.cardTx = value;
}
/**
* Gets the value of the ntryDtls property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the ntryDtls property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getNtryDtls().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link EntryDetails3 }
*
*
*/
public List<EntryDetails3> getNtryDtls() {
if (ntryDtls == null) {
ntryDtls = new ArrayList<EntryDetails3>();
}
|
return this.ntryDtls;
}
/**
* Gets the value of the addtlNtryInf property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAddtlNtryInf() {
return addtlNtryInf;
}
/**
* Sets the value of the addtlNtryInf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAddtlNtryInf(String value) {
this.addtlNtryInf = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\ReportEntry4.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
|
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
|
repos\Spring-Boot-Advanced-Projects-main\Springboot-Employee-Search\src\main\java\spring\project\configure\Employee.java
| 2
|
请完成以下Java代码
|
public static String getSqlInjectField(String field) {
if(oConvertUtils.isEmpty(field)){
return field;
}
field = field.trim();
if (field.contains(SymbolConstant.COMMA)) {
return getSqlInjectField(field.split(SymbolConstant.COMMA));
}
/**
* 校验表字段是否有效
*
* 字段定义只能是是字母 数字 下划线的组合(不允许有空格、转义字符串等)
*/
boolean isValidField = fieldPattern.matcher(field).matches();
if (!isValidField) {
String errorMsg = "字段不合法,存在SQL注入风险!--->" + field;
log.error(errorMsg);
throw new JeecgSqlInjectionException(errorMsg);
}
//进一步验证是否存在SQL注入风险
filterContentMulti(field);
return field;
}
/**
* 获取多个字段
* 返回: 逗号拼接
*
* @param fields
* @return
*/
public static String getSqlInjectField(String... fields) {
for (String s : fields) {
getSqlInjectField(s);
}
return String.join(SymbolConstant.COMMA, fields);
}
/**
* 获取排序字段
* 返回:字符串
*
* 1.将驼峰命名转化成下划线
* 2.限制sql注入
* @param sortField 排序字段
* @return
*/
public static String getSqlInjectSortField(String sortField) {
String field = SqlInjectionUtil.getSqlInjectField(oConvertUtils.camelToUnderline(sortField));
return field;
}
/**
* 获取多个排序字段
* 返回:数组
*
|
* 1.将驼峰命名转化成下划线
* 2.限制sql注入
* @param sortFields 多个排序字段
* @return
*/
public static List getSqlInjectSortFields(String... sortFields) {
List list = new ArrayList<String>();
for (String sortField : sortFields) {
list.add(getSqlInjectSortField(sortField));
}
return list;
}
/**
* 获取 orderBy type
* 返回:字符串
* <p>
* 1.检测是否为 asc 或 desc 其中的一个
* 2.限制sql注入
*
* @param orderType
* @return
*/
public static String getSqlInjectOrderType(String orderType) {
if (orderType == null) {
return null;
}
orderType = orderType.trim();
if (CommonConstant.ORDER_TYPE_ASC.equalsIgnoreCase(orderType)) {
return CommonConstant.ORDER_TYPE_ASC;
} else {
return CommonConstant.ORDER_TYPE_DESC;
}
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\SqlInjectionUtil.java
| 1
|
请完成以下Java代码
|
public GridField getField() {
return m_mField;
}
/**
* Set Text
* @param text text
*/
public void setText (String text)
{
m_text.setText (text);
validateOnTextChanged();
} // setText
/**
* Get Text (clear)
* @return text
*/
public String getText ()
{
String text = m_text.getText();
return text;
} // getText
/**
* Focus Gained.
* Enabled with Obscure
* @param e event
*/
public void focusGained (FocusEvent e)
{
m_infocus = true;
setText(getText()); // clear
} // focusGained
/**
* Focus Lost
* Enabled with Obscure
* @param e event
*/
|
public void focusLost (FocusEvent e)
{
m_infocus = false;
setText(getText()); // obscure
} // focus Lost
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport();
}
} // VURL
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VURL.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public java.lang.String getExternalReferenceURL()
{
return get_ValueAsString(COLUMNNAME_ExternalReferenceURL);
}
@Override
public void setExternalSystem_ID (final int ExternalSystem_ID)
{
if (ExternalSystem_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID);
}
@Override
public int getExternalSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID);
}
/**
* ProjectType AD_Reference_ID=541118
* Reference name: ExternalProjectType
*/
public static final int PROJECTTYPE_AD_Reference_ID=541118;
/** Budget = Budget */
public static final String PROJECTTYPE_Budget = "Budget";
/** Development = Effort */
public static final String PROJECTTYPE_Development = "Effort";
@Override
public void setProjectType (final java.lang.String ProjectType)
{
set_Value (COLUMNNAME_ProjectType, ProjectType);
}
@Override
public java.lang.String getProjectType()
{
return get_ValueAsString(COLUMNNAME_ProjectType);
}
@Override
public void setSeqNo (final int SeqNo)
{
|
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setS_ExternalProjectReference_ID (final int S_ExternalProjectReference_ID)
{
if (S_ExternalProjectReference_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_ExternalProjectReference_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_ExternalProjectReference_ID, S_ExternalProjectReference_ID);
}
@Override
public int getS_ExternalProjectReference_ID()
{
return get_ValueAsInt(COLUMNNAME_S_ExternalProjectReference_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_ExternalProjectReference.java
| 2
|
请完成以下Java代码
|
public void setCreditLimitIndicator (java.lang.String CreditLimitIndicator)
{
set_Value (COLUMNNAME_CreditLimitIndicator, CreditLimitIndicator);
}
/** Get Credit limit indicator %.
@return Percent of Credit used from the limit
*/
@Override
public java.lang.String getCreditLimitIndicator ()
{
return (java.lang.String)get_Value(COLUMNNAME_CreditLimitIndicator);
}
/** Set Offene Posten.
@param OpenItems Offene Posten */
@Override
public void setOpenItems (java.math.BigDecimal OpenItems)
{
set_Value (COLUMNNAME_OpenItems, OpenItems);
}
/** Get Offene Posten.
@return Offene Posten */
@Override
public java.math.BigDecimal getOpenItems ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenItems);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Kredit gewährt.
@param SO_CreditUsed
Gegenwärtiger Aussenstand
*/
@Override
public void setSO_CreditUsed (java.math.BigDecimal SO_CreditUsed)
{
set_Value (COLUMNNAME_SO_CreditUsed, SO_CreditUsed);
}
/** Get Kredit gewährt.
@return Gegenwärtiger Aussenstand
*/
@Override
public java.math.BigDecimal getSO_CreditUsed ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_SO_CreditUsed);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
|
/**
* SOCreditStatus AD_Reference_ID=289
* Reference name: C_BPartner SOCreditStatus
*/
public static final int SOCREDITSTATUS_AD_Reference_ID=289;
/** CreditStop = S */
public static final String SOCREDITSTATUS_CreditStop = "S";
/** CreditHold = H */
public static final String SOCREDITSTATUS_CreditHold = "H";
/** CreditWatch = W */
public static final String SOCREDITSTATUS_CreditWatch = "W";
/** NoCreditCheck = X */
public static final String SOCREDITSTATUS_NoCreditCheck = "X";
/** CreditOK = O */
public static final String SOCREDITSTATUS_CreditOK = "O";
/** NurEineRechnung = I */
public static final String SOCREDITSTATUS_NurEineRechnung = "I";
/** Set Kreditstatus.
@param SOCreditStatus
Kreditstatus des Geschäftspartners
*/
@Override
public void setSOCreditStatus (java.lang.String SOCreditStatus)
{
set_Value (COLUMNNAME_SOCreditStatus, SOCreditStatus);
}
/** Get Kreditstatus.
@return Kreditstatus des Geschäftspartners
*/
@Override
public java.lang.String getSOCreditStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_SOCreditStatus);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Stats.java
| 1
|
请完成以下Java代码
|
public class JsonPointerBasedInboundEventTenantDetector implements InboundEventTenantDetector<JsonNode> {
private static final Logger LOGGER = LoggerFactory.getLogger(JsonPointerBasedInboundEventTenantDetector.class);
protected String jsonPointerExpression;
protected JsonPointer jsonPointer;
public JsonPointerBasedInboundEventTenantDetector(String jsonPointerExpression) {
this.jsonPointerExpression = jsonPointerExpression;
this.jsonPointer = JsonPointer.compile(jsonPointerExpression);
}
@Override
public String detectTenantId(JsonNode payload) {
JsonNode result = payload.at(jsonPointer);
if (result == null || result.isMissingNode() || result.isNull()) {
LOGGER.warn("JsonPointer expression {} did not detect event tenant", jsonPointer);
return null;
}
|
if (result.isString()) {
return result.asString();
}
return null;
}
public String getJsonPointerExpression() {
return jsonPointerExpression;
}
public void setJsonPointerExpression(String jsonPointerExpression) {
this.jsonPointerExpression = jsonPointerExpression;
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\tenantdetector\JsonPointerBasedInboundEventTenantDetector.java
| 1
|
请完成以下Java代码
|
public class CorrelateMessageCmd extends AbstractCorrelateMessageCmd implements Command<MessageCorrelationResultImpl> {
private final static CommandLogger LOG = ProcessEngineLogger.CMD_LOGGER;
protected boolean startMessageOnly;
/**
* Initialize the command with a builder
*
* @param messageCorrelationBuilderImpl
*/
public CorrelateMessageCmd(MessageCorrelationBuilderImpl messageCorrelationBuilderImpl, boolean collectVariables, boolean deserializeVariableValues, boolean startMessageOnly) {
super(messageCorrelationBuilderImpl, collectVariables, deserializeVariableValues);
this.startMessageOnly = startMessageOnly;
}
public MessageCorrelationResultImpl execute(final CommandContext commandContext) {
ensureAtLeastOneNotNull(
"At least one of the following correlation criteria has to be present: " + "messageName, businessKey, correlationKeys, processInstanceId", messageName,
builder.getBusinessKey(), builder.getCorrelationProcessInstanceVariables(), builder.getProcessInstanceId());
final CorrelationHandler correlationHandler = Context.getProcessEngineConfiguration().getCorrelationHandler();
final CorrelationSet correlationSet = new CorrelationSet(builder);
CorrelationHandlerResult correlationResult = null;
if (startMessageOnly) {
List<CorrelationHandlerResult> correlationResults = commandContext.runWithoutAuthorization(new Callable<List<CorrelationHandlerResult>>() {
public List<CorrelationHandlerResult> call() throws Exception {
return correlationHandler.correlateStartMessages(commandContext, messageName, correlationSet);
}
});
if (correlationResults.isEmpty()) {
throw new MismatchingMessageCorrelationException(messageName, "No process definition matches the parameters");
} else if (correlationResults.size() > 1) {
throw LOG.exceptionCorrelateMessageToSingleProcessDefinition(messageName, correlationResults.size(), correlationSet);
} else {
|
correlationResult = correlationResults.get(0);
}
} else {
correlationResult = commandContext.runWithoutAuthorization(new Callable<CorrelationHandlerResult>() {
public CorrelationHandlerResult call() throws Exception {
return correlationHandler.correlateMessage(commandContext, messageName, correlationSet);
}
});
if (correlationResult == null) {
throw new MismatchingMessageCorrelationException(messageName, "No process definition or execution matches the parameters");
}
}
// check authorization
checkAuthorization(correlationResult);
return createMessageCorrelationResult(commandContext, correlationResult);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\CorrelateMessageCmd.java
| 1
|
请完成以下Java代码
|
public ContactAddressType getContact() {
return contact;
}
/**
* Sets the value of the contact property.
*
* @param value
* allowed object is
* {@link ContactAddressType }
*
*/
public void setContact(ContactAddressType value) {
this.contact = value;
}
/**
* Gets the value of the pending property.
*
* @return
* possible object is
* {@link PendingType }
*
*/
public PendingType getPending() {
return pending;
}
/**
* Sets the value of the pending property.
*
* @param value
* allowed object is
* {@link PendingType }
*
*/
public void setPending(PendingType value) {
this.pending = value;
}
/**
* Gets the value of the accepted property.
*
* @return
* possible object is
* {@link AcceptedType }
*
*/
public AcceptedType getAccepted() {
return accepted;
}
/**
* Sets the value of the accepted property.
|
*
* @param value
* allowed object is
* {@link AcceptedType }
*
*/
public void setAccepted(AcceptedType value) {
this.accepted = value;
}
/**
* Gets the value of the rejected property.
*
* @return
* possible object is
* {@link RejectedType }
*
*/
public RejectedType getRejected() {
return rejected;
}
/**
* Sets the value of the rejected property.
*
* @param value
* allowed object is
* {@link RejectedType }
*
*/
public void setRejected(RejectedType value) {
this.rejected = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\BodyType.java
| 1
|
请完成以下Java代码
|
private void assertUomWeightable(@NonNull final UomId catchUomId)
{
final IUOMDAO uomDAO = Services.get(IUOMDAO.class);
final UOMType catchUOMType = uomDAO.getUOMTypeById(catchUomId);
if (!catchUOMType.isWeight())
{
throw new AdempiereException("CatchUomId=" + catchUomId + " needs to be weightable");
}
}
@NonNull
private Optional<Quantity> getTrxCatchWeight(
@NonNull final IHUContext huContext,
@NonNull final Quantity qtyPicked,
@NonNull final I_M_HU hu,
@NonNull final I_M_HU_Trx_Line trxLine)
{
final AttributeId weightNetAttributeId = Services.get(IAttributeDAO.class)
.getAttributeIdByCode(Weightables.ATTR_WeightNet);
final List<IHUTransactionAttribute> trxAttributeCandidates = huContext.getProperty(IHUContext.PROPERTY_AttributeTrxCandidates);
if (Check.isEmpty(trxAttributeCandidates))
{
return Optional.empty();
}
final HuId targetHUId = qtyPicked.signum() < 0
? HuId.ofRepoId(Services.get(IHUTrxDAO.class).retrieveCounterpartTrxLine(trxLine).getM_HU_ID())
: HuId.ofRepoId(trxLine.getM_HU_ID());
|
final Function<BigDecimal, Quantity> toNetWeightQty = netWeight -> {
final IAttributeStorage attributeStorage = huContext.getHUAttributeStorageFactory().getAttributeStorage(hu);
final IWeightable weightable = Weightables.wrap(attributeStorage);
return Quantity.of(netWeight, weightable.getWeightNetUOM());
};
return trxAttributeCandidates
.stream()
.filter(trx -> trx.getAttributeId().equals(weightNetAttributeId))
.filter(trx -> trx.getReferencedObject() instanceof I_M_HU)
.filter(trx -> ((I_M_HU)trx.getReferencedObject()).getM_HU_ID() == targetHUId.getRepoId())
.findFirst()
.map(IHUTransactionAttribute::getValueNumber)
.map(toNetWeightQty);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\util\CatchWeightHelper.java
| 1
|
请完成以下Java代码
|
public DataFetcherResult<ArticlePayload> updateArticle(
@InputArgument("slug") String slug, @InputArgument("changes") UpdateArticleInput params) {
Article article =
articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new);
User user = SecurityUtil.getCurrentUser().orElseThrow(AuthenticationException::new);
if (!AuthorizationService.canWriteArticle(user, article)) {
throw new NoAuthorizationException();
}
article =
articleCommandService.updateArticle(
article,
new UpdateArticleParam(params.getTitle(), params.getBody(), params.getDescription()));
return DataFetcherResult.<ArticlePayload>newResult()
.data(ArticlePayload.newBuilder().build())
.localContext(article)
.build();
}
@DgsMutation(field = MUTATION.FavoriteArticle)
public DataFetcherResult<ArticlePayload> favoriteArticle(@InputArgument("slug") String slug) {
User user = SecurityUtil.getCurrentUser().orElseThrow(AuthenticationException::new);
Article article =
articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new);
ArticleFavorite articleFavorite = new ArticleFavorite(article.getId(), user.getId());
articleFavoriteRepository.save(articleFavorite);
return DataFetcherResult.<ArticlePayload>newResult()
.data(ArticlePayload.newBuilder().build())
.localContext(article)
.build();
}
@DgsMutation(field = MUTATION.UnfavoriteArticle)
public DataFetcherResult<ArticlePayload> unfavoriteArticle(@InputArgument("slug") String slug) {
User user = SecurityUtil.getCurrentUser().orElseThrow(AuthenticationException::new);
|
Article article =
articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new);
articleFavoriteRepository
.find(article.getId(), user.getId())
.ifPresent(
favorite -> {
articleFavoriteRepository.remove(favorite);
});
return DataFetcherResult.<ArticlePayload>newResult()
.data(ArticlePayload.newBuilder().build())
.localContext(article)
.build();
}
@DgsMutation(field = MUTATION.DeleteArticle)
public DeletionStatus deleteArticle(@InputArgument("slug") String slug) {
User user = SecurityUtil.getCurrentUser().orElseThrow(AuthenticationException::new);
Article article =
articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new);
if (!AuthorizationService.canWriteArticle(user, article)) {
throw new NoAuthorizationException();
}
articleRepository.remove(article);
return DeletionStatus.newBuilder().success(true).build();
}
}
|
repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\graphql\ArticleMutation.java
| 1
|
请完成以下Java代码
|
public class AuthResponse implements Message {
public static final String TYPE = "AUTH_RESPONSE";
/**
* 响应状态码
*/
private Integer code;
/**
* 响应提示
*/
private String message;
public Integer getCode() {
return code;
}
|
public AuthResponse setCode(Integer code) {
this.code = code;
return this;
}
public String getMessage() {
return message;
}
public AuthResponse setMessage(String message) {
this.message = message;
return this;
}
}
|
repos\SpringBoot-Labs-master\lab-25\lab-websocket-25-01\src\main\java\cn\iocoder\springboot\lab25\springwebsocket\message\AuthResponse.java
| 1
|
请完成以下Java代码
|
public EventModel getEventModelById(String eventDefinitionId) {
return commandExecutor.execute(new GetEventModelCmd(null, eventDefinitionId));
}
@Override
public EventModel getEventModelByKey(String eventDefinitionKey) {
return commandExecutor.execute(new GetEventModelCmd(eventDefinitionKey, null));
}
@Override
public EventModel getEventModelByKey(String eventDefinitionKey, String tenantId) {
return commandExecutor.execute(new GetEventModelCmd(eventDefinitionKey, tenantId, null));
}
@Override
public EventModel getEventModelByKeyAndParentDeploymentId(String eventDefinitionKey, String parentDeploymentId) {
return commandExecutor.execute(new GetEventModelCmd(eventDefinitionKey, null, parentDeploymentId));
}
@Override
public EventModel getEventModelByKeyAndParentDeploymentId(String eventDefinitionKey, String parentDeploymentId, String tenantId) {
return commandExecutor.execute(new GetEventModelCmd(eventDefinitionKey, tenantId, parentDeploymentId));
}
@Override
public ChannelModel getChannelModelById(String channelDefinitionId) {
return commandExecutor.execute(new GetChannelModelCmd(null, channelDefinitionId));
}
@Override
public ChannelModel getChannelModelByKey(String channelDefinitionKey) {
return commandExecutor.execute(new GetChannelModelCmd(channelDefinitionKey, null));
}
@Override
public ChannelModel getChannelModelByKey(String channelDefinitionKey, String tenantId) {
return commandExecutor.execute(new GetChannelModelCmd(channelDefinitionKey, tenantId, null));
}
@Override
public ChannelModel getChannelModelByKeyAndParentDeploymentId(String channelDefinitionKey, String parentDeploymentId) {
return commandExecutor.execute(new GetChannelModelCmd(channelDefinitionKey, null, parentDeploymentId));
}
@Override
public ChannelModel getChannelModelByKeyAndParentDeploymentId(String channelDefinitionKey, String parentDeploymentId, String tenantId) {
|
return commandExecutor.execute(new GetChannelModelCmd(channelDefinitionKey, tenantId, parentDeploymentId));
}
@Override
public EventModelBuilder createEventModelBuilder() {
return new EventModelBuilderImpl(this, eventRegistryEngineConfiguration.getEventJsonConverter());
}
@Override
public InboundChannelModelBuilder createInboundChannelModelBuilder() {
return new InboundChannelDefinitionBuilderImpl(this, eventRegistryEngineConfiguration.getChannelJsonConverter());
}
@Override
public OutboundChannelModelBuilder createOutboundChannelModelBuilder() {
return new OutboundChannelDefinitionBuilderImpl(this, eventRegistryEngineConfiguration.getChannelJsonConverter());
}
public void registerEventModel(EventModel eventModel) {
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\EventRepositoryServiceImpl.java
| 1
|
请完成以下Java代码
|
public void setFromBillLocation(final I_C_Order from)
{
final DocumentLocation fromDocumentLocationAdapter = OrderDocumentLocationAdapterFactory.billLocationAdapter(from).toDocumentLocation();
final BPartnerContactId fromContactId = fromDocumentLocationAdapter.getContactId();
final BPartnerContactId invoiceContactId = getBPartnerContactId().orElse(null);
if(invoiceContactId != null && !BPartnerContactId.equals(invoiceContactId, fromContactId))
{
setFrom(fromDocumentLocationAdapter.withContactId(null));
}
else
{
setFrom(fromDocumentLocationAdapter);
}
}
public void setFrom(final I_C_Invoice from)
{
final DocumentLocation fromDocumentLocationAdapter = new InvoiceDocumentLocationAdapter(from).toDocumentLocation();
final BPartnerContactId fromContactId = fromDocumentLocationAdapter.getContactId();
final BPartnerContactId invoiceContactId = getBPartnerContactId().orElse(null);
if(invoiceContactId != null && !BPartnerContactId.equals(invoiceContactId, fromContactId))
{
|
setFrom(fromDocumentLocationAdapter.withContactId(null));
}
else
{
setFrom(fromDocumentLocationAdapter);
}
}
@Override
public I_C_Invoice getWrappedRecord()
{
return delegate;
}
@Override
public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL)
{
return documentLocationBL.toPlainDocumentLocation(this);
}
@Override
public InvoiceDocumentLocationAdapter toOldValues()
{
InterfaceWrapperHelper.assertNotOldValues(delegate);
return new InvoiceDocumentLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_Invoice.class));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\location\adapter\InvoiceDocumentLocationAdapter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Result<?> edit(@RequestBody OpenApiLog OpenApiLog) {
service.updateById(OpenApiLog);
return Result.ok("修改成功!");
}
/**
* 通过id删除
*
* @param id
* @return
*/
@DeleteMapping(value = "/delete")
public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
service.removeById(id);
return Result.ok("删除成功!");
}
/**
* 批量删除
*
* @param ids
* @return
*/
@DeleteMapping(value = "/deleteBatch")
public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
|
this.service.removeByIds(Arrays.asList(ids.split(",")));
return Result.ok("批量删除成功!");
}
/**
* 通过id查询
*
* @param id
* @return
*/
@GetMapping(value = "/queryById")
public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
OpenApiLog OpenApiLog = service.getById(id);
return Result.ok(OpenApiLog);
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\openapi\controller\OpenApiLogController.java
| 2
|
请完成以下Java代码
|
public static JsonOLCandCreateBulkResponse error(@NonNull final JsonErrorItem error)
{
final List<JsonOLCand> olCands = null;
return new JsonOLCandCreateBulkResponse(olCands, ImmutableList.of(error));
}
@JsonInclude(JsonInclude.Include.NON_NULL)
private final List<JsonOLCand> result;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private final List<JsonErrorItem> errors;
@JsonCreator
private JsonOLCandCreateBulkResponse(
@JsonProperty("result") @Nullable final List<JsonOLCand> olCands,
@JsonProperty("errors") @Nullable @Singular final List<JsonErrorItem> errors)
{
if (errors == null || errors.isEmpty())
{
this.result = olCands != null ? ImmutableList.copyOf(olCands) : ImmutableList.of();
this.errors = ImmutableList.of();
}
else
{
Check.assume(olCands == null || olCands.isEmpty(), "No olCands shall be provided when error");
this.result = null;
this.errors = ImmutableList.copyOf(errors);
}
}
public boolean isError()
{
|
return !errors.isEmpty();
}
public JsonErrorItem getError()
{
if (errors.isEmpty())
{
throw new IllegalStateException("Not an error result: " + this);
}
return Check.singleElement(errors);
}
public List<JsonOLCand> getResult()
{
if (!errors.isEmpty())
{
throw new IllegalStateException("Not a successful result: " + this, getError().getThrowable());
}
return result;
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-ordercandidates\src\main\java\de\metas\common\ordercandidates\v1\response\JsonOLCandCreateBulkResponse.java
| 1
|
请完成以下Java代码
|
public Integer getQtyTU()
{
return ediDesadvPackItems.stream()
.map(EDIDesadvPackItem::getQtyTu)
.filter(Objects::nonNull)
.reduce(0, Integer::sum);
}
@NonNull
public BigDecimal getQtyCUsPerTU()
{
return ediDesadvPackItems.stream()
.map(EDIDesadvPackItem::getQtyCUsPerTU)
.filter(Objects::nonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
@NonNull
public BigDecimal getQtyCUsPerLU()
{
return ediDesadvPackItems.stream()
.map(EDIDesadvPackItem::getQtyCUsPerLU)
.filter(Objects::nonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
@Value
@Builder
public static class EDIDesadvPackItem
{
@NonNull
EDIDesadvPackItemId ediDesadvPackItemId;
@NonNull
EDIDesadvPackId ediDesadvPackId;
@NonNull
EDIDesadvLineId ediDesadvLineId;
int line;
@NonNull
BigDecimal movementQty;
@Nullable
InOutId inOutId;
@Nullable
InOutLineId inOutLineId;
@Nullable
BigDecimal qtyItemCapacity;
@Nullable
Integer qtyTu;
|
@Nullable
BigDecimal qtyCUsPerTU;
@Nullable
BigDecimal qtyCUPerTUinInvoiceUOM;
@Nullable
BigDecimal qtyCUsPerLU;
@Nullable
BigDecimal qtyCUsPerLUinInvoiceUOM;
@Nullable
Timestamp bestBeforeDate;
@Nullable
String lotNumber;
@Nullable
PackagingCodeId huPackagingCodeTuId;
@Nullable
String gtinTuPackingMaterial;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\impl\pack\EDIDesadvPack.java
| 1
|
请完成以下Java代码
|
public static Optional<BankStatementId> optionalOfRepoId(final int repoId) {return Optional.ofNullable(ofRepoIdOrNull(repoId));}
public static Set<Integer> toIntSet(final Collection<BankStatementId> bankStatementIds)
{
if (bankStatementIds == null || bankStatementIds.isEmpty())
{
return ImmutableSet.of();
}
else
{
return bankStatementIds
.stream()
.map(BankStatementId::getRepoId)
.collect(ImmutableSet.toImmutableSet());
}
}
private BankStatementId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_BankStatement_ID");
|
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable BankStatementId id1, @Nullable BankStatementId id2)
{
return Objects.equals(id1, id2);
}
public static int toRepoId(@Nullable BankStatementId id) {return id != null ? id.getRepoId() : -1;}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\banking\BankStatementId.java
| 1
|
请完成以下Java代码
|
public void updateFromSalesPartnerCode(@NonNull final DocumentSalesRepDescriptor documentSalesRepDescriptor)
{
final String salesPartnerCode = documentSalesRepDescriptor.getSalesPartnerCode();
if (isEmpty(salesPartnerCode, true))
{
documentSalesRepDescriptor.setSalesRep(null);
return;
}
final Optional<BPartnerId> salesPartnerId = bpartnerDAO.getBPartnerIdBySalesPartnerCode(
salesPartnerCode,
ImmutableSet.of(documentSalesRepDescriptor.getOrgId(), OrgId.ANY));
documentSalesRepDescriptor.setSalesRep(salesPartnerId.map(Beneficiary::of).orElse(null));
}
public void updateFromSalesRep(@NonNull final DocumentSalesRepDescriptor documentSalesRepDescriptor)
{
if (documentSalesRepDescriptor.getSalesRep() == null)
|
{
documentSalesRepDescriptor.setSalesPartnerCode(null);
return;
}
final I_C_BPartner salesBPartnerRecord = bpartnerDAO.getById(documentSalesRepDescriptor.getSalesRep().getBPartnerId());
documentSalesRepDescriptor.setSalesPartnerCode(salesBPartnerRecord.getSalesPartnerCode());
}
public AdempiereException createMissingSalesRepException()
{
throw new AdempiereException(MSG_CUSTOMER_NEEDS_SALES_PARTNER).markAsUserValidationError();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\salesrep\DocumentSalesRepDescriptorService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
final class TrxRunConfig implements ITrxRunConfig
{
private final TrxPropagation trxPropagation;
private final OnRunnableSuccess onRunnableSuccess;
private final OnRunnableFail onRunnableFail;
private final boolean autocommit;
public TrxRunConfig(final TrxPropagation trxMode,
final OnRunnableSuccess onRunnableSuccess,
final OnRunnableFail onRunnableFail,
final boolean autoCommit)
{
Check.assumeNotNull(trxMode, "Param 'trxMode' is not null");
Check.assumeNotNull(onRunnableSuccess, "Param 'onRunnableSuccess' is not null");
Check.assumeNotNull(onRunnableFail, "Param 'onRunnableFail' is not null");
this.trxPropagation = trxMode;
this.onRunnableSuccess = onRunnableSuccess;
this.onRunnableFail = onRunnableFail;
this.autocommit = autoCommit;
}
@Override
public String toString()
{
return "TrxRunConfig [trxPropagation=" + trxPropagation + ", onRunnableSuccess=" + onRunnableSuccess + ", onRunnableFail=" + onRunnableFail + "]";
}
|
@Override
public TrxPropagation getTrxPropagation()
{
return trxPropagation;
}
@Override
public OnRunnableSuccess getOnRunnableSuccess()
{
return onRunnableSuccess;
}
@Override
public OnRunnableFail getOnRunnableFail()
{
return onRunnableFail;
}
@Override
public boolean isAutoCommit()
{
return autocommit;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\TrxRunConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Result confirmReceive(String orderId, HttpServletRequest httpReq) {
// 获取买家ID
String buyerId = getUserId(httpReq);
// 确认收货
orderService.confirmReceive(orderId, buyerId);
// 成功
return Result.newSuccessResult();
}
|
/**
* 获取用户ID
* @param httpReq HTTP请求
* @return 用户ID
*/
private String getUserId(HttpServletRequest httpReq) {
UserEntity userEntity = userUtil.getUser(httpReq);
if (userEntity == null) {
throw new CommonBizException(ExpCodeEnum.UNLOGIN);
}
return userEntity.getId();
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Controller\src\main\java\com\gaoxi\controller\order\OrderControllerImpl.java
| 2
|
请完成以下Java代码
|
public class QueryStringBuilder {
StringBuilder builder;
public QueryStringBuilder(String field, String str, boolean not, boolean addQuot) {
builder = this.createBuilder(field, str, not, addQuot);
}
public QueryStringBuilder(String field, String str, boolean not) {
builder = this.createBuilder(field, str, not, true);
}
/**
* 创建 StringBuilder
*
* @param field
* @param str
* @param not 是否是不匹配
* @param addQuot 是否添加双引号
* @return
*/
public StringBuilder createBuilder(String field, String str, boolean not, boolean addQuot) {
StringBuilder sb = new StringBuilder(field).append(":(");
if (not) {
sb.append(" NOT ");
}
this.addQuotEffect(sb, str, addQuot);
return sb;
}
public QueryStringBuilder and(String str) {
return this.and(str, true);
}
public QueryStringBuilder and(String str, boolean addQuot) {
builder.append(" AND ");
this.addQuot(str, addQuot);
return this;
}
public QueryStringBuilder or(String str) {
return this.or(str, true);
}
public QueryStringBuilder or(String str, boolean addQuot) {
builder.append(" OR ");
this.addQuot(str, addQuot);
return this;
}
|
public QueryStringBuilder not(String str) {
return this.not(str, true);
}
public QueryStringBuilder not(String str, boolean addQuot) {
builder.append(" NOT ");
this.addQuot(str, addQuot);
return this;
}
/**
* 添加双引号(模糊查询,不能加双引号)
*/
private QueryStringBuilder addQuot(String str, boolean addQuot) {
return this.addQuotEffect(this.builder, str, addQuot);
}
/**
* 是否在两边加上双引号
* @param builder
* @param str
* @param addQuot
* @return
*/
private QueryStringBuilder addQuotEffect(StringBuilder builder, String str, boolean addQuot) {
if (addQuot) {
builder.append('"');
}
builder.append(str);
if (addQuot) {
builder.append('"');
}
return this;
}
@Override
public String toString() {
return builder.append(")").toString();
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\es\QueryStringBuilder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CacheInvalidationQueueConfiguration implements IEventBusQueueConfiguration
{
public static final Topic EVENTBUS_TOPIC = Topic.distributed("de.metas.cache.CacheInvalidationRemoteHandler");
static final String QUEUE_NAME_SPEL = "#{metasfreshCacheInvalidationEventsQueue.name}";
private static final String QUEUE_BEAN_NAME = "metasfreshCacheInvalidationEventsQueue";
private static final String EXCHANGE_NAME_PREFIX = "metasfresh-cache-events";
@Value(RabbitMQEventBusConfiguration.APPLICATION_NAME_SPEL)
private String appName;
@Bean(QUEUE_BEAN_NAME)
public AnonymousQueue cacheInvalidationQueue()
{
final NamingStrategy eventQueueNamingStrategy = new Base64UrlNamingStrategy(EVENTBUS_TOPIC.getName() + "." + appName + "-");
return new AnonymousQueue(eventQueueNamingStrategy);
}
@Bean
public DirectExchange cacheInvalidationExchange()
{
return new DirectExchange(EXCHANGE_NAME_PREFIX);
}
@Bean
public Binding cacheInvalidationBinding()
{
return BindingBuilder.bind(cacheInvalidationQueue())
.to(cacheInvalidationExchange()).with(EXCHANGE_NAME_PREFIX);
}
@Override
public String getQueueName()
{
|
return cacheInvalidationQueue().getName();
}
@Override
public Optional<String> getTopicName()
{
return Optional.of(EVENTBUS_TOPIC.getName());
}
@Override
public String getExchangeName()
{
return cacheInvalidationExchange().getName();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\remote\rabbitmq\queues\cache_invalidation\CacheInvalidationQueueConfiguration.java
| 2
|
请完成以下Java代码
|
private static boolean isWithinPause(final I_C_SubscriptionProgress subscriptionProgress)
{
final boolean withinPause = subscriptionProgress.getContractStatus().equals(X_C_SubscriptionProgress.CONTRACTSTATUS_DeliveryPause)
|| subscriptionProgress.getEventType().equals(X_C_SubscriptionProgress.EVENTTYPE_BeginOfPause)
|| subscriptionProgress.getEventType().equals(X_C_SubscriptionProgress.EVENTTYPE_EndOfPause);
return withinPause;
}
private static I_C_SubscriptionProgress retrieveFirstPauseRecordSearchBackwards(final I_C_SubscriptionProgress firstSp)
{
final SubscriptionProgressQuery query = SubscriptionProgressQuery.endingRightBefore(firstSp)
.includedContractStatus(X_C_SubscriptionProgress.CONTRACTSTATUS_DeliveryPause)
.build();
final I_C_SubscriptionProgress preceedingPauseRecord = Services.get(ISubscriptionDAO.class).retrieveFirstSubscriptionProgress(query);
final I_C_SubscriptionProgress firstPauseRecord = preceedingPauseRecord != null ? preceedingPauseRecord : firstSp;
return firstPauseRecord;
}
private static int deletePauseBeginEndRecordsAndUpdatePausedRecords(@NonNull final List<I_C_SubscriptionProgress> allPauseRecords)
{
int seqNoOffset = 0;
for (final I_C_SubscriptionProgress pauseRecord : allPauseRecords)
{
final boolean pauseStartOrEnd = X_C_SubscriptionProgress.EVENTTYPE_BeginOfPause.equals(pauseRecord.getEventType()) || X_C_SubscriptionProgress.EVENTTYPE_EndOfPause.equals(pauseRecord.getEventType());
if (pauseStartOrEnd)
{
delete(pauseRecord);
seqNoOffset++;
continue;
}
|
else if (isWithinPause(pauseRecord))
{
pauseRecord.setContractStatus(X_C_SubscriptionProgress.CONTRACTSTATUS_Running);
if (pauseRecord.getM_ShipmentSchedule_ID() > 0)
{
Services.get(IShipmentScheduleBL.class).openShipmentSchedule(InterfaceWrapperHelper.load(pauseRecord.getM_ShipmentSchedule_ID(), I_M_ShipmentSchedule.class));
}
}
subtractFromSeqNoAndSave(pauseRecord, seqNoOffset);
}
return seqNoOffset;
}
private static void subtractFromSeqNoAndSave(final I_C_SubscriptionProgress record, final int seqNoOffset)
{
record.setSeqNo(record.getSeqNo() - seqNoOffset); // might be a not-within-pause-record if there are multiple pause periods between pausesFrom and pausesUntil
save(record);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\impl\subscriptioncommands\RemovePauses.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Duration connectTimeout() {
return obtain(AtlasProperties::getConnectTimeout, AtlasConfig.super::connectTimeout);
}
@Override
public Duration readTimeout() {
return obtain(AtlasProperties::getReadTimeout, AtlasConfig.super::readTimeout);
}
@Override
public int numThreads() {
return obtain(AtlasProperties::getNumThreads, AtlasConfig.super::numThreads);
}
@Override
public int batchSize() {
return obtain(AtlasProperties::getBatchSize, AtlasConfig.super::batchSize);
}
@Override
public String uri() {
return obtain(AtlasProperties::getUri, AtlasConfig.super::uri);
}
@Override
public Duration meterTTL() {
return obtain(AtlasProperties::getMeterTimeToLive, AtlasConfig.super::meterTTL);
}
@Override
public boolean lwcEnabled() {
return obtain(AtlasProperties::isLwcEnabled, AtlasConfig.super::lwcEnabled);
}
@Override
public Duration lwcStep() {
return obtain(AtlasProperties::getLwcStep, AtlasConfig.super::lwcStep);
}
@Override
public boolean lwcIgnorePublishStep() {
return obtain(AtlasProperties::isLwcIgnorePublishStep, AtlasConfig.super::lwcIgnorePublishStep);
|
}
@Override
public Duration configRefreshFrequency() {
return obtain(AtlasProperties::getConfigRefreshFrequency, AtlasConfig.super::configRefreshFrequency);
}
@Override
public Duration configTTL() {
return obtain(AtlasProperties::getConfigTimeToLive, AtlasConfig.super::configTTL);
}
@Override
public String configUri() {
return obtain(AtlasProperties::getConfigUri, AtlasConfig.super::configUri);
}
@Override
public String evalUri() {
return obtain(AtlasProperties::getEvalUri, AtlasConfig.super::evalUri);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\atlas\AtlasPropertiesConfigAdapter.java
| 2
|
请完成以下Java代码
|
Collection<OptionHelp> getOptionHelp() {
return Collections.unmodifiableList(this.help);
}
}
private static class OptionHelpAdapter implements OptionHelp {
private final Set<String> options;
private final String description;
OptionHelpAdapter(OptionDescriptor descriptor) {
this.options = new LinkedHashSet<>();
for (String option : descriptor.options()) {
String prefix = (option.length() != 1) ? "--" : "-";
this.options.add(prefix + option);
}
if (this.options.contains("--cp")) {
this.options.remove("--cp");
this.options.add("-cp");
|
}
this.description = descriptor.description();
}
@Override
public Set<String> getOptions() {
return this.options;
}
@Override
public String getUsageHelp() {
return this.description;
}
}
}
|
repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\options\OptionHandler.java
| 1
|
请完成以下Java代码
|
default Collection<T> getAllRows()
{
return getDocumentId2AllRows().values();
}
default Collection<T> getTopLevelRows()
{
return getDocumentId2TopLevelRows().values();
}
/** @return top level or include row */
default T getById(final DocumentId rowId) throws EntityNotFoundException
{
final T row = getByIdOrNull(rowId);
if (row == null)
|
{
throw new EntityNotFoundException("Row not found")
.appendParametersToMessage()
.setParameter("rowId", rowId);
}
return row;
}
@Nullable
default T getByIdOrNull(final DocumentId rowId)
{
return getDocumentId2AllRows().get(rowId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\template\IRowsData.java
| 1
|
请完成以下Java代码
|
private HUAttributeChange extractHUAttributeChange(
final I_M_HU_Attribute record,
final I_M_Attribute attribute)
{
final I_M_HU_Attribute recordBeforeChanges = InterfaceWrapperHelper.createOld(record, I_M_HU_Attribute.class);
final AttributeValueType attributeValueType = AttributeValueType.ofCode(attribute.getAttributeValueType());
final Object valueNew;
final Object valueOld;
if (AttributeValueType.STRING.equals(attributeValueType))
{
valueNew = record.getValue();
valueOld = recordBeforeChanges.getValue();
}
else if (AttributeValueType.NUMBER.equals(attributeValueType))
{
valueNew = extractValueNumberOrNull(record);
valueOld = extractValueNumberOrNull(recordBeforeChanges);
}
else if (AttributeValueType.DATE.equals(attributeValueType))
{
valueNew = record.getValueDate();
valueOld = recordBeforeChanges.getValueDate();
}
else if (AttributeValueType.LIST.equals(attributeValueType))
{
final AttributeId attributeId = AttributeId.ofRepoId(attribute.getM_Attribute_ID());
final AttributeListValue attributeListValueNew = attributesService.retrieveAttributeValueOrNull(attributeId, record.getValue());
valueNew = attributeListValueNew != null ? attributeListValueNew.getId() : null;
final AttributeListValue attributeListValueOld = attributesService.retrieveAttributeValueOrNull(attributeId, recordBeforeChanges.getValue());
valueOld = attributeListValueOld != null ? attributeListValueOld.getId() : null;
}
|
else
{
throw new AdempiereException("Unknown attribute value type: " + attributeValueType);
}
return HUAttributeChange.builder()
.huId(HuId.ofRepoId(record.getM_HU_ID()))
.attributeId(AttributeId.ofRepoId(record.getM_Attribute_ID()))
.attributeValueType(attributeValueType)
.valueNew(valueNew)
.valueOld(valueOld)
.date(TimeUtil.asInstantNonNull(record.getUpdated()))
.build();
}
private static BigDecimal extractValueNumberOrNull(final I_M_HU_Attribute record)
{
return !InterfaceWrapperHelper.isNull(record, I_M_HU_Attribute.COLUMNNAME_ValueNumber)
? record.getValueNumber()
: null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\material\interceptor\M_HU_Attribute.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public BPPrintFormat save(@NonNull final BPPrintFormat bpPrintFormat)
{
final I_C_BP_PrintFormat bpPrintFormatRecord = createOrUpdateRecord(bpPrintFormat);
saveRecord(bpPrintFormatRecord);
return bpPrintFormat.toBuilder()
.bpPrintFormatId(bpPrintFormatRecord.getC_BP_PrintFormat_ID())
.build();
}
private I_C_BP_PrintFormat createOrUpdateRecord(@NonNull final BPPrintFormat bpPrintFormat)
{
final I_C_BP_PrintFormat bpPrintFormatRecord;
if (bpPrintFormat.getBpPrintFormatId() > 0)
{
bpPrintFormatRecord = load(bpPrintFormat.getBpPrintFormatId(), I_C_BP_PrintFormat.class);
}
else
{
bpPrintFormatRecord = newInstance(I_C_BP_PrintFormat.class);
}
|
bpPrintFormatRecord.setC_BPartner_ID(bpPrintFormat.getBpartnerId().getRepoId());
bpPrintFormatRecord.setC_DocType_ID(bpPrintFormat.getDocTypeId() == null ? 0 : bpPrintFormat.getDocTypeId().getRepoId());
bpPrintFormatRecord.setAD_Table_ID(bpPrintFormat.getAdTableId() == null ? 0 : bpPrintFormat.getAdTableId().getRepoId());
bpPrintFormatRecord.setAD_PrintFormat_ID(bpPrintFormat.getPrintFormatId() == null ? 0 : bpPrintFormat.getPrintFormatId().getRepoId());
bpPrintFormatRecord.setC_BPartner_Location_ID(bpPrintFormat.getBPartnerLocationId() == null ? 0 : bpPrintFormat.getBPartnerLocationId().getRepoId());
bpPrintFormatRecord.setDocumentCopies_Override(bpPrintFormat.getPrintCopies().toInt());
return bpPrintFormatRecord;
}
public SeqNo getNextSeqNo(@NonNull final BPartnerId bPartnerId)
{
final int lastLineInt = queryBL.createQueryBuilder(I_C_BP_PrintFormat.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_BP_PrintFormat.COLUMNNAME_C_BPartner_ID, bPartnerId)
.create()
.maxInt(I_C_BP_PrintFormat.COLUMNNAME_SeqNo);
final SeqNo lastLineNo = SeqNo.ofInt(Math.max(lastLineInt, 0));
return lastLineNo.next();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\BPartnerPrintFormatRepository.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class SampleLdapApplication {
public static void main(String[] args) {
SpringApplication.run(SampleLdapApplication.class, args);
}
@Configuration(proxyBeanMethods = false)
class ApiWebSecurityConfigurationAdapter {
@Bean
@Order(99)
public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http) throws Exception {
PathPatternRequestMatcher.Builder pathMatcherBuilder = PathPatternRequestMatcher.withDefaults().basePath("/process-api");
http
.securityMatcher(pathMatcherBuilder.matcher("/**"))
.authorizeHttpRequests(authorizeRequests -> authorizeRequests
.requestMatchers(pathMatcherBuilder.matcher("/repository/**")).hasAnyAuthority("repository-privilege")
.requestMatchers(pathMatcherBuilder.matcher("/management/**")).hasAnyAuthority("management-privilege")
.anyRequest().authenticated()
|
)
.httpBasic(Customizer.withDefaults());
return http.build();
}
}
@Bean
@ConditionalOnBean(InMemoryDirectoryServer.class)
public CommandLineRunner initializePrivileges(IdmIdentityService idmIdentityService) {
return args -> {
Privilege repositoryPrivilege = idmIdentityService.createPrivilege("repository-privilege");
Privilege managementPrivilege = idmIdentityService.createPrivilege("management-privilege");
idmIdentityService.addGroupPrivilegeMapping(repositoryPrivilege.getId(), "user");
idmIdentityService.addGroupPrivilegeMapping(managementPrivilege.getId(), "admin");
idmIdentityService.addUserPrivilegeMapping(managementPrivilege.getId(), "fozzie");
};
}
}
|
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-samples\flowable-spring-boot-sample-ldap\src\main\java\flowable\SampleLdapApplication.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public String getElementId() {
return elementId;
}
public void setElementId(String elementId) {
this.elementId = elementId;
}
public String getElementName() {
return elementName;
}
public void setElementName(String elementName) {
this.elementName = elementName;
}
public Integer getRetries() {
return retries;
}
public void setRetries(Integer retries) {
this.retries = retries;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = exceptionMessage;
}
public Date getDueDate() {
return dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
public Date getCreateTime() {
return createTime;
}
|
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantId() {
return tenantId;
}
public String getLockOwner() {
return lockOwner;
}
public void setLockOwner(String lockOwner) {
this.lockOwner = lockOwner;
}
public Date getLockExpirationTime() {
return lockExpirationTime;
}
public void setLockExpirationTime(Date lockExpirationTime) {
this.lockExpirationTime = lockExpirationTime;
}
}
|
repos\flowable-engine-main\modules\flowable-external-job-rest\src\main\java\org\flowable\external\job\rest\service\api\query\ExternalWorkerJobResponse.java
| 2
|
请完成以下Java代码
|
private static void hasNextWithDelimiter() {
printHeader("hasNext() with delimiter");
Scanner scanner = new Scanner(INPUT);
while (scanner.hasNext()) {
String token = scanner.next();
if ("dependencies:".equals(token)) {
scanner.useDelimiter(":");
}
log.info(token);
}
log.info(END_LINE);
scanner.close();
}
private static void hasNextWithDelimiterFixed() {
printHeader("hasNext() with delimiter FIX");
Scanner scanner = new Scanner(INPUT);
while (scanner.hasNext()) {
String token = scanner.next();
if ("dependencies:".equals(token)) {
scanner.useDelimiter(":|\\s+");
}
log.info(token);
}
log.info(END_LINE);
scanner.close();
}
private static void addLineNumber() {
printHeader("add line number by hasNextLine() ");
Scanner scanner = new Scanner(INPUT);
int i = 0;
while (scanner.hasNextLine()) {
log.info(String.format("%d|%s", ++i, scanner.nextLine()));
}
|
log.info(END_LINE);
scanner.close();
}
private static void printHeader(String title) {
log.info(LINE);
log.info(title);
log.info(LINE);
}
public static void main(String[] args) throws IOException {
setLogger();
hasNextBasic();
hasNextWithDelimiter();
hasNextWithDelimiterFixed();
addLineNumber();
}
//overwrite the logger config
private static void setLogger() throws IOException {
InputStream is = HasNextVsHasNextLineDemo.class.getResourceAsStream("/scanner/log4j.properties");
Properties props = new Properties();
props.load(is);
LogManager.resetConfiguration();
PropertyConfigurator.configure(props);
}
}
|
repos\tutorials-master\core-java-modules\core-java-scanner\src\main\java\com\baeldung\scanner\HasNextVsHasNextLineDemo.java
| 1
|
请完成以下Java代码
|
public String getInstanceId() {
return instanceId;
}
public String getExecutionId() {
return executionId;
}
public String getActivityId() {
return activityId;
}
public String getScopeType() {
return scopeType;
}
public boolean isWithoutScopeType() {
return withoutScopeType;
}
public String getProcessInstanceIdWithChildren() {
return processInstanceIdWithChildren;
}
public String getCaseInstanceIdWithChildren() {
return caseInstanceIdWithChildren;
}
|
public Boolean getFailed() {
return failed;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\HistoricDecisionExecutionQueryImpl.java
| 1
|
请完成以下Java代码
|
void add(ConfigurationProperty configurationProperty) {
this.properties.put(configurationProperty.getName(), configurationProperty);
}
/**
* Get the configuration property bound to the given name.
* @param name the property name
* @return the bound property or {@code null}
*/
public @Nullable ConfigurationProperty get(ConfigurationPropertyName name) {
return this.properties.get(name);
}
/**
* Get all bound properties.
* @return a map of all bound properties
*/
public Map<ConfigurationPropertyName, ConfigurationProperty> getAll() {
return Collections.unmodifiableMap(this.properties);
}
/**
* Return the {@link BoundConfigurationProperties} from the given
* {@link ApplicationContext} if it is available.
|
* @param context the context to search
* @return a {@link BoundConfigurationProperties} or {@code null}
*/
public static @Nullable BoundConfigurationProperties get(ApplicationContext context) {
return (!context.containsBeanDefinition(BEAN_NAME)) ? null
: context.getBean(BEAN_NAME, BoundConfigurationProperties.class);
}
static void register(BeanDefinitionRegistry registry) {
Assert.notNull(registry, "'registry' must not be null");
if (!registry.containsBeanDefinition(BEAN_NAME)) {
BeanDefinition definition = BeanDefinitionBuilder.rootBeanDefinition(BoundConfigurationProperties.class)
.setRole(BeanDefinition.ROLE_INFRASTRUCTURE)
.getBeanDefinition();
registry.registerBeanDefinition(BEAN_NAME, definition);
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\BoundConfigurationProperties.java
| 1
|
请完成以下Java代码
|
public Address instantiate(ValueAccess values) {
return new Address(values.getValue(0, String.class), values.getValue(1, String.class), values.getValue(2, String.class),
values.getValue(3, String.class), values.getValue(4, Integer.class));
}
@Override
public Class<?> embeddable() {
return Address.class;
}
@Override
public Class<Address> returnedClass() {
return Address.class;
}
@Override
public boolean equals(Address x, Address y) {
if (x == y) {
return true;
}
if (Objects.isNull(x) || Objects.isNull(y)) {
return false;
}
return x.equals(y);
}
@Override
public int hashCode(Address x) {
return x.hashCode();
}
@Override
public Address deepCopy(Address value) {
if (Objects.isNull(value)) {
return null;
}
Address newEmpAdd = new Address();
newEmpAdd.setAddressLine1(value.getAddressLine1());
newEmpAdd.setAddressLine2(value.getAddressLine2());
newEmpAdd.setCity(value.getCity());
newEmpAdd.setCountry(value.getCountry());
|
newEmpAdd.setZipCode(value.getZipCode());
return newEmpAdd;
}
@Override
public boolean isMutable() {
return true;
}
@Override
public Serializable disassemble(Address value) {
return (Serializable) deepCopy(value);
}
@Override
public Address assemble(Serializable cached, Object owner) {
return deepCopy((Address) cached);
}
@Override
public Address replace(Address detached, Address managed, Object owner) {
return detached;
}
@Override
public boolean isInstance(Object object) {
return CompositeUserType.super.isInstance(object);
}
@Override
public boolean isSameClass(Object object) {
return CompositeUserType.super.isSameClass(object);
}
}
|
repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\customtypes\AddressType.java
| 1
|
请完成以下Java代码
|
public @NonNull TenderType getTenderType(final @NonNull BankAccountId bankAccountId)
{
final BankAccountService bankAccountService = SpringContextHolder.instance.getBean(BankAccountService.class);
if (bankAccountService.isCashBank(bankAccountId))
{
return TenderType.Cash;
}
else
{
return TenderType.Check;
}
}
@Override
public Optional<PaymentId> getByExtIdOrgId(
@NonNull final ExternalId externalId,
@NonNull final OrgId orgId)
{
return paymentDAO.getByExternalId(externalId, orgId)
.map(payment -> PaymentId.ofRepoId(payment.getC_Payment_ID()));
}
@Override
public CurrencyConversionContext extractCurrencyConversionContext(
@NonNull final I_C_Payment payment)
{
final PaymentCurrencyContext paymentCurrencyContext = PaymentCurrencyContext.ofPaymentRecord(payment);
CurrencyConversionContext conversionCtx = currencyConversionBL.createCurrencyConversionContext(
InstantAndOrgId.ofTimestamp(payment.getDateAcct(), OrgId.ofRepoId(payment.getAD_Org_ID())),
paymentCurrencyContext.getCurrencyConversionTypeId(),
ClientId.ofRepoId(payment.getAD_Client_ID()));
final FixedConversionRate fixedConversionRate = paymentCurrencyContext.toFixedConversionRateOrNull();
if (fixedConversionRate != null)
{
conversionCtx = conversionCtx.withFixedConversionRate(fixedConversionRate);
}
return conversionCtx;
}
@Override
public void validateDocTypeIsInSync(@NonNull final I_C_Payment payment)
{
final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(payment.getC_DocType_ID());
if (docTypeId == null)
{
return;
}
final I_C_DocType docType = docTypeBL.getById(docTypeId);
// Invoice
|
final I_C_Invoice invoice = InvoiceId.optionalOfRepoId(payment.getC_Invoice_ID())
.map(invoiceBL::getById)
.orElse(null);
if (invoice != null && invoice.isSOTrx() != docType.isSOTrx())
{
// task: 07564 the SOtrx flags don't match, but that's OK *if* the invoice i a credit memo (either for the vendor or customer side)
if (!invoiceBL.isCreditMemo(invoice))
{
throw new AdempiereException(MSG_PaymentDocTypeInvoiceInconsistent);
}
}
// globalqss - Allow prepayment to Purchase Orders
// Order Waiting Payment (can only be SO)
// if (C_Order_ID != 0 && dt != null && !dt.isSOTrx())
// return "PaymentDocTypeInvoiceInconsistent";
// Order
final OrderId orderId = OrderId.ofRepoIdOrNull(payment.getC_Order_ID());
if (orderId == null)
{
return;
}
final I_C_Order order = orderDAO.getById(orderId);
if (order.isSOTrx() != docType.isSOTrx())
{
throw new AdempiereException(MSG_PaymentDocTypeInvoiceInconsistent);
}
}
@Override
public void reversePaymentById(@NonNull final PaymentId paymentId)
{
final I_C_Payment payment = getById(paymentId);
payment.setDocAction(IDocument.ACTION_Reverse_Correct);
documentBL.processEx(payment, IDocument.ACTION_Reverse_Correct, IDocument.STATUS_Reversed);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\api\impl\PaymentBL.java
| 1
|
请完成以下Java代码
|
public void setDroppedTo(@NonNull LocatorId dropToLocatorId, @NonNull final MovementId dropToMovementId)
{
for (final DDOrderMoveSchedulePickedHU pickedHU : byActualHUIdPicked.values())
{
pickedHU.setDroppedTo(dropToLocatorId, dropToMovementId);
}
}
public ExplainedOptional<LocatorId> getInTransitLocatorId()
{
final ImmutableSet<LocatorId> inTransitLocatorIds = byActualHUIdPicked.values()
.stream()
.map(DDOrderMoveSchedulePickedHU::getInTransitLocatorId)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
if (inTransitLocatorIds.isEmpty())
{
// shall not happen
return ExplainedOptional.emptyBecause("No in transit locator found");
|
}
else if (inTransitLocatorIds.size() == 1)
{
final LocatorId inTransitLocatorId = inTransitLocatorIds.iterator().next();
return ExplainedOptional.of(inTransitLocatorId);
}
else
{
// shall not happen
return ExplainedOptional.emptyBecause("More than one in transit locator found: " + inTransitLocatorIds);
}
}
public ImmutableSet<HuId> getActualHUIdsPicked()
{
return byActualHUIdPicked.keySet();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\DDOrderMoveSchedulePickedHUs.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class LiquibaseConfiguration {
private final Logger log = LoggerFactory.getLogger(LiquibaseConfiguration.class);
private final Environment env;
public LiquibaseConfiguration(Environment env) {
this.env = env;
}
@Value("${application.liquibase.async-start:true}")
private Boolean asyncStart;
@Bean
public SpringLiquibase liquibase(
@Qualifier("taskExecutor") Executor executor,
LiquibaseProperties liquibaseProperties,
@LiquibaseDataSource ObjectProvider<DataSource> liquibaseDataSource,
ObjectProvider<DataSource> dataSource,
DataSourceProperties dataSourceProperties
) {
SpringLiquibase liquibase;
if (Boolean.TRUE.equals(asyncStart)) {
liquibase = SpringLiquibaseUtil.createAsyncSpringLiquibase(
this.env,
executor,
liquibaseDataSource.getIfAvailable(),
liquibaseProperties,
dataSource.getIfUnique(),
dataSourceProperties
);
} else {
liquibase = SpringLiquibaseUtil.createSpringLiquibase(
liquibaseDataSource.getIfAvailable(),
liquibaseProperties,
dataSource.getIfUnique(),
dataSourceProperties
);
}
liquibase.setChangeLog("classpath:config/liquibase/master.xml");
|
liquibase.setContexts(liquibaseProperties.getContexts());
liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema());
liquibase.setLiquibaseSchema(liquibaseProperties.getLiquibaseSchema());
liquibase.setLiquibaseTablespace(liquibaseProperties.getLiquibaseTablespace());
liquibase.setDatabaseChangeLogLockTable(liquibaseProperties.getDatabaseChangeLogLockTable());
liquibase.setDatabaseChangeLogTable(liquibaseProperties.getDatabaseChangeLogTable());
liquibase.setDropFirst(liquibaseProperties.isDropFirst());
liquibase.setLabelFilter(liquibaseProperties.getLabelFilter());
liquibase.setChangeLogParameters(liquibaseProperties.getParameters());
liquibase.setRollbackFile(liquibaseProperties.getRollbackFile());
liquibase.setTestRollbackOnUpdate(liquibaseProperties.isTestRollbackOnUpdate());
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_NO_LIQUIBASE))) {
liquibase.setShouldRun(false);
} else {
liquibase.setShouldRun(liquibaseProperties.isEnabled());
log.debug("Configuring Liquibase");
}
return liquibase;
}
}
|
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\car-app\src\main\java\com\cars\app\config\LiquibaseConfiguration.java
| 2
|
请完成以下Java代码
|
public void restore() {
SecurityContextHolder.clearContext();
}
@Override
@Deprecated(since = "1.3.0", forRemoval = true)
public void reset() {
SecurityContextHolder.clearContext();
}
}
private static final class NoOpAccessor implements ThreadLocalAccessor<Object> {
@Override
public Object key() {
return getClass().getName();
}
@Override
public @Nullable Object getValue() {
return null;
}
@Override
public void setValue(Object value) {
}
@Override
public void setValue() {
}
|
@Override
public void restore(Object previousValue) {
}
@Override
public void restore() {
}
@Override
@Deprecated(since = "1.3.0", forRemoval = true)
public void reset() {
}
}
}
|
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\execution\SecurityContextThreadLocalAccessor.java
| 1
|
请完成以下Spring Boot application配置
|
# ===============================
# = DATA SOURCE
# ===============================
# Set here configurations for the database connection
spring.datasource.url = jdbc:mysql://localhost:3306/netgloo_blog?useSSL=false
spring.datasource.username = root
spring.datasource.password = root
# ===============================
# = JPA SETTINGS
# ===============================
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = create
# Use Jadira Usertype for mapping Joda T
|
ime types
# For Hibernate native properties must be used spring.jpa.properties.* (the
# prefix is stripped before adding them to the entity manager).
spring.jpa.properties.jadira.usertype.autoRegisterUserTypes = true
|
repos\spring-boot-samples-master\spring-boot-hibernate-joda-time\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public Date getEndTime() {
return historicProcessInstance.getEndTime();
}
@Override
public Long getDurationInMillis() {
return historicProcessInstance.getDurationInMillis();
}
@Override
public String getStartUserId() {
return historicProcessInstance.getStartUserId();
}
@Override
public String getStartActivityId() {
return historicProcessInstance.getStartActivityId();
}
@Override
public String getDeleteReason() {
return historicProcessInstance.getDeleteReason();
}
@Override
public String getSuperProcessInstanceId() {
return historicProcessInstance.getSuperProcessInstanceId();
}
@Override
public String getTenantId() {
return historicProcessInstance.getTenantId();
}
@Override
public List<HistoricData> getHistoricData() {
return historicData;
}
|
public void addHistoricData(HistoricData historicEvent) {
historicData.add(historicEvent);
}
public void addHistoricData(Collection<? extends HistoricData> historicEvents) {
historicData.addAll(historicEvents);
}
public void orderHistoricData() {
Collections.sort(
historicData,
new Comparator<HistoricData>() {
@Override
public int compare(HistoricData data1, HistoricData data2) {
return data1.getTime().compareTo(data2.getTime());
}
}
);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ProcessInstanceHistoryLogImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void updateData(PmsRole pmsRole) {
pmsRoleDao.update(pmsRole);
}
/**
* 根据id获取数据pmsOperator
*
* @param id
* @return
*/
public PmsRole getDataById(Long id) {
return pmsRoleDao.getById(id);
}
/**
* 分页查询pmsOperator
*
* @param pageParam
* @param ActivityVo
* PmsOperator
* @return
*/
public PageBean listPage(PageParam pageParam, PmsRole pmsRole) {
Map<String, Object> paramMap = new HashMap<String, Object>(); // 业务条件查询参数
paramMap.put("roleName", pmsRole.getRoleName()); // 角色名称(模糊查询)
return pmsRoleDao.listPage(pageParam, paramMap);
}
/**
* 获取所有角色列表,以供添加操作员时选择.
*
* @return roleList .
*/
public List<PmsRole> listAllRole() {
return pmsRoleDao.listAll();
}
|
/**
* 判断此权限是否关联有角色
*
* @param permissionId
* @return
*/
public List<PmsRole> listByPermissionId(Long permissionId) {
return pmsRoleDao.listByPermissionId(permissionId);
}
/**
* 根据角色名或者角色编号查询角色
*
* @param roleName
* @param roleCode
* @return
*/
public PmsRole getByRoleNameOrRoleCode(String roleName, String roleCode) {
return pmsRoleDao.getByRoleNameOrRoleCode(roleName, roleCode);
}
/**
* 删除
*
* @param roleId
*/
public void delete(Long roleId) {
pmsRoleDao.delete(roleId);
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\service\impl\PmsRoleServiceImpl.java
| 2
|
请完成以下Java代码
|
public static boolean shouldInclude(Term term)
{
return FILTER.shouldInclude(term);
}
/**
* 是否应当去掉这个词
* @param term 词
* @return 是否应当去掉
*/
public static boolean shouldRemove(Term term)
{
return !shouldInclude(term);
}
/**
* 加入停用词到停用词词典中
* @param stopWord 停用词
* @return 词典是否发生了改变
*/
public static boolean add(String stopWord)
{
return dictionary.add(stopWord);
}
/**
|
* 从停用词词典中删除停用词
* @param stopWord 停用词
* @return 词典是否发生了改变
*/
public static boolean remove(String stopWord)
{
return dictionary.remove(stopWord);
}
/**
* 对分词结果应用过滤
* @param termList
*/
public static List<Term> apply(List<Term> termList)
{
ListIterator<Term> listIterator = termList.listIterator();
while (listIterator.hasNext())
{
if (shouldRemove(listIterator.next())) listIterator.remove();
}
return termList;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\stopword\CoreStopWordDictionary.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<RouteProperties> getRoutes() {
return routes;
}
public void setRoutes(List<RouteProperties> routes) {
this.routes = routes;
}
public LinkedHashMap<String, RouteProperties> getRoutesMap() {
return routesMap;
}
public void setRoutesMap(LinkedHashMap<String, RouteProperties> routesMap) {
this.routesMap = routesMap;
}
public List<MediaType> getStreamingMediaTypes() {
return streamingMediaTypes;
}
public void setStreamingMediaTypes(List<MediaType> streamingMediaTypes) {
this.streamingMediaTypes = streamingMediaTypes;
}
public boolean isUseFrameworkRetryFilter() {
return useFrameworkRetryFilter;
}
public void setUseFrameworkRetryFilter(boolean useFrameworkRetryFilter) {
this.useFrameworkRetryFilter = useFrameworkRetryFilter;
}
public int getStreamingBufferSize() {
return streamingBufferSize;
}
|
public void setStreamingBufferSize(int streamingBufferSize) {
this.streamingBufferSize = streamingBufferSize;
}
public @Nullable String getTrustedProxies() {
return trustedProxies;
}
public void setTrustedProxies(String trustedProxies) {
this.trustedProxies = trustedProxies;
}
@Override
public String toString() {
return new ToStringCreator(this).append("routes", routes)
.append("routesMap", routesMap)
.append("streamingMediaTypes", streamingMediaTypes)
.append("streamingBufferSize", streamingBufferSize)
.append("trustedProxies", trustedProxies)
.toString();
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\config\GatewayMvcProperties.java
| 2
|
请完成以下Java代码
|
public boolean containsAll(Collection<?> c)
{
for (Object e : c)
if (!contains(e))
return false;
return true;
}
@Override
public boolean addAll(Collection<? extends String> c)
{
boolean modified = false;
for (String e : c)
if (add(e))
modified = true;
return modified;
}
@Override
public boolean retainAll(Collection<?> c)
{
boolean modified = false;
Iterator<String> it = iterator();
while (it.hasNext())
{
if (!c.contains(it.next()))
{
it.remove();
modified = true;
}
}
return modified;
|
}
@Override
public boolean removeAll(Collection<?> c)
{
boolean modified = false;
Iterator<?> it = iterator();
while (it.hasNext())
{
if (c.contains(it.next()))
{
it.remove();
modified = true;
}
}
return modified;
}
@Override
public void clear()
{
sourceNode = new MDAGNode(false);
simplifiedSourceNode = null;
if (equivalenceClassMDAGNodeHashMap != null)
equivalenceClassMDAGNodeHashMap.clear();
mdagDataArray = null;
charTreeSet.clear();
transitionCount = 0;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\MDAG\MDAGSet.java
| 1
|
请完成以下Java代码
|
public void sendAsyncMsg() {
Map<String, Object> map = new HashMap<>();
map.put( "name", "zs" );
map.put( "age", 20 );
rocketMQTemplate.asyncSend( "Topic-Normal", map, new SendCallback() {
@Override
public void onSuccess(SendResult sendResult) {
// 消息发送成功。
log.info( "async send success" );
}
@Override
public void onException(Throwable throwable) {
// 消息发送失败,需要进行重试处理,可重新发送这条消息或持久化这条数据进行补偿处理。
log.info( "async send fail" );
}
} );
}
/**
* 顺序消息
*/
public void sendOrderlyMsg() {
//根据指定的hashKey按顺序发送
for (int i = 0; i < 1000; i++) {
String orderId = "biz_" + i % 10;
// 分区顺序消息中区分不同分区的关键字段,Sharding Key与普通消息的key是完全不同的概念。
// 全局顺序消息,该字段可以设置为任意非空字符串。
String shardingKey = String.valueOf( orderId );
try {
SendResult sendResult = rocketMQTemplate.syncSendOrderly( "Topic-Order", "send order msg".getBytes(), shardingKey );
// 发送消息,只要不抛异常就是成功。
if (sendResult != null) {
System.out.println( new Date() + " Send mq message success . msgId is:" + sendResult.getMsgId() );
}
} catch (Exception e) {
// 消息发送失败,需要进行重试处理,可重新发送这条消息或持久化这条数据进行补偿处理。
System.out.println( new Date() + " Send mq message failed" );
e.printStackTrace();
}
}
}
/**
* 延时消息
*/
public void sendDelayMsg() {
rocketMQTemplate.syncSend( "Topic-Delay",
MessageBuilder.withPayload( "Hello MQ".getBytes() ).build(),
3000,
//设置延时等级3,这个消息将在10s之后发送(现在只支持固定的几个时间,详看delayTimeLevel)
//messageDelayLevel = "1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h";
3 );
}
|
/**
* 批量消息
*/
public void sendBatchMsg(List<Message> messages) {
rocketMQTemplate.syncSend( "springboot-rocketmq", messages );
}
/**
* 事务消息
*/
public void sendTransactionMsg(){
TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction(
"Topic-Tx:TagA",
MessageBuilder.withPayload( "Hello MQ transaction===".getBytes() ).build(),
null );
SendStatus sendStatus = transactionSendResult.getSendStatus();
LocalTransactionState localTransactionState = transactionSendResult.getLocalTransactionState();
System.out.println( new Date() + " Send mq message status "+ sendStatus +" , localTransactionState "+ localTransactionState );
}
}
|
repos\SpringBootLearning-master (1)\springboot-rocketmq-message\src\main\java\com\itwolfed\msg\Producer.java
| 1
|
请完成以下Java代码
|
public ImmutableCollection<DDOrderMoveSchedulePickedHU> toCollection()
{
return byActualHUIdPicked.values();
}
public Quantity getQtyPicked()
{
return byActualHUIdPicked.values()
.stream()
.map(DDOrderMoveSchedulePickedHU::getQtyPicked)
.reduce(Quantity::add)
.orElseThrow(() -> new IllegalStateException("empty list: " + this));
}
public boolean isDroppedTo()
{
return byActualHUIdPicked.values().stream().allMatch(DDOrderMoveSchedulePickedHU::isDroppedTo);
}
public void setDroppedTo(@NonNull LocatorId dropToLocatorId, @NonNull final MovementId dropToMovementId)
{
for (final DDOrderMoveSchedulePickedHU pickedHU : byActualHUIdPicked.values())
{
pickedHU.setDroppedTo(dropToLocatorId, dropToMovementId);
}
}
public ExplainedOptional<LocatorId> getInTransitLocatorId()
{
final ImmutableSet<LocatorId> inTransitLocatorIds = byActualHUIdPicked.values()
.stream()
.map(DDOrderMoveSchedulePickedHU::getInTransitLocatorId)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
if (inTransitLocatorIds.isEmpty())
{
|
// shall not happen
return ExplainedOptional.emptyBecause("No in transit locator found");
}
else if (inTransitLocatorIds.size() == 1)
{
final LocatorId inTransitLocatorId = inTransitLocatorIds.iterator().next();
return ExplainedOptional.of(inTransitLocatorId);
}
else
{
// shall not happen
return ExplainedOptional.emptyBecause("More than one in transit locator found: " + inTransitLocatorIds);
}
}
public ImmutableSet<HuId> getActualHUIdsPicked()
{
return byActualHUIdPicked.keySet();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\DDOrderMoveSchedulePickedHUs.java
| 1
|
请完成以下Java代码
|
public final class NullValidationRule implements IValidationRule
{
public static final NullValidationRule instance = new NullValidationRule();
public static boolean isNull(final IValidationRule rule)
{
return rule == null || rule == instance;
}
private NullValidationRule()
{
super();
}
@Override
public boolean isImmutable()
|
{
return true;
}
@Override
public Set<String> getAllParameters()
{
return ImmutableSet.of();
}
@Override
public IStringExpression getPrefilterWhereClause()
{
return IStringExpression.NULL;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\validationRule\impl\NullValidationRule.java
| 1
|
请完成以下Java代码
|
public String getClientSoftwareKennung() {
return clientSoftwareKennung;
}
/**
* Sets the value of the clientSoftwareKennung property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClientSoftwareKennung(String value) {
this.clientSoftwareKennung = value;
}
/**
* Gets the value of the ruecknahmeangebot property.
*
* @return
* possible object is
* {@link Ruecknahmeangebot }
|
*
*/
public Ruecknahmeangebot getRuecknahmeangebot() {
return ruecknahmeangebot;
}
/**
* Sets the value of the ruecknahmeangebot property.
*
* @param value
* allowed object is
* {@link Ruecknahmeangebot }
*
*/
public void setRuecknahmeangebot(Ruecknahmeangebot value) {
this.ruecknahmeangebot = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\RuecknahmeangebotAnfordern.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return expressionStr;
}
@Override
public int hashCode()
{
return Objects.hash(parameter);
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final SingleParameterStringExpression other = (SingleParameterStringExpression)obj;
return Objects.equals(parameter, other.parameter);
}
@Override
public String getExpressionString()
{
return expressionStr;
}
@Override
public String getFormatedExpressionString()
{
return parameter.toStringWithMarkers();
}
|
@Override
public Set<CtxName> getParameters()
{
return parametersAsCtxName;
}
@Override
public String evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException
{
try
{
return StringExpressionsHelper.evaluateParam(parameter, ctx, onVariableNotFound);
}
catch (final Exception e)
{
throw ExpressionEvaluationException.wrapIfNeeded(e)
.addExpression(this);
}
}
@Override
public IStringExpression resolvePartial(final Evaluatee ctx) throws ExpressionEvaluationException
{
try
{
final String value = StringExpressionsHelper.evaluateParam(parameter, ctx, OnVariableNotFound.ReturnNoResult);
if (value == null || value == EMPTY_RESULT)
{
return this;
}
return ConstantStringExpression.of(value);
}
catch (final Exception e)
{
throw ExpressionEvaluationException.wrapIfNeeded(e)
.addExpression(this);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\SingleParameterStringExpression.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PushBOMProductsProcessor implements Processor
{
@Override
public void process(final Exchange exchange) throws Exception
{
final PushBOMsRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange, GRSSignumConstants.ROUTE_PROPERTY_PUSH_BOMs_CONTEXT, PushBOMsRouteContext.class);
final JsonBOM jsonBOM = context.getJsonBOM();
final BOMUpsertCamelRequest camelRequest = getBOMUpsertCamelRequest(jsonBOM);
exchange.getIn().setBody(camelRequest, BOMUpsertCamelRequest.class);
}
@NonNull
private BOMUpsertCamelRequest getBOMUpsertCamelRequest(@NonNull final JsonBOM jsonBOM)
{
if (jsonBOM.getBomLines().isEmpty())
{
throw new RuntimeCamelException("Missing lines!");
}
final List<JsonCreateBOMLine> bomLines = jsonBOM.getBomLines()
.stream()
.map(line -> getJsonCreateBOMLine(line, jsonBOM.getScrap()))
.collect(ImmutableList.toImmutableList());
final JsonBOMCreateRequest jsonBOMCreateRequest = JsonBOMCreateRequest.builder()
.uomCode(GRSSignumConstants.DEFAULT_UOM_CODE)
.productIdentifier(ExternalIdentifierFormat.asExternalIdentifier(jsonBOM.getProductId()))
.name(JsonBOMUtil.getName(jsonBOM))
.isActive(jsonBOM.isActive())
.validFrom(SystemTime.asInstant())
.bomLines(bomLines)
.build();
return getBOMUpsertCamelRequest(jsonBOMCreateRequest);
}
@NonNull
private static JsonCreateBOMLine getJsonCreateBOMLine(@NonNull final JsonBOMLine jsonBOMLine, @Nullable final BigDecimal scrap)
{
final JsonCreateBOMLine.JsonCreateBOMLineBuilder jsonCreateBOMLineBuilder = JsonCreateBOMLine.builder()
.productIdentifier(ExternalIdentifierFormat.asExternalIdentifier(jsonBOMLine.getProductId()))
.line(jsonBOMLine.getLine())
.isQtyPercentage(Boolean.TRUE)
.qtyBom(JsonQuantity.builder()
.qty(jsonBOMLine.getQtyBOM())
|
.uomCode(jsonBOMLine.getUom())
.build())
.scrap(scrap);
if (Check.isNotBlank(jsonBOMLine.getCountryCode()))
{
jsonCreateBOMLineBuilder.attributeSetInstance(JsonAttributeSetInstance.builder()
.attributeInstance(JsonAttributeInstance.builder()
.attributeCode(GRSSignumConstants.HERKUNFT_ATTRIBUTE_CODE)
.valueStr(jsonBOMLine.getCountryCode())
.build())
.build());
}
return jsonCreateBOMLineBuilder.build();
}
@NonNull
private static BOMUpsertCamelRequest getBOMUpsertCamelRequest(@NonNull final JsonBOMCreateRequest jsonRequest)
{
final TokenCredentials credentials = (TokenCredentials)SecurityContextHolder.getContext().getAuthentication().getCredentials();
return BOMUpsertCamelRequest.builder()
.jsonBOMCreateRequest(jsonRequest)
.orgCode(credentials.getOrgCode())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\from_grs\bom\processor\PushBOMProductsProcessor.java
| 2
|
请完成以下Java代码
|
public void cleanContainer(Integer ID) {
cleanContainer("" + ID);
}
/**
* Clean ContainerCache for this ID
* @param ID for container to clean
*/
public void cleanContainer(String ID) {
runURLRequest("Container", ID);
}
/**
* Clean ContainerTreeCache for this WebProjectID
* @param ID for Container to clean
*/
public void cleanContainerTree(Integer ID) {
cleanContainerTree("" + ID);
}
/**
* Clean ContainerTreeCache for this WebProjectID
* @param ID for container to clean
*/
public void cleanContainerTree(String ID) {
runURLRequest("ContainerTree", ID);
}
/**
* Clean Container Element for this ID
* @param ID for container element to clean
*/
public void cleanContainerElement(Integer ID) {
cleanContainerElement("" + ID);
}
/**
* Clean Container Element for this ID
* @param ID for container element to clean
*/
public void cleanContainerElement(String ID) {
runURLRequest("ContainerElement", ID);
}
private void runURLRequest(String cache, String ID) {
String thisURL = null;
for(int i=0; i<cacheURLs.length; i++) {
try {
|
thisURL = "http://" + cacheURLs[i] + "/cache/Service?Cache=" + cache + "&ID=" + ID;
URL url = new URL(thisURL);
Proxy thisProxy = Proxy.NO_PROXY;
URLConnection urlConn = url.openConnection(thisProxy);
urlConn.setUseCaches(false);
urlConn.connect();
Reader stream = new java.io.InputStreamReader(
urlConn.getInputStream());
StringBuffer srvOutput = new StringBuffer();
try {
int c;
while ( (c=stream.read()) != -1 )
srvOutput.append( (char)c );
} catch (Exception E2) {
E2.printStackTrace();
}
} catch (IOException E) {
if (log!=null)
log.warn("Can't clean cache at:" + thisURL + " be carefull, your deployment server may use invalid or old cache data!");
}
}
}
/**
* Converts JNP URL to http URL for cache cleanup
* @param JNPURL String with JNP URL from Context
* @return clean servername
*/
public static String convertJNPURLToCacheURL(String JNPURL) {
if (JNPURL.indexOf("jnp://")>=0) {
JNPURL = JNPURL.substring(JNPURL.indexOf("jnp://")+6);
}
if (JNPURL.indexOf(':')>=0) {
JNPURL = JNPURL.substring(0,JNPURL.indexOf(':'));
}
if (JNPURL.length()>0) {
return JNPURL;
} else {
return null;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\cm\CacheHandler.java
| 1
|
请完成以下Java代码
|
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public int getAge() {
return age;
}
public void setAge(final int age) {
this.age = age;
}
public LocalDate getCreationDate() {
return creationDate;
}
public LocalDate getLastLoginDate() {
return lastLoginDate;
}
public void setLastLoginDate(LocalDate lastLoginDate) {
this.lastLoginDate = lastLoginDate;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
@Override
public String toString() {
return "User [name=" + name + ", id=" + id + "]";
}
|
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return id == user.id &&
age == user.age &&
Objects.equals(name, user.name) &&
Objects.equals(creationDate, user.creationDate) &&
Objects.equals(email, user.email) &&
Objects.equals(status, user.status);
}
@Override
public int hashCode() {
return Objects.hash(id, name, creationDate, age, email, status);
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-simple\src\main\java\com\baeldung\jpa\query\model\User.java
| 1
|
请完成以下Java代码
|
public Criteria andReplayCountNotIn(List<Integer> values) {
addCriterion("replay_count not in", values, "replayCount");
return (Criteria) this;
}
public Criteria andReplayCountBetween(Integer value1, Integer value2) {
addCriterion("replay_count between", value1, value2, "replayCount");
return (Criteria) this;
}
public Criteria andReplayCountNotBetween(Integer value1, Integer value2) {
addCriterion("replay_count not between", value1, value2, "replayCount");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
|
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsCommentExample.java
| 1
|
请完成以下Java代码
|
public long getLastHeartbeat() {
return lastHeartbeat;
}
public void setLastHeartbeat(long lastHeartbeat) {
this.lastHeartbeat = lastHeartbeat;
}
public void setHeartbeatVersion(long heartbeatVersion) {
this.heartbeatVersion = heartbeatVersion;
}
public long getHeartbeatVersion() {
return heartbeatVersion;
}
public String getVersion() {
return version;
|
}
public MachineInfoVo setVersion(String version) {
this.version = version;
return this;
}
public boolean isHealthy() {
return healthy;
}
public void setHealthy(boolean healthy) {
this.healthy = healthy;
}
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\vo\MachineInfoVo.java
| 1
|
请完成以下Java代码
|
public ResponseEntity<Object> updateDeploy(@Validated @RequestBody Deploy resources){
deployService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除部署")
@ApiOperation(value = "删除部署")
@DeleteMapping
@PreAuthorize("@el.check('deploy:del')")
public ResponseEntity<Object> deleteDeploy(@RequestBody Set<Long> ids){
deployService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
@Log("上传文件部署")
@ApiOperation(value = "上传文件部署")
@PostMapping(value = "/upload")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> uploadDeploy(@RequestBody MultipartFile file, HttpServletRequest request)throws Exception{
Long id = Long.valueOf(request.getParameter("id"));
String fileName = "";
if(file != null){
fileName = FileUtil.verifyFilename(file.getOriginalFilename());
File deployFile = new File(fileSavePath + fileName);
FileUtil.del(deployFile);
file.transferTo(deployFile);
//文件下一步要根据文件名字来
deployService.deploy(fileSavePath + fileName ,id);
}else{
log.warn("没有找到相对应的文件");
}
Map<String,Object> map = new HashMap<>(2);
map.put("error",0);
map.put("id",fileName);
return new ResponseEntity<>(map,HttpStatus.OK);
}
@Log("系统还原")
@ApiOperation(value = "系统还原")
@PostMapping(value = "/serverReduction")
@PreAuthorize("@el.check('deploy:edit')")
|
public ResponseEntity<Object> serverReduction(@Validated @RequestBody DeployHistory resources){
String result = deployService.serverReduction(resources);
return new ResponseEntity<>(result,HttpStatus.OK);
}
@Log("服务运行状态")
@ApiOperation(value = "服务运行状态")
@PostMapping(value = "/serverStatus")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> serverStatus(@Validated @RequestBody Deploy resources){
String result = deployService.serverStatus(resources);
return new ResponseEntity<>(result,HttpStatus.OK);
}
@Log("启动服务")
@ApiOperation(value = "启动服务")
@PostMapping(value = "/startServer")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> startServer(@Validated @RequestBody Deploy resources){
String result = deployService.startServer(resources);
return new ResponseEntity<>(result,HttpStatus.OK);
}
@Log("停止服务")
@ApiOperation(value = "停止服务")
@PostMapping(value = "/stopServer")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> stopServer(@Validated @RequestBody Deploy resources){
String result = deployService.stopServer(resources);
return new ResponseEntity<>(result,HttpStatus.OK);
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\rest\DeployController.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<GroupResponse> getGroups(@PathVariable String privilegeId) {
Privilege privilege = getPrivilegeById(privilegeId);
if (restApiInterceptor != null) {
restApiInterceptor.accessPrivilegeInfoById(privilege);
}
List<Group> groups = identityService.getGroupsWithPrivilege(privilegeId);
return idmRestResponseFactory.createGroupResponseList(groups);
}
@ApiOperation(value = "Deletes a privilege for a group", nickname = "deleteGroupPrivilege", tags = { "Privileges" })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates the group privilege has been deleted")
})
@DeleteMapping(value = "/privileges/{privilegeId}/group/{groupId}")
public void deleteGroupPrivilege(@PathVariable String privilegeId, @PathVariable String groupId) {
Privilege privilege = getPrivilegeById(privilegeId);
if (restApiInterceptor != null) {
restApiInterceptor.deleteGroupPrivilege(privilege, groupId);
}
identityService.deleteGroupPrivilegeMapping(privilegeId, groupId);
}
@ApiOperation(value = "Adds a privilege for a group", nickname = "addGroupPrivilege", tags = { "Privileges" })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates the group privilege has been added")
})
@PostMapping(value = "privileges/{privilegeId}/groups")
public void addGroupPrivilege(@PathVariable String privilegeId, @RequestBody AddGroupPrivilegeRequest request) {
Privilege privilege = getPrivilegeById(privilegeId);
|
if (restApiInterceptor != null) {
restApiInterceptor.addGroupPrivilege(privilege, request.getGroupId());
}
identityService.addGroupPrivilegeMapping(privilegeId, request.getGroupId());
}
protected Privilege getPrivilegeById(String privilegeId) {
Privilege privilege = identityService.createPrivilegeQuery().privilegeId(privilegeId).singleResult();
if (privilege == null) {
throw new FlowableObjectNotFoundException("Could not find privilege with id " + privilegeId, Privilege.class);
}
return privilege;
}
}
|
repos\flowable-engine-main\modules\flowable-idm-rest\src\main\java\org\flowable\idm\rest\service\api\privilege\PrivilegeCollectionResource.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class RetryTopicConfiguration {
private final List<DestinationTopic.Properties> destinationTopicProperties;
private final AllowDenyCollectionManager<String> topicAllowListManager;
private final @Nullable EndpointHandlerMethod dltHandlerMethod;
private final TopicCreation kafkaTopicAutoCreationConfig;
private final ListenerContainerFactoryResolver.Configuration factoryResolverConfig;
@Nullable
private final Integer concurrency;
RetryTopicConfiguration(List<DestinationTopic.Properties> destinationTopicProperties,
@Nullable EndpointHandlerMethod dltHandlerMethod,
TopicCreation kafkaTopicAutoCreationConfig,
AllowDenyCollectionManager<String> topicAllowListManager,
ListenerContainerFactoryResolver.Configuration factoryResolverConfig,
@Nullable Integer concurrency) {
this.destinationTopicProperties = destinationTopicProperties;
this.dltHandlerMethod = dltHandlerMethod;
this.kafkaTopicAutoCreationConfig = kafkaTopicAutoCreationConfig;
this.topicAllowListManager = topicAllowListManager;
this.factoryResolverConfig = factoryResolverConfig;
this.concurrency = concurrency;
}
public boolean hasConfigurationForTopics(String[] topics) {
return this.topicAllowListManager.areAllowed(topics);
}
public TopicCreation forKafkaTopicAutoCreation() {
return this.kafkaTopicAutoCreationConfig;
}
public ListenerContainerFactoryResolver.Configuration forContainerFactoryResolver() {
return this.factoryResolverConfig;
}
public @Nullable EndpointHandlerMethod getDltHandlerMethod() {
return this.dltHandlerMethod;
}
public List<DestinationTopic.Properties> getDestinationTopicProperties() {
return this.destinationTopicProperties;
}
@Nullable
public Integer getConcurrency() {
return this.concurrency;
}
static class TopicCreation {
private final boolean shouldCreateTopics;
private final int numPartitions;
private final short replicationFactor;
TopicCreation(@Nullable Boolean shouldCreate, @Nullable Integer numPartitions, @Nullable Short replicationFactor) {
|
this.shouldCreateTopics = shouldCreate == null || shouldCreate;
this.numPartitions = numPartitions == null ? 1 : numPartitions;
this.replicationFactor = replicationFactor == null ? -1 : replicationFactor;
}
TopicCreation() {
this.shouldCreateTopics = true;
this.numPartitions = 1;
this.replicationFactor = -1;
}
TopicCreation(boolean shouldCreateTopics) {
this.shouldCreateTopics = shouldCreateTopics;
this.numPartitions = 1;
this.replicationFactor = -1;
}
public int getNumPartitions() {
return this.numPartitions;
}
public short getReplicationFactor() {
return this.replicationFactor;
}
public boolean shouldCreateTopics() {
return this.shouldCreateTopics;
}
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\RetryTopicConfiguration.java
| 2
|
请完成以下Java代码
|
public class DomXmlEnsure extends EnsureUtil {
private static final DomXmlLogger LOG = DomXmlLogger.XML_DOM_LOGGER;
private static final String ROOT_EXPRESSION = "/";
/**
* Ensures that the element is child element of the parent element.
*
* @param parentElement the parent xml dom element
* @param childElement the child element
* @throws SpinXmlElementException if the element is not child of the parent element
*/
public static void ensureChildElement(DomXmlElement parentElement, DomXmlElement childElement) {
Node parent = childElement.unwrap().getParentNode();
if (parent == null || !parentElement.unwrap().isEqualNode(parent)) {
throw LOG.elementIsNotChildOfThisElement(childElement, parentElement);
}
}
/**
* Ensures that the expression is not the root expression '/'.
*
* @param expression the expression to ensure to be not the root expression '/'
* @throws SpinXPathException if the expression is the root expression '/'
*/
public static void ensureNotDocumentRootExpression(String expression) {
if (ROOT_EXPRESSION.equals(expression)) {
throw LOG.notAllowedXPathExpression(expression);
}
}
/**
* Ensure that the node is not null.
*
* @param node the node to ensure to be not null
* @param expression the expression was used to find the node
* @throws SpinXPathException if the node is null
*/
|
public static void ensureXPathNotNull(Node node, String expression) {
if (node == null) {
throw LOG.unableToFindXPathExpression(expression);
}
}
/**
* Ensure that the nodeList is either null or empty.
*
* @param nodeList the nodeList to ensure to be either null or empty
* @param expression the expression was used to fine the nodeList
* @throws SpinXPathException if the nodeList is either null or empty
*/
public static void ensureXPathNotEmpty(NodeList nodeList, String expression) {
if (nodeList == null || nodeList.getLength() == 0) {
throw LOG.unableToFindXPathExpression(expression);
}
}
}
|
repos\camunda-bpm-platform-master\spin\dataformat-xml-dom\src\main\java\org\camunda\spin\impl\xml\dom\util\DomXmlEnsure.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public final GrpcChannelProperties getGlobalChannel() {
// This cannot be moved to its own field,
// as Spring replaces the instance in the map and inconsistencies would occur.
return getRawChannel(GLOBAL_PROPERTIES_KEY);
}
/**
* Gets or creates the channel properties for the given client.
*
* @param name The name of the channel to get the properties for.
* @return The properties for the given channel name.
*/
private GrpcChannelProperties getRawChannel(final String name) {
return this.client.computeIfAbsent(name, key -> new GrpcChannelProperties());
}
private String defaultScheme;
/**
* Get the default scheme that should be used, if the client doesn't specify a scheme/address.
*
* @return The default scheme to use or null.
* @see #setDefaultScheme(String)
*/
|
public String getDefaultScheme() {
return this.defaultScheme;
}
/**
* Sets the default scheme to use, if the client doesn't specify a scheme/address. If not specified it will default
* to the default scheme of the {@link io.grpc.NameResolver.Factory}. Examples: {@code dns}, {@code discovery}.
*
* @param defaultScheme The default scheme to use or null.
*/
public void setDefaultScheme(String defaultScheme) {
this.defaultScheme = defaultScheme;
}
}
|
repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\config\GrpcChannelsProperties.java
| 2
|
请完成以下Java代码
|
public class MergeSort {
public static void main(String[] args) {
int[] a = { 5, 1, 6, 2, 3, 4 };
mergeSort(a, a.length);
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
}
public static void mergeSort(int[] a, int n) {
if (n < 2)
return;
int mid = n / 2;
int[] l = new int[mid];
int[] r = new int[n - mid];
for (int i = 0; i < mid; i++) {
l[i] = a[i];
}
for (int i = mid; i < n; i++) {
r[i - mid] = a[i];
}
mergeSort(l, mid);
mergeSort(r, n - mid);
merge(a, l, r, mid, n - mid);
}
public static void merge(int[] a, int[] l, int[] r, int left, int right) {
int i = 0, j = 0, k = 0;
|
while (i < left && j < right) {
if (l[i] <= r[j])
a[k++] = l[i++];
else
a[k++] = r[j++];
}
while (i < left)
a[k++] = l[i++];
while (j < right)
a[k++] = r[j++];
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-sorting\src\main\java\com\baeldung\algorithms\mergesort\MergeSort.java
| 1
|
请完成以下Java代码
|
public ImportTableDescriptor getByTableName(@NonNull final String tableName)
{
final AdTableId adTableId = AdTableId.ofRepoId(adTablesRepo.retrieveTableId(tableName));
return getByTableId(adTableId);
}
private ImportTableDescriptor retrieveByTableId(@NonNull final AdTableId adTableId)
{
final POInfo poInfo = POInfo.getPOInfo(adTableId);
Check.assumeNotNull(poInfo, "poInfo is not null for AD_Table_ID={}", adTableId);
final String tableName = poInfo.getTableName();
final String keyColumnName = poInfo.getKeyColumnName();
if (keyColumnName == null)
{
throw new AdempiereException("Table " + tableName + " has not primary key");
}
assertColumnNameExists(ImportTableDescriptor.COLUMNNAME_C_DataImport_Run_ID, poInfo);
assertColumnNameExists(ImportTableDescriptor.COLUMNNAME_I_ErrorMsg, poInfo);
return ImportTableDescriptor.builder()
.tableName(tableName)
.keyColumnName(keyColumnName)
//
.dataImportConfigIdColumnName(columnNameIfExists(COLUMNNAME_C_DataImport_ID, poInfo))
.adIssueIdColumnName(columnNameIfExists(COLUMNNAME_AD_Issue_ID, poInfo))
.importLineContentColumnName(columnNameIfExists(COLUMNNAME_I_LineContent, poInfo))
.importLineNoColumnName(columnNameIfExists(COLUMNNAME_I_LineNo, poInfo))
.errorMsgMaxLength(poInfo.getFieldLength(ImportTableDescriptor.COLUMNNAME_I_ErrorMsg))
//
.build();
}
|
private static void assertColumnNameExists(@NonNull final String columnName, @NonNull final POInfo poInfo)
{
if (!poInfo.hasColumnName(columnName))
{
throw new AdempiereException("No " + poInfo.getTableName() + "." + columnName + " defined");
}
}
private static String columnNameIfExists(@NonNull final String columnName, @NonNull final POInfo poInfo)
{
return poInfo.hasColumnName(columnName) ? columnName : null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\format\ImportTableDescriptorRepository.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public BeanDefinition parse(Element element, ParserContext parserContext) {
registerProcessScope(element, parserContext);
registerStateHandlerAnnotationBeanFactoryPostProcessor(element, parserContext);
registerProcessStartAnnotationBeanPostProcessor(element, parserContext);
return null;
}
private void configureProcessEngine(AbstractBeanDefinition abstractBeanDefinition, Element element) {
String procEngineRef = element.getAttribute(processEngineAttribute);
if (StringUtils.hasText(procEngineRef))
abstractBeanDefinition.getPropertyValues().add(Conventions.attributeNameToPropertyName(processEngineAttribute), new RuntimeBeanReference(procEngineRef));
}
private void registerStateHandlerAnnotationBeanFactoryPostProcessor(Element element, ParserContext context) {
Class clz = StateHandlerAnnotationBeanFactoryPostProcessor.class;
BeanDefinitionBuilder postProcessorBuilder = BeanDefinitionBuilder.genericBeanDefinition(clz.getName());
BeanDefinitionHolder postProcessorHolder = new BeanDefinitionHolder(
postProcessorBuilder.getBeanDefinition(),
ActivitiContextUtils.ANNOTATION_STATE_HANDLER_BEAN_FACTORY_POST_PROCESSOR_BEAN_NAME);
configureProcessEngine(postProcessorBuilder.getBeanDefinition(), element);
BeanDefinitionReaderUtils.registerBeanDefinition(postProcessorHolder, context.getRegistry());
}
private void registerProcessScope(Element element, ParserContext parserContext) {
Class clz = ProcessScope.class;
BeanDefinitionBuilder processScopeBDBuilder = BeanDefinitionBuilder.genericBeanDefinition(clz);
AbstractBeanDefinition scopeBeanDefinition = processScopeBDBuilder.getBeanDefinition();
scopeBeanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
configureProcessEngine(scopeBeanDefinition, element);
String beanName = baseBeanName(clz);
parserContext.getRegistry().registerBeanDefinition(beanName, scopeBeanDefinition);
}
|
private void registerProcessStartAnnotationBeanPostProcessor(Element element, ParserContext parserContext) {
Class clz = ProcessStartAnnotationBeanPostProcessor.class;
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clz);
AbstractBeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
configureProcessEngine(beanDefinition, element);
String beanName = baseBeanName(clz);
parserContext.getRegistry().registerBeanDefinition(beanName, beanDefinition);
}
private String baseBeanName(Class cl) {
return cl.getName().toLowerCase();
}
}
|
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\components\config\xml\ActivitiAnnotationDrivenBeanDefinitionParser.java
| 2
|
请完成以下Java代码
|
public void registerCallout()
{
Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this);
}
@CalloutMethod(columnNames = I_C_RemittanceAdvice.COLUMNNAME_C_DocType_ID)
public void updateFromDocType(final I_C_RemittanceAdvice remittanceAdviceRecord, final ICalloutField field)
{
final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(remittanceAdviceRecord.getC_DocType_ID());
if (docTypeId == null)
{
return;
}
final I_C_DocType docType = docTypeDAO.getById(docTypeId);
final IDocumentNoInfo documentNoInfo = Services.get(IDocumentNoBuilderFactory.class)
.createPreliminaryDocumentNoBuilder()
.setNewDocType(docType)
.setOldDocumentNo(remittanceAdviceRecord.getDocumentNo())
.setDocumentModel(remittanceAdviceRecord)
.buildOrNull();
if (documentNoInfo != null && documentNoInfo.isDocNoControlled())
{
remittanceAdviceRecord.setDocumentNo(documentNoInfo.getDocumentNo());
}
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_BEFORE_NEW },
ifColumnsChanged = I_C_RemittanceAdvice.COLUMNNAME_C_Payment_Doctype_Target_ID)
public void setIsSOTrxFromPaymentDocType(@NonNull final I_C_RemittanceAdvice record)
{
final I_C_DocType targetPaymentDocType = docTypeDAO.getById(record.getC_Payment_Doctype_Target_ID());
record.setIsSOTrx(targetPaymentDocType.isSOTrx());
}
|
@ModelChange(timings = { ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_AFTER_NEW },
ifColumnsChanged = I_C_RemittanceAdvice.COLUMNNAME_Processed)
public void setProcessedFlag(@NonNull final I_C_RemittanceAdvice record)
{
final RemittanceAdviceId remittanceAdviceId = RemittanceAdviceId.ofRepoId(record.getC_RemittanceAdvice_ID());
final RemittanceAdvice remittanceAdvice = remittanceAdviceRepository.getRemittanceAdvice(remittanceAdviceId);
remittanceAdvice.setProcessedFlag(record.isProcessed());
remittanceAdviceRepository.updateRemittanceAdvice(remittanceAdvice);
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE)
public void deleteLines(@NonNull final I_C_RemittanceAdvice record)
{
queryBL.createQueryBuilder(I_C_RemittanceAdvice_Line.class)
.addEqualsFilter(I_C_RemittanceAdvice_Line.COLUMN_C_RemittanceAdvice_ID, record.getC_RemittanceAdvice_ID())
.create()
.delete();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\remittanceadvice\interceptor\C_RemittanceAdvice.java
| 1
|
请完成以下Java代码
|
public java.lang.String getSenderCountry ()
{
return (java.lang.String)get_Value(COLUMNNAME_SenderCountry);
}
/** Set Haus-Nr. Absender.
@param SenderHouseNo Haus-Nr. Absender */
@Override
public void setSenderHouseNo (java.lang.String SenderHouseNo)
{
set_Value (COLUMNNAME_SenderHouseNo, SenderHouseNo);
}
/** Get Haus-Nr. Absender.
@return Haus-Nr. Absender */
@Override
public java.lang.String getSenderHouseNo ()
{
return (java.lang.String)get_Value(COLUMNNAME_SenderHouseNo);
}
/** Set Name 1 Absender.
@param SenderName1 Name 1 Absender */
@Override
public void setSenderName1 (java.lang.String SenderName1)
{
set_Value (COLUMNNAME_SenderName1, SenderName1);
}
/** Get Name 1 Absender.
@return Name 1 Absender */
@Override
public java.lang.String getSenderName1 ()
{
return (java.lang.String)get_Value(COLUMNNAME_SenderName1);
}
/** Set Name 2 Absender.
@param SenderName2 Name 2 Absender */
@Override
public void setSenderName2 (java.lang.String SenderName2)
{
set_Value (COLUMNNAME_SenderName2, SenderName2);
}
/** Get Name 2 Absender.
@return Name 2 Absender */
@Override
public java.lang.String getSenderName2 ()
{
return (java.lang.String)get_Value(COLUMNNAME_SenderName2);
}
/** Set Straße Absender.
@param SenderStreet Straße Absender */
@Override
public void setSenderStreet (java.lang.String SenderStreet)
{
set_Value (COLUMNNAME_SenderStreet, SenderStreet);
}
/** Get Straße Absender.
@return Straße Absender */
@Override
public java.lang.String getSenderStreet ()
{
return (java.lang.String)get_Value(COLUMNNAME_SenderStreet);
}
/** Set PLZ Absender.
@param SenderZipCode PLZ Absender */
@Override
public void setSenderZipCode (java.lang.String SenderZipCode)
{
set_Value (COLUMNNAME_SenderZipCode, SenderZipCode);
|
}
/** Get PLZ Absender.
@return PLZ Absender */
@Override
public java.lang.String getSenderZipCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_SenderZipCode);
}
/** Set Versandlager.
@param SendingDepot Versandlager */
@Override
public void setSendingDepot (java.lang.String SendingDepot)
{
set_Value (COLUMNNAME_SendingDepot, SendingDepot);
}
/** Get Versandlager.
@return Versandlager */
@Override
public java.lang.String getSendingDepot ()
{
return (java.lang.String)get_Value(COLUMNNAME_SendingDepot);
}
/** Set Nachverfolgungs-URL.
@param TrackingURL
URL des Spediteurs um Sendungen zu verfolgen
*/
@Override
public void setTrackingURL (java.lang.String TrackingURL)
{
set_Value (COLUMNNAME_TrackingURL, TrackingURL);
}
/** Get Nachverfolgungs-URL.
@return URL des Spediteurs um Sendungen zu verfolgen
*/
@Override
public java.lang.String getTrackingURL ()
{
return (java.lang.String)get_Value(COLUMNNAME_TrackingURL);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-gen\de\metas\shipper\gateway\dpd\model\X_DPD_StoreOrder.java
| 1
|
请完成以下Java代码
|
public static AttributeListValueTrxRestriction ofCode(@Nullable final String code)
{
if (code == null)
{
return ANY_TRANSACTION;
}
else if (SALES.code.contentEquals(code))
{
return SALES;
}
else if (PURCHASE.code.contentEquals(code))
{
return PURCHASE;
}
else
{
throw new AdempiereException("Unknown code: " + code);
}
}
public boolean isMatchingSOTrx(@Nullable final SOTrx soTrx)
|
{
if (soTrx == null)
{
return true;
}
if (this == ANY_TRANSACTION)
{
return true;
}
return (this == SALES && soTrx.isSales())
|| (this == PURCHASE && soTrx.isPurchase());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\mm\attributes\AttributeListValueTrxRestriction.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
class BankStatementDocumentHandlerRequiredServicesFacade
{
private final IBankStatementPaymentBL bankStatmentPaymentBL;
private final IBankStatementBL bankStatementBL;
private final IBankStatementDAO bankStatementDAO = Services.get(IBankStatementDAO.class);
private final IBPBankAccountDAO bpBankAccountDAO = Services.get(IBPBankAccountDAO.class);
private final IPaymentBL paymentBL = Services.get(IPaymentBL.class);
private final IFactAcctDAO factAcctDAO = Services.get(IFactAcctDAO.class);
private final IMsgBL msgBL = Services.get(IMsgBL.class);
public BankStatementDocumentHandlerRequiredServicesFacade(
@NonNull final IBankStatementPaymentBL bankStatmentPaymentBL,
@NonNull final IBankStatementBL bankStatementBL)
{
this.bankStatmentPaymentBL = bankStatmentPaymentBL;
this.bankStatementBL = bankStatementBL;
}
public BankAccount getBankAccountById(@NonNull final BankAccountId bankAccountId)
{
return bpBankAccountDAO.getById(bankAccountId);
}
public List<I_C_BankStatementLine> getBankStatementLinesByBankStatementId(@NonNull final BankStatementId bankStatementId)
{
return bankStatementBL.getLinesByBankStatementId(bankStatementId);
}
public BankStatementLineReferenceList getBankStatementLineReferences(@NonNull final BankStatementLineId bankStatementLineId)
{
return bankStatementDAO.getLineReferences(bankStatementLineId);
}
public BankStatementLineReferenceList getBankStatementLineReferences(final Collection<BankStatementLineId> bankStatementLineIds)
{
return bankStatementDAO.getLineReferences(bankStatementLineIds);
}
public void save(final I_C_BankStatementLine line)
{
bankStatementDAO.save(line);
}
public void findOrCreateSinglePaymentAndLinkIfPossible(
final I_C_BankStatement bankStatement,
final I_C_BankStatementLine line,
final Set<PaymentId> excludePaymentIds)
{
bankStatmentPaymentBL.findOrCreateSinglePaymentAndLinkIfPossible(bankStatement, line, excludePaymentIds);
}
public void markReconciled(final List<PaymentReconcileRequest> requests)
{
paymentBL.markReconciled(requests);
}
|
public void markBankStatementLinesAsProcessed(final BankStatementId bankStatementId)
{
final boolean processed = true;
bankStatementDAO.updateBankStatementLinesProcessedFlag(bankStatementId, processed);
}
public void deleteFactsForBankStatement(final I_C_BankStatement bankStatement)
{
factAcctDAO.deleteForDocumentModel(bankStatement);
}
public void unreconcile(@NonNull final List<I_C_BankStatementLine> lines)
{
bankStatementBL.unreconcile(lines);
}
public String getMsg(final AdMessageKey adMessage)
{
return msgBL.getMsg(Env.getCtx(), adMessage);
}
public String getMsg(final Properties ctx, final AdMessageKey adMessage)
{
return msgBL.getMsg(ctx, adMessage);
}
public String translate(final Properties ctx, final String adMessageOrColumnName)
{
return msgBL.translate(ctx, adMessageOrColumnName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\service\BankStatementDocumentHandlerRequiredServicesFacade.java
| 2
|
请完成以下Java代码
|
public boolean isSourceHu(final HuId huId)
{
return sourceHuDAO.isSourceHu(huId);
}
public void addSourceHUMarkerIfCarringComponents(@NonNull final HuId huId, @NonNull final ProductId productId, @NonNull final WarehouseId warehouseId)
{
addSourceHUMarkerIfCarringComponents(ImmutableSet.of(huId), productId, warehouseId);
}
/**
* Creates an M_Source_HU record for the given HU, if it carries component products and the target warehouse has
* the org.compiere.model.I_M_Warehouse#isReceiveAsSourceHU() flag.
*/
public void addSourceHUMarkerIfCarringComponents(@NonNull final Set<HuId> huIds, @NonNull final ProductId productId, @NonNull final WarehouseId warehouseId)
{
if (huIds.isEmpty()) {return;}
final I_M_Warehouse warehouse = warehousesRepo.getById(warehouseId);
if (!warehouse.isReceiveAsSourceHU())
{
return;
}
final boolean referencedInComponentOrVariant = productBOMDAO.isComponent(productId);
if (!referencedInComponentOrVariant)
{
return;
}
huIds.forEach(this::addSourceHuMarker);
}
/**
* Specifies which source HUs (products and warehouse) to retrieve in particular
*/
@lombok.Value
@lombok.Builder
@Immutable
|
public static class MatchingSourceHusQuery
{
/**
* Query for HUs that have any of the given product IDs. Empty means that no HUs will be found.
*/
@Singular
ImmutableSet<ProductId> productIds;
@Singular
ImmutableSet<WarehouseId> warehouseIds;
public static MatchingSourceHusQuery fromHuId(final HuId huId)
{
final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class);
final I_M_HU hu = handlingUnitsBL.getById(huId);
final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory();
final IHUStorage storage = storageFactory.getStorage(hu);
final ImmutableSet<ProductId> productIds = storage.getProductStorages().stream()
.filter(productStorage -> !productStorage.isEmpty())
.map(IProductStorage::getProductId)
.collect(ImmutableSet.toImmutableSet());
final WarehouseId warehouseId = IHandlingUnitsBL.extractWarehouseId(hu);
return new MatchingSourceHusQuery(productIds, ImmutableSet.of(warehouseId));
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\sourcehu\SourceHUsService.java
| 1
|
请完成以下Java代码
|
public int getCustomer_Group_ID()
{
return get_ValueAsInt(COLUMNNAME_Customer_Group_ID);
}
@Override
public void setIsExcludeBPGroup (final boolean IsExcludeBPGroup)
{
set_Value (COLUMNNAME_IsExcludeBPGroup, IsExcludeBPGroup);
}
@Override
public boolean isExcludeBPGroup()
{
return get_ValueAsBoolean(COLUMNNAME_IsExcludeBPGroup);
}
@Override
public void setIsExcludeProductCategory (final boolean IsExcludeProductCategory)
{
set_Value (COLUMNNAME_IsExcludeProductCategory, IsExcludeProductCategory);
}
@Override
public boolean isExcludeProductCategory()
{
return get_ValueAsBoolean(COLUMNNAME_IsExcludeProductCategory);
}
@Override
public void setM_Product_Category_ID (final int M_Product_Category_ID)
{
if (M_Product_Category_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_ID, null);
else
|
set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID);
}
@Override
public int getM_Product_Category_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID);
}
@Override
public void setPercentOfBasePoints (final BigDecimal PercentOfBasePoints)
{
set_Value (COLUMNNAME_PercentOfBasePoints, PercentOfBasePoints);
}
@Override
public BigDecimal getPercentOfBasePoints()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PercentOfBasePoints);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_CommissionSettingsLine.java
| 1
|
请完成以下Java代码
|
public int getLogoWeb_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_LogoWeb_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Product getM_ProductFreight() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_ProductFreight_ID, org.compiere.model.I_M_Product.class);
}
@Override
public void setM_ProductFreight(org.compiere.model.I_M_Product M_ProductFreight)
{
set_ValueFromPO(COLUMNNAME_M_ProductFreight_ID, org.compiere.model.I_M_Product.class, M_ProductFreight);
}
/** Set Produkt für Fracht.
@param M_ProductFreight_ID Produkt für Fracht */
@Override
public void setM_ProductFreight_ID (int M_ProductFreight_ID)
{
if (M_ProductFreight_ID < 1)
set_Value (COLUMNNAME_M_ProductFreight_ID, null);
|
else
set_Value (COLUMNNAME_M_ProductFreight_ID, Integer.valueOf(M_ProductFreight_ID));
}
/** Get Produkt für Fracht.
@return Produkt für Fracht */
@Override
public int getM_ProductFreight_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductFreight_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_AD_ClientInfo.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getPOBox() {
return poBox;
}
/**
* Sets the value of the poBox property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPOBox(String value) {
this.poBox = value;
}
/**
* City information.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTown() {
return town;
}
/**
* Sets the value of the town property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTown(String value) {
this.town = value;
}
/**
* ZIP code.
*
* @return
* possible object is
* {@link String }
*
*/
public String getZIP() {
return zip;
}
/**
* Sets the value of the zip property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setZIP(String value) {
this.zip = value;
}
/**
|
* Country information.
*
* @return
* possible object is
* {@link CountryType }
*
*/
public CountryType getCountry() {
return country;
}
/**
* Sets the value of the country property.
*
* @param value
* allowed object is
* {@link CountryType }
*
*/
public void setCountry(CountryType value) {
this.country = value;
}
/**
* Any further elements or attributes which are necessary for an address may be provided here.
* Note that extensions should be used with care and only those extensions shall be used, which are officially provided by ERPEL.
* Gets the value of the addressExtension property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the addressExtension property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAddressExtension().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getAddressExtension() {
if (addressExtension == null) {
addressExtension = new ArrayList<String>();
}
return this.addressExtension;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\AddressType.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class SqlInsertTsRepository extends AbstractInsertRepository implements InsertTsRepository<TsKvEntity> {
private static final String INSERT_ON_CONFLICT_DO_UPDATE = "INSERT INTO ts_kv (entity_id, key, ts, bool_v, str_v, long_v, dbl_v, json_v) VALUES (?, ?, ?, ?, ?, ?, ?, cast(? AS json)) " +
"ON CONFLICT (entity_id, key, ts) DO UPDATE SET bool_v = ?, str_v = ?, long_v = ?, dbl_v = ?, json_v = cast(? AS json);";
@Override
public void saveOrUpdate(List<TsKvEntity> entities) {
jdbcTemplate.batchUpdate(INSERT_ON_CONFLICT_DO_UPDATE, new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
TsKvEntity tsKvEntity = entities.get(i);
ps.setObject(1, tsKvEntity.getEntityId());
ps.setInt(2, tsKvEntity.getKey());
ps.setLong(3, tsKvEntity.getTs());
if (tsKvEntity.getBooleanValue() != null) {
ps.setBoolean(4, tsKvEntity.getBooleanValue());
ps.setBoolean(9, tsKvEntity.getBooleanValue());
} else {
ps.setNull(4, Types.BOOLEAN);
ps.setNull(9, Types.BOOLEAN);
}
ps.setString(5, replaceNullChars(tsKvEntity.getStrValue()));
ps.setString(10, replaceNullChars(tsKvEntity.getStrValue()));
if (tsKvEntity.getLongValue() != null) {
ps.setLong(6, tsKvEntity.getLongValue());
ps.setLong(11, tsKvEntity.getLongValue());
} else {
ps.setNull(6, Types.BIGINT);
ps.setNull(11, Types.BIGINT);
}
if (tsKvEntity.getDoubleValue() != null) {
ps.setDouble(7, tsKvEntity.getDoubleValue());
ps.setDouble(12, tsKvEntity.getDoubleValue());
|
} else {
ps.setNull(7, Types.DOUBLE);
ps.setNull(12, Types.DOUBLE);
}
ps.setString(8, replaceNullChars(tsKvEntity.getJsonValue()));
ps.setString(13, replaceNullChars(tsKvEntity.getJsonValue()));
}
@Override
public int getBatchSize() {
return entities.size();
}
});
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sqlts\insert\sql\SqlInsertTsRepository.java
| 2
|
请完成以下Java代码
|
protected ModelEntityManager getModelManager() {
return getSession(ModelEntityManager.class);
}
protected ExecutionEntityManager getProcessInstanceManager() {
return getSession(ExecutionEntityManager.class);
}
protected TaskEntityManager getTaskManager() {
return getSession(TaskEntityManager.class);
}
protected IdentityLinkEntityManager getIdentityLinkManager() {
return getSession(IdentityLinkEntityManager.class);
}
protected EventSubscriptionEntityManager getEventSubscriptionManager() {
return (getSession(EventSubscriptionEntityManager.class));
}
protected VariableInstanceEntityManager getVariableInstanceManager() {
return getSession(VariableInstanceEntityManager.class);
}
protected HistoricProcessInstanceEntityManager getHistoricProcessInstanceManager() {
return getSession(HistoricProcessInstanceEntityManager.class);
}
protected HistoricDetailEntityManager getHistoricDetailManager() {
return getSession(HistoricDetailEntityManager.class);
}
protected HistoricActivityInstanceEntityManager getHistoricActivityInstanceManager() {
return getSession(HistoricActivityInstanceEntityManager.class);
}
protected HistoricVariableInstanceEntityManager getHistoricVariableInstanceManager() {
return getSession(HistoricVariableInstanceEntityManager.class);
}
|
protected HistoricTaskInstanceEntityManager getHistoricTaskInstanceManager() {
return getSession(HistoricTaskInstanceEntityManager.class);
}
protected HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() {
return getSession(HistoricIdentityLinkEntityManager.class);
}
protected AttachmentEntityManager getAttachmentManager() {
return getSession(AttachmentEntityManager.class);
}
protected HistoryManager getHistoryManager() {
return getSession(HistoryManager.class);
}
protected ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return Context.getProcessEngineConfiguration();
}
@Override
public void close() {
}
@Override
public void flush() {
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\AbstractManager.java
| 1
|
请完成以下Java代码
|
public void updateReferenced_Record_ID(final I_S_ExternalReference record)
{
record.setReferenced_Record_ID(record.getRecord_ID());
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_BEFORE_NEW }, ifColumnsChanged = { I_S_ExternalReference.COLUMNNAME_Type })
@CalloutMethod(columnNames = { I_S_ExternalReference.COLUMNNAME_Type })
public void updateReferenced_Table_ID(final I_S_ExternalReference record)
{
final IExternalReferenceType externalReferenceType = externalReferenceTypes.ofCode(record.getType())
.orElseThrow(() -> new AdempiereException("Unsupported S_ExternalReference.Type=" + record.getType())
.appendParametersToMessage()
.setParameter("S_ExternalReference", record));
record.setReferenced_AD_Table_ID(adTableDAO.retrieveTableId(externalReferenceType.getTableName()));
}
|
private void validateUserId(@NonNull final UserId userId)
{
try
{
userDAO.getByIdInTrx(userId);
}
catch (final AdempiereException ex)
{
throw new AdempiereException("No user found for the given recordId! ", ex)
.appendParametersToMessage()
.setParameter("recordId", userId.getRepoId());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalreference\src\main\java\de\metas\externalreference\user\S_ExternalReference.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected Task getTaskFromRequest(String taskId) {
Task task = getTaskFromRequestWithoutAccessCheck(taskId);
if (restApiInterceptor != null) {
restApiInterceptor.accessTaskInfoById(task);
}
return task;
}
/**
* Returns the {@link Task} that is requested without calling the access interceptor
* Throws the right exceptions when bad request was made or instance was not found.
*/
protected Task getTaskFromRequestWithoutAccessCheck(String taskId) {
Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
if (task == null) {
throw new FlowableObjectNotFoundException("Could not find a task with id '" + taskId + "'.", Task.class);
}
return task;
}
/**
* Returns the {@link HistoricTaskInstance} that is requested and calls the access interceptor.
* Throws the right exceptions when bad request was made or instance was not found.
*/
protected HistoricTaskInstance getHistoricTaskFromRequest(String taskId) {
HistoricTaskInstance task = getHistoricTaskFromRequestWithoutAccessCheck(taskId);
|
if (restApiInterceptor != null) {
restApiInterceptor.accessHistoryTaskInfoById(task);
}
return task;
}
/**
* Returns the {@link HistoricTaskInstance} that is requested without calling the access interceptor
* Throws the right exceptions when bad request was made or instance was not found.
*/
protected HistoricTaskInstance getHistoricTaskFromRequestWithoutAccessCheck(String taskId) {
HistoricTaskInstance task = historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
if (task == null) {
throw new FlowableObjectNotFoundException("Could not find a task with id '" + taskId + "'.", Task.class);
}
return task;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\task\TaskBaseResource.java
| 2
|
请完成以下Java代码
|
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
public Integer getPriority() {
return priority;
}
public void setPriority(Integer priority) {
this.priority = priority;
}
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
}
public String getParentTaskId() {
|
return parentTaskId;
}
public void setParentTaskId(String parentTaskId) {
this.parentTaskId = parentTaskId;
}
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
}
|
repos\Activiti-develop\activiti-api\activiti-api-task-model\src\main\java\org\activiti\api\task\model\payloads\UpdateTaskPayload.java
| 1
|
请完成以下Java代码
|
protected void initializeVariableOnParts(CmmnElement element, CmmnSentryDeclaration sentryDeclaration,
CmmnHandlerContext context, List<CamundaVariableOnPart> variableOnParts) {
for(CamundaVariableOnPart variableOnPart: variableOnParts) {
initializeVariableOnPart(variableOnPart, sentryDeclaration, context);
}
}
protected void initializeVariableOnPart(CamundaVariableOnPart variableOnPart, CmmnSentryDeclaration sentryDeclaration, CmmnHandlerContext context) {
VariableTransition variableTransition;
try {
variableTransition = variableOnPart.getVariableEvent();
} catch(IllegalArgumentException illegalArgumentexception) {
throw LOG.nonMatchingVariableEvents(sentryDeclaration.getId());
} catch(NullPointerException nullPointerException) {
throw LOG.nonMatchingVariableEvents(sentryDeclaration.getId());
}
String variableName = variableOnPart.getVariableName();
String variableEventName = variableTransition.name();
if (variableName != null) {
if (!sentryDeclaration.hasVariableOnPart(variableEventName, variableName)) {
CmmnVariableOnPartDeclaration variableOnPartDeclaration = new CmmnVariableOnPartDeclaration();
variableOnPartDeclaration.setVariableEvent(variableEventName);
variableOnPartDeclaration.setVariableName(variableName);
sentryDeclaration.addVariableOnParts(variableOnPartDeclaration);
}
|
} else {
throw LOG.emptyVariableName(sentryDeclaration.getId());
}
}
protected <V extends ModelElementInstance> List<V> queryExtensionElementsByClass(CmmnElement element, Class<V> cls) {
ExtensionElements extensionElements = element.getExtensionElements();
if (extensionElements != null) {
Query<ModelElementInstance> query = extensionElements.getElementsQuery();
return query.filterByType(cls).list();
} else {
return new ArrayList<V>();
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\handler\SentryHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UserController2 {
/**
* 查询用户列表
*
* @return 用户列表
*/
@GetMapping("/list") // URL 修改成 /list
public List<UserVO> list() {
// 查询列表
List<UserVO> result = new ArrayList<>();
result.add(new UserVO().setId(1).setUsername("yudaoyuanma"));
result.add(new UserVO().setId(2).setUsername("woshiyutou"));
result.add(new UserVO().setId(3).setUsername("chifanshuijiao"));
// 返回列表
return result;
}
/**
* 获得指定用户编号的用户
*
* @param id 用户编号
* @return 用户
*/
@GetMapping("/get") // URL 修改成 /get
public UserVO get(@RequestParam("id") Integer id) {
// 查询并返回用户
return new UserVO().setId(id).setUsername(UUID.randomUUID().toString());
}
/**
* 添加用户
*
* @param addDTO 添加用户信息 DTO
* @return 添加成功的用户编号
*/
@PostMapping("add") // URL 修改成 /add
public Integer add(UserAddDTO addDTO) {
// 插入用户记录,返回编号
Integer returnId = UUID.randomUUID().hashCode();
// 返回用户编号
return returnId;
}
/**
* 更新指定用户编号的用户
*
|
* @param updateDTO 更新用户信息 DTO
* @return 是否修改成功
*/
@PostMapping("/update") // URL 修改成 /update ,RequestMethod 改成 POST
public Boolean update(UserUpdateDTO updateDTO) {
// 更新用户记录
Boolean success = true;
// 返回更新是否成功
return success;
}
/**
* 删除指定用户编号的用户
*
* @param id 用户编号
* @return 是否删除成功
*/
@DeleteMapping("/delete") // URL 修改成 /delete ,RequestMethod 改成 DELETE
public Boolean delete(@RequestParam("id") Integer id) {
// 删除用户记录
Boolean success = false;
// 返回是否更新成功
return success;
}
}
|
repos\SpringBoot-Labs-master\lab-23\lab-springmvc-23-01\src\main\java\cn\iocoder\springboot\lab23\springmvc\controller\UserController2.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Application {
@Value("${server.port}")
String serverPort;
@Value("${baeldung.api.path}")
String contextPath;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
ServletRegistrationBean servletRegistrationBean() {
ServletRegistrationBean servlet = new ServletRegistrationBean(new CamelHttpTransportServlet(), contextPath + "/*");
servlet.setName("CamelServlet");
return servlet;
}
@Component
class RestApi extends RouteBuilder {
@Override
public void configure() {
CamelContext context = new DefaultCamelContext();
// http://localhost:8080/camel/api-doc
restConfiguration().contextPath(contextPath) //
.port(serverPort)
.enableCORS(true)
.apiContextPath("/api-doc")
.apiProperty("api.title", "Test REST API")
.apiProperty("api.version", "v1")
.apiProperty("cors", "true") // cross-site
.apiContextRouteId("doc-api")
.component("servlet")
.bindingMode(RestBindingMode.json)
.dataFormatProperty("prettyPrint", "true");
/**
The Rest DSL supports automatic binding json/xml contents to/from
POJOs using Camels Data Format.
By default the binding mode is off, meaning there is no automatic
binding happening for incoming and outgoing messages.
You may want to use binding if you develop POJOs that maps to
your REST services request and response types.
*/
rest("/api/").description("Teste REST Service")
|
.id("api-route")
.post("/bean")
.produces(MediaType.APPLICATION_JSON)
.consumes(MediaType.APPLICATION_JSON)
// .get("/hello/{place}")
.bindingMode(RestBindingMode.auto)
.type(MyBean.class)
.enableCORS(true)
// .outType(OutBean.class)
.to("direct:remoteService");
from("direct:remoteService").routeId("direct-route")
.tracing()
.log(">>> ${body.id}")
.log(">>> ${body.name}")
// .transform().simple("blue ${in.body.name}")
.process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
MyBean bodyIn = (MyBean) exchange.getIn()
.getBody();
ExampleServices.example(bodyIn);
exchange.getIn()
.setBody(bodyIn);
}
})
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(201));
}
}
}
|
repos\tutorials-master\messaging-modules\spring-apache-camel\src\main\java\com\baeldung\camel\boot\Application.java
| 2
|
请完成以下Java代码
|
public int getAD_User_SortPref_Line_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_SortPref_Line_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sortierbegriff pro Benutzer Position Produkt.
@param AD_User_SortPref_Line_Product_ID Sortierbegriff pro Benutzer Position Produkt */
@Override
public void setAD_User_SortPref_Line_Product_ID (int AD_User_SortPref_Line_Product_ID)
{
if (AD_User_SortPref_Line_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_User_SortPref_Line_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_SortPref_Line_Product_ID, Integer.valueOf(AD_User_SortPref_Line_Product_ID));
}
/** Get Sortierbegriff pro Benutzer Position Produkt.
@return Sortierbegriff pro Benutzer Position Produkt */
@Override
public int getAD_User_SortPref_Line_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_SortPref_Line_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@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_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (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();
}
/** 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.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_SortPref_Line_Product.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
private TokenStore tokenStore = new InMemoryTokenStore();
private final String NOOP_PASSWORD_ENCODE = "{noop}";
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Autowired
private MongoUserDetailsService userDetailsService;
@Autowired
private Environment env;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// TODO persist clients details
// @formatter:off
clients.inMemory()
.withClient("browser")
.authorizedGrantTypes("refresh_token", "password")
.scopes("ui")
.and()
.withClient("account-service")
.secret(env.getProperty("ACCOUNT_SERVICE_PASSWORD"))
.authorizedGrantTypes("client_credentials", "refresh_token")
.scopes("server")
|
.and()
.withClient("statistics-service")
.secret(env.getProperty("STATISTICS_SERVICE_PASSWORD"))
.authorizedGrantTypes("client_credentials", "refresh_token")
.scopes("server")
.and()
.withClient("notification-service")
.secret(env.getProperty("NOTIFICATION_SERVICE_PASSWORD"))
.authorizedGrantTypes("client_credentials", "refresh_token")
.scopes("server");
// @formatter:on
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.tokenStore(tokenStore)
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()")
.passwordEncoder(NoOpPasswordEncoder.getInstance());
}
}
|
repos\piggymetrics-master\auth-service\src\main\java\com\piggymetrics\auth\config\OAuth2AuthorizationConfig.java
| 2
|
请完成以下Java代码
|
private Optional<String> retrieveRuestplatz(final BPartnerLocationId deliveryLocationId)
{
return extractRuestplatz(bpartnerService.getBPartnerLocationByIdEvenInactive(deliveryLocationId));
}
private static Optional<String> extractRuestplatz(@Nullable final I_C_BPartner_Location location)
{
return Optional.ofNullable(location)
.map(I_C_BPartner_Location::getSetup_Place_No)
.map(StringUtils::trimBlankToNull);
}
@Nullable
private String getHandoverAddress(@NonNull final Context pickingJob, @Nullable AddressDisplaySequence displaySequence)
{
final BPartnerLocationId bpLocationId = pickingJob.getHandoverLocationIdWithFallback();
return bpLocationId != null
? renderedAddressProvider.getAddress(bpLocationId, displaySequence)
: null;
}
@Nullable
private String getDeliveryAddress(@NonNull final Context context, @Nullable AddressDisplaySequence displaySequence)
{
final BPartnerLocationId bpLocationId = context.getDeliveryLocationId();
return bpLocationId != null
? renderedAddressProvider.getAddress(bpLocationId, displaySequence)
: null;
}
|
@Value
@Builder
private static class Context
{
@Nullable String salesOrderDocumentNo;
@Nullable String customerName;
@Nullable ZonedDateTime preparationDate;
@Nullable BPartnerLocationId deliveryLocationId;
@Nullable BPartnerLocationId handoverLocationId;
@Nullable ITranslatableString productName;
@Nullable Quantity qtyToDeliver;
@Nullable
public BPartnerLocationId getHandoverLocationIdWithFallback()
{
return handoverLocationId != null ? handoverLocationId : deliveryLocationId;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\DisplayValueProvider.java
| 1
|
请完成以下Java代码
|
public class WEBUI_M_HU_MoveToGarbage_Partial extends HUEditorProcessTemplate implements IProcessPrecondition
{
private final InventoryService inventoryService = SpringContextHolder.instance.getBean(InventoryService.class);
private final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class);
@Param(parameterName = "QtyTU", mandatory = true)
private int p_qtyTU_Int;
@Param(parameterName = "C_DocType_ID")
@Nullable
private DocTypeId p_internalUseInventoryDocTypeId;
@Param(parameterName = "Description")
private String p_description;
@Override
protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (!isHUEditorView())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("not the HU view");
}
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
if (!selectedRowIds.isSingleDocumentId())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
final DocumentId rowId = selectedRowIds.getSingleDocumentId();
final HUEditorRow huRow = getView().getById(rowId);
if (huRow.isLU())
{
if (!huRow.hasIncludedTUs())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("no TUs");
}
}
else if (huRow.isTU())
{
// OK
}
else
{
return ProcessPreconditionsResolution.rejectWithInternalReason("not a LU or TU");
}
if (!huRow.isHUStatusActive())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("HUStatus is not Active");
}
return ProcessPreconditionsResolution.accept();
}
@Override
// @RunOutOfTrx // run in transaction!
protected String doIt()
{
final LUTUResult.TUsList tus = extractTUs();
|
inventoryService.moveToGarbage(
HUInternalUseInventoryCreateRequest.builder()
.hus(tus.toHURecords())
.movementDate(Env.getZonedDateTime(getCtx()))
.internalUseInventoryDocTypeId(p_internalUseInventoryDocTypeId)
.description(p_description)
.completeInventory(true)
.moveEmptiesToEmptiesWarehouse(true)
.sendNotifications(true)
.build());
return MSG_OK;
}
private LUTUResult.TUsList extractTUs()
{
if (p_qtyTU_Int <= 0)
{
throw new FillMandatoryException("QtyTU");
}
final QtyTU qtyTU = QtyTU.ofInt(p_qtyTU_Int);
final I_M_HU topLevelHU = handlingUnitsBL.getById(HuId.ofRepoId(getRecord_ID()));
final LUTUResult.TUsList tus = HUTransformService.newInstance()
.husToNewTUs(HUTransformService.HUsToNewTUsRequest.forSourceHuAndQty(topLevelHU, qtyTU.toInt()));
if (tus.getQtyTU().toInt() != qtyTU.toInt())
{
throw new AdempiereException(WEBUI_HU_Constants.MSG_NotEnoughTUsFound, qtyTU.toInt(), tus.getQtyTU());
}
return tus;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_MoveToGarbage_Partial.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 8088
spring:
profiles:
active: native
output:
ansi:
enabled: always
logging:
pattern:
console: "%clr(%d{y
|
yyy-MM-dd HH:mm:ss}){blue} %clr(${LOG_LEVEL_PATTERN:-%5p}) %m%n"
|
repos\sample-spring-microservices-new-master\config-service\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public final CurrencyConversionContext getInOutCurrencyConversionCtx()
{
CurrencyConversionContext inoutCurrencyConversionCtx = this._inoutCurrencyConversionCtx;
if (inoutCurrencyConversionCtx == null)
{
inoutCurrencyConversionCtx = this._inoutCurrencyConversionCtx = inOutBL.getCurrencyConversionContext(getReceipt());
}
return inoutCurrencyConversionCtx;
}
private boolean isCreditMemoInvoice()
{
return isCreditMemoInvoice;
}
/**
* Updates dimensions and UOM of given FactLine from invoice line
*/
private void updateFromInvoiceLine(@Nullable final FactLine fl)
{
if (fl == null)
{
return;
}
final I_C_InvoiceLine invoiceLine = getInvoiceLine();
//fl.setC_UOM_ID(firstGreaterThanZero(invoiceLine.getPrice_UOM_ID(), invoiceLine.getC_UOM_ID()));
final Dimension invoiceLineDimension = services.extractDimensionFromModel(invoiceLine);
fl.setFromDimension(invoiceLineDimension);
}
private CostAmountDetailed getCreateCostDetails(final AcctSchema as)
{
Check.assume(!isSOTrx(), "Cannot create cost details for sales match invoice");
final I_M_InOut receipt = getReceipt();
final Quantity qtyMatched = getQty();
final MatchInvType type = matchInv.getType();
final Money amtMatched;
final CostElement costElement;
if (type.isMaterial())
{
amtMatched = getInvoiceLineMatchedAmt();
costElement = null;
}
else if (type.isCost())
{
|
final MatchInvCostPart costPart = matchInv.getCostPartNotNull();
amtMatched = costPart.getCostAmountInvoiced();
costElement = services.getCostElementById(costPart.getCostElementId());
}
else
{
throw new AdempiereException("Unhandled type: " + type);
}
return services.createCostDetail(
CostDetailCreateRequest.builder()
.acctSchemaId(as.getId())
.clientId(matchInv.getClientId())
.orgId(matchInv.getOrgId())
.productId(matchInv.getProductId())
.attributeSetInstanceId(matchInv.getAsiId())
.documentRef(CostingDocumentRef.ofMatchInvoiceId(matchInv.getId()))
.costElement(costElement)
.qty(qtyMatched)
.amt(CostAmount.ofMoney(amtMatched))
.currencyConversionContext(inOutBL.getCurrencyConversionContext(receipt))
.date(getDateAcctAsInstant())
.description(getDescription())
.build())
.getTotalAmountToPost(as);
}
@Nullable
private CostElementId getCostElementId()
{
final MatchInvType type = matchInv.getType();
if (type.isMaterial())
{
return null;
}
else if (type.isCost())
{
return matchInv.getCostPartNotNull().getCostElementId();
}
else
{
throw new AdempiereException("Unhandled type: " + type);
}
}
} // Doc_MatchInv
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_MatchInv.java
| 1
|
请完成以下Java代码
|
public String toString() {
return "AppInfo{" + "app='" + app + ", machines=" + machines + '}';
}
public boolean addMachine(MachineInfo machineInfo) {
machines.remove(machineInfo);
return machines.add(machineInfo);
}
public synchronized boolean removeMachine(String ip, int port) {
Iterator<MachineInfo> it = machines.iterator();
while (it.hasNext()) {
MachineInfo machine = it.next();
if (machine.getIp().equals(ip) && machine.getPort() == port) {
it.remove();
return true;
}
}
return false;
}
public Optional<MachineInfo> getMachine(String ip, int port) {
return machines.stream()
.filter(e -> e.getIp().equals(ip) && e.getPort().equals(port))
.findFirst();
}
private boolean heartbeatJudge(final int threshold) {
if (machines.size() == 0) {
return false;
}
if (threshold > 0) {
long healthyCount = machines.stream()
.filter(MachineInfo::isHealthy)
.count();
if (healthyCount == 0) {
// No healthy machines.
return machines.stream()
.max(Comparator.comparingLong(MachineInfo::getLastHeartbeat))
.map(e -> System.currentTimeMillis() - e.getLastHeartbeat() < threshold)
|
.orElse(false);
}
}
return true;
}
/**
* Check whether current application has no healthy machines and should not be displayed.
*
* @return true if the application should be displayed in the sidebar, otherwise false
*/
public boolean isShown() {
return heartbeatJudge(DashboardConfig.getHideAppNoMachineMillis());
}
/**
* Check whether current application has no healthy machines and should be removed.
*
* @return true if the application is dead and should be removed, otherwise false
*/
public boolean isDead() {
return !heartbeatJudge(DashboardConfig.getRemoveAppNoMachineMillis());
}
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\discovery\AppInfo.java
| 1
|
请完成以下Java代码
|
public void focusLost (FocusEvent e)
{
//log.info( "VMemo.focusLost " + e.getSource(), e.paramString());
// something changed?
return;
} // focusLost
/*************************************************************************/
// Field for Value Preference
private GridField m_mField = null;
/**
* Set Field/WindowNo for ValuePreference (NOP)
* @param mField
*/
@Override
public void setField (org.compiere.model.GridField mField)
{
m_mField = mField;
EditorContextPopupMenu.onGridFieldSet(this);
} // setField
@Override
public GridField getField() {
return m_mField;
}
private class CInputVerifier extends InputVerifier {
@Override
public boolean verify(JComponent input) {
|
//NOTE: We return true no matter what since the InputVerifier is only introduced to fireVetoableChange in due time
if (getText() == null && m_oldText == null)
return true;
else if (getText().equals(m_oldText))
return true;
//
try
{
String text = getText();
fireVetoableChange(m_columnName, null, text);
m_oldText = text;
return true;
}
catch (PropertyVetoException pve) {}
return true;
} // verify
} // CInputVerifier
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
} // VMemo
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VMemo.java
| 1
|
请完成以下Java代码
|
public OutputValues getOutputValues() {
return outputValuesChild.getChild(this);
}
public void setOutputValues(OutputValues outputValues) {
outputValuesChild.setChild(this, outputValues);
}
public DefaultOutputEntry getDefaultOutputEntry() {
return defaultOutputEntryChild.getChild(this);
}
public void setDefaultOutputEntry(DefaultOutputEntry defaultOutputEntry) {
defaultOutputEntryChild.setChild(this, defaultOutputEntry);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(OutputClause.class, DMN_ELEMENT_OUTPUT_CLAUSE)
.namespaceUri(LATEST_DMN_NS)
.extendsType(DmnElement.class)
.instanceProvider(new ModelTypeInstanceProvider<OutputClause>() {
public OutputClause newInstance(ModelTypeInstanceContext instanceContext) {
|
return new OutputClauseImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_NAME)
.build();
typeRefAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_TYPE_REF)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
outputValuesChild = sequenceBuilder.element(OutputValues.class)
.build();
defaultOutputEntryChild = sequenceBuilder.element(DefaultOutputEntry.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\OutputClauseImpl.java
| 1
|
请完成以下Java代码
|
public class AppRun {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(AppRun.class);
// 监控应用的PID,启动时可指定PID路径:--spring.pid.file=/home/eladmin/app.pid
// 或者在 application.yml 添加文件路径,方便 kill,kill `cat /home/eladmin/app.pid`
springApplication.addListeners(new ApplicationPidFileWriter());
ConfigurableApplicationContext context = springApplication.run(args);
String port = context.getEnvironment().getProperty("server.port");
log.info("---------------------------------------------");
log.info("Local: http://localhost:{}", port);
log.info("Swagger: http://localhost:{}/doc.html", port);
log.info("---------------------------------------------");
}
|
@Bean
public SpringBeanHolder springContextHolder() {
return new SpringBeanHolder();
}
/**
* 访问首页提示
*
* @return /
*/
@AnonymousGetMapping("/")
public String index() {
return "Backend service started successfully";
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\AppRun.java
| 1
|
请完成以下Java代码
|
public void setAuthenticationDetailsSource(
AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) {
Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource required");
this.authenticationDetailsSource = authenticationDetailsSource;
}
/**
* If set to {@code false} (the default) and authentication is successful, the request
* will be processed by the next filter in the chain. If {@code true} and
* authentication is successful, the filter chain will stop here.
* @param shouldStop set to {@code true} to prevent the next filter in the chain from
* processing the request after a successful authentication.
* @since 1.0.2
*/
public void setStopFilterChainOnSuccessfulAuthentication(boolean shouldStop) {
this.stopFilterChainOnSuccessfulAuthentication = shouldStop;
}
/**
* Sets the {@link SecurityContextRepository} to save the {@link SecurityContext} on
* authentication success. The default action is not to save the
* {@link SecurityContext}.
* @param securityContextRepository the {@link SecurityContextRepository} to use.
* Cannot be null.
*/
|
public void setSecurityContextRepository(SecurityContextRepository securityContextRepository) {
Assert.notNull(securityContextRepository, "securityContextRepository cannot be null");
this.securityContextRepository = securityContextRepository;
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
* @param securityContextHolderStrategy the {@link SecurityContextHolderStrategy} to
* use. Cannot be null.
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
}
|
repos\spring-security-main\kerberos\kerberos-web\src\main\java\org\springframework\security\kerberos\web\authentication\SpnegoAuthenticationProcessingFilter.java
| 1
|
请完成以下Java代码
|
public void setSeparator (final java.lang.String Separator)
{
set_Value (COLUMNNAME_Separator, Separator);
}
@Override
public java.lang.String getSeparator()
{
return get_ValueAsString(COLUMNNAME_Separator);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
|
@Override
public void setAD_User_ID (final int AD_User_ID)
{
if (AD_User_ID < 0)
set_Value (COLUMNNAME_AD_User_ID, null);
else
set_Value (COLUMNNAME_AD_User_ID, AD_User_ID);
}
@Override
public int getAD_User_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Warehouse.java
| 1
|
请完成以下Java代码
|
public void setJobDefinitionId(String jobDefinitionId) {
this.jobDefinitionId = jobDefinitionId;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getBatchId() {
return batchId;
}
public void setBatchId(String batchId) {
this.batchId = batchId;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public String getExternalTaskId() {
return externalTaskId;
}
public void setExternalTaskId(String externalTaskId) {
this.externalTaskId = externalTaskId;
|
}
public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[taskId=" + taskId
+ ", deploymentId=" + deploymentId
+ ", processDefinitionKey=" + processDefinitionKey
+ ", jobId=" + jobId
+ ", jobDefinitionId=" + jobDefinitionId
+ ", batchId=" + batchId
+ ", operationId=" + operationId
+ ", operationType=" + operationType
+ ", userId=" + userId
+ ", timestamp=" + timestamp
+ ", property=" + property
+ ", orgValue=" + orgValue
+ ", newValue=" + newValue
+ ", id=" + id
+ ", eventType=" + eventType
+ ", executionId=" + executionId
+ ", processDefinitionId=" + processDefinitionId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", processInstanceId=" + processInstanceId
+ ", externalTaskId=" + externalTaskId
+ ", tenantId=" + tenantId
+ ", entityType=" + entityType
+ ", category=" + category
+ ", annotation=" + annotation
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\UserOperationLogEntryEventEntity.java
| 1
|
请完成以下Java代码
|
public String getCaption(final String adLanguage)
{
return caption.translate(adLanguage);
}
public String getDescription(final String adLanguage)
{
return description.translate(adLanguage);
}
public KPIField getGroupByField()
{
final KPIField groupByField = getGroupByFieldOrNull();
if (groupByField == null)
{
throw new IllegalStateException("KPI has no group by field defined");
}
return groupByField;
}
@Nullable
public KPIField getGroupByFieldOrNull()
{
return groupByField;
}
public boolean hasCompareOffset()
{
return compareOffset != null;
}
public Set<CtxName> getRequiredContextParameters()
{
if (elasticsearchDatasource != null)
{
return elasticsearchDatasource.getRequiredContextParameters();
}
else if (sqlDatasource != null)
{
|
return sqlDatasource.getRequiredContextParameters();
}
else
{
throw new AdempiereException("Unknown datasource type: " + datasourceType);
}
}
public boolean isZoomToDetailsAvailable()
{
return sqlDatasource != null;
}
@NonNull
public SQLDatasourceDescriptor getSqlDatasourceNotNull()
{
return Check.assumeNotNull(getSqlDatasource(), "Not an SQL data source: {}", this);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\descriptor\KPI.java
| 1
|
请完成以下Java代码
|
/* package */void putOtherProperty(final String name, final Object jsonValue)
{
otherProperties.put(name, jsonValue);
}
private JSONDocumentLayout putDebugProperty(final String name, final Object jsonValue)
{
otherProperties.put("debug-" + name, jsonValue);
return this;
}
private void putDebugProperties(final Map<String, ?> debugProperties)
{
if (debugProperties == null || debugProperties.isEmpty())
{
return;
}
for (final Map.Entry<String, ?> e : debugProperties.entrySet())
{
putDebugProperty(e.getKey(), e.getValue());
}
}
private static void setAdvSearchWindows(
|
@NonNull final List<JSONDocumentLayoutSection> sections,
@NonNull final WindowId windowId,
@Nullable final DetailId tabId,
@NonNull final JSONDocumentLayoutOptions jsonOpts)
{
sections.stream()
.flatMap(section -> section.getColumns().stream())
.flatMap(column -> column.getElementGroups().stream())
.flatMap(elementGroup -> elementGroup.getElementLines().stream())
.flatMap(elementLine -> elementLine.getElements().stream())
.flatMap(element -> element.getFields().stream())
.forEach(field -> field.setAdvSearchWindow(windowId, tabId, jsonOpts));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentLayout.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
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 instanceof User)) {
return false;
}
return id != null && id.equals(((User) o).id);
}
@Override
public int hashCode() {
// see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
|
return getClass().hashCode();
}
// prettier-ignore
@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-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\domain\User.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getTenantIdLike() {
return tenantIdLike;
}
public void setTenantIdLike(String tenantIdLike) {
this.tenantIdLike = tenantIdLike;
}
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Boolean getWithoutDeleteReason() {
return withoutDeleteReason;
}
public void setWithoutDeleteReason(Boolean withoutDeleteReason) {
this.withoutDeleteReason = withoutDeleteReason;
}
public String getTaskCandidateGroup() {
return taskCandidateGroup;
}
public void setTaskCandidateGroup(String taskCandidateGroup) {
this.taskCandidateGroup = taskCandidateGroup;
}
public boolean isIgnoreTaskAssignee() {
return ignoreTaskAssignee;
}
public void setIgnoreTaskAssignee(boolean ignoreTaskAssignee) {
this.ignoreTaskAssignee = ignoreTaskAssignee;
}
|
public String getRootScopeId() {
return rootScopeId;
}
public void setRootScopeId(String rootScopeId) {
this.rootScopeId = rootScopeId;
}
public String getParentScopeId() {
return parentScopeId;
}
public void setParentScopeId(String parentScopeId) {
this.parentScopeId = parentScopeId;
}
public Set<String> getScopeIds() {
return scopeIds;
}
public void setScopeIds(Set<String> scopeIds) {
this.scopeIds = scopeIds;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskInstanceQueryRequest.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void onProcessingEnd(UUID id, RuleNodeId ruleNodeId) {
if (profilerEnabled) {
long processingTime = msgProfilerMap.computeIfAbsent(id, TbMsgProfilerInfo::new).onEnd(ruleNodeId);
if (processingTime > 0) {
ruleNodeProfilerMap.computeIfAbsent(ruleNodeId.getId(), TbRuleNodeProfilerInfo::new).record(processingTime);
}
}
}
public void onTimeout(TbMsgProfilerInfo profilerInfo) {
Map.Entry<UUID, Long> ruleNodeInfo = profilerInfo.onTimeout();
if (ruleNodeInfo != null) {
ruleNodeProfilerMap.computeIfAbsent(ruleNodeInfo.getKey(), TbRuleNodeProfilerInfo::new).record(ruleNodeInfo.getValue());
}
}
public RuleNodeInfo getLastVisitedRuleNode(UUID id) {
return lastRuleNodeMap.get(id);
}
public void printProfilerStats() {
if (profilerEnabled) {
log.debug("Top Rule Nodes by max execution time:");
ruleNodeProfilerMap.values().stream()
.sorted(Comparator.comparingLong(TbRuleNodeProfilerInfo::getMaxExecutionTime).reversed()).limit(5)
.forEach(info -> log.debug("[{}][{}] max execution time: {}. {}", queueName, info.getRuleNodeId(), info.getMaxExecutionTime(), info.getLabel()));
log.info("Top Rule Nodes by avg execution time:");
ruleNodeProfilerMap.values().stream()
.sorted(Comparator.comparingDouble(TbRuleNodeProfilerInfo::getAvgExecutionTime).reversed()).limit(5)
.forEach(info -> log.info("[{}][{}] avg execution time: {}. {}", queueName, info.getRuleNodeId(), info.getAvgExecutionTime(), info.getLabel()));
|
log.info("Top Rule Nodes by execution count:");
ruleNodeProfilerMap.values().stream()
.sorted(Comparator.comparingInt(TbRuleNodeProfilerInfo::getExecutionCount).reversed()).limit(5)
.forEach(info -> log.info("[{}][{}] execution count: {}. {}", queueName, info.getRuleNodeId(), info.getExecutionCount(), info.getLabel()));
}
}
public void cleanup() {
canceled = true;
pendingMap.clear();
successMap.clear();
failedMap.clear();
}
public boolean isCanceled() {
return skipTimeoutMsgsPossible && canceled;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\TbMsgPackProcessingContext.java
| 2
|
请完成以下Java代码
|
public I_M_DemandLine getM_DemandLine() throws RuntimeException
{
return (I_M_DemandLine)MTable.get(getCtx(), I_M_DemandLine.Table_Name)
.getPO(getM_DemandLine_ID(), get_TrxName()); }
/** Set Demand Line.
@param M_DemandLine_ID
Material Demand Line
*/
public void setM_DemandLine_ID (int M_DemandLine_ID)
{
if (M_DemandLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DemandLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DemandLine_ID, Integer.valueOf(M_DemandLine_ID));
}
/** Get Demand Line.
@return Material Demand Line
*/
public int getM_DemandLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_DemandLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_ForecastLine getM_ForecastLine() throws RuntimeException
{
return (I_M_ForecastLine)MTable.get(getCtx(), I_M_ForecastLine.Table_Name)
.getPO(getM_ForecastLine_ID(), get_TrxName()); }
/** Set Forecast Line.
@param M_ForecastLine_ID
Forecast Line
*/
public void setM_ForecastLine_ID (int M_ForecastLine_ID)
{
if (M_ForecastLine_ID < 1)
set_Value (COLUMNNAME_M_ForecastLine_ID, null);
else
set_Value (COLUMNNAME_M_ForecastLine_ID, Integer.valueOf(M_ForecastLine_ID));
}
/** Get Forecast Line.
@return Forecast Line
*/
public int getM_ForecastLine_ID ()
{
|
Integer ii = (Integer)get_Value(COLUMNNAME_M_ForecastLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_RequisitionLine getM_RequisitionLine() throws RuntimeException
{
return (I_M_RequisitionLine)MTable.get(getCtx(), I_M_RequisitionLine.Table_Name)
.getPO(getM_RequisitionLine_ID(), get_TrxName()); }
/** Set Requisition Line.
@param M_RequisitionLine_ID
Material Requisition Line
*/
public void setM_RequisitionLine_ID (int M_RequisitionLine_ID)
{
if (M_RequisitionLine_ID < 1)
set_Value (COLUMNNAME_M_RequisitionLine_ID, null);
else
set_Value (COLUMNNAME_M_RequisitionLine_ID, Integer.valueOf(M_RequisitionLine_ID));
}
/** Get Requisition Line.
@return Material Requisition Line
*/
public int getM_RequisitionLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_RequisitionLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DemandDetail.java
| 1
|
请完成以下Java代码
|
public class TextAnnotation extends Artifact {
protected String text;
protected String textFormat;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getTextFormat() {
return textFormat;
}
|
public void setTextFormat(String textFormat) {
this.textFormat = textFormat;
}
public TextAnnotation clone() {
TextAnnotation clone = new TextAnnotation();
clone.setValues(this);
return clone;
}
public void setValues(TextAnnotation otherElement) {
super.setValues(otherElement);
setText(otherElement.getText());
setTextFormat(otherElement.getTextFormat());
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\TextAnnotation.java
| 1
|
请完成以下Java代码
|
public ITrxItemExecutorBuilder<IT, RT> setContext(final Properties ctx, final String trxName)
{
this._processorCtx = null;
this._ctx = ctx;
this._trxName = trxName;
return this;
}
@Override
public ITrxItemExecutorBuilder<IT, RT> setContext(final ITrxItemProcessorContext processorCtx)
{
this._processorCtx = processorCtx;
this._ctx = null;
this._trxName = null;
return this;
}
@Override
public ITrxItemExecutorBuilder<IT, RT> setProcessor(final ITrxItemProcessor<IT, RT> processor)
{
this._processor = processor;
return this;
}
private final ITrxItemProcessor<IT, RT> getProcessor()
{
Check.assumeNotNull(_processor, "processor is set");
return _processor;
}
@Override
public TrxItemExecutorBuilder<IT, RT> setExceptionHandler(@NonNull final ITrxItemExceptionHandler exceptionHandler)
{
this._exceptionHandler = exceptionHandler;
return this;
}
private final ITrxItemExceptionHandler getExceptionHandler()
{
return _exceptionHandler;
}
|
@Override
public ITrxItemExecutorBuilder<IT, RT> setOnItemErrorPolicy(@NonNull final OnItemErrorPolicy onItemErrorPolicy)
{
this._onItemErrorPolicy = onItemErrorPolicy;
return this;
}
@Override
public ITrxItemExecutorBuilder<IT, RT> setItemsPerBatch(final int itemsPerBatch)
{
if (itemsPerBatch == Integer.MAX_VALUE)
{
this.itemsPerBatch = null;
}
else
{
this.itemsPerBatch = itemsPerBatch;
}
return this;
}
@Override
public ITrxItemExecutorBuilder<IT, RT> setUseTrxSavepoints(final boolean useTrxSavepoints)
{
this._useTrxSavepoints = useTrxSavepoints;
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\impl\TrxItemExecutorBuilder.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.