instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public BigDecimal getQtyPicked()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPicked);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyToPick (final BigDecimal QtyToPick)
{
set_ValueNoCheck (COLUMNNAME_QtyToPick, QtyToPick);
}
@Override
public BigDecimal getQtyToPick()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* RejectReason AD_Reference_ID=541422
* Reference name: QtyNotPicked RejectReason
*/
public static final int REJECTREASON_AD_Reference_ID=541422;
/** NotFound = N */
public static final String REJECTREASON_NotFound = "N";
/** Damaged = D */
public static final String REJECTREASON_Damaged = "D";
@Override
public void setRejectReason (final @Nullable java.lang.String RejectReason)
{
set_Value (COLUMNNAME_RejectReason, RejectReason);
}
@Override
public java.lang.String getRejectReason() | {
return get_ValueAsString(COLUMNNAME_RejectReason);
}
/**
* Status AD_Reference_ID=541435
* Reference name: DD_OrderLine_Schedule_Status
*/
public static final int STATUS_AD_Reference_ID=541435;
/** NotStarted = NS */
public static final String STATUS_NotStarted = "NS";
/** InProgress = IP */
public static final String STATUS_InProgress = "IP";
/** Completed = CO */
public static final String STATUS_Completed = "CO";
@Override
public void setStatus (final java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return get_ValueAsString(COLUMNNAME_Status);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_DD_Order_MoveSchedule.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public PageBean queryAccountHistoryListPage(PageParam pageParam, String accountNo){
Map<String, Object> params = new HashMap<String, Object>();
params.put("accountNo", accountNo);
return rpAccountDao.listPage(pageParam, params);
}
/**
* 分页查询账户历史单角色
*/
public PageBean queryAccountHistoryListPageByRole(PageParam pageParam, Map<String, Object> params){
String accountType = (String) params.get("accountType");
if (StringUtils.isBlank(accountType)) {
throw AccountBizException.ACCOUNT_TYPE_IS_NULL;
}
return rpAccountDao.listPage(pageParam, params);
}
/**
* 获取账户历史单角色
*
* @param accountNo
* 账户编号
* @param requestNo
* 请求号
* @param trxType
* 业务类型
* @return AccountHistory
*/
public RpAccountHistory getAccountHistoryByAccountNo_requestNo_trxType(String accountNo, String requestNo, Integer trxType) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("accountNo", accountNo);
map.put("requestNo", requestNo);
map.put("trxType", trxType);
return rpAccountHistoryDao.getBy(map);
}
/**
* 日汇总账户待结算金额 .
*
* @param accountNo
* 账户编号
* @param statDate
* 统计日期
* @param riskDay
* 风险预测期
* @param fundDirection
* 资金流向
* @return
*/
public List<DailyCollectAccountHistoryVo> listDailyCollectAccountHistoryVo(String accountNo, String statDate, Integer riskDay, Integer fundDirection) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("accountNo", accountNo);
params.put("statDate", statDate);
params.put("riskDay", riskDay);
params.put("fundDirection", fundDirection);
return rpAccountHistoryDao.listDailyCollectAccountHistoryVo(params);
}
/** | * 根据参数分页查询账户.
*
* @param pageParam
* 分页参数.
* @param params
* 查询参数,可以为null.
* @return AccountList.
* @throws BizException
*/
public PageBean queryAccountListPage(PageParam pageParam, Map<String, Object> params) {
return rpAccountDao.listPage(pageParam, params);
}
/**
* 根据参数分页查询账户历史.
*
* @param pageParam
* 分页参数.
* @param params
* 查询参数,可以为null.
* @return AccountHistoryList.
* @throws BizException
*/
public PageBean queryAccountHistoryListPage(PageParam pageParam, Map<String, Object> params) {
return rpAccountHistoryDao.listPage(pageParam, params);
}
/**
* 获取所有账户
* @return
*/
@Override
public List<RpAccount> listAll(){
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("status", PublicStatusEnum.ACTIVE.name());
return rpAccountDao.listBy(paramMap);
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\service\impl\RpAccountQueryServiceImpl.java | 2 |
请完成以下Java代码 | public void cacheReset()
{
viewActionInstancesByViewId.reset();
}
@ToString
private static final class ViewActionInstancesList
{
private final String viewId;
private final AtomicInteger nextIdSupplier = new AtomicInteger(1);
private final ConcurrentHashMap<DocumentId, ViewActionInstance> instances = new ConcurrentHashMap<>();
public ViewActionInstancesList(@NonNull final String viewId)
{
this.viewId = viewId;
}
public ViewActionInstance getByInstanceId(final DocumentId pinstanceId)
{
final ViewActionInstance actionInstance = instances.get(pinstanceId);
if (actionInstance == null)
{
throw new EntityNotFoundException("No view action instance found for " + pinstanceId);
}
return actionInstance;
}
private DocumentId nextPInstanceId()
{ | final int nextId = nextIdSupplier.incrementAndGet();
return DocumentId.ofString(viewId + "_" + nextId);
}
public static String extractViewId(@NonNull final DocumentId pinstanceId)
{
final String pinstanceIdStr = pinstanceId.toJson();
final int idx = pinstanceIdStr.indexOf("_");
return pinstanceIdStr.substring(0, idx);
}
public void add(final ViewActionInstance viewActionInstance)
{
instances.put(viewActionInstance.getInstanceId(), viewActionInstance);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\view\ViewProcessInstancesRepository.java | 1 |
请完成以下Java代码 | public Optional<Document> getDocumentById(final DocumentId documentId)
{
final Document document = DocumentQuery.builder(entityDescriptor)
.setParentDocument(parentDocument)
.setRecordId(documentId)
.retriveDocumentOrNull();
if (document == null)
{
return Optional.empty();
}
return Optional.of(document);
}
@Override
public void updateStatusFromParent()
{
// nothing
}
@Override
public void assertNewDocumentAllowed()
{
throw new InvalidDocumentStateException(parentDocument, RESULT_TabReadOnly.getName());
}
@Override
public LogicExpressionResult getAllowCreateNewDocument()
{
return RESULT_TabReadOnly;
}
@Override
public Document createNewDocument()
{
throw new InvalidDocumentStateException(parentDocument, RESULT_TabReadOnly.getName());
}
@Override
public LogicExpressionResult getAllowDeleteDocument()
{
return RESULT_TabReadOnly;
}
@Override
public void deleteDocuments(final DocumentIdsSelection documentIds)
{
throw new InvalidDocumentStateException(parentDocument, RESULT_TabReadOnly.getName());
}
@Override | public DocumentValidStatus checkAndGetValidStatus(final OnValidStatusChanged onValidStatusChanged)
{
return DocumentValidStatus.documentValid();
}
@Override
public boolean hasChangesRecursivelly()
{
return false;
}
@Override
public void saveIfHasChanges()
{
}
@Override
public void markStaleAll()
{
}
@Override
public void markStale(final DocumentIdsSelection rowIds)
{
}
@Override
public boolean isStale()
{
return false;
}
@Override
public int getNextLineNo()
{
throw new UnsupportedOperationException();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\HighVolumeReadonlyIncludedDocumentsCollection.java | 1 |
请完成以下Java代码 | public JXTaskPane getComponent()
{
return panel;
}
public int getTopNodeId()
{
return topNodeId;
}
public void removeAllItems()
{
toolbar.removeAll();
}
public void addFavorite(final MTreeNode node)
{
if (node2item.get(node) != null)
{
// already added
return;
}
final FavoriteItem item = new FavoriteItem(this, node);
item.addMouseListener(itemMouseListener);
item.addActionListener(itemActionListener);
final JComponent itemComp = item.getComponent();
node2item.put(node, item);
component2item.put(itemComp, item);
node.setOnBar(true);
toolbar.add(itemComp); | }
public boolean isEmpty()
{
return node2item.isEmpty();
}
public void removeItem(final FavoriteItem item)
{
Check.assumeNotNull(item, "item not null");
final MTreeNode node = item.getNode();
final JComponent itemComp = item.getComponent();
node2item.remove(node);
component2item.remove(itemComp);
node.setOnBar(false);
toolbar.remove(itemComp);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\tree\FavoritesGroup.java | 1 |
请完成以下Java代码 | default CountryId getDefaultCountryId()
{
return CountryId.ofRepoId(getDefault(Env.getCtx()).getC_Country_ID());
}
@Deprecated
I_C_Country get(Properties ctx, int C_Country_ID);
/**
* Return Countries as Array
*
* @param ctx
* context
* @return countries
*/
List<I_C_Country> getCountries(Properties ctx);
List<I_C_Region> retrieveRegions(Properties ctx, int countryId);
Optional<CountrySequences> getCountrySequences(CountryId countryId, OrgId orgId, String adLanguage); | I_C_Country retrieveCountryByCountryCode(String countryCode);
CountryId getCountryIdByCountryCode(String countryCode);
CountryId getCountryIdByCountryCode(@NonNull CountryCode countryCode);
CountryId getCountryIdByCountryCodeOrNull(String countryCode);
String retrieveCountryCode2ByCountryId(CountryId countryId);
String retrieveCountryCode3ByCountryId(CountryId countryId);
ITranslatableString getCountryNameById(CountryId countryId);
Optional<CurrencyId> getCountryCurrencyId(CountryId countryId);
String getCountryCode(@NonNull CountryId countryId);
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\ICountryDAO.java | 1 |
请完成以下Java代码 | public static <S, T> void addToMapOfSets(Map<S, Set<T>> map, S key, T value) {
Set<T> set = map.get(key);
if (set == null) {
set = new HashSet<>();
map.put(key, set);
}
set.add(value);
}
public static <S, T> void addCollectionToMapOfSets(Map<S, Set<T>> map, S key, Collection<T> values) {
Set<T> set = map.get(key);
if (set == null) {
set = new HashSet<>();
map.put(key, set);
}
set.addAll(values);
}
/**
* Chops a list into non-view sublists of length partitionSize. Note: the argument list
* may be included in the result.
*/
public static <T> List<List<T>> partition(List<T> list, final int partitionSize) {
List<List<T>> parts = new ArrayList<>();
final int listSize = list.size();
if (listSize <= partitionSize) {
// no need for partitioning
parts.add(list);
} else {
for (int i = 0; i < listSize; i += partitionSize) {
parts.add(new ArrayList<>(list.subList(i, Math.min(listSize, i + partitionSize))));
}
}
return parts;
}
public static <T> List<T> collectInList(Iterator<T> iterator) {
List<T> result = new ArrayList<>();
while (iterator.hasNext()) {
result.add(iterator.next());
} | return result;
}
public static <T> T getLastElement(final Iterable<T> elements) {
T lastElement = null;
if (elements instanceof List) {
return ((List<T>) elements).get(((List<T>) elements).size() - 1);
}
for (T element : elements) {
lastElement = element;
}
return lastElement;
}
public static boolean isEmpty(Collection<?> collection) {
return collection == null || collection.isEmpty();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\CollectionUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MealWithMultipleEntities {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@Column(name = "description")
private String description;
@Column(name = "price")
private BigDecimal price;
@OneToOne(mappedBy = "meal")
private AllergensAsEntity allergens;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
} | public void setDescription(String description) {
this.description = description;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public AllergensAsEntity getAllergens() {
return allergens;
}
public void setAllergens(AllergensAsEntity allergens) {
this.allergens = allergens;
}
public Long getId() {
return id;
}
@Override
public String toString() {
return "MealWithMultipleEntities [id=" + id + ", name=" + name + ", description=" + description + ", price=" + price + ", allergens=" + allergens + "]";
}
} | repos\tutorials-master\persistence-modules\java-jpa-2\src\main\java\com\baeldung\jpa\multipletables\multipleentities\MealWithMultipleEntities.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ButtonEventHandlerController {
private static final Logger logger = LoggerFactory.getLogger(ButtonEventHandlerController.class);
@FXML
private Button button;
@FXML
private Label label;
@FXML
private void initialize() {
button.setText("Click me");
handleClickEvent();
handleHoverEffect();
reuseRightClickEventHandler();
}
private void handleClickEvent() {
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
logger.info("OnAction {}", event);
}
});
button.setOnAction(event -> logger.info("OnAction {}", event)); | button.setOnAction(event -> logger.info("OnAction2 {}", event));
}
private void handleHoverEffect() {
Effect shadow = new DropShadow();
button.setOnMouseEntered(e -> button.setEffect(shadow));
button.setOnMouseExited(e -> button.setEffect(null));
}
private void reuseRightClickEventHandler() {
EventHandler<MouseEvent> rightClickHandler = event -> {
if (MouseButton.SECONDARY.equals(event.getButton())) {
button.setFont(new Font(button.getFont()
.getSize() + 1));
}
};
button.setOnMousePressed(rightClickHandler);
label.setOnMousePressed(rightClickHandler);
}
} | repos\tutorials-master\javafx\src\main\java\com\baeldung\button\eventhandler\ButtonEventHandlerController.java | 2 |
请完成以下Java代码 | public class ClassDelegateExecutionListener extends ClassDelegate implements ExecutionListener {
protected static final BpmnBehaviorLogger LOG = ProcessEngineLogger.BPMN_BEHAVIOR_LOGGER;
public ClassDelegateExecutionListener(String className, List<FieldDeclaration> fieldDeclarations) {
super(className, fieldDeclarations);
}
public ClassDelegateExecutionListener(Class<?> clazz, List<FieldDeclaration> fieldDeclarations) {
super(clazz, fieldDeclarations);
}
// Execution listener
public void notify(DelegateExecution execution) throws Exception {
ExecutionListener executionListenerInstance = getExecutionListenerInstance();
Context.getProcessEngineConfiguration()
.getDelegateInterceptor()
.handleInvocation(new ExecutionListenerInvocation(executionListenerInstance, execution)); | }
protected ExecutionListener getExecutionListenerInstance() {
Object delegateInstance = instantiateDelegate(className, fieldDeclarations);
if (delegateInstance instanceof ExecutionListener) {
return (ExecutionListener) delegateInstance;
} else if (delegateInstance instanceof JavaDelegate) {
return new ServiceTaskJavaDelegateActivityBehavior((JavaDelegate) delegateInstance);
} else {
throw LOG.missingDelegateParentClassException(delegateInstance.getClass().getName(),
ExecutionListener.class.getName(), JavaDelegate.class.getName());
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\listener\ClassDelegateExecutionListener.java | 1 |
请完成以下Java代码 | public Builder setFromPreviousResult(@Nullable final KPIDataResult previousResult)
{
if (previousResult == null)
{
builtDatasets(ImmutableList.of());
range(null);
}
else
{
builtDatasets(previousResult.getDatasets());
range(previousResult.getRange());
datasetsComputedTime(previousResult.getDatasetsComputedTime());
datasetsComputeDuration(previousResult.getDatasetsComputeDuration());
}
return this;
}
public KPIDataSet.KPIDataSetBuilder dataSet(final String name)
{
if (builtDatasets != null)
{
throw new AdempiereException("datasets were already built");
}
if (datasets == null)
{
datasets = new LinkedHashMap<>();
}
return datasets.computeIfAbsent(name, KPIDataSet::builder);
}
private void datasetsComputedTime(@Nullable final Instant datasetsComputedTime)
{
this.datasetsComputedTime = datasetsComputedTime;
}
private void builtDatasets(final ImmutableList<KPIDataSet> builtDatasets)
{
if (datasets != null && !datasets.isEmpty())
{
throw new AdempiereException("Setting builtDatasets not allowed when some datasets builder were previously set");
}
this.builtDatasets = builtDatasets;
}
public Builder range(@Nullable final TimeRange range)
{
this.range = range;
return this;
}
@Nullable
public TimeRange getRange()
{
return range;
}
public Builder datasetsComputeDuration(@Nullable final Duration datasetsComputeDuration) | {
this.datasetsComputeDuration = datasetsComputeDuration;
return this;
}
public void putValue(
@NonNull final String dataSetName,
@NonNull final KPIDataSetValuesAggregationKey dataSetValueKey,
@NonNull final String fieldName,
@NonNull final KPIDataValue value)
{
dataSet(dataSetName).putValue(dataSetValueKey, fieldName, value);
}
public void putValueIfAbsent(
@NonNull final String dataSetName,
@NonNull final KPIDataSetValuesAggregationKey dataSetValueKey,
@NonNull final String fieldName,
@NonNull final KPIDataValue value)
{
dataSet(dataSetName).putValueIfAbsent(dataSetValueKey, fieldName, value);
}
public Builder error(@NonNull final Exception exception)
{
final ITranslatableString errorMessage = AdempiereException.isUserValidationError(exception)
? AdempiereException.extractMessageTrl(exception)
: TranslatableStrings.adMessage(MSG_FailedLoadingKPI);
this.error = WebuiError.of(exception, errorMessage);
return this;
}
public Builder error(@NonNull final ITranslatableString errorMessage)
{
this.error = WebuiError.of(errorMessage);
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\KPIDataResult.java | 1 |
请完成以下Java代码 | public class JaxbParser {
private File file;
public JaxbParser(File file) {
this.file = file;
}
public Tutorials getFullDocument() {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Tutorials.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Tutorials tutorials = (Tutorials) jaxbUnmarshaller.unmarshal(this.getFile());
return tutorials;
} catch (JAXBException e) {
e.printStackTrace();
return null;
}
}
public void createNewDocument() {
Tutorials tutorials = new Tutorials();
tutorials.setTutorial(new ArrayList<Tutorial>());
Tutorial tut = new Tutorial();
tut.setTutId("01");
tut.setType("XML");
tut.setTitle("XML with Jaxb");
tut.setDescription("XML Binding with Jaxb");
tut.setDate("04/02/2015"); | tut.setAuthor("Jaxb author");
tutorials.getTutorial().add(tut);
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Tutorials.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(tutorials, file);
} catch (JAXBException e) {
e.printStackTrace();
}
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
} | repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\xml\JaxbParser.java | 1 |
请完成以下Java代码 | public String getTransitionInstanceId() {
return transitionInstanceId;
}
public void setTransitionInstanceId(String transitionInstanceId) {
this.transitionInstanceId = transitionInstanceId;
}
public String getAncestorActivityInstanceId() {
return ancestorActivityInstanceId;
}
public void setAncestorActivityInstanceId(String ancestorActivityInstanceId) {
this.ancestorActivityInstanceId = ancestorActivityInstanceId;
}
public boolean isCancelCurrentActiveActivityInstances() {
return cancelCurrentActiveActivityInstances;
}
public void setCancelCurrentActiveActivityInstances(boolean cancelCurrentActiveActivityInstances) {
this.cancelCurrentActiveActivityInstances = cancelCurrentActiveActivityInstances;
}
public abstract void applyTo(ProcessInstanceModificationBuilder builder, ProcessEngine engine, ObjectMapper mapper);
public abstract void applyTo(InstantiationBuilder<?> builder, ProcessEngine engine, ObjectMapper mapper);
protected String buildErrorMessage(String message) {
return "For instruction type '" + type + "': " + message;
}
protected void applyVariables(ActivityInstantiationBuilder<?> builder, | ProcessEngine engine, ObjectMapper mapper) {
if (variables != null) {
for (Map.Entry<String, TriggerVariableValueDto> variableValue : variables.entrySet()) {
TriggerVariableValueDto value = variableValue.getValue();
if (value.isLocal()) {
builder.setVariableLocal(variableValue.getKey(), value.toTypedValue(engine, mapper));
}
else {
builder.setVariable(variableValue.getKey(), value.toTypedValue(engine, mapper));
}
}
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\modification\ProcessInstanceModificationInstructionDto.java | 1 |
请完成以下Java代码 | public Integer getAdminCount() {
return adminCount;
}
public void setAdminCount(Integer adminCount) {
this.adminCount = adminCount;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getSort() {
return sort; | }
public void setSort(Integer sort) {
this.sort = sort;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", description=").append(description);
sb.append(", adminCount=").append(adminCount);
sb.append(", createTime=").append(createTime);
sb.append(", status=").append(status);
sb.append(", sort=").append(sort);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsRole.java | 1 |
请完成以下Java代码 | private final void reportAD_Issue(final ILoggingEvent event)
{
// Skip creating the issue if database connection is not available or if the system was not configured to AutoReportError
if (!DB.isConnected())
{
return;
}
final IErrorManager errorManager = Services.get(IErrorManager.class);
errorManager.createIssue(IssueCreateRequest.builder()
.summary(event.getMessage())
.sourceClassname(extractSourceClassName(event))
.sourceMethodName(extractSourceMethodName(event))
.loggerName(event.getLoggerName())
.throwable(extractThrowable(event))
.build());
}
private static final String extractSourceClassName(final ILoggingEvent event)
{
if (event == null)
{
return null;
}
final StackTraceElement[] callerData = event.getCallerData();
if (callerData == null || callerData.length < 1)
{
return null;
}
return callerData[0].getClassName();
}
private static final String extractSourceMethodName(final ILoggingEvent event)
{
if (event == null)
{
return null;
}
final StackTraceElement[] callerData = event.getCallerData();
if (callerData == null || callerData.length < 1)
{
return null; | }
return callerData[0].getMethodName();
}
private static final Throwable extractThrowable(final ILoggingEvent event)
{
if (event == null)
{
return null;
}
final IThrowableProxy throwableProxy = event.getThrowableProxy();
if (throwableProxy instanceof ThrowableProxy)
{
return ((ThrowableProxy)throwableProxy).getThrowable();
}
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\logging\MetasfreshIssueAppender.java | 1 |
请完成以下Java代码 | public Result processWorkPackage(@NonNull final I_C_Queue_WorkPackage workpackage, final String localTrxName)
{
trxManager.assertTrxNameNull(localTrxName);
final Properties ctx = InterfaceWrapperHelper.getCtx(workpackage);
final int adClientId = workpackage.getAD_Client_ID();
Check.assume(adClientId > 0, "No point in calling this process with AD_Client_ID=0");
//
// Get parameters
final int maxInvoiceCandidatesToUpdate = getMaxInvoiceCandidatesToUpdate();
//
// Update invalid ICs
invoiceCandBL.updateInvalid()
.setContext(ctx, localTrxName)
// Only those which are not locked at all
.setLockedBy(ILock.NULL)
.setTaggedWithNoTag()
.setLimit(maxInvoiceCandidatesToUpdate)
.update();
//
// If we updated just a limited set of invoice candidates,
// then create a new workpackage to update the rest of them.
if (maxInvoiceCandidatesToUpdate > 0)
{
final int countRemaining = invoiceCandDAO.tagToRecompute()
.setContext(ctx, localTrxName)
.setLockedBy(ILock.NULL)
.setTaggedWithNoTag()
.countToBeTagged();
if (countRemaining > 0) | {
final AsyncBatchId asyncBatchId = AsyncBatchId.ofRepoIdOrNull(getC_Queue_WorkPackage().getC_Async_Batch_ID());
final IInvoiceCandUpdateSchedulerRequest request = InvoiceCandUpdateSchedulerRequest.of(ctx, localTrxName, asyncBatchId);
schedule(request);
Loggables.addLog("Scheduled another workpackage for {} remaining recompute records", countRemaining);
}
}
return Result.SUCCESS;
}
private int getMaxInvoiceCandidatesToUpdate()
{
return sysConfigBL.getIntValue(SYSCONFIG_MaxInvoiceCandidatesToUpdate, DEFAULT_MaxInvoiceCandidatesToUpdate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\async\spi\impl\UpdateInvalidInvoiceCandidatesWorkpackageProcessor.java | 1 |
请完成以下Java代码 | private IExternalSystemChildConfigId getExternalSystemChildConfigId(@NonNull final GlobalQRCode scannedQRCode)
{
if (ResourceQRCode.isTypeMatching(scannedQRCode))
{
return getExternalSystemChildConfigId(ResourceQRCode.ofGlobalQRCode(scannedQRCode));
}
else if (ExternalSystemConfigQRCode.isTypeMatching(scannedQRCode))
{
final ExternalSystemConfigQRCode configQRCode = ExternalSystemConfigQRCode.ofGlobalQRCode(scannedQRCode);
return configQRCode.getChildConfigId();
}
else
{
throw new AdempiereException(NOT_AN_EXTERNAL_SYSTEM_ERR_MESSAGE_KEY);
}
} | @NonNull
private IExternalSystemChildConfigId getExternalSystemChildConfigId(@NonNull final ResourceQRCode resourceQRCode)
{
final Resource externalSystemResource = resourceService.getById(resourceQRCode.getResourceId());
if (!externalSystemResource.isExternalSystem())
{
throw new AdempiereException(NOT_AN_EXTERNAL_SYSTEM_ERR_MESSAGE_KEY);
}
return ExternalSystemParentConfigId.ofRepoIdOptional(externalSystemResource.getExternalSystemParentConfigId())
.flatMap(externalSystemConfigRepo::getChildByParentId)
.map(IExternalSystemChildConfig::getId)
.orElseThrow(() -> new AdempiereException(NOT_AN_EXTERNAL_SYSTEM_ERR_MESSAGE_KEY));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\activity_handlers\callExternalSystem\CallExternalSystemActivityHandler.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public TenantProfileData getProfileData() {
if (profileData != null) {
return profileData;
} else {
if (profileDataBytes != null) {
try {
profileData = mapper.readValue(new ByteArrayInputStream(profileDataBytes), TenantProfileData.class);
} catch (IOException e) {
log.warn("Can't deserialize tenant profile data: ", e);
return createDefaultTenantProfileData();
}
return profileData;
} else {
return createDefaultTenantProfileData();
}
}
}
@JsonIgnore
public Optional<DefaultTenantProfileConfiguration> getProfileConfiguration() {
return Optional.ofNullable(getProfileData().getConfiguration())
.filter(profileConfiguration -> profileConfiguration instanceof DefaultTenantProfileConfiguration)
.map(profileConfiguration -> (DefaultTenantProfileConfiguration) profileConfiguration); | }
@JsonIgnore
public DefaultTenantProfileConfiguration getDefaultProfileConfiguration() {
return getProfileConfiguration().orElse(null);
}
public TenantProfileData createDefaultTenantProfileData() {
TenantProfileData tpd = new TenantProfileData();
tpd.setConfiguration(new DefaultTenantProfileConfiguration());
this.profileData = tpd;
return tpd;
}
public void setProfileData(TenantProfileData data) {
this.profileData = data;
try {
this.profileDataBytes = data != null ? mapper.writeValueAsBytes(data) : null;
} catch (JsonProcessingException e) {
log.warn("Can't serialize tenant profile data: ", e);
}
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\TenantProfile.java | 1 |
请完成以下Java代码 | public I_M_AttributeSetInstance getM_AttributeSetInstance()
{
return olCand.getM_AttributeSetInstance();
}
@Override
public int getM_AttributeSetInstance_ID()
{
return olCand.getM_AttributeSetInstance_ID();
}
@Override
public void setM_AttributeSetInstance(final I_M_AttributeSetInstance asi)
{
olCand.setM_AttributeSetInstance(asi);
} | @Override
public String toString()
{
return "IAttributeSetInstanceAware[" + olCand.toString() + "]";
}
@Override
public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID)
{
olCand.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID);
}
};
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\spi\impl\OLCandASIAwareFactory.java | 1 |
请完成以下Java代码 | public TenantId getTenantId() {
return TenantId.SYS_TENANT_ID;
}
@Override
public EntityId getOriginatorEntityId() {
return TenantId.SYS_TENANT_ID;
}
@Override
public DeduplicationStrategy getDeduplicationStrategy() {
return DeduplicationStrategy.ONLY_MATCHING;
}
@Override
public String getDeduplicationKey() {
return String.join(":", resource.name(), serviceId, serviceType); | }
@Override
public long getDefaultDeduplicationDuration() {
return TimeUnit.HOURS.toMillis(1);
}
@Override
public NotificationRuleTriggerType getType() {
return NotificationRuleTriggerType.RESOURCES_SHORTAGE;
}
public enum Resource {
CPU, RAM, STORAGE
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\notification\rule\trigger\ResourcesShortageTrigger.java | 1 |
请完成以下Java代码 | public void setC_UOM_ID (final int C_UOM_ID)
{
if (C_UOM_ID < 1)
set_Value (COLUMNNAME_C_UOM_ID, null);
else
set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID);
}
@Override
public int getC_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_C_UOM_ID);
}
@Override
public void setC_Workplace_ID (final int C_Workplace_ID)
{
if (C_Workplace_ID < 1)
set_Value (COLUMNNAME_C_Workplace_ID, null);
else
set_Value (COLUMNNAME_C_Workplace_ID, C_Workplace_ID);
}
@Override
public int getC_Workplace_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Workplace_ID);
}
@Override
public void setM_Picking_Job_Schedule_ID (final int M_Picking_Job_Schedule_ID)
{
if (M_Picking_Job_Schedule_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Picking_Job_Schedule_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Picking_Job_Schedule_ID, M_Picking_Job_Schedule_ID);
}
@Override
public int getM_Picking_Job_Schedule_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Picking_Job_Schedule_ID);
}
@Override
public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID)
{
if (M_ShipmentSchedule_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID);
}
@Override
public int getM_ShipmentSchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); | }
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setQtyToPick (final BigDecimal QtyToPick)
{
set_Value (COLUMNNAME_QtyToPick, QtyToPick);
}
@Override
public BigDecimal getQtyToPick()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_Picking_Job_Schedule.java | 1 |
请完成以下Java代码 | public void setPage_Size (int Page_Size)
{
set_ValueNoCheck (COLUMNNAME_Page_Size, Integer.valueOf(Page_Size));
}
/** Get Page_Size.
@return Page_Size */
@Override
public int getPage_Size ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Page_Size);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Result_Time.
@param Result_Time Result_Time */
@Override
public void setResult_Time (java.sql.Timestamp Result_Time)
{
set_ValueNoCheck (COLUMNNAME_Result_Time, Result_Time);
}
/** Get Result_Time.
@return Result_Time */
@Override
public java.sql.Timestamp getResult_Time ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_Result_Time);
}
/** Set Total_Size.
@param Total_Size Total_Size */ | @Override
public void setTotal_Size (int Total_Size)
{
set_ValueNoCheck (COLUMNNAME_Total_Size, Integer.valueOf(Total_Size));
}
/** Get Total_Size.
@return Total_Size */
@Override
public int getTotal_Size ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Total_Size);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set UUID.
@param UUID UUID */
@Override
public void setUUID (java.lang.String UUID)
{
set_ValueNoCheck (COLUMNNAME_UUID, UUID);
}
/** Get UUID.
@return UUID */
@Override
public java.lang.String getUUID ()
{
return (java.lang.String)get_Value(COLUMNNAME_UUID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dao\selection\model\X_T_Query_Selection_Pagination.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private AnnotationAttributes resolveAnnotationAttributes(List<AnnotationAttributes> annotationAttributesList,
int index) {
if (index < annotationAttributesList.size()) {
return annotationAttributesList.get(index);
}
else {
AnnotationAttributes newAnnotationAttributes = new AnnotationAttributes();
annotationAttributesList.add(newAnnotationAttributes);
return newAnnotationAttributes;
}
}
private PropertyResolver getPropertyResolver(ConditionContext context) {
return context.getEnvironment();
}
private List<String> collectPropertyNames(AnnotationAttributes annotationAttributes) {
String prefix = getPrefix(annotationAttributes);
String[] names = getNames(annotationAttributes);
return Arrays.stream(names).map(name -> prefix + name).collect(Collectors.toList());
}
private String[] getNames(AnnotationAttributes annotationAttributes) {
String[] names = annotationAttributes.getStringArray("name");
String[] values = annotationAttributes.getStringArray("value");
Assert.isTrue(names.length > 0 || values.length > 0,
String.format("The name or value attribute of @%s is required",
ConditionalOnMissingProperty.class.getSimpleName())); | // TODO remove; not needed when using @AliasFor.
/*
Assert.isTrue(names.length * values.length == 0,
String.format("The name and value attributes of @%s are exclusive",
ConditionalOnMissingProperty.class.getSimpleName()));
*/
return names.length > 0 ? names : values;
}
private String getPrefix(AnnotationAttributes annotationAttributes) {
String prefix = annotationAttributes.getString("prefix");
return StringUtils.hasText(prefix) ? prefix.trim().endsWith(".") ? prefix.trim() : prefix.trim() + "." : "";
}
private Collection<String> findMatchingProperties(PropertyResolver propertyResolver, List<String> propertyNames) {
return propertyNames.stream().filter(propertyResolver::containsProperty).collect(Collectors.toSet());
}
private ConditionOutcome determineConditionOutcome(Collection<String> matchingProperties) {
if (!matchingProperties.isEmpty()) {
return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnMissingProperty.class)
.found("property already defined", "properties already defined")
.items(matchingProperties));
}
return ConditionOutcome.match();
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\condition\OnMissingPropertyCondition.java | 2 |
请完成以下Java代码 | public List<CaseSentryPartEntity> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
List<CaseSentryPartEntity> result = commandContext
.getCaseSentryPartManager()
.findCaseSentryPartByQueryCriteria(this, page);
return result;
}
// getters /////////////////////////////////////////////
public String getId() {
return id;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String getCaseExecutionId() {
return caseExecutionId;
}
public String getSentryId() {
return sentryId;
}
public String getType() {
return type;
} | public String getSourceCaseExecutionId() {
return sourceCaseExecutionId;
}
public String getStandardEvent() {
return standardEvent;
}
public String getVariableEvent() {
return variableEvent;
}
public String getVariableName() {
return variableName;
}
public boolean isSatisfied() {
return satisfied;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\runtime\CaseSentryPartQueryImpl.java | 1 |
请完成以下Java代码 | public void setTechnicalNote (final @Nullable java.lang.String TechnicalNote)
{
set_Value (COLUMNNAME_TechnicalNote, TechnicalNote);
}
@Override
public java.lang.String getTechnicalNote()
{
return get_ValueAsString(COLUMNNAME_TechnicalNote);
}
@Override
public void setValueMax (final @Nullable java.lang.String ValueMax)
{
set_Value (COLUMNNAME_ValueMax, ValueMax);
}
@Override
public java.lang.String getValueMax()
{
return get_ValueAsString(COLUMNNAME_ValueMax);
}
@Override
public void setValueMin (final @Nullable java.lang.String ValueMin)
{
set_Value (COLUMNNAME_ValueMin, ValueMin);
}
@Override
public java.lang.String getValueMin() | {
return get_ValueAsString(COLUMNNAME_ValueMin);
}
@Override
public void setVersion (final BigDecimal Version)
{
set_Value (COLUMNNAME_Version, Version);
}
@Override
public BigDecimal getVersion()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Version);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setVFormat (final @Nullable java.lang.String VFormat)
{
set_Value (COLUMNNAME_VFormat, VFormat);
}
@Override
public java.lang.String getVFormat()
{
return get_ValueAsString(COLUMNNAME_VFormat);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Column.java | 1 |
请完成以下Java代码 | private void assertLastHUTrxWasThisInventoryLine(@NonNull final InventoryLine line, @NonNull final InventoryLineHU lineHU)
{
final HuId huId = Objects.requireNonNull(lineHU.getHuId());
final InventoryLineId lineId = Objects.requireNonNull(line.getId());
if (!huTransactionBL.isLatestHUTrx(huId, TableRecordReference.of(I_M_InventoryLine.Table_Name, lineId)))
{
throw new HUException("@InventoryReverseError@")
.setParameter("line", line)
.setParameter("lineHU", lineHU);
}
}
@DocValidate(timings = ModelValidator.TIMING_AFTER_REVERSECORRECT)
public void afterReverseCorrect(final I_M_Inventory inventory)
{
if (inventoryService.isMaterialDisposal(inventory))
{
restoreHUsFromSnapshots(inventory);
reverseEmptiesMovements(inventory);
}
}
private void restoreHUsFromSnapshots(final I_M_Inventory inventory)
{
final String snapshotId = inventory.getSnapshot_UUID();
if (Check.isBlank(snapshotId))
{
throw new HUException("@NotFound@ @Snapshot_UUID@ (" + inventory + ")");
}
final InventoryId inventoryId = InventoryId.ofRepoId(inventory.getM_Inventory_ID());
final List<Integer> topLevelHUIds = inventoryDAO.retrieveLinesForInventoryId(inventoryId, I_M_InventoryLine.class)
.stream()
.map(I_M_InventoryLine::getM_HU_ID)
.collect(ImmutableList.toImmutableList());
huSnapshotDAO.restoreHUs()
.setContext(PlainContextAware.newWithThreadInheritedTrx())
.setSnapshotId(snapshotId) | .setDateTrx(inventory.getMovementDate())
.addModelIds(topLevelHUIds)
.setReferencedModel(inventory)
.restoreFromSnapshot();
}
private void reverseEmptiesMovements(final I_M_Inventory inventory)
{
final InventoryId inventoryId = InventoryId.ofRepoId(inventory.getM_Inventory_ID());
movementDAO.retrieveMovementsForInventoryQuery(inventoryId)
.addEqualsFilter(I_M_Inventory.COLUMNNAME_DocStatus, X_M_Inventory.DOCSTATUS_Completed)
.create()
.stream()
.forEach(emptiesMovement -> documentBL.processEx(emptiesMovement, X_M_Movement.DOCACTION_Reverse_Correct, X_M_Movement.DOCSTATUS_Reversed));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\interceptor\M_Inventory.java | 1 |
请完成以下Java代码 | public boolean isLastAppendedIsSeparator()
{
return lastAppendedIsSeparator;
}
public String getSeparator()
{
return separator;
}
public TokenizedStringBuilder append(final Object obj)
{
if (autoAppendSeparator)
{
appendSeparatorIfNeeded();
}
sb.append(obj);
lastAppendedIsSeparator = false; | return this;
}
public TokenizedStringBuilder appendSeparatorIfNeeded()
{
if (lastAppendedIsSeparator)
{
return this;
}
if (sb.length() <= 0)
{
return this;
}
sb.append(separator);
lastAppendedIsSeparator = true;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\text\TokenizedStringBuilder.java | 1 |
请完成以下Java代码 | private void appendForwarded(URI uri) {
String forwarded = headers.getFirst("forwarded");
if (forwarded != null) {
forwarded = forwarded + ",";
}
else {
forwarded = "";
}
forwarded = forwarded + forwarded(uri, exchange.getRequest().getHeaders().getFirst("host"));
headers.set("forwarded", forwarded);
}
private String forwarded(URI uri, @Nullable String hostHeader) {
if (StringUtils.hasText(hostHeader)) {
return "host=" + hostHeader;
}
if ("http".equals(uri.getScheme())) {
return "host=" + uri.getHost();
}
return String.format("host=%s;proto=%s", uri.getHost(), uri.getScheme());
}
private @Nullable Publisher<?> body() {
Publisher<?> body = this.body;
if (body != null) {
return body;
}
body = getRequestBody();
hasBody = true; // even if it's null
return body;
}
/**
* Search for the request body if it was already deserialized using
* <code>@RequestBody</code>. If it is not found then deserialize it in the same way
* that it would have been for a <code>@RequestBody</code>.
* @return the request body | */
private @Nullable Mono<Object> getRequestBody() {
for (String key : bindingContext.getModel().asMap().keySet()) {
if (key.startsWith(BindingResult.MODEL_KEY_PREFIX)) {
BindingResult result = (BindingResult) bindingContext.getModel().asMap().get(key);
Object target = result.getTarget();
if (target != null) {
return Mono.just(target);
}
}
}
return null;
}
protected static class BodyGrabber {
public Publisher<Object> body(@RequestBody Publisher<Object> body) {
return body;
}
}
protected static class BodySender {
@ResponseBody
public @Nullable Publisher<Object> body() {
return null;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-proxyexchange-webflux\src\main\java\org\springframework\cloud\gateway\webflux\ProxyExchange.java | 1 |
请完成以下Java代码 | protected List<ExecutionEntity> fetchExecutionsForProcessInstance(ExecutionEntity execution) {
List<ExecutionEntity> executions = new ArrayList<ExecutionEntity>();
executions.addAll(execution.getExecutions());
for (ExecutionEntity child : execution.getExecutions()) {
executions.addAll(fetchExecutionsForProcessInstance(child));
}
return executions;
}
protected List<ExecutionEntity> findLeaves(List<ExecutionEntity> executions) {
List<ExecutionEntity> leaves = new ArrayList<ExecutionEntity>();
for (ExecutionEntity execution : executions) {
if (isLeaf(execution)) {
leaves.add(execution);
}
} | return leaves;
}
/**
* event-scope executions are not considered in this mapping and must be ignored
*/
protected boolean isLeaf(ExecutionEntity execution) {
if (CompensationBehavior.isCompensationThrowing(execution)) {
return true;
}
else {
return !execution.isEventScope() && execution.getNonEventScopeExecutions().isEmpty();
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ActivityExecutionTreeMapping.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class ChatbotService {
private static final Logger logger = LoggerFactory.getLogger(ChatbotService.class);
private final ChatClient primaryChatClient;
private final ChatClient secondaryChatClient;
private final ChatClient tertiaryChatClient;
ChatbotService(
ChatClient primaryChatClient,
@Qualifier("secondaryChatClient") ChatClient secondaryChatClient,
@Qualifier("tertiaryChatClient") ChatClient tertiaryChatClient
) {
this.primaryChatClient = primaryChatClient;
this.secondaryChatClient = secondaryChatClient;
this.tertiaryChatClient = tertiaryChatClient;
}
@Retryable(retryFor = Exception.class, maxAttempts = 3)
String chat(String prompt) {
logger.debug("Attempting to process prompt '{}' with primary LLM. Attempt #{}",
prompt, RetrySynchronizationManager.getContext().getRetryCount() + 1);
return primaryChatClient
.prompt(prompt)
.call()
.content();
}
@Recover
String chat(Exception exception, String prompt) {
logger.warn("Primary LLM failure. Error received: {}", exception.getMessage());
logger.debug("Attempting to process prompt '{}' with secondary LLM", prompt); | try {
return secondaryChatClient
.prompt(prompt)
.call()
.content();
} catch (Exception e) {
logger.warn("Secondary LLM failure: {}", e.getMessage());
logger.debug("Attempting to process prompt '{}' with tertiary LLM", prompt);
return tertiaryChatClient
.prompt(prompt)
.call()
.content();
}
}
} | repos\tutorials-master\spring-ai-modules\spring-ai-multiple-llms\src\main\java\com\baeldung\multillm\ChatbotService.java | 2 |
请完成以下Java代码 | public boolean isMethodRequiresTiming()
{
return methodTimingParameterType != null;
}
public Object convertToMethodTimingParameterType(final int timing)
{
if (methodTimingParameterType == null)
{
// shall not happen
throw new AdempiereException("Method does not required timing parameter: " + getMethod());
}
else if (int.class.isAssignableFrom(methodTimingParameterType))
{
return timing;
}
else if (ModelChangeType.class.isAssignableFrom(methodTimingParameterType))
{
return ModelChangeType.valueOf(timing);
}
else if (DocTimingType.class.isAssignableFrom(methodTimingParameterType))
{
return DocTimingType.valueOf(timing);
}
else
{
// shall not happen because we already validated the parameter type when we set it
throw new AdempiereException("Not supported timing parameter type '" + methodTimingParameterType + "' for method " + getMethod());
}
}
/**
* Returns <code>true</code> if the other instance is also a PointCut and if {@link #compareTo(Pointcut)} returns 0.<br>
* Just added this method because the javadoc of {@link java.util.SortedSet} states that {@link #equals(Object)} and {@link #compareTo(Pointcut)} need to be consistent.
*
* @task https://metasfresh.atlassian.net/browse/FRESH-318
*/
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
final Pointcut other = EqualsBuilder.getOther(this, obj);
if (other == null)
{
return false;
}
// we use PointCut in a sorted set, so equals has to be consistent with compareTo()
if (compareTo(other) == 0)
{
return true;
}
return false;
}; | /**
* Compares this instance with the given {@link Pointcut} by comparing their.
* <ul>
* <li>TableName</li>
* <li>Method's name</li>
* <li>Method's declaring class name</li>
* </ul>
*
* @task https://metasfresh.atlassian.net/browse/FRESH-318
*/
@Override
public int compareTo(final Pointcut o)
{
return ComparisonChain.start()
.compare(getTableName(), o.getTableName())
.compare(getMethod() == null ? null : getMethod().getDeclaringClass().getName(),
o.getMethod() == null ? null : o.getMethod().getDeclaringClass().getName())
.compare(getMethod() == null ? null : getMethod().getName(),
o.getMethod() == null ? null : o.getMethod().getName())
.compare(getMethod() == null ? null : getMethod().getName(),
o.getMethod() == null ? null : o.getMethod().getName())
.result();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\Pointcut.java | 1 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
final I_C_Doc_Outbound_Log docOutboundLog = ediDocOutBoundLogService.retreiveById(DocOutboundLogId.ofRepoId(context.getSingleSelectedRecordId()));
if (ChangeEDI_ExportStatusHelper.checkIsNotInvoiceWithEDI(docOutboundLog))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Selected record is not an EDI Invoice: " + docOutboundLog);
}
final EDIExportStatus fromExportStatus = EDIExportStatus.ofNullableCode(docOutboundLog.getEDI_ExportStatus());
if (fromExportStatus == null)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Selected record is not an EDI Invoice: " + docOutboundLog);
}
if (ChangeEDI_ExportStatusHelper.getAvailableTargetExportStatuses(fromExportStatus).isEmpty())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Cannot change ExportStatus from the current one: " + fromExportStatus);
}
return ProcessPreconditionsResolution.accept();
}
@ProcessParamLookupValuesProvider(parameterName = PARAM_TargetExportStatus, numericKey = false, lookupSource = LookupSource.list)
private LookupValuesList getTargetExportStatusLookupValues(final LookupDataSourceContext context)
{
final I_C_Doc_Outbound_Log docOutboundLog = ediDocOutBoundLogService.retreiveById(DocOutboundLogId.ofRepoId(getRecord_ID()));
final EDIExportStatus fromExportStatus = EDIExportStatus.ofCode(docOutboundLog.getEDI_ExportStatus());
return ChangeEDI_ExportStatusHelper.computeTargetExportStatusLookupValues(fromExportStatus); | }
@Override
@Nullable
public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
final I_C_Doc_Outbound_Log docOutboundLog = ediDocOutBoundLogService.retreiveById(DocOutboundLogId.ofRepoId(getRecord_ID()));
final EDIExportStatus fromExportStatus = EDIExportStatus.ofCode(docOutboundLog.getEDI_ExportStatus());
return ChangeEDI_ExportStatusHelper.computeParameterDefaultValue(fromExportStatus);
}
@Override
protected String doIt() throws Exception
{
final EDIExportStatus targetExportStatus = EDIExportStatus.ofCode(p_TargetExportStatus);
ChangeEDI_ExportStatusHelper.C_DocOutbound_LogDoIt(targetExportStatus, DocOutboundLogId.ofRepoId(getRecord_ID()));
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\edi_desadv\ChangeEDI_ExportStatus_C_Doc_Outbound_Log_SingleView.java | 1 |
请完成以下Java代码 | public boolean isEnabled() {
return true;
}
public void setUsername(String username) {
this.username = username;
}
@JsonIgnore
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
public void setGrantedAuthorities(List<? extends GrantedAuthority> authorities) {
this.authorities = authorities;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCnname() {
return cnname;
}
public void setCnname(String cnname) {
this.cnname = cnname;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
public String getRePassword() {
return rePassword;
} | public void setRePassword(String rePassword) {
this.rePassword = rePassword;
}
public String getHistoryPassword() {
return historyPassword;
}
public void setHistoryPassword(String historyPassword) {
this.historyPassword = historyPassword;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", cnname=" + cnname +
", username=" + username +
", password=" + password +
", email=" + email +
", telephone=" + telephone +
", mobilePhone=" + mobilePhone +
'}';
}
} | repos\springBoot-master\springboot-springSecurity4\src\main\java\com\yy\example\bean\User.java | 1 |
请完成以下Java代码 | public MethodInfo getMethodInfo(ELContext context) {
return new MethodInfo(method.getName(), method.getReturnType(), method.getParameterTypes());
}
};
} else if (value instanceof MethodExpression) {
return (MethodExpression) value;
}
throw new MethodNotFoundException(
LocalMessages.get("error.identifier.method.notamethod", name, value.getClass())
);
}
public MethodInfo getMethodInfo(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes) {
return getMethodExpression(bindings, context, returnType, paramTypes).getMethodInfo(context);
}
public Object invoke(
Bindings bindings,
ELContext context,
Class<?> returnType,
Class<?>[] paramTypes,
Object[] params
) {
return getMethodExpression(bindings, context, returnType, paramTypes).invoke(context, params);
}
@Override
public String toString() {
return name;
}
@Override
public void appendStructure(StringBuilder b, Bindings bindings) { | b.append(bindings != null && bindings.isVariableBound(index) ? "<var>" : name);
}
public int getIndex() {
return index;
}
public String getName() {
return name;
}
public int getCardinality() {
return 0;
}
public AstNode getChild(int i) {
return null;
}
} | repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstIdentifier.java | 1 |
请完成以下Java代码 | public IHUPackingMaterialsCollector<IHUPackingMaterialCollectorSource> getHUPackingMaterialsCollector()
{
return _huPackingMaterialsCollector;
}
@Override
public IMutableHUContext setHUPackingMaterialsCollector(@NonNull final IHUPackingMaterialsCollector<IHUPackingMaterialCollectorSource> huPackingMaterialsCollector)
{
this._huPackingMaterialsCollector = huPackingMaterialsCollector;
return this;
}
@Override
public CompositeHUTrxListener getTrxListeners()
{
if (_trxListeners == null)
{
final CompositeHUTrxListener trxListeners = new CompositeHUTrxListener();
// Add system registered listeners
final IHUTrxBL huTrxBL = Services.get(IHUTrxBL.class);
trxListeners.addListeners(huTrxBL.getHUTrxListenersList());
_trxListeners = trxListeners;
}
return _trxListeners;
}
@Override
public void addEmptyHUListener(@NonNull final EmptyHUListener emptyHUListener)
{
emptyHUListeners.add(emptyHUListener);
}
@Override | public List<EmptyHUListener> getEmptyHUListeners()
{
return ImmutableList.copyOf(emptyHUListeners);
}
@Override
public void flush()
{
final IAttributeStorageFactory attributesStorageFactory = _attributesStorageFactory;
if(attributesStorageFactory != null)
{
attributesStorageFactory.flush();
}
}
@Override
public IAutoCloseable temporarilyDontDestroyHU(@NonNull final HuId huId)
{
huIdsToNotDestroy.add(huId);
return () -> huIdsToNotDestroy.remove(huId);
}
@Override
public boolean isDontDestroyHu(@NonNull final HuId huId)
{
return huIdsToNotDestroy.contains(huId);
}
@Override
public boolean isPropertyTrue(@NonNull final String propertyName)
{
final Boolean isPropertyTrue = getProperty(propertyName);
return isPropertyTrue != null && isPropertyTrue;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\MutableHUContext.java | 1 |
请完成以下Java代码 | protected ComponentDescription getProcessApplicationComponent(DeploymentUnit deploymentUnit) {
return ProcessApplicationAttachments.getProcessApplicationComponent(deploymentUnit);
}
protected ServiceName getProcessEngineServiceName(ProcessArchiveXml processArchive) {
ServiceName serviceName = null;
if(processArchive.getProcessEngineName() == null || processArchive.getProcessEngineName().isEmpty()) {
serviceName = ServiceNames.forDefaultProcessEngine();
} else {
serviceName = ServiceNames.forManagedProcessEngine(processArchive.getProcessEngineName());
}
return serviceName;
}
protected Map<String, byte[]> getDeploymentResources(ProcessArchiveXml processArchive, DeploymentUnit deploymentUnit, VirtualFile processesXmlFile) {
final Module module = deploymentUnit.getAttachment(MODULE);
Map<String, byte[]> resources = new HashMap<>();
// first, add all resources listed in the processes.xml
List<String> process = processArchive.getProcessResourceNames();
ModuleClassLoader classLoader = module.getClassLoader();
for (String resource : process) {
InputStream inputStream = null;
try {
inputStream = classLoader.getResourceAsStream(resource);
resources.put(resource, IoUtil.readInputStream(inputStream, resource));
} finally {
IoUtil.closeSilently(inputStream);
}
} | // scan for process definitions
if(PropertyHelper.getBooleanProperty(processArchive.getProperties(), ProcessArchiveXml.PROP_IS_SCAN_FOR_PROCESS_DEFINITIONS, process.isEmpty())) {
//always use VFS scanner on JBoss
final VfsProcessApplicationScanner scanner = new VfsProcessApplicationScanner();
String resourceRootPath = processArchive.getProperties().get(ProcessArchiveXml.PROP_RESOURCE_ROOT_PATH);
String[] additionalResourceSuffixes = StringUtil.split(processArchive.getProperties().get(ProcessArchiveXml.PROP_ADDITIONAL_RESOURCE_SUFFIXES), ProcessArchiveXml.PROP_ADDITIONAL_RESOURCE_SUFFIXES_SEPARATOR);
URL processesXmlUrl = vfsFileAsUrl(processesXmlFile);
resources.putAll(scanner.findResources(classLoader, resourceRootPath, processesXmlUrl, additionalResourceSuffixes));
}
return resources;
}
protected URL vfsFileAsUrl(VirtualFile processesXmlFile) {
try {
return processesXmlFile.toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
} | repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\deployment\processor\ProcessApplicationDeploymentProcessor.java | 1 |
请完成以下Java代码 | public static boolean isEnablePackingInstructionsField()
{
return Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_EnablePackingInstructionsField, true);
}
public static boolean isLUFieldsEnabled(@NonNull final SOTrx soTrx)
{
return soTrx.isPurchase() && Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_EnableLUFields, false);
}
public static boolean isEnableBestBeforePolicy()
{
return Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_EnableBestBeforePolicy, true);
} | public static boolean isEnableVatCodeField()
{
return Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_EnableVatCodeField, false);
}
public static boolean isEnableContractConditionsField()
{
return Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_EnableContractConditionsField, false);
}
public static boolean isContractConditionsFieldMandatory()
{
return Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_IsContractConditionsFieldMandatory, false);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\QuickInputConstants.java | 1 |
请完成以下Java代码 | public List<String> shortcutFieldOrder() {
return Arrays.asList(PARTS_KEY);
}
@Override
public GatewayFilter apply(Config config) {
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
addOriginalRequestUrl(exchange, request.getURI());
String path = request.getURI().getRawPath();
String[] originalParts = StringUtils.tokenizeToStringArray(path, "/");
// all new paths start with /
StringBuilder newPath = new StringBuilder("/");
for (int i = 0; i < originalParts.length; i++) {
if (i >= config.getParts()) {
// only append slash if this is the second part or greater
if (newPath.length() > 1) {
newPath.append('/');
}
newPath.append(originalParts[i]);
}
}
if (newPath.length() > 1 && path.endsWith("/")) {
newPath.append('/');
}
ServerHttpRequest newRequest = request.mutate().path(newPath.toString()).build();
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());
return chain.filter(exchange.mutate().request(newRequest).build());
} | @Override
public String toString() {
return filterToStringCreator(StripPrefixGatewayFilterFactory.this).append("parts", config.getParts())
.toString();
}
};
}
public static class Config {
private int parts = 1;
public int getParts() {
return parts;
}
public void setParts(int parts) {
this.parts = parts;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\StripPrefixGatewayFilterFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonOrder
{
@NonNull
@JsonProperty("id")
String id;
@NonNull
@JsonProperty("billingAddressId")
String billingAddressId;
@NonNull
@JsonProperty("orderCustomer")
JsonOrderCustomer orderCustomer;
@NonNull
@JsonProperty("currencyId")
String currencyId;
@Nullable
@JsonProperty("orderNumber")
String orderNumber;
@Nullable
@JsonProperty("orderDate")
ZonedDateTime orderDate;
@Nullable
@JsonProperty("stateMachineState") | JsonStateMachine stateMachine;
@NonNull
@JsonProperty("createdAt")
ZonedDateTime createdAt;
@Nullable
@JsonProperty("updatedAt")
ZonedDateTime updatedAt;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPOJOBuilder(withPrefix = "")
static class JsonOrderBuilder
{
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\api\model\order\JsonOrder.java | 2 |
请完成以下Java代码 | public DbOperation deleteTaskMetricsByRemovalTime(Date currentTimestamp, Integer timeToLive, int minuteFrom, int minuteTo, int batchSize) {
Map<String, Object> parameters = new HashMap<>();
// data inserted prior to now minus timeToLive-days can be removed
Date removalTime = Date.from(currentTimestamp.toInstant().minus(timeToLive, ChronoUnit.DAYS));
parameters.put("removalTime", removalTime);
if (minuteTo - minuteFrom + 1 < 60) {
parameters.put("minuteFrom", minuteFrom);
parameters.put("minuteTo", minuteTo);
}
parameters.put("batchSize", batchSize);
return getDbEntityManager()
.deletePreserveOrder(TaskMeterLogEntity.class, DELETE_TASK_METER_BY_REMOVAL_TIME,
new ListQueryParameterObject(parameters, 0, batchSize));
}
@SuppressWarnings("unchecked") | public List<String> findTaskMetricsForCleanup(int batchSize, Integer timeToLive, int minuteFrom, int minuteTo) {
Map<String, Object> queryParameters = new HashMap<>();
queryParameters.put("currentTimestamp", ClockUtil.getCurrentTime());
queryParameters.put("timeToLive", timeToLive);
if (minuteTo - minuteFrom + 1 < 60) {
queryParameters.put("minuteFrom", minuteFrom);
queryParameters.put("minuteTo", minuteTo);
}
ListQueryParameterObject parameterObject = new ListQueryParameterObject(queryParameters, 0, batchSize);
parameterObject.getOrderingProperties().add(new QueryOrderingProperty(new QueryPropertyImpl("TIMESTAMP_"), Direction.ASCENDING));
return (List<String>) getDbEntityManager().selectList(SELECT_TASK_METER_FOR_CLEANUP, parameterObject);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\MeterLogManager.java | 1 |
请完成以下Java代码 | public class MoveCostsResult
{
private final AggregatedCostAmount outboundCosts;
private final AggregatedCostAmount inboundCosts;
@Builder(toBuilder = true)
private MoveCostsResult(
@NonNull final AggregatedCostAmount outboundCosts,
@NonNull final AggregatedCostAmount inboundCosts)
{
this.outboundCosts = outboundCosts;
this.inboundCosts = inboundCosts;
}
public CostAmount getOutboundAmountToPost(@NonNull final AcctSchema as)
{
return outboundCosts.getTotalAmountToPost(as).getMainAmt(); | }
public CostAmount getInboundAmountToPost(@NonNull final AcctSchema as)
{
return inboundCosts.getTotalAmountToPost(as).getMainAmt();
}
public MoveCostsResult add(@NonNull final MoveCostsResult partialResult)
{
return toBuilder()
.outboundCosts(outboundCosts.add(partialResult.outboundCosts))
.inboundCosts(inboundCosts.add(partialResult.inboundCosts))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\MoveCostsResult.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PrivilegeResource {
@Autowired
protected IdmRestResponseFactory restResponseFactory;
@Autowired
protected IdmIdentityService identityService;
@Autowired(required=false)
protected IdmRestApiInterceptor restApiInterceptor;
@ApiOperation(value = "Get a single privilege", tags = { "Privileges" })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates the privilege exists and is returned."),
@ApiResponse(code = 404, message = "Indicates the requested privilege does not exist.")
})
@GetMapping(value = "/privileges/{privilegeId}", produces = "application/json")
public PrivilegeResponse getUser(@ApiParam(name = "privilegeId") @PathVariable String privilegeId) {
Privilege privilege = identityService.createPrivilegeQuery().privilegeId(privilegeId).singleResult(); | if (privilege == null) {
throw new FlowableObjectNotFoundException("Could not find privilege with id " + privilegeId, Privilege.class);
}
if (restApiInterceptor != null) {
restApiInterceptor.accessPrivilegeInfoById(privilege);
}
List<User> users = identityService.getUsersWithPrivilege(privilege.getId());
List<Group> groups = identityService.getGroupsWithPrivilege(privilege.getId());
return restResponseFactory.createPrivilegeResponse(privilege, users, groups);
}
} | repos\flowable-engine-main\modules\flowable-idm-rest\src\main\java\org\flowable\idm\rest\service\api\privilege\PrivilegeResource.java | 2 |
请完成以下Java代码 | protected final String doIt()
{
newImportProcess().run();
return MSG_OK;
}
private IImportProcess<ImportRecordType> newImportProcess()
{
final IImportProcess<ImportRecordType> importProcess = importProcessFactory.newImportProcess(importRecordClass)
.async(false)
.setCtx(getCtx())
.setLoggable(this)
.setParameters(getParameterAsIParams())
.limit(QueryLimit.NO_LIMIT) | .notifyUserId(getUserId());
customizeImportProcess(importProcess);
return importProcess;
}
protected void customizeImportProcess(@NonNull final IImportProcess<ImportRecordType> importProcess) {}
protected final QueryLimit getBatchSize()
{
int batchSize = sysConfigBL.getIntValue(SYSCONFIG_BatchSize, -1, getClientId().getRepoId(), OrgId.ANY.getRepoId());
return QueryLimit.ofInt(batchSize > 0 ? batchSize : DEFAULT_BatchSize);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\AbstractImportJavaProcess.java | 1 |
请完成以下Java代码 | public class MaxAllowedLengthVariableVerifier implements VariableLengthVerifier {
protected final int maxAllowedLength;
public MaxAllowedLengthVariableVerifier(int maxAllowedLength) {
if (maxAllowedLength <= 0) {
throw new FlowableIllegalArgumentException("The maximum allowed length must be greater than 0");
}
this.maxAllowedLength = maxAllowedLength;
}
@Override
public void verifyLength(int length, ValueFields valueFields, VariableType variableType) {
if (length > maxAllowedLength) {
String scopeId;
String scopeType;
if (StringUtils.isNotEmpty(valueFields.getTaskId())) {
scopeId = valueFields.getTaskId(); | scopeType = ScopeTypes.TASK;
} else if (StringUtils.isNotEmpty(valueFields.getProcessInstanceId())) {
scopeId = valueFields.getProcessInstanceId();
scopeType = ScopeTypes.BPMN;
} else {
scopeId = valueFields.getScopeId();
scopeType = valueFields.getScopeType();
}
throw new FlowableIllegalArgumentException(
"The length of the " + variableType.getTypeName() + " value exceeds the maximum allowed length of " + maxAllowedLength
+ " characters. Current length: " + length
+ ", for variable: " + valueFields.getName() + " in scope " + scopeType + " with id " + scopeId);
}
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\variable\MaxAllowedLengthVariableVerifier.java | 1 |
请完成以下Java代码 | public String pingPong() {
return "PONG";
}
@GetMapping("/")
public String home() {
return String.format("%s is running!",
environment.getProperty("spring.application.name", "UNKNOWN"));
}
public static class CustomerHolder {
public static CustomerHolder from(Customer customer) {
return new CustomerHolder(customer);
}
private boolean cacheMiss = true;
private final Customer customer;
protected CustomerHolder(Customer customer) {
Assert.notNull(customer, "Customer must not be null");
this.customer = customer;
}
public CustomerHolder setCacheMiss(boolean cacheMiss) { | this.cacheMiss = cacheMiss;
return this;
}
public boolean isCacheMiss() {
return this.cacheMiss;
}
public Customer getCustomer() {
return customer;
}
}
}
// end::class[] | repos\spring-boot-data-geode-main\spring-geode-samples\caching\multi-site\src\main\java\example\app\caching\multisite\client\web\CustomerController.java | 1 |
请完成以下Java代码 | public class FallbackSpinObjectValueSerializer extends AbstractObjectValueSerializer {
private final static SpinPluginLogger LOG = SpinPluginLogger.LOGGER;
public static final String DESERIALIZED_OBJECTS_EXCEPTION_MESSAGE = "Fallback serializer cannot handle deserialized objects";
protected String serializationFormat;
public FallbackSpinObjectValueSerializer(String serializationFormat) {
super(serializationFormat);
this.serializationFormat = serializationFormat;
}
@Override
public String getName() {
return "spin://" + serializationFormat;
}
@Override
protected String getTypeNameForDeserialized(Object deserializedObject) {
throw LOG.fallbackSerializerCannotDeserializeObjects();
} | @Override
protected byte[] serializeToByteArray(Object deserializedObject) throws Exception {
throw LOG.fallbackSerializerCannotDeserializeObjects();
}
@Override
protected Object deserializeFromByteArray(byte[] object, String objectTypeName) throws Exception {
throw LOG.fallbackSerializerCannotDeserializeObjects();
}
@Override
protected boolean isSerializationTextBased() {
return true;
}
@Override
protected boolean canSerializeValue(Object value) {
throw LOG.fallbackSerializerCannotDeserializeObjects();
}
} | repos\camunda-bpm-platform-master\engine-plugins\spin-plugin\src\main\java\org\camunda\spin\plugin\impl\FallbackSpinObjectValueSerializer.java | 1 |
请完成以下Java代码 | public class SetRemovalTimeToHistoricBatchesBuilderImpl implements SetRemovalTimeSelectModeForHistoricBatchesBuilder {
protected HistoricBatchQuery query;
protected List<String> ids;
protected Mode mode;
protected Date removalTime;
protected CommandExecutor commandExecutor;
public SetRemovalTimeToHistoricBatchesBuilderImpl(CommandExecutor commandExecutor) {
mode = null;
this.commandExecutor = commandExecutor;
}
public SetRemovalTimeToHistoricBatchesBuilder byQuery(HistoricBatchQuery query) {
this.query = query;
return this;
}
public SetRemovalTimeToHistoricBatchesBuilder byIds(String... ids) {
this.ids = ids != null ? Arrays.asList(ids) : null;
return this;
}
public SetRemovalTimeToHistoricBatchesBuilder absoluteRemovalTime(Date removalTime) {
ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode);
this.mode = Mode.ABSOLUTE_REMOVAL_TIME;
this.removalTime = removalTime;
return this;
}
public SetRemovalTimeToHistoricBatchesBuilder calculatedRemovalTime() {
ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode);
this.mode = Mode.CALCULATED_REMOVAL_TIME;
return this;
}
public SetRemovalTimeToHistoricBatchesBuilder clearedRemovalTime() {
ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode); | mode = Mode.CLEARED_REMOVAL_TIME;
return this;
}
public Batch executeAsync() {
return commandExecutor.execute(new SetRemovalTimeToHistoricBatchesCmd(this));
}
public HistoricBatchQuery getQuery() {
return query;
}
public List<String> getIds() {
return ids;
}
public Date getRemovalTime() {
return removalTime;
}
public Mode getMode() {
return mode;
}
public enum Mode
{
CALCULATED_REMOVAL_TIME,
ABSOLUTE_REMOVAL_TIME,
CLEARED_REMOVAL_TIME;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\SetRemovalTimeToHistoricBatchesBuilderImpl.java | 1 |
请完成以下Java代码 | public boolean hasNext()
{
return index < size;
}
@Override
public KeyValuePair next()
{
if (index >= size)
{
throw new NoSuchElementException();
}
else if (index == 0)
{
}
else
{
while (path.size() > 0)
{
int charPoint = path.pop();
int base = path.getLast();
int n = getNext(base, charPoint);
if (n != -1) break;
path.removeLast();
}
}
++index;
return this;
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
/**
* 遍历下一个终止路径
*
* @param parent 父节点
* @param charPoint 子节点的char
* @return
*/
private int getNext(int parent, int charPoint) | {
int startChar = charPoint + 1;
int baseParent = getBase(parent);
int from = parent;
for (int i = startChar; i < charMap.getCharsetSize(); i++)
{
int to = baseParent + i;
if (check.size() > to && check.get(to) == from)
{
path.append(i);
from = to;
path.append(from);
baseParent = base.get(from);
if (getCheck(baseParent + UNUSED_CHAR_VALUE) == from)
{
value = getLeafValue(getBase(baseParent + UNUSED_CHAR_VALUE));
int[] ids = new int[path.size() / 2];
for (int k = 0, j = 1; j < path.size(); ++k, j += 2)
{
ids[k] = path.get(j);
}
key = charMap.toString(ids);
path.append(UNUSED_CHAR_VALUE);
currentBase = baseParent;
return from;
}
else
{
return getNext(from, 0);
}
}
}
return -1;
}
@Override
public String toString()
{
return key + '=' + value;
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\datrie\MutableDoubleArrayTrieInteger.java | 1 |
请完成以下Java代码 | public void setImportedBPartnerLanguage (final @Nullable java.lang.String ImportedBPartnerLanguage)
{
set_Value (COLUMNNAME_ImportedBPartnerLanguage, ImportedBPartnerLanguage);
}
@Override
public java.lang.String getImportedBPartnerLanguage()
{
return get_ValueAsString(COLUMNNAME_ImportedBPartnerLanguage);
}
@Override
public org.compiere.model.I_C_BP_Group getImportedMunicipalityBP_Group()
{
return get_ValueAsPO(COLUMNNAME_ImportedMunicipalityBP_Group_ID, org.compiere.model.I_C_BP_Group.class);
}
@Override
public void setImportedMunicipalityBP_Group(final org.compiere.model.I_C_BP_Group ImportedMunicipalityBP_Group)
{
set_ValueFromPO(COLUMNNAME_ImportedMunicipalityBP_Group_ID, org.compiere.model.I_C_BP_Group.class, ImportedMunicipalityBP_Group);
}
@Override
public void setImportedMunicipalityBP_Group_ID (final int ImportedMunicipalityBP_Group_ID)
{
if (ImportedMunicipalityBP_Group_ID < 1)
set_Value (COLUMNNAME_ImportedMunicipalityBP_Group_ID, null);
else
set_Value (COLUMNNAME_ImportedMunicipalityBP_Group_ID, ImportedMunicipalityBP_Group_ID);
}
@Override
public int getImportedMunicipalityBP_Group_ID()
{
return get_ValueAsInt(COLUMNNAME_ImportedMunicipalityBP_Group_ID);
}
@Override
public org.compiere.model.I_C_BP_Group getImportedPartientBP_Group()
{
return get_ValueAsPO(COLUMNNAME_ImportedPartientBP_Group_ID, org.compiere.model.I_C_BP_Group.class);
}
@Override
public void setImportedPartientBP_Group(final org.compiere.model.I_C_BP_Group ImportedPartientBP_Group)
{
set_ValueFromPO(COLUMNNAME_ImportedPartientBP_Group_ID, org.compiere.model.I_C_BP_Group.class, ImportedPartientBP_Group);
}
@Override
public void setImportedPartientBP_Group_ID (final int ImportedPartientBP_Group_ID)
{ | if (ImportedPartientBP_Group_ID < 1)
set_Value (COLUMNNAME_ImportedPartientBP_Group_ID, null);
else
set_Value (COLUMNNAME_ImportedPartientBP_Group_ID, ImportedPartientBP_Group_ID);
}
@Override
public int getImportedPartientBP_Group_ID()
{
return get_ValueAsInt(COLUMNNAME_ImportedPartientBP_Group_ID);
}
@Override
public void setStoreDirectory (final @Nullable java.lang.String StoreDirectory)
{
set_Value (COLUMNNAME_StoreDirectory, StoreDirectory);
}
@Override
public java.lang.String getStoreDirectory()
{
return get_ValueAsString(COLUMNNAME_StoreDirectory);
}
@Override
public void setVia_EAN (final java.lang.String Via_EAN)
{
set_Value (COLUMNNAME_Via_EAN, Via_EAN);
}
@Override
public java.lang.String getVia_EAN()
{
return get_ValueAsString(COLUMNNAME_Via_EAN);
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java-gen\de\metas\vertical\healthcare\forum_datenaustausch_ch\commons\model\X_HC_Forum_Datenaustausch_Config.java | 1 |
请完成以下Java代码 | public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public List<AuthorList> getAuthors() {
return authors;
}
public void setAuthors(List<AuthorList> authors) {
this.authors = authors;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false; | }
return id != null && id.equals(((BookList) obj).id);
}
@Override
public int hashCode() {
return 2021;
}
@Override
public String toString() {
return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootManyToManyBidirectionalListVsSet\src\main\java\com\bookstore\entity\BookList.java | 1 |
请完成以下Java代码 | protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (getSelectedRowIds().isEmpty())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection().toInternal();
}
return ProcessPreconditionsResolution.accept();
}
@Override
@RunOutOfTrx
protected String doIt()
{
final Set<SumUpTransactionId> ids = getSelectedIdsAsSet();
if (ids.isEmpty())
{
throw new AdempiereException("@NoSelection@");
}
final BulkUpdateByQueryResult result = sumUpService.bulkUpdateTransactions(SumUpTransactionQuery.ofLocalIds(ids), true);
return result.getSummary().translate(Env.getADLanguageOrBaseLanguage());
}
private Set<SumUpTransactionId> getSelectedIdsAsSet()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); | if (selectedRowIds.isEmpty())
{
return ImmutableSet.of();
}
else if (selectedRowIds.isAll())
{
return getView().streamByIds(selectedRowIds)
.map(row -> row.getId().toId(SumUpTransactionId::ofRepoId))
.collect(ImmutableSet.toImmutableSet());
}
else
{
return selectedRowIds.toIds(SumUpTransactionId::ofRepoId);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup.webui\src\main\java\de\metas\payment\sumup\webui\process\SUMUP_Transaction_UpdateSelectedRows.java | 1 |
请完成以下Java代码 | public void endpointDeactivation(MessageEndpointFactory endpointFactory, ActivationSpec spec) {
try {
if(jobHandlerActivation != null) {
jobHandlerActivation.stop();
}
} finally {
jobHandlerActivation = null;
}
}
// unsupported (No TX Support) ////////////////////////////////////////////
public XAResource[] getXAResources(ActivationSpec[] specs) throws ResourceException {
log.finest("getXAResources()");
return null;
}
// getters ///////////////////////////////////////////////////////////////
public ExecutorServiceWrapper getExecutorServiceWrapper() {
return executorServiceWrapper;
}
public JobExecutionHandlerActivation getJobHandlerActivation() {
return jobHandlerActivation;
}
public Boolean getIsUseCommonJWorkManager() {
return isUseCommonJWorkManager;
}
public void setIsUseCommonJWorkManager(Boolean isUseCommonJWorkManager) {
this.isUseCommonJWorkManager = isUseCommonJWorkManager;
}
public String getCommonJWorkManagerName() {
return commonJWorkManagerName;
}
public void setCommonJWorkManagerName(String commonJWorkManagerName) {
this.commonJWorkManagerName = commonJWorkManagerName;
}
// misc ////////////////////////////////////////////////////////////////// | @Override
public int hashCode() {
return 17;
}
@Override
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (other == this) {
return true;
}
if (!(other instanceof JcaExecutorServiceConnector)) {
return false;
}
return true;
}
} | repos\camunda-bpm-platform-master\javaee\jobexecutor-ra\src\main\java\org\camunda\bpm\container\impl\threading\ra\JcaExecutorServiceConnector.java | 1 |
请完成以下Java代码 | public class C_Printing_Queue_RecipientHandler extends PrintingQueueHandlerAdapter
{
public static C_Printing_Queue_RecipientHandler INSTANCE = new C_Printing_Queue_RecipientHandler();
private C_Printing_Queue_RecipientHandler()
{
}
/**
* Returns {@code true} if the given {@code item} has an {@code AD_User_ID > 0} and if that user also has {@link I_AD_User#COLUMNNAME_C_Printing_Queue_Recipient_ID} {@code > 0}.
*/
@Override
public boolean isApplyHandler(final I_C_Printing_Queue queueItem, final I_AD_Archive IGNORED)
{
if (queueItem.getAD_User_ID() <= 0)
{
return false;
}
// return true if the item's user has a C_Printing_Queue_Recipient
final I_AD_User queueUser = Services.get(IUserDAO.class).getByIdInTrx(UserId.ofRepoId(queueItem.getAD_User_ID()), I_AD_User.class);
return queueUser.getC_Printing_Queue_Recipient_ID() > 0;
}
/**
* Updates the given {@code item}, see the javadoc of this class for further details.
*/
@Override
public void afterEnqueueAfterSave(final I_C_Printing_Queue queueItem, final I_AD_Archive IGNORED)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final List<I_C_Printing_Queue_Recipient> recipients = queryBL.createQueryBuilder(I_C_Printing_Queue_Recipient.class, queueItem)
.addOnlyActiveRecordsFilter() // we must retrieve ALL; the caller shall decide
.addEqualsFilter(I_C_Printing_Queue_Recipient.COLUMN_C_Printing_Queue_ID, queueItem.getC_Printing_Queue_ID())
.create()
.list();
if (recipients.isEmpty())
{
resetToUserPrintingQueueRecipient(queueItem);
}
else
{
for (final I_C_Printing_Queue_Recipient queueRecipient : recipients)
{
final I_AD_User userToPrint = InterfaceWrapperHelper.loadOutOfTrx(queueRecipient.getAD_User_ToPrint_ID(), I_AD_User.class);
final int newUserToPrintId = getEffectiveUserToPrint(userToPrint, new HashSet<>()).getAD_User_ID();
queueRecipient.setAD_User_ToPrint_ID(newUserToPrintId);
InterfaceWrapperHelper.save(queueRecipient);
} | }
}
private void resetToUserPrintingQueueRecipient(final I_C_Printing_Queue queueItem)
{
final I_AD_User itemUser = Services.get(IUserDAO.class).getByIdInTrx(UserId.ofRepoId(queueItem.getAD_User_ID()), I_AD_User.class);
final int userToPrintId = getEffectiveUserToPrint(itemUser, new HashSet<>()).getAD_User_ID();
final IPrintingQueueBL printingQueueBL = Services.get(IPrintingQueueBL.class);
printingQueueBL.setPrintoutForOtherUsers(queueItem, ImmutableSet.of(userToPrintId));
}
private I_AD_User getEffectiveUserToPrint(final I_AD_User user, final Set<Integer> alreadSeenUserIDs)
{
if (user.getC_Printing_Queue_Recipient_ID() <= 0)
{
return user;
}
if (!alreadSeenUserIDs.add(user.getC_Printing_Queue_Recipient_ID()))
{
return user;
}
return getEffectiveUserToPrint(user.getC_Printing_Queue_Recipient(), alreadSeenUserIDs);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\spi\impl\C_Printing_Queue_RecipientHandler.java | 1 |
请完成以下Java代码 | public E set(int index, E element) {
E oldElement = (E) internal[index];
internal[index] = element;
return oldElement;
}
@Override
public void clear() {
internal = new Object[0];
}
@Override
public int indexOf(Object object) {
for (int i = 0; i < internal.length; i++) {
if (object.equals(internal[i])) {
return i;
}
}
return -1;
}
@Override
public int lastIndexOf(Object object) {
for (int i = internal.length - 1; i >= 0; i--) {
if (object.equals(internal[i])) {
return i;
}
}
return -1;
}
@SuppressWarnings("unchecked")
@Override
public List<E> subList(int fromIndex, int toIndex) {
Object[] temp = new Object[toIndex - fromIndex];
System.arraycopy(internal, fromIndex, temp, 0, temp.length);
return (List<E>) Arrays.asList(temp);
}
@Override
public Object[] toArray() {
return Arrays.copyOf(internal, internal.length);
}
@SuppressWarnings("unchecked")
@Override
public <T> T[] toArray(T[] array) {
if (array.length < internal.length) {
return (T[]) Arrays.copyOf(internal, internal.length, array.getClass());
}
System.arraycopy(internal, 0, array, 0, internal.length);
if (array.length > internal.length) {
array[internal.length] = null;
}
return array;
}
@Override
public Iterator<E> iterator() { | return new CustomIterator();
}
@Override
public ListIterator<E> listIterator() {
return null;
}
@Override
public ListIterator<E> listIterator(int index) {
// ignored for brevity
return null;
}
private class CustomIterator implements Iterator<E> {
int index;
@Override
public boolean hasNext() {
return index != internal.length;
}
@SuppressWarnings("unchecked")
@Override
public E next() {
E element = (E) CustomList.this.internal[index];
index++;
return element;
}
}
} | repos\tutorials-master\core-java-modules\core-java-collections-list-7\src\main\java\com\baeldung\list\CustomList.java | 1 |
请完成以下Java代码 | public Publisher<Boolean> apply(ServerWebExchange exchange) {
Class inClass = config.getInClass();
Object cachedBody = exchange.getAttribute(CACHE_REQUEST_BODY_OBJECT_KEY);
Mono<?> modifiedBody;
// We can only read the body from the request once, once that happens if
// we try to read the body again an exception will be thrown. The below
// if/else caches the body object as a request attribute in the
// ServerWebExchange so if this filter is run more than once (due to more
// than one route using it) we do not try to read the request body
// multiple times
if (cachedBody != null) {
try {
boolean test = config.predicate != null && config.predicate.test(cachedBody);
exchange.getAttributes().put(TEST_ATTRIBUTE, test);
return Mono.just(test);
}
catch (ClassCastException e) {
if (log.isDebugEnabled()) {
log.debug("Predicate test failed because class in predicate "
+ "does not match the cached body object", e);
}
}
return Mono.just(false);
}
else {
Objects.requireNonNull(inClass, "inClass must not be null");
return ServerWebExchangeUtils.cacheRequestBodyAndRequest(exchange,
(serverHttpRequest) -> ServerRequest
.create(exchange.mutate().request(serverHttpRequest).build(), messageReaders)
.bodyToMono(inClass)
.doOnNext(objectValue -> exchange.getAttributes()
.put(CACHE_REQUEST_BODY_OBJECT_KEY, objectValue))
.map(objectValue -> config.getPredicate() != null
&& config.getPredicate().test(objectValue)));
}
}
@Override
public Object getConfig() {
return config;
}
@Override
public String toString() {
return String.format("ReadBody: %s", config.getInClass());
}
};
}
@Override
@SuppressWarnings("unchecked")
public Predicate<ServerWebExchange> apply(Config config) {
throw new UnsupportedOperationException("ReadBodyPredicateFactory is only async.");
}
public static class Config { | private @Nullable Class inClass;
private @Nullable Predicate predicate;
private @Nullable Map<String, Object> hints;
public @Nullable Class getInClass() {
return inClass;
}
public Config setInClass(Class inClass) {
this.inClass = inClass;
return this;
}
public @Nullable Predicate getPredicate() {
return predicate;
}
public Config setPredicate(Predicate predicate) {
this.predicate = predicate;
return this;
}
public <T> Config setPredicate(Class<T> inClass, Predicate<T> predicate) {
setInClass(inClass);
this.predicate = predicate;
return this;
}
public @Nullable Map<String, Object> getHints() {
return hints;
}
public Config setHints(Map<String, Object> hints) {
this.hints = hints;
return this;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\ReadBodyRoutePredicateFactory.java | 1 |
请完成以下Java代码 | public void actionPerformed(ActionEvent e)
{
showPopup();
}
});
}
private CColumnControlButton getCColumnControlButton()
{
final GridController currentGridController = this.parent.getCurrentGridController();
if (currentGridController == null)
{
return null;
}
final VTable table = currentGridController.getVTable();
if (table == null)
{
return null;
} | final CColumnControlButton columnControlButton = table.getColumnControl();
return columnControlButton;
}
public void showPopup()
{
final CColumnControlButton columnControlButton = getCColumnControlButton();
if (columnControlButton == null)
{
return;
}
final AbstractButton button = action.getButton();
columnControlButton.togglePopup(button);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\AGridColumnsToggle.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AdWindowId implements RepoIdAware
{
@NonNull @JsonCreator
public static AdWindowId ofRepoId(final int repoId)
{
return new AdWindowId(repoId);
}
@Nullable public static AdWindowId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new AdWindowId(repoId) : null;
}
public static Optional<AdWindowId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static int toRepoId(@Nullable final AdWindowId id)
{
return id != null ? id.getRepoId() : -1;
} | int repoId;
private AdWindowId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "AD_Window_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable final AdWindowId id1, @Nullable final AdWindowId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\element\api\AdWindowId.java | 2 |
请完成以下Java代码 | protected void updateStatementDifferenceAndEndingBalance(final BankStatementId bankStatementId)
{
// StatementDifference
{
final String sql = "UPDATE C_BankStatement bs"
+ " SET StatementDifference=(SELECT COALESCE(SUM(StmtAmt),0) FROM C_BankStatementLine bsl "
+ "WHERE bsl.C_BankStatement_ID=bs.C_BankStatement_ID AND bsl.IsActive='Y') "
+ "WHERE C_BankStatement_ID=?";
DB.executeUpdateAndThrowExceptionOnFail(sql, new Object[] { bankStatementId }, ITrx.TRXNAME_ThreadInherited);
}
// EndingBalance
{
final String sql = "UPDATE C_BankStatement bs"
+ " SET EndingBalance=BeginningBalance+StatementDifference "
+ "WHERE C_BankStatement_ID=?";
DB.executeUpdateAndThrowExceptionOnFail(sql, new Object[] { bankStatementId }, ITrx.TRXNAME_ThreadInherited);
}
} | @VisibleForTesting
protected void updateBankStatementIsReconciledFlag(final BankStatementId bankStatementId)
{
final String sql = "UPDATE C_BankStatement bs"
+ " SET IsReconciled=(CASE WHEN (SELECT COUNT(1) FROM C_BankStatementLine bsl WHERE bsl.C_BankStatement_ID = bs.C_BankStatement_ID AND bsl.IsReconciled = 'N') = 0 THEN 'Y' ELSE 'N' END)"
+ " WHERE C_BankStatement_ID=?";
DB.executeUpdateAndThrowExceptionOnFail(sql, new Object[] { bankStatementId }, ITrx.TRXNAME_ThreadInherited);
}
private void assertReconcilationConsistent(final I_C_BankStatementLine line)
{
if (line.getLink_BankStatementLine_ID() > 0 && line.getC_Payment_ID() > 0)
{
throw new AdempiereException("Invalid reconcilation: cannot have bank transfer and payment at the same time");
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\model\validator\C_BankStatementLine.java | 1 |
请完成以下Java代码 | public ELContextBuilder withVariables(Map<String, Object> variables) {
this.variables = variables;
return this;
}
public ELContext build() {
CompositeELResolver elResolver = createCompositeResolver();
return new ActivitiElContext(elResolver);
}
public ELContext buildWithCustomFunctions(List<CustomFunctionProvider> customFunctionProviders) {
CompositeELResolver elResolver = createCompositeResolver();
ActivitiElContext elContext = new ActivitiElContext(elResolver);
try {
addDateFunctions(elContext);
addListFunctions(elContext);
if (customFunctionProviders != null) {
customFunctionProviders.forEach(provider -> {
try {
provider.addCustomFunctions(elContext);
} catch (Exception e) {
logger.error("Error setting up EL custom functions", e);
}
});
}
} catch (NoSuchMethodException e) {
logger.error("Error setting up EL custom functions", e);
}
return elContext; | }
private void addResolvers(CompositeELResolver compositeResolver) {
Stream.ofNullable(resolvers).flatMap(Collection::stream).forEach(compositeResolver::add);
}
private CompositeELResolver createCompositeResolver() {
CompositeELResolver elResolver = new CompositeELResolver();
elResolver.add(
new ReadOnlyMapELResolver((Objects.nonNull(variables) ? new HashMap<>(variables) : Collections.emptyMap()))
);
addResolvers(elResolver);
return elResolver;
}
} | repos\Activiti-develop\activiti-core-common\activiti-expression-language\src\main\java\org\activiti\core\el\ELContextBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SecretService {
private Map<String, String> secrets = new HashMap<>();
private SigningKeyResolver signingKeyResolver = new SigningKeyResolverAdapter() {
@Override
public byte[] resolveSigningKeyBytes(JwsHeader header, Claims claims) {
return TextCodec.BASE64.decode(secrets.get(header.getAlgorithm()));
}
};
@PostConstruct
public void setup() throws NoSuchAlgorithmException {
refreshSecrets();
}
public SigningKeyResolver getSigningKeyResolver() {
return signingKeyResolver;
}
public Map<String, String> getSecrets() {
return secrets;
}
public void setSecrets(Map<String, String> secrets) {
Assert.notNull(secrets);
Assert.hasText(secrets.get(SignatureAlgorithm.HS256.getJcaName()));
Assert.hasText(secrets.get(SignatureAlgorithm.HS384.getJcaName()));
Assert.hasText(secrets.get(SignatureAlgorithm.HS512.getJcaName()));
this.secrets = secrets; | }
public byte[] getHS256SecretBytes() {
return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS256.getJcaName()));
}
public byte[] getHS384SecretBytes() {
return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS384.getJcaName()));
}
public byte[] getHS512SecretBytes() {
return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS512.getJcaName()));
}
public Map<String, String> refreshSecrets() throws NoSuchAlgorithmException {
SecretKey key = KeyGenerator.getInstance(SignatureAlgorithm.HS256.getJcaName()).generateKey();
secrets.put(SignatureAlgorithm.HS256.getJcaName(), TextCodec.BASE64.encode(key.getEncoded()));
key = KeyGenerator.getInstance(SignatureAlgorithm.HS384.getJcaName()).generateKey();
secrets.put(SignatureAlgorithm.HS384.getJcaName(), TextCodec.BASE64.encode(key.getEncoded()));
key = KeyGenerator.getInstance(SignatureAlgorithm.HS512.getJcaName()).generateKey();
secrets.put(SignatureAlgorithm.HS512.getJcaName(), TextCodec.BASE64.encode(key.getEncoded()));
return secrets;
}
} | repos\tutorials-master\security-modules\jjwt\src\main\java\io\jsonwebtoken\jjwtfun\service\SecretService.java | 2 |
请完成以下Java代码 | public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCaptcha() {
return captcha;
} | public void setCaptcha(String captcha) {
this.captcha = captcha;
}
public String getCheckKey() {
return checkKey;
}
public void setCheckKey(String checkKey) {
this.checkKey = checkKey;
}
public String getLoginOrgCode() {
return loginOrgCode;
}
public void setLoginOrgCode(String loginOrgCode) {
this.loginOrgCode = loginOrgCode;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\SysLoginModel.java | 1 |
请完成以下Java代码 | private static class Result
{
public static Result ofMap(@NonNull final Map<UserDashboardItemId, UserDashboardItemDataResponse> map)
{
return !map.isEmpty() ? new Result(map) : EMPTY;
}
public static Result ofCollection(@NonNull final Collection<UserDashboardItemDataResponse> itemDataList)
{
return ofMap(Maps.uniqueIndex(itemDataList, UserDashboardItemDataResponse::getItemId));
}
private static final Result EMPTY = new Result(ImmutableMap.of());
private final ImmutableMap<UserDashboardItemId, UserDashboardItemDataResponse> map;
private Result(final Map<UserDashboardItemId, UserDashboardItemDataResponse> map)
{
this.map = ImmutableMap.copyOf(map);
}
public ImmutableList<UserDashboardItemDataResponse> getChangesFromOldVersion(@Nullable final Result oldResult)
{
if (oldResult == null)
{
return toList();
}
final ImmutableList.Builder<UserDashboardItemDataResponse> resultEffective = ImmutableList.builder(); | for (final Map.Entry<UserDashboardItemId, UserDashboardItemDataResponse> e : map.entrySet())
{
final UserDashboardItemId itemId = e.getKey();
final UserDashboardItemDataResponse newValue = e.getValue();
final UserDashboardItemDataResponse oldValue = oldResult.get(itemId);
if (oldValue == null || !newValue.isSameDataAs(oldValue))
{
resultEffective.add(newValue);
}
}
return resultEffective.build();
}
@Nullable
private UserDashboardItemDataResponse get(final UserDashboardItemId itemId)
{
return map.get(itemId);
}
public ImmutableList<UserDashboardItemDataResponse> toList()
{
return ImmutableList.copyOf(map.values());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\websocket\UserDashboardWebsocketProducer.java | 1 |
请完成以下Java代码 | public String getExecutorHandler() {
return executorHandler;
}
public void setExecutorHandler(String executorHandler) {
this.executorHandler = executorHandler;
}
public String getExecutorParam() {
return executorParam;
}
public void setExecutorParam(String executorParam) {
this.executorParam = executorParam;
}
public String getExecutorBlockStrategy() {
return executorBlockStrategy;
}
public void setExecutorBlockStrategy(String executorBlockStrategy) {
this.executorBlockStrategy = executorBlockStrategy;
}
public int getExecutorTimeout() {
return executorTimeout;
}
public void setExecutorTimeout(int executorTimeout) {
this.executorTimeout = executorTimeout;
}
public int getExecutorFailRetryCount() {
return executorFailRetryCount;
}
public void setExecutorFailRetryCount(int executorFailRetryCount) {
this.executorFailRetryCount = executorFailRetryCount;
}
public String getGlueType() {
return glueType;
}
public void setGlueType(String glueType) {
this.glueType = glueType;
}
public String getGlueSource() {
return glueSource;
}
public void setGlueSource(String glueSource) {
this.glueSource = glueSource;
}
public String getGlueRemark() {
return glueRemark;
}
public void setGlueRemark(String glueRemark) { | this.glueRemark = glueRemark;
}
public Date getGlueUpdatetime() {
return glueUpdatetime;
}
public void setGlueUpdatetime(Date glueUpdatetime) {
this.glueUpdatetime = glueUpdatetime;
}
public String getChildJobId() {
return childJobId;
}
public void setChildJobId(String childJobId) {
this.childJobId = childJobId;
}
public int getTriggerStatus() {
return triggerStatus;
}
public void setTriggerStatus(int triggerStatus) {
this.triggerStatus = triggerStatus;
}
public long getTriggerLastTime() {
return triggerLastTime;
}
public void setTriggerLastTime(long triggerLastTime) {
this.triggerLastTime = triggerLastTime;
}
public long getTriggerNextTime() {
return triggerNextTime;
}
public void setTriggerNextTime(long triggerNextTime) {
this.triggerNextTime = triggerNextTime;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobInfo.java | 1 |
请完成以下Java代码 | private String convertToDateTimeString(final ZonedDateTime dateTime)
{
if (dateTime == null)
{
return "";
}
return dateTimeFormat.format(TimeUtil.asDate(dateTime));
}
private String buildSummaryInfo(final RecordChangeLog changeLog)
{
final StringBuilder info = new StringBuilder();
//
// Created / Created By
final UserId createdBy = changeLog.getCreatedByUserId();
final ZonedDateTime createdTS = TimeUtil.asZonedDateTime(changeLog.getCreatedTimestamp());
info.append(" ")
.append(msgBL.translate(Env.getCtx(), "CreatedBy"))
.append(": ").append(getUserName(createdBy))
.append(" - ").append(convertToDateTimeString(createdTS)).append("\n");
//
// Last Changed / Last Changed By
if (changeLog.hasChanges())
{
final UserId lastChangedBy = changeLog.getLastChangedByUserId();
final ZonedDateTime lastChangedTS = TimeUtil.asZonedDateTime(changeLog.getLastChangedTimestamp());
info.append(" ")
.append(msgBL.translate(Env.getCtx(), "UpdatedBy")) | .append(": ").append(getUserName(lastChangedBy))
.append(" - ").append(convertToDateTimeString(lastChangedTS)).append("\n");
}
//
// TableName / RecordId(s)
info.append(changeLog.getTableName())
.append(" (").append(changeLog.getRecordId().toInfoString()).append(")");
return info.toString();
}
private final String getUserName(@Nullable final UserId userId)
{
if (userId == null)
{
return "?";
}
return userNamesById.computeIfAbsent(userId, usersRepo::retrieveUserFullName);
}
@Override
public void actionPerformed(final ActionEvent e)
{
dispose();
} // actionPerformed
} // RecordInfo | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\RecordInfo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DemoController {
Logger logger = LoggerFactory.getLogger(MachineRegistryController.class);
@RequestMapping("/greeting")
public String greeting() {
return "index";
}
@RequestMapping("/link")
@ResponseBody
public String link() throws BlockException {
Entry entry = SphU.entry("head1", EntryType.IN);
Entry entry1 = SphU.entry("head2", EntryType.IN);
Entry entry2 = SphU.entry("head3", EntryType.IN);
Entry entry3 = SphU.entry("head4", EntryType.IN);
entry3.exit();
entry2.exit();
entry1.exit();
entry.exit();
return "successfully create a call link";
}
@RequestMapping("/loop")
@ResponseBody
public String loop(String name, int time) throws BlockException {
for (int i = 0; i < 10; i++) {
Thread timer = new Thread(new RunTask(name, time, false));
timer.setName("false");
timer.start();
}
return "successfully create a loop thread";
}
@RequestMapping("/slow")
@ResponseBody
public String slow(String name, int time) throws BlockException {
for (int i = 0; i < 10; i++) {
Thread timer = new Thread(new RunTask(name, time, true));
timer.setName("false");
timer.start();
}
return "successfully create a loop thread";
}
static class RunTask implements Runnable {
int time;
boolean stop = false;
String name;
boolean slow = false;
public RunTask(String name, int time, boolean slow) {
super();
this.time = time;
this.name = name;
this.slow = slow; | }
@Override
public void run() {
long startTime = System.currentTimeMillis();
ContextUtil.enter(String.valueOf(startTime));
while (!stop) {
long now = System.currentTimeMillis();
if (now - startTime > time * 1000) {
stop = true;
}
Entry e1 = null;
try {
e1 = SphU.entry(name);
if (slow == true) {
TimeUnit.MILLISECONDS.sleep(3000);
}
} catch (Exception e) {
} finally {
if (e1 != null) {
e1.exit();
}
}
Random random2 = new Random();
try {
TimeUnit.MILLISECONDS.sleep(random2.nextInt(200));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ContextUtil.exit();
}
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\DemoController.java | 2 |
请完成以下Java代码 | private JScrollPane getParentScrollPane(final JScrollPane scrollPane)
{
if (scrollPane == null)
{
return null;
}
Component parent = scrollPane.getParent();
while (parent != null)
{
if (parent instanceof JScrollPane)
{
return (JScrollPane)parent;
}
parent = parent.getParent();
}
return null;
}
/** @return cloned event */
private final MouseWheelEvent cloneEvent(final JScrollPane scrollPane, final MouseWheelEvent event)
{
return new MouseWheelEvent(scrollPane | , event.getID()
, event.getWhen()
, event.getModifiers()
, event.getX()
, event.getY()
, event.getClickCount()
, event.isPopupTrigger()
, event.getScrollType()
, event.getScrollAmount()
, event.getWheelRotation());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\AdempiereScrollPaneUI.java | 1 |
请完成以下Java代码 | protected String doIt()
{
final String importTableName = getTableName();
final ImportDataDeleteMode deleteMode = getDeleteMode();
final String viewSqlWhereClause = getViewSqlWhereClause(DocumentIdsSelection.ALL)
.map(SqlViewRowsWhereClause::toSqlString)
.orElse(null);
final String selectionSqlWhereClause = ImportDataDeleteMode.ONLY_SELECTED.equals(deleteMode)
? getSelectionSqlWhereClause().map(SqlViewRowsWhereClause::toSqlString).orElse(null)
: null;
final int deletedCount = dataImportService.deleteImportRecords(ImportDataDeleteRequest.builder()
.importTableName(importTableName)
.mode(deleteMode)
.viewSqlWhereClause(viewSqlWhereClause)
.selectionSqlWhereClause(selectionSqlWhereClause)
.additionalParameters(Params.copyOf(getParameterAsIParams()))
.build());
return "@Deleted@ " + deletedCount;
}
@Override
protected void postProcess(final boolean success)
{
invalidateView();
}
private Optional<SqlViewRowsWhereClause> getSelectionSqlWhereClause()
{
final DocumentIdsSelection rowIds = getSelectedRowIds(); | if (rowIds.isEmpty())
{
throw new AdempiereException("@NoSelection@");
}
return getViewSqlWhereClause(rowIds);
}
private Optional<SqlViewRowsWhereClause> getViewSqlWhereClause(@NonNull final DocumentIdsSelection rowIds)
{
final IView view = getView();
final String importTableName = getTableName();
final SqlViewRowsWhereClause viewRowsWhereClause = view.getSqlWhereClause(rowIds, SqlOptions.usingTableName(importTableName));
return Optional.ofNullable(viewRowsWhereClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\impexp\DeleteImportDataProcess.java | 1 |
请完成以下Java代码 | private final String getProductName(final IProductStorage productStorage)
{
if (productStorage == null)
{
return "";
}
return Services.get(IProductBL.class).getProductName(productStorage.getProductId());
}
};
ProductId getProductId();
I_C_UOM getC_UOM();
BigDecimal getQtyFree();
Quantity getQty();
default BigDecimal getQtyAsBigDecimal()
{
return getQty().toBigDecimal();
}
default Quantity getQty(@NonNull final UomId uomId)
{
final I_C_UOM uomRecord = Services.get(IUOMDAO.class).getById(uomId);
return getQty(uomRecord);
} | /**
* Gets storage Qty, converted to given UOM.
*
* @return Qty converted to given UOM.
*/
Quantity getQty(I_C_UOM uom);
/**
* @return storage capacity
*/
BigDecimal getQtyCapacity();
IAllocationRequest removeQty(IAllocationRequest request);
IAllocationRequest addQty(IAllocationRequest request);
void markStaled();
boolean isEmpty();
/**
* @return true if this storage allows negative storages
*/
boolean isAllowNegativeStorage();
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\IProductStorage.java | 1 |
请完成以下Java代码 | void setKeyEntry(String alias, PrivateKey privateKey, String keyPassword, Certificate[] certificateChain) throws KeyStoreException {
keyStore.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), certificateChain);
}
void setCertificateEntry(String alias, Certificate certificate) throws KeyStoreException {
keyStore.setCertificateEntry(alias, certificate);
}
Certificate getCertificate(String alias) throws KeyStoreException {
return keyStore.getCertificate(alias);
}
void deleteEntry(String alias) throws KeyStoreException {
keyStore.deleteEntry(alias);
}
void deleteKeyStore() throws KeyStoreException, IOException { | Enumeration<String> aliases = keyStore.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
keyStore.deleteEntry(alias);
}
keyStore = null;
Path keyStoreFile = Paths.get(keyStoreName);
Files.delete(keyStoreFile);
}
KeyStore getKeyStore() {
return this.keyStore;
}
} | repos\tutorials-master\core-java-modules\core-java-security\src\main\java\com\baeldung\keystore\JavaKeyStore.java | 1 |
请完成以下Java代码 | public <V extends ModelElementInstance> ElementReferenceCollectionBuilder<V, T> idElementReferenceCollection(Class<V> referenceTargetType) {
ChildElementCollectionImpl<T> collection = (ChildElementCollectionImpl<T>) build();
ElementReferenceCollectionBuilder<V,T> builder = new ElementReferenceCollectionBuilderImpl<V,T>(childElementType, referenceTargetType, collection);
setReferenceBuilder(builder);
return builder;
}
public <V extends ModelElementInstance> ElementReferenceCollectionBuilder<V, T> idsElementReferenceCollection(Class<V> referenceTargetType) {
ChildElementCollectionImpl<T> collection = (ChildElementCollectionImpl<T>) build();
ElementReferenceCollectionBuilder<V,T> builder = new IdsElementReferenceCollectionBuilderImpl<V,T>(childElementType, referenceTargetType, collection);
setReferenceBuilder(builder);
return builder;
}
public <V extends ModelElementInstance> ElementReferenceCollectionBuilder<V, T> uriElementReferenceCollection(Class<V> referenceTargetType) {
ChildElementCollectionImpl<T> collection = (ChildElementCollectionImpl<T>) build();
ElementReferenceCollectionBuilder<V,T> builder = new UriElementReferenceCollectionBuilderImpl<V, T>(childElementType, referenceTargetType, collection);
setReferenceBuilder(builder);
return builder;
}
protected void setReferenceBuilder(ElementReferenceCollectionBuilder<?, ?> referenceBuilder) {
if (this.referenceBuilder != null) {
throw new ModelException("An collection cannot have more than one reference"); | }
this.referenceBuilder = referenceBuilder;
modelBuildOperations.add(referenceBuilder);
}
public void performModelBuild(Model model) {
ModelElementType elementType = model.getType(childElementType);
if(elementType == null) {
throw new ModelException(parentElementType +" declares undefined child element of type "+childElementType+".");
}
parentElementType.registerChildElementType(elementType);
parentElementType.registerChildElementCollection(collection);
for (ModelBuildOperation modelBuildOperation : modelBuildOperations) {
modelBuildOperation.performModelBuild(model);
}
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\child\ChildElementCollectionBuilderImpl.java | 1 |
请完成以下Java代码 | public String getStyleValue() {
return null;
}
@Override
public String getDValue() {
return null;
}
@Override
public void drawIcon(int imageX, int imageY, int iconPadding, ProcessDiagramSVGGraphics2D svgGenerator) {
Element gTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_G_TAG);
gTag.setAttributeNS(null, "transform", "translate(" + (imageX - 8) + "," + (imageY - 6) + ")");
Element polygonTag1 = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_POLYGON_TAG);
polygonTag1.setAttributeNS(null, "points", "14 8 14 22 7 15 ");
polygonTag1.setAttributeNS(null, "fill", this.getFillValue());
polygonTag1.setAttributeNS(null, "stroke", this.getStrokeValue());
polygonTag1.setAttributeNS(null, "stroke-width", this.getStrokeWidth());
polygonTag1.setAttributeNS(null, "stroke-linecap", "butt");
polygonTag1.setAttributeNS(null, "stroke-linejoin", "miter");
polygonTag1.setAttributeNS(null, "stroke-miterlimit", "10");
gTag.appendChild(polygonTag1);
Element polygonTag2 = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_POLYGON_TAG);
polygonTag2.setAttributeNS(null, "points", "21 8 21 22 14 15 ");
polygonTag2.setAttributeNS(null, "fill", this.getFillValue());
polygonTag2.setAttributeNS(null, "stroke", this.getStrokeValue());
polygonTag2.setAttributeNS(null, "stroke-width", this.getStrokeWidth());
polygonTag2.setAttributeNS(null, "stroke-linecap", "butt");
polygonTag2.setAttributeNS(null, "stroke-linejoin", "miter"); | polygonTag2.setAttributeNS(null, "stroke-miterlimit", "10");
gTag.appendChild(polygonTag2);
svgGenerator.getExtendDOMGroupManager().addElement(gTag);
}
@Override
public String getStrokeValue() {
return "#585858";
}
@Override
public String getStrokeWidth() {
return "1.4";
}
@Override
public String getAnchorValue() {
return null;
}
} | repos\Activiti-develop\activiti-core\activiti-image-generator\src\main\java\org\activiti\image\impl\icon\CompensateIconType.java | 1 |
请完成以下Java代码 | public class DDOrderUnpickCommand
{
@NonNull private final ITrxManager trxManager = Services.get(ITrxManager.class);
@NonNull private final IWarehouseBL warehouseBL = Services.get(IWarehouseBL.class);
@NonNull private final DDOrderMoveScheduleRepository ddOrderMoveScheduleRepository;
@NonNull private final HUQRCodesService huqrCodesService;
// Params
@NonNull private final DDOrderMoveScheduleId scheduleId;
@Nullable private final HUQRCode unpickToTargetQRCode;
// State
private DDOrderMoveSchedule schedule;
@Builder
private DDOrderUnpickCommand(
final @NonNull DDOrderMoveScheduleRepository ddOrderMoveScheduleRepository,
final @NonNull HUQRCodesService huqrCodesService,
final @NonNull DDOrderMoveScheduleId scheduleId,
final @Nullable HUQRCode unpickToTargetQRCode)
{
this.ddOrderMoveScheduleRepository = ddOrderMoveScheduleRepository;
this.huqrCodesService = huqrCodesService;
this.scheduleId = scheduleId;
this.unpickToTargetQRCode = unpickToTargetQRCode;
}
public void execute()
{
trxManager.runInThreadInheritedTrx(this::executeInTrx);
}
private void executeInTrx()
{
trxManager.assertThreadInheritedTrxExists();
loadState();
validateState();
//
// generate movement InTransit -> Pick From Locator
moveBackTheHU();
deleteSchedule();
}
private void moveBackTheHU()
{
MoveHUCommand.builder()
.huQRCodesService(huqrCodesService)
.requestItems(ImmutableSet.of(MoveHURequestItem.ofHUIdAndQRCode(HUIdAndQRCode.ofHuId(schedule.getPickFromHUId()))))
.targetQRCode(getTargetQRCode())
.build()
.execute();
}
private void loadState()
{
schedule = ddOrderMoveScheduleRepository.getById(scheduleId);
} | private void validateState()
{
if (!schedule.isPickedFrom())
{
throw new AdempiereException("Not picked");
}
if (schedule.isDropTo())
{
throw new AdempiereException("Already dropped!");
}
}
private void deleteSchedule()
{
schedule.removePickedHUs();
ddOrderMoveScheduleRepository.save(schedule);
ddOrderMoveScheduleRepository.deleteNotStarted(schedule.getId());
}
private ScannedCode getTargetQRCode()
{
if (unpickToTargetQRCode != null)
{
return unpickToTargetQRCode.toScannedCode();
}
else
{
return warehouseBL.getLocatorQRCode(schedule.getPickFromLocatorId()).toScannedCode();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\commands\unpick\DDOrderUnpickCommand.java | 1 |
请完成以下Java代码 | public int getXmlColumnNumber() {
return xmlColumnNumber;
}
public void setXmlColumnNumber(int xmlColumnNumber) {
this.xmlColumnNumber = xmlColumnNumber;
}
public boolean equals(GraphicInfo ginfo) {
if (this.getX() != ginfo.getX()) {
return false;
}
if (this.getY() != ginfo.getY()) {
return false;
}
if (this.getHeight() != ginfo.getHeight()) {
return false;
}
if (this.getWidth() != ginfo.getWidth()) {
return false; | }
// check for zero value in case we are comparing model value to BPMN DI value
// model values do not have xml location information
if (0 != this.getXmlColumnNumber() && 0 != ginfo.getXmlColumnNumber() && this.getXmlColumnNumber() != ginfo.getXmlColumnNumber()) {
return false;
}
if (0 != this.getXmlRowNumber() && 0 != ginfo.getXmlRowNumber() && this.getXmlRowNumber() != ginfo.getXmlRowNumber()) {
return false;
}
// only check for elements that support this value
if (null != this.getExpanded() && null != ginfo.getExpanded() && !this.getExpanded().equals(ginfo.getExpanded())) {
return false;
}
return true;
}
} | repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\GraphicInfo.java | 1 |
请完成以下Java代码 | public String getTypeName(String paramName) {
return params.get(paramName).name;
}
@Override
public String[] getParameterNames() {
return params.keySet().toArray(new String[]{});
}
public void addUuidParameter(String name, UUID value) {
addParameter(name, value, UUID_TYPE.getJdbcTypeCode(), UUID_TYPE.getFriendlyName());
}
public void addStringParameter(String name, String value) {
addParameter(name, value, Types.VARCHAR, "VARCHAR");
}
public void addDoubleParameter(String name, double value) {
addParameter(name, value, Types.DOUBLE, "DOUBLE");
}
public void addLongParameter(String name, long value) {
addParameter(name, value, Types.BIGINT, "BIGINT");
}
public void addStringListParameter(String name, List<String> value) {
addParameter(name, value, Types.VARCHAR, "VARCHAR");
}
public void addBooleanParameter(String name, boolean value) {
addParameter(name, value, Types.BOOLEAN, "BOOLEAN");
}
public void addUuidListParameter(String name, List<UUID> value) {
addParameter(name, value, UUID_TYPE.getJdbcTypeCode(), UUID_TYPE.getFriendlyName());
}
public String getQuery() {
return query.toString();
}
public static class Parameter {
private final Object value;
private final int type; | private final String name;
public Parameter(Object value, int type, String name) {
this.value = value;
this.type = type;
this.name = name;
}
}
public TenantId getTenantId() {
return securityCtx.getTenantId();
}
public CustomerId getCustomerId() {
return securityCtx.getCustomerId();
}
public EntityType getEntityType() {
return securityCtx.getEntityType();
}
public boolean isIgnorePermissionCheck() {
return securityCtx.isIgnorePermissionCheck();
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\query\SqlQueryContext.java | 1 |
请完成以下Java代码 | public Authorization authorize(String requestMethod, String requestUri) {
boolean secured = false;
for (RequestMatcher pattern : deniedPaths) {
Match match = pattern.match(requestMethod, requestUri);
if (match != null) {
secured = true;
break;
}
}
if (!secured) {
return Authorization.granted(Authentication.ANONYMOUS);
}
for (RequestMatcher pattern : allowedPaths) {
Match match = pattern.match(requestMethod, requestUri);
if (match != null) { | return match.authorize();
}
}
return null;
}
public List<RequestMatcher> getAllowedPaths() {
return allowedPaths;
}
public List<RequestMatcher> getDeniedPaths() {
return deniedPaths;
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\PathFilterRule.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String qrcodeBase64(String orderNo) {
String message = "";
try {
message = QRCodeGenerator.writeToStream(orderNo, 350, 350);
} catch (Exception e) {
e.printStackTrace();
}
return message;
}
@RequestMapping("/hblog/qrcode/image1")
public String hblogImages1() {
String message = "";
try {
QrConfig config = new QrConfig(300, 300);
// Set the margin, that is, the margin between the QR code and the background
config.setMargin(3);
// Set the foreground color, which is the QR code color (cyan)
config.setForeColor(Color.CYAN.getRGB());
// Set background color (gray)
config.setBackColor(Color.GRAY.getRGB());
// Generate QR code to file or stream
QrCodeUtil.generate("http://www.liuhiahua.cn/", config, FileUtil.file("D:\\tmp\\hblog1.png"));
} catch (Exception e) { | e.printStackTrace();
}
return message;
}
@RequestMapping("/hblog/qrcode/image2")
public String hblogImages2() {
String message = "";
try {
QrCodeUtil.generate(//
"http://www.liuhiahua.cn/", //content
QrConfig.create().setImg("D:\\tmp\\logo.png"), //logo
FileUtil.file("D:\\tmp\\qrcodeWithLogo.jpg")//output file
);
} catch (Exception e) {
e.printStackTrace();
}
return message;
}
} | repos\springboot-demo-master\qrcode\src\main\java\com\et\qrcode\controller\QRCodeController.java | 2 |
请完成以下Java代码 | public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getActivityId() {
return activityId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getProcessInstanceIds() {
return null;
}
public String getBusinessKey() {
return businessKey;
}
public String getExecutionId() {
return executionId;
}
public SuspensionState getSuspensionState() {
return suspensionState;
}
public void setSuspensionState(SuspensionState suspensionState) {
this.suspensionState = suspensionState;
}
public List<EventSubscriptionQueryValue> getEventSubscriptions() {
return eventSubscriptions;
} | public void setEventSubscriptions(List<EventSubscriptionQueryValue> eventSubscriptions) {
this.eventSubscriptions = eventSubscriptions;
}
public String getIncidentId() {
return incidentId;
}
public String getIncidentType() {
return incidentType;
}
public String getIncidentMessage() {
return incidentMessage;
}
public String getIncidentMessageLike() {
return incidentMessageLike;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ExecutionQueryImpl.java | 1 |
请完成以下Java代码 | public Object execute(CommandContext commandContext) {
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
AttachmentEntity attachment = processEngineConfiguration.getAttachmentEntityManager().findById(attachmentId);
String processInstanceId = attachment.getProcessInstanceId();
String processDefinitionId = null;
ExecutionEntity processInstance = null;
if (attachment.getProcessInstanceId() != null) {
processInstance = processEngineConfiguration.getExecutionEntityManager().findById(processInstanceId);
if (processInstance != null) {
processDefinitionId = processInstance.getProcessDefinitionId();
if (Flowable5Util.isFlowable5ProcessDefinitionId(commandContext, processInstance.getProcessDefinitionId())) {
Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler();
compatibilityHandler.deleteAttachment(attachmentId);
return null;
}
}
}
processEngineConfiguration.getAttachmentEntityManager().delete(attachment, false);
if (attachment.getContentId() != null) {
processEngineConfiguration.getByteArrayEntityManager().deleteByteArrayById(attachment.getContentId());
}
TaskEntity task = null; | if (attachment.getTaskId() != null) {
task = processEngineConfiguration.getTaskServiceConfiguration().getTaskService().getTask(attachment.getTaskId());
}
if (attachment.getTaskId() != null) {
processEngineConfiguration.getHistoryManager().createAttachmentComment(task, processInstance, attachment.getName(), false);
}
FlowableEventDispatcher eventDispatcher = processEngineConfiguration.getEventDispatcher();
if (eventDispatcher != null && eventDispatcher.isEnabled()) {
eventDispatcher.dispatchEvent(FlowableEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_DELETED,
attachment, processInstanceId, processInstanceId, processDefinitionId),
processEngineConfiguration.getEngineCfgKey());
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\DeleteAttachmentCmd.java | 1 |
请完成以下Java代码 | private HttpStatus parseHttpStatus(@Nullable final String httpCode)
{
try
{
if (Check.isBlank(httpCode))
{
throw new AdempiereException("HTTP Code is blank")
.appendParametersToMessage()
.setParameter("HttpCode", httpCode);
}
final int statusCode = Integer.parseInt(httpCode.trim());
return HttpStatus.valueOf(statusCode);
}
catch (final Exception e)
{
throw new AdempiereException("Error while parsing HTTP Code", e)
.appendParametersToMessage()
.setParameter("HttpCode", httpCode);
}
}
@NonNull | private HttpHeaders reconstructHeaders(@Nullable final String httpHeadersJson)
{
final HttpHeaders headers = new HttpHeaders();
if (Check.isNotBlank(httpHeadersJson))
{
final HttpHeadersWrapper headersWrapper = HttpHeadersWrapper
.fromJson(httpHeadersJson, JsonObjectMapperHolder.sharedJsonObjectMapper());
headersWrapper.streamHeaders()
.forEach(entry -> headers.add(entry.getKey(), entry.getValue()));
}
return headers;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\audit\ApiAuditController.java | 1 |
请完成以下Java代码 | public class KafkaMessageHeaders {
private static Logger logger = LoggerFactory.getLogger(KafkaMessageHeaders.class);
private static String TOPIC = "baeldung";
private static String MESSAGE_KEY = "message";
private static String MESSAGE_VALUE = "Hello World";
private static String HEADER_KEY = "website";
private static String HEADER_VALUE = "baeldung.com";
private static KafkaProducer<String, String> producer;
private static KafkaConsumer<String, String> consumer;
public static void main(String[] args) {
setup();
publishMessageWithCustomHeaders();
consumeMessageWithCustomHeaders();
}
private static void consumeMessageWithCustomHeaders() {
consumer.subscribe(Arrays.asList(TOPIC));
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMinutes(1));
for (ConsumerRecord<String, String> record : records) {
logger.info(record.key());
logger.info(record.value());
Headers headers = record.headers();
for (Header header : headers) {
logger.info(header.key());
logger.info(new String(header.value()));
}
}
}
private static void publishMessageWithCustomHeaders() { | List<Header> headers = new ArrayList<>();
headers.add(new RecordHeader(HEADER_KEY, HEADER_VALUE.getBytes()));
ProducerRecord<String, String> record1 = new ProducerRecord<>(TOPIC, null, MESSAGE_KEY, MESSAGE_VALUE, headers);
producer.send(record1);
ProducerRecord<String, String> record2 = new ProducerRecord<>(TOPIC, null, System.currentTimeMillis(), MESSAGE_KEY, MESSAGE_VALUE, headers);
producer.send(record2);
}
private static void setup() {
Properties producerProperties = new Properties();
producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
Properties consumerProperties = new Properties();
consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "ConsumerGroup1");
producer = new KafkaProducer<>(producerProperties);
consumer = new KafkaConsumer<>(consumerProperties);
}
} | repos\tutorials-master\apache-kafka\src\main\java\com\baeldung\kafka\headers\KafkaMessageHeaders.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class ArtemisAutoConfiguration {
@Bean
@ConditionalOnMissingBean
ArtemisConnectionDetails artemisConnectionDetails(ArtemisProperties properties) {
return new PropertiesArtemisConnectionDetails(properties);
}
/**
* Adapts {@link ArtemisProperties} to {@link ArtemisConnectionDetails}.
*/
static class PropertiesArtemisConnectionDetails implements ArtemisConnectionDetails {
private final ArtemisProperties properties;
PropertiesArtemisConnectionDetails(ArtemisProperties properties) {
this.properties = properties;
}
@Override
public @Nullable ArtemisMode getMode() {
return this.properties.getMode(); | }
@Override
public @Nullable String getBrokerUrl() {
return this.properties.getBrokerUrl();
}
@Override
public @Nullable String getUser() {
return this.properties.getUser();
}
@Override
public @Nullable String getPassword() {
return this.properties.getPassword();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-artemis\src\main\java\org\springframework\boot\artemis\autoconfigure\ArtemisAutoConfiguration.java | 2 |
请完成以下Java代码 | public boolean isTenantIdSet() {
return isTenantIdSet;
}
protected <T> T execute(Command<T> command) {
return commandExecutor.execute(command);
}
@Override
public ConditionEvaluationBuilder processInstanceBusinessKey(String businessKey) {
ensureNotNull("businessKey", businessKey);
this.businessKey = businessKey;
return this;
}
@Override
public ConditionEvaluationBuilder processDefinitionId(String processDefinitionId) {
ensureNotNull("processDefinitionId", processDefinitionId);
this.processDefinitionId = processDefinitionId;
return this;
}
@Override
public ConditionEvaluationBuilder setVariable(String variableName, Object variableValue) {
ensureNotNull("variableName", variableName);
this.variables.put(variableName, variableValue);
return this;
}
@Override
public ConditionEvaluationBuilder setVariables(Map<String, Object> variables) {
ensureNotNull("variables", variables);
if (variables != null) {
this.variables.putAll(variables);
}
return this;
} | @Override
public ConditionEvaluationBuilder tenantId(String tenantId) {
ensureNotNull(
"The tenant-id cannot be null. Use 'withoutTenantId()' if you want to evaluate conditional start event with a process definition which has no tenant-id.",
"tenantId", tenantId);
isTenantIdSet = true;
this.tenantId = tenantId;
return this;
}
@Override
public ConditionEvaluationBuilder withoutTenantId() {
isTenantIdSet = true;
tenantId = null;
return this;
}
@Override
public List<ProcessInstance> evaluateStartConditions() {
return execute(new EvaluateStartConditionCmd(this));
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ConditionEvaluationBuilderImpl.java | 1 |
请完成以下Java代码 | public SqlDocumentQueryBuilder noSorting(final boolean noSorting)
{
this.noSorting = noSorting;
if (noSorting)
{
orderBys = DocumentQueryOrderByList.EMPTY;
}
return this;
}
public boolean isSorting()
{
return !isNoSorting();
}
public SqlDocumentQueryBuilder setOrderBys(final DocumentQueryOrderByList orderBys)
{
// Don't throw exception if noSorting is true. Just do nothing.
// REASON: it gives us better flexibility when this builder is handled by different methods, each of them adding stuff to it
// Check.assume(!noSorting, "sorting enabled for {}", this);
if (noSorting)
{
return this;
}
this.orderBys = orderBys != null ? orderBys : DocumentQueryOrderByList.EMPTY;
return this;
}
public SqlDocumentQueryBuilder setPage(final int firstRow, final int pageLength)
{
this.firstRow = firstRow;
this.pageLength = pageLength;
return this;
}
private int getFirstRow()
{
return firstRow;
}
private int getPageLength()
{
return pageLength; | }
public static SqlComposedKey extractComposedKey(
final DocumentId recordId,
final List<? extends SqlEntityFieldBinding> keyFields)
{
final int count = keyFields.size();
if (count < 1)
{
throw new AdempiereException("Invalid composed key: " + keyFields);
}
final List<Object> composedKeyParts = recordId.toComposedKeyParts();
if (composedKeyParts.size() != count)
{
throw new AdempiereException("Invalid composed key '" + recordId + "'. Expected " + count + " parts but it has " + composedKeyParts.size());
}
final ImmutableSet.Builder<String> keyColumnNames = ImmutableSet.builder();
final ImmutableMap.Builder<String, Object> values = ImmutableMap.builder();
for (int i = 0; i < count; i++)
{
final SqlEntityFieldBinding keyField = keyFields.get(i);
final String keyColumnName = keyField.getColumnName();
keyColumnNames.add(keyColumnName);
final Object valueObj = composedKeyParts.get(i);
@Nullable final Object valueConv = DataTypes.convertToValueClass(
keyColumnName,
valueObj,
keyField.getWidgetType(),
keyField.getSqlValueClass(),
null);
if (!JSONNullValue.isNull(valueConv))
{
values.put(keyColumnName, valueConv);
}
}
return SqlComposedKey.of(keyColumnNames.build(), values.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\SqlDocumentQueryBuilder.java | 1 |
请完成以下Java代码 | public Path createDistributionFile(Path dir, String extension) {
Path download = dir.resolveSibling(dir.getFileName() + extension);
addTempFile(dir, download);
return download;
}
private void addTempFile(Path group, Path file) {
this.temporaryFiles.compute(group, (path, paths) -> {
List<Path> newPaths = (paths != null) ? paths : new ArrayList<>();
newPaths.add(file);
return newPaths;
});
}
/**
* Clean all the temporary files that are related to this root directory.
* @param dir the directory to clean
* @see #createDistributionFile
*/
public void cleanTempFiles(Path dir) {
List<Path> tempFiles = this.temporaryFiles.remove(dir);
if (!tempFiles.isEmpty()) {
tempFiles.forEach((path) -> {
try {
FileSystemUtils.deleteRecursively(path);
}
catch (IOException ex) {
// Continue
}
});
}
}
private byte[] generateBuild(ProjectGenerationContext context) throws IOException { | ProjectDescription description = context.getBean(ProjectDescription.class);
StringWriter out = new StringWriter();
BuildWriter buildWriter = context.getBeanProvider(BuildWriter.class).getIfAvailable();
if (buildWriter != null) {
buildWriter.writeBuild(out);
return out.toString().getBytes();
}
else {
throw new IllegalStateException("No BuildWriter implementation found for " + description.getLanguage());
}
}
private void customizeProjectGenerationContext(AnnotationConfigApplicationContext context,
InitializrMetadata metadata) {
context.setParent(this.parentApplicationContext);
context.registerBean(InitializrMetadata.class, () -> metadata);
context.registerBean(BuildItemResolver.class, () -> new MetadataBuildItemResolver(metadata,
context.getBean(ProjectDescription.class).getPlatformVersion()));
context.registerBean(MetadataProjectDescriptionCustomizer.class,
() -> new MetadataProjectDescriptionCustomizer(metadata));
}
private void publishProjectGeneratedEvent(R request, ProjectGenerationContext context) {
InitializrMetadata metadata = context.getBean(InitializrMetadata.class);
ProjectGeneratedEvent event = new ProjectGeneratedEvent(request, metadata);
this.eventPublisher.publishEvent(event);
}
private void publishProjectFailedEvent(R request, InitializrMetadata metadata, Exception cause) {
ProjectFailedEvent event = new ProjectFailedEvent(request, metadata, cause);
this.eventPublisher.publishEvent(event);
}
} | repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\project\ProjectGenerationInvoker.java | 1 |
请完成以下Java代码 | public boolean isUpdate()
{
return updateMerge || updateRemove;
}
public boolean isAttemptUpdate()
{
return updateMerge || updateRemove || assertUnchanged;
}
}
@JsonInclude(Include.NON_NULL)
IfNotExists ifNotExists;
@JsonInclude(Include.NON_NULL)
IfExists ifExists;
@Builder
@JsonCreator
private SyncAdvise(
@JsonProperty("ifNotExists") @Nullable final IfNotExists ifNotExists, | @JsonProperty("ifExists") @Nullable final IfExists ifExists)
{
this.ifNotExists = CoalesceUtil.coalesce(ifNotExists, IfNotExists.FAIL);
this.ifExists = CoalesceUtil.coalesce(ifExists, IfExists.DONT_UPDATE);
}
@JsonIgnore
public boolean isFailIfNotExists()
{
return IfNotExists.FAIL.equals(ifNotExists);
}
/**
* If {@code true} then the sync code can attempt to lookup readonlydata. Maybe this info helps with caching.
*/
@JsonIgnore
public boolean isLoadReadOnly()
{
return READ_ONLY.equals(this) || READ_ONLY_UNCHANGED.equals(this);
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-rest_api\src\main\java\de\metas\common\rest_api\v1\SyncAdvise.java | 1 |
请完成以下Java代码 | public class ESRPaymentStringDataProvider extends AbstractPaymentStringDataProvider
{
public ESRPaymentStringDataProvider(final PaymentString paymentString)
{
super(paymentString);
}
@Override
public List<org.compiere.model.I_C_BP_BankAccount> getC_BP_BankAccounts()
{
final PaymentString paymentString = getPaymentString();
final String postAccountNo = paymentString.getPostAccountNo();
final String innerAccountNo = paymentString.getInnerAccountNo();
final IESRBPBankAccountDAO esrbpBankAccountDAO = Services.get(IESRBPBankAccountDAO.class);
final List<org.compiere.model.I_C_BP_BankAccount> bankAccounts = InterfaceWrapperHelper.createList(
esrbpBankAccountDAO.retrieveESRBPBankAccounts(postAccountNo, innerAccountNo),
org.compiere.model.I_C_BP_BankAccount.class);
return bankAccounts;
}
@Override
public I_C_BP_BankAccount createNewC_BP_BankAccount(final IContextAware contextProvider, final int bpartnerId)
{
final PaymentString paymentString = getPaymentString(); | final I_C_BP_BankAccount bpBankAccount = InterfaceWrapperHelper.newInstance(I_C_BP_BankAccount.class, contextProvider);
Check.assume(bpartnerId > 0, "We assume the bPartnerId to be greater than 0. This={}", this);
bpBankAccount.setC_BPartner_ID(bpartnerId);
// bpBankAccount.setC_Bank_ID(C_Bank_ID); // introduce a standard ESR-Dummy-Bank, or leave it empty
final Currency currency = Services.get(ICurrencyDAO.class).getByCurrencyCode(CurrencyCode.CHF); // CHF, because it's ESR
bpBankAccount.setC_Currency_ID(currency.getId().getRepoId());
bpBankAccount.setIsEsrAccount(true); // ..because we are creating this from an ESR string
bpBankAccount.setIsACH(true);
final String bPartnerName = Services.get(IBPartnerDAO.class).getBPartnerNameById(BPartnerId.ofRepoId(bpartnerId));
bpBankAccount.setA_Name(bPartnerName);
bpBankAccount.setName(bPartnerName);
bpBankAccount.setAccountNo(paymentString.getInnerAccountNo());
bpBankAccount.setESR_RenderedAccountNo(paymentString.getPostAccountNo());
InterfaceWrapperHelper.save(bpBankAccount);
return bpBankAccount;
}
@Override
public String toString()
{
return String.format("ESRPaymentStringDataProvider [getPaymentString()=%s]", getPaymentString());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\api\impl\ESRPaymentStringDataProvider.java | 1 |
请完成以下Java代码 | public void setIsOnDistinctICTypes (final boolean IsOnDistinctICTypes)
{
set_Value (COLUMNNAME_IsOnDistinctICTypes, IsOnDistinctICTypes);
}
@Override
public boolean isOnDistinctICTypes()
{
return get_ValueAsBoolean(COLUMNNAME_IsOnDistinctICTypes);
}
@Override
public void setIsSOTrx (final boolean IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, IsSOTrx);
}
@Override
public boolean isSOTrx()
{
return get_ValueAsBoolean(COLUMNNAME_IsSOTrx);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
} | @Override
public void setNegative_Amt_C_DocType_ID (final int Negative_Amt_C_DocType_ID)
{
if (Negative_Amt_C_DocType_ID < 1)
set_Value (COLUMNNAME_Negative_Amt_C_DocType_ID, null);
else
set_Value (COLUMNNAME_Negative_Amt_C_DocType_ID, Negative_Amt_C_DocType_ID);
}
@Override
public int getNegative_Amt_C_DocType_ID()
{
return get_ValueAsInt(COLUMNNAME_Negative_Amt_C_DocType_ID);
}
@Override
public void setPositive_Amt_C_DocType_ID (final int Positive_Amt_C_DocType_ID)
{
if (Positive_Amt_C_DocType_ID < 1)
set_Value (COLUMNNAME_Positive_Amt_C_DocType_ID, null);
else
set_Value (COLUMNNAME_Positive_Amt_C_DocType_ID, Positive_Amt_C_DocType_ID);
}
@Override
public int getPositive_Amt_C_DocType_ID()
{
return get_ValueAsInt(COLUMNNAME_Positive_Amt_C_DocType_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocType_Invoicing_Pool.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_C_Country getC_Country()
{
return get_ValueAsPO(COLUMNNAME_C_Country_ID, org.compiere.model.I_C_Country.class);
}
@Override
public void setC_Country(final org.compiere.model.I_C_Country C_Country)
{
set_ValueFromPO(COLUMNNAME_C_Country_ID, org.compiere.model.I_C_Country.class, C_Country);
}
@Override
public void setC_Country_ID (final int C_Country_ID)
{
if (C_Country_ID < 1)
set_Value (COLUMNNAME_C_Country_ID, null);
else
set_Value (COLUMNNAME_C_Country_ID, C_Country_ID);
}
@Override
public int getC_Country_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Country_ID);
}
@Override
public void setC_Currency_ID (final int C_Currency_ID)
{
if (C_Currency_ID < 1)
set_Value (COLUMNNAME_C_Currency_ID, null);
else
set_Value (COLUMNNAME_C_Currency_ID, C_Currency_ID);
}
@Override
public int getC_Currency_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Currency_ID);
}
@Override
public void setFreightAmt (final BigDecimal FreightAmt)
{
set_Value (COLUMNNAME_FreightAmt, FreightAmt);
}
@Override
public BigDecimal getFreightAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_FreightAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setM_FreightCostDetail_ID (final int M_FreightCostDetail_ID)
{
if (M_FreightCostDetail_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_FreightCostDetail_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_FreightCostDetail_ID, M_FreightCostDetail_ID);
}
@Override
public int getM_FreightCostDetail_ID()
{
return get_ValueAsInt(COLUMNNAME_M_FreightCostDetail_ID);
} | @Override
public org.adempiere.model.I_M_FreightCostShipper getM_FreightCostShipper()
{
return get_ValueAsPO(COLUMNNAME_M_FreightCostShipper_ID, org.adempiere.model.I_M_FreightCostShipper.class);
}
@Override
public void setM_FreightCostShipper(final org.adempiere.model.I_M_FreightCostShipper M_FreightCostShipper)
{
set_ValueFromPO(COLUMNNAME_M_FreightCostShipper_ID, org.adempiere.model.I_M_FreightCostShipper.class, M_FreightCostShipper);
}
@Override
public void setM_FreightCostShipper_ID (final int M_FreightCostShipper_ID)
{
if (M_FreightCostShipper_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_FreightCostShipper_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_FreightCostShipper_ID, M_FreightCostShipper_ID);
}
@Override
public int getM_FreightCostShipper_ID()
{
return get_ValueAsInt(COLUMNNAME_M_FreightCostShipper_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setShipmentValueAmt (final BigDecimal ShipmentValueAmt)
{
set_Value (COLUMNNAME_ShipmentValueAmt, ShipmentValueAmt);
}
@Override
public BigDecimal getShipmentValueAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ShipmentValueAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\model\X_M_FreightCostDetail.java | 1 |
请完成以下Spring Boot application配置 | server:
port: 8888
spring:
application:
name: gateway-application
# Zipkin 配置项,对应 ZipkinProperties 类
zipkin:
base-url: http://127.0.0.1:9411 # Zipkin 服务的地址
# Spring Cloud Sleuth 配置项
sleuth:
# Spring Cloud Sleuth 针对 Web 组件的配置项,例如说 SpringMVC
web:
enabled: true # 是否开启,默认为 true
cloud:
# Spring Cloud Gateway 配置项,对应 GatewayProperties 类
gateway | :
# 路由配置项,对应 RouteDefinition 数组
routes:
- id: feign-service-route
uri: http://127.0.0.1:8081
predicates:
- Path=/** | repos\SpringBoot-Labs-master\labx-13\labx-13-sc-sleuth-springcloudgateway\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | public ResponseEntity<SalesInvoicePaymentStatusResponse> retrievePaymentStatus(
@ApiParam(required = true, value = "Organisation for which we retrieve the payment status.<br>Either `AD_Org.Value` or the GLN of a location of the org's business partner.") //
@PathVariable("orgCode") final String orgCode,
@ApiParam(required = true, value = "Invoice document number prefix of the invoice(s) for which we retrieve the payment status") //
@PathVariable("invoiceDocumentNoPrefix") final String invoiceDocumentNoPrefix)
{
final PaymentStatusQuery query = PaymentStatusQuery
.builder()
.orgValue(orgCode)
.invoiceDocumentNoPrefix(invoiceDocumentNoPrefix)
.build();
try
{
final ImmutableList<SalesInvoicePaymentStatus> result = salesInvoicePaymentStatusRepository.getBy(query);
return new ResponseEntity<>(new SalesInvoicePaymentStatusResponse(result), HttpStatus.OK);
}
catch (final OrgIdNotFoundException e)
{
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@ApiOperation(value = "Gets regular sales invoice(s) for the given org and invoice date range, together with their payment status.", notes = "Does *not* get sales credit memos and all kinds of purchase invoices.")
@GetMapping("{orgCode}")
public ResponseEntity<SalesInvoicePaymentStatusResponse> retrievePaymentStatus(
@ApiParam(required = true, value = "Organisation for which we retrieve the payment status.<br>Either `AD_Org.Value` or the GLN of a location of the org's business partner.") //
@PathVariable("orgCode") final String orgCode,
@ApiParam(required = true, example = "2019-02-01", value = "Return the status for invoices that have `C_Invoice.DateInvoiced` greater </b>or equal</b> to the given date at 00:00") // | @RequestParam("startDateIncl") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) final LocalDate startDate,
@ApiParam(required = true, example = "2019-03-01", value = "Return the status for invoices that have `C_Invoice.DateInvoiced` less than the given date at 00:00") //
@RequestParam("endDateExcl") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) final LocalDate endDate)
{
if (Check.isEmpty(orgCode, true) || startDate == null || endDate == null)
{
return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
}
final PaymentStatusQuery query = PaymentStatusQuery
.builder()
.orgValue(orgCode)
.dateInvoicedFrom(startDate)
.dateInvoicedTo(endDate)
.build();
try
{
final ImmutableList<SalesInvoicePaymentStatus> result = salesInvoicePaymentStatusRepository.getBy(query);
return new ResponseEntity<>(new SalesInvoicePaymentStatusResponse(result), HttpStatus.OK);
}
catch (final OrgIdNotFoundException e)
{
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\invoice\impl\SalesInvoicePaymentStatusRestController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class XmlFileItemReaderDemo {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Bean
public Job xmlFileItemReaderJob() {
return jobBuilderFactory.get("xmlFileItemReaderJob")
.start(step())
.build();
}
private Step step() {
return stepBuilderFactory.get("step")
.<TestData, TestData>chunk(2)
.reader(xmlFileItemReader())
.writer(list -> list.forEach(System.out::println))
.build();
} | private ItemReader<TestData> xmlFileItemReader() {
StaxEventItemReader<TestData> reader = new StaxEventItemReader<>();
reader.setResource(new ClassPathResource("file.xml")); // 设置xml文件源
reader.setFragmentRootElementName("test"); // 指定xml文件的根标签
// 将xml数据转换为TestData对象
XStreamMarshaller marshaller = new XStreamMarshaller();
// 指定需要转换的目标数据类型
Map<String, Class<TestData>> map = new HashMap<>(1);
map.put("test", TestData.class);
marshaller.setAliases(map);
reader.setUnmarshaller(marshaller);
return reader;
}
} | repos\SpringAll-master\68.spring-batch-itemreader\src\main\java\cc\mrbird\batch\job\XmlFileItemReaderDemo.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public BigInteger getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setValue(BigInteger value) {
this.value = value;
}
/**
* Gets the value of the bankCodeType property.
*
* @return | * possible object is
* {@link CountryCodeType }
*
*/
public CountryCodeType getBankCodeType() {
return bankCodeType;
}
/**
* Sets the value of the bankCodeType property.
*
* @param value
* allowed object is
* {@link CountryCodeType }
*
*/
public void setBankCodeType(CountryCodeType value) {
this.bankCodeType = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\BankCodeCType.java | 2 |
请完成以下Java代码 | public class SendToAllRequest implements Message {
public static final String TYPE = "SEND_TO_ALL_REQUEST";
/**
* 消息编号
*/
private String msgId;
/**
* 内容
*/
private String content;
public String getContent() {
return content;
} | public SendToAllRequest setContent(String content) {
this.content = content;
return this;
}
public String getMsgId() {
return msgId;
}
public SendToAllRequest setMsgId(String msgId) {
this.msgId = msgId;
return this;
}
} | repos\SpringBoot-Labs-master\lab-25\lab-websocket-25-01\src\main\java\cn\iocoder\springboot\lab25\springwebsocket\message\SendToAllRequest.java | 1 |
请完成以下Java代码 | protected void prepare()
{
// nothing to do
}
@Override
protected String doIt() throws Exception
{
final I_C_Order order = getRecord(I_C_Order.class);
orderCheckupBL.generateReportsIfEligible(order);
return "@Success@";
}
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
final I_C_Order order = context.getSelectedModel(I_C_Order.class);
if (order == null)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("context contains no order");
}
// Make sure this feature is enabled (sysconfig)
if (!sysConfigBL.getBooleanValue(SYSCONFIG_EnableProcessGear, false, order.getAD_Client_ID(), order.getAD_Org_ID()))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("not enabled");
} | // Only completed/closed orders
if (!docActionBL.isDocumentCompletedOrClosed(order))
{
logger.debug("{} has DocStatus={}; nothing to do", new Object[] { order, order.getDocStatus() });
return ProcessPreconditionsResolution.reject("only completed/closed orders are allowed");
}
// Only eligible orders
if (!orderCheckupBL.isEligibleForReporting(order))
{
return ProcessPreconditionsResolution.reject("not eligible for reporting");
}
return ProcessPreconditionsResolution.accept();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\ordercheckup\process\C_Order_MFGWarehouse_Report_Generate.java | 1 |
请完成以下Java代码 | public java.lang.String getInvoiceWeekDayCutoff ()
{
return (java.lang.String)get_Value(COLUMNNAME_InvoiceWeekDayCutoff);
}
/** Set Betragsgrenze.
@param IsAmount
Send invoices only if the amount exceeds the limit
IMPORTANT: currently not used;
*/
@Override
public void setIsAmount (boolean IsAmount)
{
set_Value (COLUMNNAME_IsAmount, Boolean.valueOf(IsAmount));
}
/** Get Betragsgrenze.
@return Send invoices only if the amount exceeds the limit
IMPORTANT: currently not used;
*/
@Override
public boolean isAmount ()
{
Object oo = get_Value(COLUMNNAME_IsAmount);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Standard.
@param IsDefault
Default value
*/
@Override
public void setIsDefault (boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
}
/** Get Standard.
@return Default value
*/
@Override
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue(); | return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_InvoiceSchedule.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected Map<String, Object> extractVariables(List<EngineRestVariable> restVariables) {
if (restVariables != null && !restVariables.isEmpty()) {
Map<String, Object> variables = new HashMap<>();
for (EngineRestVariable restVariable : restVariables) {
if (restVariable.getName() == null) {
throw new FlowableIllegalArgumentException("Variable name is required.");
}
variables.put(restVariable.getName(), restResponseFactory.getVariableValue(restVariable));
}
return variables;
}
return Collections.emptyMap();
}
protected ExternalWorkerJobAcquireBuilder createExternalWorkerAcquireBuilder() {
if (managementService != null) {
return managementService.createExternalWorkerJobAcquireBuilder();
} else if (cmmnManagementService != null) {
return cmmnManagementService.createExternalWorkerJobAcquireBuilder(); | } else {
throw new FlowableException("Cannot acquire external jobs. There is no BPMN or CMMN engine available");
}
}
protected ExternalWorkerJobFailureBuilder createExternalWorkerJobFailureBuilder(String jobId, String workerId) {
if (managementService != null) {
return managementService.createExternalWorkerJobFailureBuilder(jobId, workerId);
} else if (cmmnManagementService != null) {
return cmmnManagementService.createExternalWorkerJobFailureBuilder(jobId, workerId);
} else {
throw new FlowableException("Cannot fail external jobs. There is no BPMN or CMMN engine available");
}
}
} | repos\flowable-engine-main\modules\flowable-external-job-rest\src\main\java\org\flowable\external\job\rest\service\api\acquire\ExternalWorkerAcquireJobResource.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InsuranceContractVisitInterval insuranceContractVisitInterval = (InsuranceContractVisitInterval) o;
return Objects.equals(this.frequency, insuranceContractVisitInterval.frequency) &&
Objects.equals(this.amount, insuranceContractVisitInterval.amount) &&
Objects.equals(this.timePeriod, insuranceContractVisitInterval.timePeriod) &&
Objects.equals(this.annotation, insuranceContractVisitInterval.annotation);
}
@Override
public int hashCode() {
return Objects.hash(frequency, amount, timePeriod, annotation);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class InsuranceContractVisitInterval {\n"); | sb.append(" frequency: ").append(toIndentedString(frequency)).append("\n");
sb.append(" amount: ").append(toIndentedString(amount)).append("\n");
sb.append(" timePeriod: ").append(toIndentedString(timePeriod)).append("\n");
sb.append(" annotation: ").append(toIndentedString(annotation)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\InsuranceContractVisitInterval.java | 2 |
请完成以下Java代码 | public int getLag(String topic) {
return Optional.ofNullable(storage.get(topic)).map(Collection::size).orElse(0);
}
@Override
public boolean put(String topic, TbQueueMsg msg) {
return storage.computeIfAbsent(topic, (t) -> new LinkedBlockingQueue<>()).add(msg);
}
@SuppressWarnings("unchecked")
@Override
public <T extends TbQueueMsg> List<T> get(String topic) throws InterruptedException {
final BlockingQueue<TbQueueMsg> queue = storage.get(topic);
if (queue != null) {
final TbQueueMsg firstMsg = queue.poll(); | if (firstMsg != null) {
final int queueSize = queue.size();
if (queueSize > 0) {
final List<TbQueueMsg> entities = new ArrayList<>(Math.min(queueSize, 999) + 1);
entities.add(firstMsg);
queue.drainTo(entities, 999);
return (List<T>) entities;
}
return Collections.singletonList((T) firstMsg);
}
}
return Collections.emptyList();
}
} | repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\memory\DefaultInMemoryStorage.java | 1 |
请完成以下Java代码 | public void save(OAuth2AuthorizationConsent authorizationConsent) {
Assert.notNull(authorizationConsent, "authorizationConsent cannot be null");
int id = getId(authorizationConsent);
this.authorizationConsents.put(id, authorizationConsent);
}
@Override
public void remove(OAuth2AuthorizationConsent authorizationConsent) {
Assert.notNull(authorizationConsent, "authorizationConsent cannot be null");
int id = getId(authorizationConsent);
this.authorizationConsents.remove(id, authorizationConsent);
}
@Override
@Nullable | public OAuth2AuthorizationConsent findById(String registeredClientId, String principalName) {
Assert.hasText(registeredClientId, "registeredClientId cannot be empty");
Assert.hasText(principalName, "principalName cannot be empty");
int id = getId(registeredClientId, principalName);
return this.authorizationConsents.get(id);
}
private static int getId(String registeredClientId, String principalName) {
return Objects.hash(registeredClientId, principalName);
}
private static int getId(OAuth2AuthorizationConsent authorizationConsent) {
return getId(authorizationConsent.getRegisteredClientId(), authorizationConsent.getPrincipalName());
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\InMemoryOAuth2AuthorizationConsentService.java | 1 |
请完成以下Java代码 | public void setParentElementValue_ID (final int ParentElementValue_ID)
{
if (ParentElementValue_ID < 1)
set_Value (COLUMNNAME_ParentElementValue_ID, null);
else
set_Value (COLUMNNAME_ParentElementValue_ID, ParentElementValue_ID);
}
@Override
public int getParentElementValue_ID()
{
return get_ValueAsInt(COLUMNNAME_ParentElementValue_ID);
}
@Override
public void setParentValue (final @Nullable java.lang.String ParentValue)
{
set_Value (COLUMNNAME_ParentValue, ParentValue);
}
@Override
public java.lang.String getParentValue()
{
return get_ValueAsString(COLUMNNAME_ParentValue);
}
@Override
public void setPostActual (final boolean PostActual)
{
set_Value (COLUMNNAME_PostActual, PostActual);
}
@Override
public boolean isPostActual()
{
return get_ValueAsBoolean(COLUMNNAME_PostActual);
}
@Override
public void setPostBudget (final boolean PostBudget)
{
set_Value (COLUMNNAME_PostBudget, PostBudget);
}
@Override
public boolean isPostBudget()
{
return get_ValueAsBoolean(COLUMNNAME_PostBudget);
}
@Override
public void setPostEncumbrance (final boolean PostEncumbrance)
{
set_Value (COLUMNNAME_PostEncumbrance, PostEncumbrance);
}
@Override
public boolean isPostEncumbrance()
{
return get_ValueAsBoolean(COLUMNNAME_PostEncumbrance);
}
@Override
public void setPostStatistical (final boolean PostStatistical)
{
set_Value (COLUMNNAME_PostStatistical, PostStatistical);
}
@Override
public boolean isPostStatistical()
{
return get_ValueAsBoolean(COLUMNNAME_PostStatistical);
} | @Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setValue (final @Nullable java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_ElementValue.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.