instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | protected String doIt() throws Exception
{
final PInstanceId productsSelectionId = createProductsSelection();
final Instant startDate = getStartDate();
getCostElements().forEach(costElement -> recomputeCosts(costElement, productsSelectionId, startDate));
return MSG_OK;
}
private PInstanceId createProductsSelection()
{
final Set<ProductId> productIds = inventoryDAO.retrieveUsedProductsByInventoryIds(getSelectedInventoryIds());
if (productIds.isEmpty())
{
throw new AdempiereException("No Products");
}
return DB.createT_Selection(productIds, ITrx.TRXNAME_ThreadInherited);
}
private Set<InventoryId> getSelectedInventoryIds()
{
return retrieveSelectedRecordsQueryBuilder(I_M_Inventory.class)
.create()
.listIds()
.stream()
.map(InventoryId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
}
private void recomputeCosts(
@NonNull final CostElement costElement,
@NonNull final PInstanceId productsSelectionId,
@NonNull final Instant startDate)
{ | DB.executeFunctionCallEx(getTrxName()
, "select \"de_metas_acct\".product_costs_recreate_from_date( p_C_AcctSchema_ID :=" + getAccountingSchemaId().getRepoId()
+ ", p_M_CostElement_ID:=" + costElement.getId().getRepoId()
+ ", p_m_product_selection_id:=" + productsSelectionId.getRepoId()
+ " , p_ReorderDocs_DateAcct_Trunc:='MM'"
+ ", p_StartDateAcct:=" + DB.TO_SQL(startDate) + "::date)" //
, null //
);
}
private Instant getStartDate()
{
return inventoryDAO.getMinInventoryDate(getSelectedInventoryIds())
.orElseThrow(() -> new AdempiereException("Cannot determine Start Date"));
}
private List<CostElement> getCostElements()
{
if (p_costingMethod != null)
{
return costElementRepository.getMaterialCostingElementsForCostingMethod(p_costingMethod);
}
return costElementRepository.getActiveMaterialCostingElements(getClientID());
}
private AcctSchemaId getAccountingSchemaId() {return p_C_AcctSchema_ID;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inventory\process\M_Inventory_RecomputeCosts.java | 1 |
请完成以下Java代码 | public class PMMQtyReportEventsProcessor
{
public static final PMMQtyReportEventsProcessor newInstance()
{
return new PMMQtyReportEventsProcessor();
}
private final transient ITrxItemProcessorExecutorService trxItemProcessorExecutorService = Services.get(ITrxItemProcessorExecutorService.class);
private PMMQtyReportEventsProcessor()
{
super();
}
/**
* Process all events. | */
public void processAll()
{
final Properties ctx = Env.getCtx();
final EventSource<I_PMM_QtyReport_Event> events = new EventSource<>(ctx, I_PMM_QtyReport_Event.class);
final PMMQtyReportEventTrxItemProcessor itemProcessor = new PMMQtyReportEventTrxItemProcessor();
trxItemProcessorExecutorService.<I_PMM_QtyReport_Event, Void> createExecutor()
.setContext(ctx, ITrx.TRXNAME_ThreadInherited)
.setExceptionHandler(FailTrxItemExceptionHandler.instance)
.setProcessor(itemProcessor)
.process(events);
Loggables.addLog(itemProcessor.getProcessSummary());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\event\impl\PMMQtyReportEventsProcessor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DeleteHistoryJobCmd implements Command<Object>, Serializable {
private static final Logger LOGGER = LoggerFactory.getLogger(DeleteHistoryJobCmd.class);
private static final long serialVersionUID = 1L;
protected JobServiceConfiguration jobServiceConfiguration;
protected String historyJobId;
public DeleteHistoryJobCmd(String historyJobId, JobServiceConfiguration jobServiceConfiguration) {
this.historyJobId = historyJobId;
this.jobServiceConfiguration = jobServiceConfiguration;
}
@Override
public Object execute(CommandContext commandContext) {
HistoryJobEntity jobToDelete = getJobToDelete(commandContext);
sendCancelEvent(jobToDelete);
jobServiceConfiguration.getHistoryJobEntityManager().delete(jobToDelete);
return null;
}
protected void sendCancelEvent(HistoryJobEntity jobToDelete) {
FlowableEventDispatcher eventDispatcher = jobServiceConfiguration.getEventDispatcher();
if (eventDispatcher != null && eventDispatcher.isEnabled()) {
eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.JOB_CANCELED, jobToDelete),
jobServiceConfiguration.getEngineName());
}
}
protected HistoryJobEntity getJobToDelete(CommandContext commandContext) {
if (historyJobId == null) { | throw new FlowableIllegalArgumentException("jobId is null");
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Deleting job {}", historyJobId);
}
HistoryJobEntity job = jobServiceConfiguration.getHistoryJobEntityManager().findById(historyJobId);
if (job == null) {
throw new FlowableObjectNotFoundException("No history job found with id '" + historyJobId + "'", Job.class);
}
return job;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\DeleteHistoryJobCmd.java | 2 |
请完成以下Java代码 | public Board findNextMove(Board board, int playerNo) {
long start = System.currentTimeMillis();
long end = start + 60 * getMillisForCurrentLevel();
opponent = 3 - playerNo;
Tree tree = new Tree();
Node rootNode = tree.getRoot();
rootNode.getState().setBoard(board);
rootNode.getState().setPlayerNo(opponent);
while (System.currentTimeMillis() < end) {
// Phase 1 - Selection
Node promisingNode = selectPromisingNode(rootNode);
// Phase 2 - Expansion
if (promisingNode.getState().getBoard().checkStatus() == Board.IN_PROGRESS)
expandNode(promisingNode);
// Phase 3 - Simulation
Node nodeToExplore = promisingNode;
if (promisingNode.getChildArray().size() > 0) {
nodeToExplore = promisingNode.getRandomChildNode();
}
int playoutResult = simulateRandomPlayout(nodeToExplore);
// Phase 4 - Update
backPropogation(nodeToExplore, playoutResult);
}
Node winnerNode = rootNode.getChildWithMaxScore();
tree.setRoot(winnerNode);
return winnerNode.getState().getBoard();
}
private Node selectPromisingNode(Node rootNode) {
Node node = rootNode;
while (node.getChildArray().size() != 0) {
node = UCT.findBestNodeWithUCT(node);
}
return node;
}
private void expandNode(Node node) {
List<State> possibleStates = node.getState().getAllPossibleStates();
possibleStates.forEach(state -> {
Node newNode = new Node(state);
newNode.setParent(node);
newNode.getState().setPlayerNo(node.getState().getOpponent());
node.getChildArray().add(newNode);
});
}
private void backPropogation(Node nodeToExplore, int playerNo) {
Node tempNode = nodeToExplore;
while (tempNode != null) {
tempNode.getState().incrementVisit(); | if (tempNode.getState().getPlayerNo() == playerNo)
tempNode.getState().addScore(WIN_SCORE);
tempNode = tempNode.getParent();
}
}
private int simulateRandomPlayout(Node node) {
Node tempNode = new Node(node);
State tempState = tempNode.getState();
int boardStatus = tempState.getBoard().checkStatus();
if (boardStatus == opponent) {
tempNode.getParent().getState().setWinScore(Integer.MIN_VALUE);
return boardStatus;
}
while (boardStatus == Board.IN_PROGRESS) {
tempState.togglePlayer();
tempState.randomPlay();
boardStatus = tempState.getBoard().checkStatus();
}
return boardStatus;
}
} | repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\mcts\montecarlo\MonteCarloTreeSearch.java | 1 |
请完成以下Java代码 | public class GlobalExceptionHandler {
private Logger logger = LoggerFactory.getLogger(getClass());
/**
* 处理 ServiceException 异常
*/
@ResponseBody
@ExceptionHandler(value = ServiceException.class)
public CommonResult serviceExceptionHandler(ServiceException ex) {
logger.debug("[serviceExceptionHandler]", ex);
// 包装 CommonResult 结果
return CommonResult.error(ex.getCode(), ex.getMessage());
}
/**
* 处理 ServerWebInputException 异常
*
* WebFlux 参数不正确
*/
@ResponseBody
@ExceptionHandler(value = ServerWebInputException.class)
public CommonResult serverWebInputExceptionHandler(ServerWebInputException ex) {
logger.debug("[ServerWebInputExceptionHandler]", ex);
// 包装 CommonResult 结果
return CommonResult.error(ServiceExceptionEnum.MISSING_REQUEST_PARAM_ERROR.getCode(),
ServiceExceptionEnum.MISSING_REQUEST_PARAM_ERROR.getMessage()); | }
/**
* 处理其它 Exception 异常
*/
@ResponseBody
@ExceptionHandler(value = Exception.class)
public CommonResult exceptionHandler(Exception e) {
// 记录异常日志
logger.error("[exceptionHandler]", e);
// 返回 ERROR CommonResult
return CommonResult.error(ServiceExceptionEnum.SYS_ERROR.getCode(),
ServiceExceptionEnum.SYS_ERROR.getMessage());
}
} | repos\SpringBoot-Labs-master\lab-27\lab-27-webflux-02\src\main\java\cn\iocoder\springboot\lab27\springwebflux\core\web\GlobalExceptionHandler.java | 1 |
请完成以下Java代码 | private Set<EDIDesadvPackId> generateLabels()
{
return trxManager.callInThreadInheritedTrx(this::generateLabelsInTrx);
}
private Set<EDIDesadvPackId> generateLabelsInTrx()
{
if(!p_IsDefault && p_Counter <= 0)
{
throw new FillMandatoryException(PARAM_Counter);
}
final List<I_EDI_DesadvLine> desadvLines = getSelectedLines();
if (desadvLines.isEmpty())
{
throw new AdempiereException("@NoSelection@");
}
final DesadvLineSSCC18Generator desadvLineLabelsGenerator = DesadvLineSSCC18Generator.builder()
.sscc18CodeService(sscc18CodeService)
.desadvBL(desadvBL)
.ediDesadvPackService(ediDesadvPackService)
.printExistingLabels(true)
.bpartnerId(extractBPartnerId(desadvLines))
.build();
final LinkedHashSet<EDIDesadvPackId> lineSSCCIdsToPrint = new LinkedHashSet<>();
for (final I_EDI_DesadvLine desadvLine : desadvLines)
{
final PrintableDesadvLineSSCC18Labels desadvLineLabels = PrintableDesadvLineSSCC18Labels.builder()
.setEDI_DesadvLine(desadvLine)
.setRequiredSSCC18Count(!p_IsDefault ? p_Counter : null)
.build();
desadvLineLabelsGenerator.generateAndEnqueuePrinting(desadvLineLabels);
lineSSCCIdsToPrint.addAll(desadvLineLabelsGenerator.getLineSSCCIdsToPrint());
}
return lineSSCCIdsToPrint;
} | private static BPartnerId extractBPartnerId(@NonNull final List<I_EDI_DesadvLine> desadvLines)
{
final I_EDI_Desadv ediDesadvRecord = desadvLines.get(0).getEDI_Desadv();
final int bpartnerRepoId = CoalesceUtil.firstGreaterThanZero(
ediDesadvRecord.getDropShip_BPartner_ID(),
ediDesadvRecord.getC_BPartner_ID());
return BPartnerId.ofRepoId(bpartnerRepoId);
}
private List<I_EDI_DesadvLine> getSelectedLines()
{
final Set<Integer> lineIds = getSelectedLineIds();
return desadvBL.retrieveLinesByIds(lineIds);
}
private I_EDI_DesadvLine getSingleSelectedLine()
{
return CollectionUtils.singleElement(getSelectedLines());
}
private Set<Integer> getSelectedLineIds()
{
return getSelectedIncludedRecordIds(I_EDI_DesadvLine.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\EDI_Desadv_GenerateSSCCLabels.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private URL getAPIUrl(@NonNull final ReportContext reportContext)
{
final String apiBaseURL = getAPIBaseUrl();
final String apiPath = getAPIPath(reportContext);
try
{
return new URL(apiBaseURL + apiPath);
}
catch (final MalformedURLException e)
{
final ITranslatableString errorMsg = msgBL.getTranslatableMsgText(MSG_URLNotValid);
throw new AdempiereException(errorMsg, e);
}
}
private String getAPIBaseUrl()
{
final String url = StringUtils.trimBlankToNull(sysConfigBL.getValue(SYSCONFIG_JSON_API_URL, ""));
if (url == null || "-".equals(url))
{
logger.warn("Sysconfig {} is not configured. Report will not work", SYSCONFIG_JSON_API_URL);
throw new AdempiereException(MSG_URLNotValid)
.appendParametersToMessage()
.setParameter("reason", "Sysconfig `" + SYSCONFIG_JSON_API_URL + "` is not configured");
}
return url;
}
private String getAPIPath(final @NonNull ReportContext reportContext)
{
final String path = StringUtils.trimBlankToNull(reportContext.getJSONPath());
if (path == null || "-".equals(path))
{
throw new AdempiereException(MSG_URLNotValid)
.appendParametersToMessage()
.setParameter("reason", "JSONPath is not set");
}
final IStringExpression pathExpression = expressionFactory.compile(path, IStringExpression.class);
final Evaluatee evalCtx = createEvalCtx(reportContext);
return pathExpression.evaluate(evalCtx, OnVariableNotFound.Fail);
}
@Nullable
private String retrieveJsonSqlValue(@NonNull final ReportContext reportContext)
{
//
// Get SQL
final String sql = StringUtils.trimBlankToNull(reportContext.getSQLStatement());
if (sql == null)
{
return null;
} | // Parse the SQL Statement
final IStringExpression sqlExpression = expressionFactory.compile(sql, IStringExpression.class);
final Evaluatee evalCtx = createEvalCtx(reportContext);
final String sqlFinal = sqlExpression.evaluate(evalCtx, OnVariableNotFound.Fail);
return DB.getSQLValueStringEx(ITrx.TRXNAME_ThreadInherited, sqlFinal);
}
private static Evaluatee createEvalCtx(@NonNull final ReportContext reportContext)
{
final ArrayList<Evaluatee> contexts = new ArrayList<>();
//
// 1: Add process parameters
contexts.add(Evaluatees.ofRangeAwareParams(new ProcessParams(reportContext.getProcessInfoParameters())));
//
// 2: underlying record
final String recordTableName = reportContext.getTableNameOrNull();
final int recordId = reportContext.getRecord_ID();
if (recordTableName != null && recordId > 0)
{
final TableRecordReference recordRef = TableRecordReference.of(recordTableName, recordId);
final Evaluatee evalCtx = Evaluatees.ofTableRecordReference(recordRef);
if (evalCtx != null)
{
contexts.add(evalCtx);
}
}
//
// 3: global context
contexts.add(Evaluatees.ofCtx(Env.getCtx()));
return Evaluatees.compose(contexts);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\data_source\RemoteRestAPIDataSource.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static void main(final String[] args)
{
try (final IAutoCloseable c = ModelValidationEngine.postponeInit())
{
Ini.setRunMode(RunMode.BACKEND);
Adempiere.instance.startup(RunMode.BACKEND);
final String headless = System.getProperty(SYSTEM_PROPERTY_HEADLESS, Boolean.toString(true));
new SpringApplicationBuilder(ReportServiceMain.class)
.headless(StringUtils.toBoolean(headless)) // we need headless=false for initial connection setup popup (if any), usually this only applies on dev workstations.
.web(WebApplicationType.SERVLET)
.profiles(Profiles.PROFILE_ReportService, Profiles.PROFILE_ReportService_Standalone)
.beanNameGenerator(new MetasfreshBeanNameGenerator())
.run(args);
}
// now init the model validation engine
ModelValidationEngine.get();
}
@Bean
@Primary
public ObjectMapper jsonObjectMapper()
{
return JsonObjectMapperHolder.sharedJsonObjectMapper(); | }
@Profile(Profiles.PROFILE_NotTest)
@Bean(Adempiere.BEAN_NAME)
public Adempiere adempiere()
{
// as of right now, we are not interested in loading *any* model validator whatsoever within this service
// therefore we don't e.g. have to deal with the async-processor. It just won't be started.
ModelValidationEngine.setInitEntityTypes(Collections.emptyList());
final Adempiere adempiere = Env.getSingleAdempiereInstance(applicationContext);
adempiere.startup(RunMode.BACKEND);
return adempiere;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service-standalone\src\main\java\de\metas\report\ReportServiceMain.java | 2 |
请完成以下Java代码 | public void setCreditPassInfo(final I_C_Order order)
{
final BPartnerId bPartnerId = BPartnerId.ofRepoId(order.getC_BPartner_ID());
final CreditPassConfig config = creditPassConfigRepository.getConfigByBPartnerId(bPartnerId);
final Optional<TransactionResult> transactionResult = transactionResultService.findLastTransactionResult(order.getPaymentRule(), BPartnerId.ofRepoId(order.getC_BPartner_ID()));
final Optional<CreditPassConfig> configuration = Optional.ofNullable(config);
final IMsgBL msgBL = Services.get(IMsgBL.class);
if (configuration.isPresent() && configuration.get().getCreditPassConfigPaymentRuleList().stream()
.map(CreditPassConfigPaymentRule::getPaymentRule)
.anyMatch(pr -> StringUtils.equals(pr, order.getPaymentRule())))
{
if (transactionResult.filter(tr -> tr.getRequestDate().until(LocalDateTime.now(), ChronoUnit.DAYS) < config.getRetryDays()).isPresent())
{
if (transactionResult.filter(tr -> tr.getResultCodeEffective() == ResultCode.P).isPresent())
{
order.setCreditpassFlag(false);
final ITranslatableString message = msgBL.getTranslatableMsgText(CreditPassConstants.CREDITPASS_STATUS_SUCCESS_MESSAGE_KEY);
order.setCreditpassStatus(message.translate(Env.getAD_Language()));
}
else
{
order.setCreditpassFlag(true);
final ITranslatableString message = msgBL.getTranslatableMsgText(CreditPassConstants.CREDITPASS_REQUEST_NEEDED_MESSAGE_KEY);
order.setCreditpassStatus(message.translate(Env.getAD_Language()));
}
}
else
{
order.setCreditpassFlag(true);
final ITranslatableString message = msgBL.getTranslatableMsgText(CreditPassConstants.CREDITPASS_REQUEST_NEEDED_MESSAGE_KEY);
order.setCreditpassStatus(message.translate(Env.getAD_Language()));
}
} | else
{
order.setCreditpassFlag(false);
final ITranslatableString message = msgBL.getTranslatableMsgText(CreditPassConstants.CREDITPASS_REQUEST_NOT_NEEDED_MESSAGE_KEY);
order.setCreditpassStatus(message.translate(Env.getAD_Language()));
}
}
@DocValidate(timings = { ModelValidator.TIMING_BEFORE_COMPLETE })
public void validateCreditpassForOrder(final I_C_Order order)
{
if (order.getCreditpassFlag() && order.isSOTrx())
{
throw new AdempiereException(CreditPassConstants.ORDER_COMPLETED_CREDITPASS_ERROR);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java\de\metas\vertical\creditscore\creditpass\interceptor\C_Order.java | 1 |
请完成以下Java代码 | public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PersonWithEqualsAndComparable that = (PersonWithEqualsAndComparable) o;
return firstName.equals(that.firstName) &&
lastName.equals(that.lastName) &&
Objects.equals(birthDate, that.birthDate);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName);
}
@Override
public int compareTo(PersonWithEqualsAndComparable o) {
int lastNamesComparison = this.lastName.compareTo(o.lastName);
if (lastNamesComparison == 0) {
int firstNamesComparison = this.firstName.compareTo(o.firstName);
if (firstNamesComparison == 0) {
if (this.birthDate != null && o.birthDate != null) { | return this.birthDate.compareTo(o.birthDate);
} else if (this.birthDate != null) {
return 1;
} else if (o.birthDate != null) {
return -1;
} else {
return 0;
}
} else {
return firstNamesComparison;
}
} else {
return lastNamesComparison;
}
}
} | repos\tutorials-master\core-java-modules\core-java-lang\src\main\java\com\baeldung\comparing\PersonWithEqualsAndComparable.java | 1 |
请完成以下Java代码 | public void executeJob() {
try {
ManagementService managementService = engine.getManagementService();
managementService.executeJob(this.jobId);
} catch (AuthorizationException e) {
throw e;
} catch (ProcessEngineException e) {
throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage());
} catch (RuntimeException r) {
throw new RestException(Status.INTERNAL_SERVER_ERROR, r.getMessage());
}
}
@Override
public void setJobDuedate(JobDuedateDto dto) {
try {
ManagementService managementService = engine.getManagementService();
managementService.setJobDuedate(jobId, dto.getDuedate(), dto.isCascade());
} catch (AuthorizationException e) {
throw e;
} catch (ProcessEngineException e) {
throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, e.getMessage());
}
}
@Override
public void recalculateDuedate(boolean creationDateBased) {
try {
ManagementService managementService = engine.getManagementService();
managementService.recalculateJobDuedate(jobId, creationDateBased);
} catch (AuthorizationException e) {
throw e;
} catch(NotFoundException e) {// rewrite status code from bad request (400) to not found (404)
throw new InvalidRequestException(Status.NOT_FOUND, e, e.getMessage());
} catch (ProcessEngineException e) {
throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, e.getMessage());
}
} | public void updateSuspensionState(JobSuspensionStateDto dto) {
dto.setJobId(jobId);
dto.updateSuspensionState(engine);
}
@Override
public void setJobPriority(PriorityDto dto) {
if (dto.getPriority() == null) {
throw new RestException(Status.BAD_REQUEST, "Priority for job '" + jobId + "' cannot be null.");
}
try {
ManagementService managementService = engine.getManagementService();
managementService.setJobPriority(jobId, dto.getPriority());
} catch (AuthorizationException e) {
throw e;
} catch (NotFoundException e) {
throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage());
} catch (ProcessEngineException e) {
throw new RestException(Status.INTERNAL_SERVER_ERROR, e.getMessage());
}
}
public void deleteJob() {
try {
engine.getManagementService()
.deleteJob(jobId);
} catch (AuthorizationException e) {
throw e;
} catch (NullValueException e) {
throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage());
} catch (ProcessEngineException e) {
throw new RestException(Status.INTERNAL_SERVER_ERROR, e.getMessage());
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\runtime\impl\JobResourceImpl.java | 1 |
请完成以下Java代码 | public static Builder method(String name) {
return new Builder(name);
}
String getName() {
return this.name;
}
String getReturnType() {
return this.returnType;
}
List<Parameter> getParameters() {
return this.parameters;
}
int getModifiers() {
return this.modifiers;
}
CodeBlock getCode() {
return this.code;
}
@Override
public AnnotationContainer annotations() {
return this.annotations;
}
/**
* Builder for creating a {@link GroovyMethodDeclaration}.
*/
public static final class Builder {
private final String name;
private List<Parameter> parameters = new ArrayList<>();
private String returnType = "void";
private int modifiers = Modifier.PUBLIC;
private Builder(String name) {
this.name = name;
}
/**
* Sets the modifiers.
* @param modifiers the modifiers
* @return this for method chaining
*/
public Builder modifiers(int modifiers) {
this.modifiers = modifiers;
return this; | }
/**
* Sets the return type.
* @param returnType the return type
* @return this for method chaining
*/
public Builder returning(String returnType) {
this.returnType = returnType;
return this;
}
/**
* Sets the parameters.
* @param parameters the parameters
* @return this for method chaining
*/
public Builder parameters(Parameter... parameters) {
this.parameters = Arrays.asList(parameters);
return this;
}
/**
* Sets the body.
* @param code the code for the body
* @return the method for the body
*/
public GroovyMethodDeclaration body(CodeBlock code) {
return new GroovyMethodDeclaration(this, code);
}
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\groovy\GroovyMethodDeclaration.java | 1 |
请完成以下Java代码 | public int getM_Product_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Order_ID);
}
@Override
public void setPointsBase_Forecasted (final BigDecimal PointsBase_Forecasted)
{
set_Value (COLUMNNAME_PointsBase_Forecasted, PointsBase_Forecasted);
}
@Override
public BigDecimal getPointsBase_Forecasted()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsBase_Forecasted);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPointsBase_Invoiceable (final BigDecimal PointsBase_Invoiceable)
{
set_Value (COLUMNNAME_PointsBase_Invoiceable, PointsBase_Invoiceable);
}
@Override
public BigDecimal getPointsBase_Invoiceable()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsBase_Invoiceable);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPointsBase_Invoiced (final BigDecimal PointsBase_Invoiced)
{
set_Value (COLUMNNAME_PointsBase_Invoiced, PointsBase_Invoiced);
}
@Override
public BigDecimal getPointsBase_Invoiced()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsBase_Invoiced);
return bd != null ? bd : BigDecimal.ZERO;
} | @Override
public void setPOReference (final @Nullable java.lang.String POReference)
{
set_Value (COLUMNNAME_POReference, POReference);
}
@Override
public java.lang.String getPOReference()
{
return get_ValueAsString(COLUMNNAME_POReference);
}
@Override
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_Commission_Instance.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Integer getSessionInvalidateTime() {
return sessionInvalidateTime;
}
public void setSessionInvalidateTime(Integer sessionInvalidateTime) {
this.sessionInvalidateTime = sessionInvalidateTime;
}
public Integer getSessionValidationInterval() {
return sessionValidationInterval;
}
public void setSessionValidationInterval(Integer sessionValidationInterval) {
this.sessionValidationInterval = sessionValidationInterval;
}
public String getFilesUrlPrefix() {
return filesUrlPrefix;
}
public void setFilesUrlPrefix(String filesUrlPrefix) {
this.filesUrlPrefix = filesUrlPrefix;
}
public String getFilesPath() {
return filesPath;
}
public void setFilesPath(String filesPath) {
this.filesPath = filesPath;
}
public Integer getHeartbeatTimeout() { | return heartbeatTimeout;
}
public void setHeartbeatTimeout(Integer heartbeatTimeout) {
this.heartbeatTimeout = heartbeatTimeout;
}
public String getPicsPath() {
return picsPath;
}
public void setPicsPath(String picsPath) {
this.picsPath = picsPath;
}
public String getPosapiUrlPrefix() {
return posapiUrlPrefix;
}
public void setPosapiUrlPrefix(String posapiUrlPrefix) {
this.posapiUrlPrefix = posapiUrlPrefix;
}
} | repos\SpringBootBucket-master\springboot-shiro\src\main\java\com\xncoding\pos\config\properties\MyProperties.java | 2 |
请完成以下Java代码 | public int intValueExact()
{
return toBigDecimal().intValueExact();
}
public boolean isWeightable()
{
return UOMType.ofNullableCodeOrOther(uom.getUOMType()).isWeight();
}
public Percent percentageOf(@NonNull final Quantity whole)
{
assertSameUOM(this, whole);
return Percent.of(toBigDecimal(), whole.toBigDecimal());
}
private void assertUOMOrSourceUOM(@NonNull final UomId uomId)
{
if (!getUomId().equals(uomId) && !getSourceUomId().equals(uomId))
{
throw new QuantitiesUOMNotMatchingExpection("UOMs are not compatible")
.appendParametersToMessage()
.setParameter("Qty.UOM", getUomId())
.setParameter("assertUOM", uomId);
}
}
@NonNull
public BigDecimal toBigDecimalAssumingUOM(@NonNull final UomId uomId)
{
assertUOMOrSourceUOM(uomId);
return getUomId().equals(uomId) ? toBigDecimal() : getSourceQty();
}
public List<Quantity> spreadEqually(final int count)
{
if (count <= 0)
{
throw new AdempiereException("count shall be greater than zero, but it was " + count);
}
else if (count == 1)
{
return ImmutableList.of(this);
}
else // count > 1
{ | final ImmutableList.Builder<Quantity> result = ImmutableList.builder();
final Quantity qtyPerPart = divide(count);
Quantity qtyRemainingToSpread = this;
for (int i = 1; i <= count; i++)
{
final boolean isLast = i == count;
if (isLast)
{
result.add(qtyRemainingToSpread);
}
else
{
result.add(qtyPerPart);
qtyRemainingToSpread = qtyRemainingToSpread.subtract(qtyPerPart);
}
}
return result.build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\Quantity.java | 1 |
请完成以下Java代码 | public class ExportProcessor2Wrapper implements IExportProcessor2
{
private final IExportProcessor exportProcessor;
public ExportProcessor2Wrapper(IExportProcessor exportProcessor)
{
this.exportProcessor = exportProcessor;
}
@Override
public void createInitialParameters(MEXPProcessor processor)
{
exportProcessor.createInitialParameters(processor);
}
@Override
public void process(Properties ctx, MEXPProcessor expProcessor, Document document, Trx trx) throws ExportProcessorException
{
try
{
exportProcessor.process(ctx, expProcessor, document, trx);
}
catch (Exception e)
{
// TODO add AD_Message | throw new ExportProcessorException(null, e);
}
}
@Override
public void process(MEXPProcessor expProcessor, Document document, PO po) throws ExportProcessorException
{
final Properties ctx = po.getCtx();
final Trx trx = Trx.get(po.get_TrxName(), false);
try
{
exportProcessor.process(ctx, expProcessor, document, trx);
}
catch (final Exception e)
{
// TODO add AD_Message
throw new ExportProcessorException(e.getClass().getSimpleName(), e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\process\rpl\ExportProcessor2Wrapper.java | 1 |
请完成以下Java代码 | public AnnotationContainer annotations() {
return this.annotations;
}
/**
* Builder for creating a {@link KotlinFunctionDeclaration}.
*/
public static final class Builder {
private final String name;
private List<Parameter> parameters = new ArrayList<>();
private List<KotlinModifier> modifiers = new ArrayList<>();
private String returnType;
private Builder(String name) {
this.name = name;
}
/**
* Sets the modifiers.
* @param modifiers the modifiers
* @return this for method chaining
*/
public Builder modifiers(KotlinModifier... modifiers) {
this.modifiers = Arrays.asList(modifiers);
return this;
}
/**
* Sets the return type. | * @param returnType the return type
* @return this for method chaining
*/
public Builder returning(String returnType) {
this.returnType = returnType;
return this;
}
/**
* Sets the parameters.
* @param parameters the parameters
* @return this for method chaining
*/
public Builder parameters(Parameter... parameters) {
this.parameters = Arrays.asList(parameters);
return this;
}
/**
* Sets the body.
* @param code the code for the body
* @return the function declaration containing the body
*/
public KotlinFunctionDeclaration body(CodeBlock code) {
return new KotlinFunctionDeclaration(this, code);
}
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\kotlin\KotlinFunctionDeclaration.java | 1 |
请完成以下Java代码 | public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
public String toString() {
return "CamundaBpmRunLdapProperty [enabled=" + enabled +
", initialContextFactory=" + initialContextFactory +
", securityAuthentication=" + securityAuthentication +
", contextProperties=" + contextProperties +
", serverUrl=******" + // sensitive for logging
", managerDn=******" + // sensitive for logging
", managerPassword=******" + // sensitive for logging
", baseDn=" + baseDn +
", userDnPattern=" + userDnPattern +
", userSearchBase=" + userSearchBase +
", userSearchFilter=" + userSearchFilter +
", groupSearchBase=" + groupSearchBase +
", groupSearchFilter=" + groupSearchFilter + | ", userIdAttribute=" + userIdAttribute +
", userFirstnameAttribute=" + userFirstnameAttribute +
", userLastnameAttribute=" + userLastnameAttribute +
", userEmailAttribute=" + userEmailAttribute +
", userPasswordAttribute=" + userPasswordAttribute +
", groupIdAttribute=" + groupIdAttribute +
", groupNameAttribute=" + groupNameAttribute +
", groupTypeAttribute=" + groupTypeAttribute +
", groupMemberAttribute=" + groupMemberAttribute +
", sortControlSupported=" + sortControlSupported +
", useSsl=" + useSsl +
", usePosixGroups=" + usePosixGroups +
", allowAnonymousLogin=" + allowAnonymousLogin +
", authorizationCheckEnabled=" + authorizationCheckEnabled +
", passwordCheckCatchAuthenticationException=" + passwordCheckCatchAuthenticationException + "]";
}
} | repos\camunda-bpm-platform-master\distro\run\core\src\main\java\org\camunda\bpm\run\property\CamundaBpmRunLdapProperties.java | 1 |
请完成以下Java代码 | static UomId extractUomIdOrNull(final @NonNull I_M_HU_LUTU_Configuration lutuConfiguration)
{
return UomId.ofRepoIdOrNull(lutuConfiguration.getC_UOM_ID());
}
static BPartnerId extractBPartnerIdOrNull(final I_M_HU_LUTU_Configuration lutuConfiguration)
{
return BPartnerId.ofRepoIdOrNull(lutuConfiguration.getC_BPartner_ID());
}
static I_M_HU_PI_Item_Product extractHUPIItemProduct(@NonNull final I_M_HU_LUTU_Configuration lutuConfiguration)
{
final I_M_HU_PI_Item_Product huPIItemProduct = extractHUPIItemProductOrNull(lutuConfiguration);
if (huPIItemProduct == null)
{
throw new HUException("No PI Item Product set for " + lutuConfiguration);
}
return huPIItemProduct;
}
static I_M_HU_PI_Item_Product extractHUPIItemProductOrNull(@NonNull final I_M_HU_LUTU_Configuration lutuConfiguration)
{
final HUPIItemProductId huPIItemProductId = HUPIItemProductId.ofRepoIdOrNull(lutuConfiguration.getM_HU_PI_Item_Product_ID());
return huPIItemProductId != null
? Services.get(IHUPIItemProductDAO.class).getRecordById(huPIItemProductId)
: null;
}
@Value
@Builder | class CreateLUTUConfigRequest
{
@NonNull
I_M_HU_LUTU_Configuration baseLUTUConfiguration;
@NonNull
BigDecimal qtyTU;
@NonNull
BigDecimal qtyCUsPerTU;
@NonNull
Integer tuHUPIItemProductID;
@Nullable
BigDecimal qtyLU;
@Nullable
Integer luHUPIID;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\ILUTUConfigurationFactory.java | 1 |
请完成以下Java代码 | public boolean isNotPicked() {return pickedTo == null;}
public void assertPicked()
{
if (!isPicked())
{
throw new AdempiereException("PickFrom was not picked: " + this);
}
}
public PickingJobStepPickFrom assertNotPicked()
{
if (isPicked())
{
throw new AdempiereException("PickFrom already picked: " + this); | }
return this;
}
public PickingJobStepPickFrom withPickedEvent(@NonNull final PickingJobStepPickedTo pickedTo)
{
return withPickedTo(pickedTo);
}
public PickingJobStepPickFrom withUnPickedEvent(@NonNull PickingJobStepUnpickInfo unpickEvent)
{
return withPickedTo(pickedTo != null ? pickedTo.removing(unpickEvent.getUnpickedHUs()) : null);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobStepPickFrom.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void configure() throws Exception
{
CamelRouteUtil.setupProperties(getContext());
final String maximumRedeliveries = CamelRouteUtil.resolveProperty(getContext(), GRSSignumConstants.EXPORT_BPARTNER_RETRY_COUNT, "0");
final String redeliveryDelay = CamelRouteUtil.resolveProperty(getContext(), GRSSignumConstants.EXPORT_BPARTNER_RETRY_DELAY, "0");
errorHandler(deadLetterChannel(GRS_DEADLETTER_ROUTE_ID)
.logHandled(true)
.maximumRedeliveries(Integer.parseInt(maximumRedeliveries))
.redeliveryDelay(Integer.parseInt(redeliveryDelay)));
from(GRS_DEADLETTER_ROUTE_ID)
.routeId(GRS_DEADLETTER_ROUTE_ID)
.to(direct(MF_ERROR_ROUTE_ID));
from(direct(GRS_DISPATCHER_ROUTE_ID))
.routeId(GRS_DISPATCHER_ROUTE_ID)
.streamCache("true")
.process(this::extractAndAttachGRSSignumHttpRequest)
.to(direct(GRS_MESSAGE_SENDER));
from(direct(GRS_MESSAGE_SENDER))
.routeId(GRS_MESSAGE_SENDER)
//dev-note: we need the whole route to be replayed in case of redelivery
.errorHandler(noErrorHandler())
.log("invoked")
//uncomment this to get an "escaped" JSON string with e.g. "\{ blabla \}"
//.marshal(CamelRouteUtil.setupJacksonDataFormatFor(getContext(), String.class))
//dev-note: the actual path is computed in this.extractAndAttachGRSSignumHttpRequest()
.to("https://placeholder").id(GRS_ENDPOINT_ID);
}
private void extractAndAttachGRSSignumHttpRequest(@NonNull final Exchange exchange)
{ | final Object dispatchMessageRequestCandidate = exchange.getIn().getBody();
if (!(dispatchMessageRequestCandidate instanceof DispatchRequest))
{
throw new RuntimeCamelException("The route " + GRS_DISPATCHER_ROUTE_ID
+ " requires the body to be instanceof DispatchMessageRequest."
+ " However, it is " + (dispatchMessageRequestCandidate == null ? "null" : dispatchMessageRequestCandidate.getClass().getName()));
}
final DispatchRequest dispatchMessageRequest = (DispatchRequest)dispatchMessageRequestCandidate;
exchange.getIn().removeHeaders("CamelHttp*");
exchange.getIn().removeHeader(AUTHORIZATION); // remove the token from metasfresh's API
exchange.getIn().setHeader(HTTP_URI, dispatchMessageRequest.getUrl());
exchange.getIn().setHeader(Exchange.HTTP_METHOD, HttpMethods.POST);
if (Check.isNotBlank(dispatchMessageRequest.getAuthToken()))
{
exchange.getIn().setHeader(AUTHORIZATION, dispatchMessageRequest.getAuthToken());
}
exchange.getIn().setBody(dispatchMessageRequest.getRequest());
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\to_grs\client\GRSSignumDispatcherRouteBuilder.java | 2 |
请完成以下Java代码 | public ExplainedOptional<HULabelConfig> getFirstMatching(final HULabelConfigQuery query)
{
return huLabelConfigService.getFirstMatching(query);
}
public void print(@NonNull final HULabelPrintRequest request)
{
HULabelPrintCommand.builder()
.handlingUnitsBL(handlingUnitsBL)
.huLabelConfigService(huLabelConfigService)
.huProcessDAO(huProcessDAO)
.huQRCodesService(huQRCodesService)
.huLabelService(this)
.request(request)
.build()
.execute();
}
public void printNow(final HULabelDirectPrintRequest request)
{
if (request.getHus().isEmpty())
{
return;
}
final AdProcessId printFormatProcessId = request.getPrintFormatProcessId();
final HUReportExecutor printExecutor = HUReportExecutor.newInstance()
.printPreview(false)
.numberOfCopies(CoalesceUtil.coalesceNotNull(request.getPrintCopies(), PrintCopies.ONE));
if (request.isOnlyOneHUPerPrint())
{
for (final HUToReport hu : request.getHus())
{
printExecutor.executeNow(printFormatProcessId, ImmutableList.of(hu));
}
}
else
{
printExecutor.executeNow(printFormatProcessId, request.getHus());
}
}
@NonNull
public HULabelPrintProcessesList getHULabelPrintFormatProcesses() | {
return printProcessesCache.getOrLoadNonNull(0, this::retrieveHULabelPrintFormatProcesses);
}
private HULabelPrintProcessesList retrieveHULabelPrintFormatProcesses()
{
return processDAO.retrieveProcessRecordsByValRule(HU_LABEL_PRINTING_OPTIONS_VAL_RULE_ID)
.stream()
.map(HULabelService::toHULabelPrintProcess)
.collect(HULabelPrintProcessesList.collect());
}
private static HULabelPrintProcess toHULabelPrintProcess(final I_AD_Process adProcess)
{
final IModelTranslationMap trlMap = InterfaceWrapperHelper.getModelTranslationMap(adProcess);
return HULabelPrintProcess.builder()
.processId(AdProcessId.ofRepoId(adProcess.getAD_Process_ID()))
.name(trlMap.getColumnTrl(I_AD_Process.COLUMNNAME_Name, adProcess.getName()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\report\labels\HULabelService.java | 1 |
请完成以下Java代码 | public void hit(int begin, int end, V value)
{
if (wordNet[end] == null || wordNet[end].word.length() < end - begin)
{
wordNet[end] = new ResultTerm<V>(new String(charArray, begin, end - begin), value, begin);
}
}
});
for (int i = charArray.length; i > 0;)
{
if (wordNet[i] == null)
{
StringBuilder sbTerm = new StringBuilder();
int offset = i - 1;
byte preCharType = CharType.get(charArray[offset]);
while (i > 0 && wordNet[i] == null && CharType.get(charArray[i - 1]) == preCharType)
{
sbTerm.append(charArray[i - 1]); | preCharType = CharType.get(charArray[i - 1]);
--i;
}
termList.addFirst(new ResultTerm<V>(sbTerm.reverse().toString(), null, offset));
}
else
{
termList.addFirst(wordNet[i]);
i -= wordNet[i].word.length();
}
}
return termList;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\Other\CommonAhoCorasickSegmentUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class C_PurchaseCandidate
{
private final PurchaseCandidateReminderScheduler scheduler;
private final CurrencyRepository currencyRepository;
public C_PurchaseCandidate(@NonNull final PurchaseCandidateReminderScheduler scheduler,
@NonNull final CurrencyRepository currencyRepository)
{
this.scheduler = scheduler;
this.currencyRepository = currencyRepository;
}
@ModelChange( //
timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_AFTER_DELETE }, //
ifColumnsChanged = { I_C_PurchaseCandidate.COLUMNNAME_ReminderDate, I_C_PurchaseCandidate.COLUMNNAME_Vendor_ID }, //
afterCommit = true)
public void scheduleReminderForWebui(final I_C_PurchaseCandidate record)
{
final PurchaseCandidateReminder reminder = PurchaseCandidateRepository.toPurchaseCandidateReminderOrNull(record);
if (reminder == null)
{
return;
}
scheduler.scheduleNotification(reminder);
} | @ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_PurchaseCandidate.COLUMNNAME_PriceEntered, I_C_PurchaseCandidate.COLUMNNAME_Discount, I_C_PurchaseCandidate.COLUMNNAME_IsManualPrice, I_C_PurchaseCandidate.COLUMNNAME_IsManualDiscount })
public void setPriceEffective(final I_C_PurchaseCandidate candidate)
{
final CurrencyId currencyId = CurrencyId.ofRepoIdOrNull(candidate.getC_Currency_ID());
if (currencyId == null)
{
return;
}
final @NonNull CurrencyPrecision precision = currencyRepository.getById(currencyId).getPrecision();
final BigDecimal priceEffective = candidate.isManualPrice() ? candidate.getPriceEntered() : candidate.getPriceInternal();
candidate.setPriceEffective(priceEffective);
candidate.setDiscountEff(candidate.isManualDiscount() ? candidate.getDiscount() : candidate.getDiscountInternal());
final @NonNull Percent discount = Percent.of(candidate.getDiscountEff());
candidate.setPurchasePriceActual(discount.subtractFromBase(priceEffective, precision.toInt()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\purchasecandidate\interceptor\C_PurchaseCandidate.java | 2 |
请完成以下Java代码 | public boolean isSendNotification ()
{
Object oo = get_Value(COLUMNNAME_IsSendNotification);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{ | set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Table_AttachmentListener.java | 1 |
请完成以下Spring Boot application配置 | flowable.idm.ldap.enabled=true
flowable.idm.ldap.base-dn=o=flowable
flowable.idm.ldap.server=ldap://localhost
flowable.idm.ldap.port=33389
flowable.idm.ldap.user=uid=admin, ou=users, o=flowable
flowable.idm.ldap.password=pass
spring.ldap.embedded.base-dn=${flowable.idm.ldap.base-dn}
spring.ldap.embedded.port=${flowable.idm.ldap.port}
spring.ldap.embedded.ldif=classpath:users.ldif
spring.ldap.embedded.validation.enabled=false
spring.ldap.embedded.credential.username=${flowable.idm.ldap.user}
spring.ldap.embedded.credential.password=${flowable.idm.ldap.password}
spring.ldap.username=${flowable.idm.ldap.user}
spring.ldap.password=${flowable.idm.ldap.password}
# Query params
flowable.idm.ldap.query.userById=(&(objectClass=inetOrgPerson)(uid={0}))
flowable.idm.ldap.query.userByFullNameLike=(&(objectClass=inetOrgPerson)(|({0}=*{1}*)({2}=*{3}*)))
flowable.idm.ldap.query.allUsers=(objectClass=inetOrgPerson)
flowable.idm.ldap.query.groupsForUser=(&(objectClass=groupOfUniqueNames)(uniqueMember={0}))
flowable.idm.ldap.query.allGroups=(objectC | lass=groupOfUniqueNames)
# Attribute config
flowable.idm.ldap.attribute.userId=uid
flowable.idm.ldap.attribute.firstName=cn
flowable.idm.ldap.attribute.lastName=sn
flowable.idm.ldap.attribute.emailAttribute=mail
flowable.idm.ldap.attribute.groupId=uid
flowable.idm.ldap.attribute.groupName=cn
# Group cache settings
# Setting it really low for testing purposes -->
flowable.idm.ldap.cache.groupSize=2
flowable.idm.ldap.cache.groupExpiration=1800000 | repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-samples\flowable-spring-boot-sample-ldap\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public void setC_BPartner_ID (int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_Value (COLUMNNAME_C_BPartner_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID));
}
/** Get Geschäftspartner.
@return Bezeichnet einen Geschäftspartner
*/
@Override
public int getC_BPartner_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Geschäftspartner Document Line Sorting Preferences.
@param C_BP_DocLine_Sort_ID Geschäftspartner Document Line Sorting Preferences */
@Override
public void setC_BP_DocLine_Sort_ID (int C_BP_DocLine_Sort_ID)
{
if (C_BP_DocLine_Sort_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BP_DocLine_Sort_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BP_DocLine_Sort_ID, Integer.valueOf(C_BP_DocLine_Sort_ID));
}
/** Get Geschäftspartner Document Line Sorting Preferences.
@return Geschäftspartner Document Line Sorting Preferences */
@Override
public int getC_BP_DocLine_Sort_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BP_DocLine_Sort_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_DocLine_Sort getC_DocLine_Sort() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_DocLine_Sort_ID, org.compiere.model.I_C_DocLine_Sort.class);
}
@Override
public void setC_DocLine_Sort(org.compiere.model.I_C_DocLine_Sort C_DocLine_Sort)
{ | set_ValueFromPO(COLUMNNAME_C_DocLine_Sort_ID, org.compiere.model.I_C_DocLine_Sort.class, C_DocLine_Sort);
}
/** Set Document Line Sorting Preferences.
@param C_DocLine_Sort_ID Document Line Sorting Preferences */
@Override
public void setC_DocLine_Sort_ID (int C_DocLine_Sort_ID)
{
if (C_DocLine_Sort_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_DocLine_Sort_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_DocLine_Sort_ID, Integer.valueOf(C_DocLine_Sort_ID));
}
/** Get Document Line Sorting Preferences.
@return Document Line Sorting Preferences */
@Override
public int getC_DocLine_Sort_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DocLine_Sort_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_DocLine_Sort.java | 1 |
请完成以下Java代码 | public class JwtAuthorizationFilter extends BasicAuthenticationFilter {
private UserRepository userRepository;
public JwtAuthorizationFilter(AuthenticationManager authenticationManager, UserRepository userRepository) {
super(authenticationManager);
this.userRepository = userRepository;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
//Read the Authorization header, where the JWT token should be
String header = request.getHeader(JwtProperties.HEADER_STRING);
//If header does not contain BEARER or is null delegate to Spring impl and exit
if (header == null || !header.startsWith(JwtProperties.TOKEN_PREFIX)) {
chain.doFilter(request, response);
return;
}
// If header is present, try grab user principal from db and perform authorization
Authentication authentication = getUsernamePasswordAuthentication(request);
SecurityContextHolder.getContext().setAuthentication(authentication);
// Continue filter execution
chain.doFilter(request, response);
}
private Authentication getUsernamePasswordAuthentication(HttpServletRequest request){
String token = request.getHeader(JwtProperties.HEADER_STRING)
.replace(JwtProperties.TOKEN_PREFIX, ""); | if(token !=null){
//parse the token validate it
String userName = JWT.require(Algorithm.HMAC512(JwtProperties.SECRET.getBytes()))
.build()
.verify(token)
.getSubject();
// Search in the DB if we find the user by token subject(username)
// If so, then grab user details and create auth token using username, pass, authorities/roles
if(userName != null){
User user = userRepository.findByUsername(userName);
UserPrincipal principal = new UserPrincipal(user);
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userName, null, principal.getAuthorities());
return authenticationToken;
}
return null;
}
return null;
}
} | repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\11.SpringSecurityJwt\src\main\java\spring\security\security\JwtAuthorizationFilter.java | 1 |
请完成以下Java代码 | public class VarExample {
public String name() {
var name = "name";
name = "newName";
System.out.println("Name: " + name);
return name;
}
public Integer age() {
var age = Integer.valueOf(30);
age = 35;
System.out.println("Age: " + age);
return age;
}
public ArrayList<String> listOf() {
var agenda = new ArrayList<String>();
agenda.add("Day 1");
agenda = new ArrayList<String>(Arrays.asList("Day 2"));
System.out.println("Agenda: " + agenda); | return agenda;
}
public Map<Integer, String> mapOf() {
var books = new HashMap<Integer, String>();
books.put(1, "Book 1");
books.put(2, "Book 2");
books = new HashMap<Integer, String>();
books.put(3, "Book 3");
books.put(4, "Book 4");
System.out.println("Books:");
for (var entry : books.entrySet()) {
System.out.printf("- %d. %s\n", entry.getKey(), entry.getValue());
}
return books;
}
} | repos\tutorials-master\lombok-modules\lombok-2\src\main\java\com\baeldung\lombok\valvar\VarExample.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public EmailConfig find() {
Optional<EmailConfig> emailConfig = emailRepository.findById(1L);
return emailConfig.orElseGet(EmailConfig::new);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void send(EmailVo emailVo, EmailConfig emailConfig){
if(emailConfig.getId() == null){
throw new BadRequestException("请先配置,再操作");
}
// 封装
MailAccount account = new MailAccount();
// 设置用户
String user = emailConfig.getFromUser().split("@")[0];
account.setUser(user);
account.setHost(emailConfig.getHost());
account.setPort(Integer.parseInt(emailConfig.getPort()));
account.setAuth(true);
try {
// 对称解密
account.setPass(EncryptUtils.desDecrypt(emailConfig.getPass()));
} catch (Exception e) {
throw new BadRequestException(e.getMessage());
} | account.setFrom(emailConfig.getUser()+"<"+emailConfig.getFromUser()+">");
// ssl方式发送
account.setSslEnable(true);
// 使用STARTTLS安全连接
account.setStarttlsEnable(true);
// 解决jdk8之后默认禁用部分tls协议,导致邮件发送失败的问题
account.setSslProtocols("TLSv1 TLSv1.1 TLSv1.2");
String content = emailVo.getContent();
// 发送
try {
int size = emailVo.getTos().size();
Mail.create(account)
.setTos(emailVo.getTos().toArray(new String[size]))
.setTitle(emailVo.getSubject())
.setContent(content)
.setHtml(true)
//关闭session
.setUseGlobalSession(false)
.send();
}catch (Exception e){
throw new BadRequestException(e.getMessage());
}
}
} | repos\eladmin-master\eladmin-tools\src\main\java\me\zhengjie\service\impl\EmailServiceImpl.java | 2 |
请完成以下Java代码 | public void setCM_Ad_Cat_ID (int CM_Ad_Cat_ID)
{
if (CM_Ad_Cat_ID < 1)
set_Value (COLUMNNAME_CM_Ad_Cat_ID, null);
else
set_Value (COLUMNNAME_CM_Ad_Cat_ID, Integer.valueOf(CM_Ad_Cat_ID));
}
/** Get Advertisement Category.
@return Advertisement Category like Banner Homepage
*/
public int getCM_Ad_Cat_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_Ad_Cat_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_CM_Template getCM_Template() throws RuntimeException
{
return (I_CM_Template)MTable.get(getCtx(), I_CM_Template.Table_Name)
.getPO(getCM_Template_ID(), get_TrxName()); }
/** Set Template.
@param CM_Template_ID
Template defines how content is displayed
*/
public void setCM_Template_ID (int CM_Template_ID)
{
if (CM_Template_ID < 1)
set_Value (COLUMNNAME_CM_Template_ID, null);
else
set_Value (COLUMNNAME_CM_Template_ID, Integer.valueOf(CM_Template_ID));
}
/** Get Template.
@return Template defines how content is displayed
*/
public int getCM_Template_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_Template_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
} | /** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Template_Ad_Cat.java | 1 |
请完成以下Java代码 | public String processUnauthorizedException(NativeWebRequest request, Model model, UnauthorizedException e) {
model.addAttribute("exception", e.getMessage());
logger.error("权限异常。{}", e.getMessage());
return ERROR_403;
}
/**
* 运行时异常
*
* @param exception
* @return
*/
@ExceptionHandler({RuntimeException.class})
@ResponseStatus(HttpStatus.OK)
public String processException(RuntimeException exception, Model model) {
model.addAttribute("exception", exception.getMessage());
logger.error("程序异常", exception);
return ERROR_500;
} | /**
* Exception异常
*
* @param exception
* @return
*/
@ExceptionHandler({Exception.class})
@ResponseStatus(HttpStatus.OK)
public String processException(Exception exception, Model model) {
model.addAttribute("exception", exception.getMessage());
logger.error("程序异常", exception);
return ERROR_500;
//logger.info("自定义异常处理-Exception");
//ModelAndView m = new ModelAndView();
//m.addObject("exception", exception.getMessage());
//m.setViewName("error/500");
//return m;
}
} | repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\exception\DefaultExceptionHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static class InvoiceProcessingContext
{
@NonNull
BPartnerId serviceCompanyId;
@NonNull
ZonedDateTime paymentDate;
}
private static InvoiceProcessingContext extractInvoiceProcessingContext(
@NonNull final InvoiceRow row,
@NonNull final List<PaymentDocument> paymentDocuments,
@NonNull final InvoiceProcessingServiceCompanyService invoiceProcessingServiceCompanyService)
{
if (paymentDocuments.isEmpty())
{
final @NonNull ZonedDateTime evaluationDate = SystemTime.asZonedDateTime();
final InvoiceProcessingServiceCompanyConfig config = invoiceProcessingServiceCompanyService.getByCustomerId(row.getBPartnerId(), evaluationDate)
.orElseThrow(() -> new AdempiereException("Invoice with Service Fees: no config found for invoice-C_BPartner_ID=" + BPartnerId.toRepoId(row.getBPartnerId()))
.appendParametersToMessage()
.setParameter("C_Invoice_ID", InvoiceId.toRepoId(row.getInvoiceId()))
.setParameter("C_Invoice.DocumentNo", row.getDocumentNo())
);
return InvoiceProcessingContext.builder()
.serviceCompanyId(config.getServiceCompanyBPartnerId())
.paymentDate(evaluationDate)
.build();
}
else
{
final ImmutableSet<InvoiceProcessingContext> contexts = paymentDocuments.stream()
.map(PaymentsViewAllocateCommand::extractInvoiceProcessingContext)
.collect(ImmutableSet.toImmutableSet());
if (contexts.size() != 1)
{
throw new AdempiereException("Invoice with Service Fees: Please select exactly 1 Payment at a time for Allocation.");
}
return contexts.iterator().next();
}
}
private static InvoiceProcessingContext extractInvoiceProcessingContext(@NonNull final PaymentDocument paymentDocument)
{
return InvoiceProcessingContext.builder()
.serviceCompanyId(paymentDocument.getBpartnerId())
.paymentDate(TimeUtil.asZonedDateTime(paymentDocument.getDateTrx()))
.build();
}
private PaymentDocument toPaymentDocument(@NonNull final PaymentRow row)
{ | return toPaymentDocument(row, moneyService);
}
@VisibleForTesting
static PaymentDocument toPaymentDocument(
@NonNull final PaymentRow row,
@NonNull final MoneyService moneyService)
{
final PaymentAmtMultiplier amtMultiplier = row.getPaymentAmtMultiplier();
final Money openAmt = amtMultiplier.convertToRealValue(row.getOpenAmt())
.toMoney(moneyService::getCurrencyIdByCurrencyCode);
return PaymentDocument.builder()
.paymentId(row.getPaymentId())
.bpartnerId(row.getBPartnerId())
.documentNo(row.getDocumentNo())
.paymentDirection(row.getPaymentDirection())
.openAmt(openAmt)
.amountToAllocate(openAmt)
.dateTrx(row.getDateTrx())
.clientAndOrgId(row.getClientAndOrgId())
.paymentCurrencyContext(row.getPaymentCurrencyContext())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\process\PaymentsViewAllocateCommand.java | 2 |
请完成以下Java代码 | public I_M_Transaction retrieveReversalTransaction(final Object referencedModelReversal, final I_M_Transaction originalTrx)
{
Check.assumeNotNull(referencedModelReversal, "referencedModelReversal not null");
Check.assumeNotNull(originalTrx, "originalTrx not null");
final IQueryFilter<I_M_Transaction> referencedModelFilter = createReferencedModelQueryFilter(referencedModelReversal);
final ICompositeQueryFilter<I_M_Transaction> filters = Services.get(IQueryBL.class).createCompositeQueryFilter(I_M_Transaction.class);
filters.addFilter(referencedModelFilter)
.addEqualsFilter(I_M_Transaction.COLUMNNAME_M_Product_ID, originalTrx.getM_Product_ID())
.addEqualsFilter(I_M_Transaction.COLUMNNAME_M_AttributeSetInstance_ID, originalTrx.getM_AttributeSetInstance_ID())
.addEqualsFilter(I_M_Transaction.COLUMNNAME_MovementType, originalTrx.getMovementType())
.addEqualsFilter(I_M_Transaction.COLUMNNAME_MovementQty, originalTrx.getMovementQty().negate())
//
;
final I_M_Transaction reversalTrx = Services.get(IQueryBL.class).createQueryBuilder(I_M_Transaction.class, referencedModelReversal)
.filter(filters) | .create()
.setOnlyActiveRecords(true)
.firstOnly(I_M_Transaction.class);
if (reversalTrx == null)
{
throw new AdempiereException("@NotFound@ @Reversal_ID@ @M_Transaction_ID@ ("
+ "@ReversalLine_ID@: " + referencedModelFilter
+ ", @M_Transaction_ID@: " + originalTrx
+ ")");
}
return reversalTrx;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\materialtransaction\impl\MTransactionDAO.java | 1 |
请完成以下Java代码 | public boolean isHistoryEnabledForVariableInstance(String processDefinitionId, VariableInstanceEntity variableInstanceEntity) {
return isHistoryLevelAtLeast(HistoryLevel.ACTIVITY, processDefinitionId);
}
@Override
public boolean isHistoryEnabledForVariables(String processDefinitionId) {
return isHistoryLevelAtLeast(HistoryLevel.ACTIVITY, processDefinitionId);
}
@Override
public boolean isHistoryEnabledForIdentityLink(IdentityLinkEntity identityLink) {
String processDefinitionId = getProcessDefinitionId(identityLink);
return isHistoryLevelAtLeast(HistoryLevel.AUDIT, processDefinitionId);
}
protected String getProcessDefinitionId(IdentityLinkEntity identityLink) {
String processDefinitionId = null;
if (identityLink.getProcessInstanceId() != null) {
ExecutionEntity execution = processEngineConfiguration.getExecutionEntityManager().findById(identityLink.getProcessInstanceId());
if (execution != null) {
processDefinitionId = execution.getProcessDefinitionId();
}
} else if (identityLink.getTaskId() != null) {
TaskEntity task = processEngineConfiguration.getTaskServiceConfiguration().getTaskService().getTask(identityLink.getTaskId());
if (task != null) {
processDefinitionId = task.getProcessDefinitionId();
}
}
return processDefinitionId;
}
@Override
public boolean isHistoryEnabledForEntityLink(EntityLinkEntity entityLink) {
String processDefinitionId = getProcessDefinitionId(entityLink);
return isHistoryEnabled(processDefinitionId);
}
@Override
public boolean isHistoryEnabledForVariables(HistoricTaskInstance historicTaskInstance) {
return processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY);
} | protected String getProcessDefinitionId(EntityLinkEntity entityLink) {
String processDefinitionId = null;
if (ScopeTypes.BPMN.equals(entityLink.getScopeType()) && entityLink.getScopeId() != null) {
ExecutionEntity execution = processEngineConfiguration.getExecutionEntityManager().findById(entityLink.getScopeId());
if (execution != null) {
processDefinitionId = execution.getProcessDefinitionId();
}
} else if (ScopeTypes.TASK.equals(entityLink.getScopeType()) && entityLink.getScopeId() != null) {
TaskEntity task = processEngineConfiguration.getTaskServiceConfiguration().getTaskService().getTask(entityLink.getScopeId());
if (task != null) {
processDefinitionId = task.getProcessDefinitionId();
}
}
return processDefinitionId;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\history\DefaultHistoryConfigurationSettings.java | 1 |
请完成以下Java代码 | public boolean isAll() {
return all;
}
public void setAll(boolean all) {
this.all = all;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public String getProcessInstanceId() {
return processInstanceId; | }
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public boolean isResultEnabled() {
return resultEnabled;
}
public void setResultEnabled(boolean resultEnabled) {
this.resultEnabled = resultEnabled;
}
public boolean isVariablesInResultEnabled() {
return variablesInResultEnabled;
}
public void setVariablesInResultEnabled(boolean variablesInResultEnabled) {
this.variablesInResultEnabled = variablesInResultEnabled;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\message\CorrelationMessageDto.java | 1 |
请完成以下Java代码 | public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public boolean isCreationLog() {
return state == JobState.CREATED.getStateCode();
}
public boolean isFailureLog() { | return state == JobState.FAILED.getStateCode();
}
public boolean isSuccessLog() {
return state == JobState.SUCCESSFUL.getStateCode();
}
public boolean isDeletionLog() {
return state == JobState.DELETED.getStateCode();
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public String getFailedActivityId() {
return failedActivityId;
}
public void setFailedActivityId(String failedActivityId) {
this.failedActivityId = failedActivityId;
}
public String getBatchId() {
return batchId;
}
public void setBatchId(String batchId) {
this.batchId = batchId;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricJobLogEvent.java | 1 |
请完成以下Java代码 | public class EchoServer extends Thread {
protected DatagramSocket socket = null;
protected boolean running;
protected byte[] buf = new byte[256];
public EchoServer() throws IOException {
socket = new DatagramSocket(4445);
}
public void run() {
running = true;
while (running) {
try {
DatagramPacket packet = new DatagramPacket(buf, buf.length); | socket.receive(packet);
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
String received = new String(packet.getData(), 0, packet.getLength());
if (received.equals("end")) {
running = false;
continue;
}
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
running = false;
}
}
socket.close();
}
} | repos\tutorials-master\core-java-modules\core-java-networking-5\src\main\java\com\baeldung\networking\udp\EchoServer.java | 1 |
请完成以下Java代码 | public Date getStartTime() {
return startTime;
}
@Override
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
@Override
public Date getEndTime() {
return endTime;
}
@Override
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
@Override
public String getInstanceId() {
return instanceId;
}
@Override
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
@Override
public String getExecutionId() {
return executionId;
}
@Override
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
@Override
public String getActivityId() {
return activityId;
}
@Override
public void setActivityId(String activityId) {
this.activityId = activityId;
}
@Override
public String getScopeType() {
return scopeType;
}
@Override
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
@Override
public boolean isFailed() {
return failed;
}
@Override
public void setFailed(boolean failed) {
this.failed = failed;
}
@Override | public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String getExecutionJson() {
return executionJson;
}
@Override
public void setExecutionJson(String executionJson) {
this.executionJson = executionJson;
}
@Override
public String getDecisionKey() {
return decisionKey;
}
public void setDecisionKey(String decisionKey) {
this.decisionKey = decisionKey;
}
@Override
public String getDecisionName() {
return decisionName;
}
public void setDecisionName(String decisionName) {
this.decisionName = decisionName;
}
@Override
public String getDecisionVersion() {
return decisionVersion;
}
public void setDecisionVersion(String decisionVersion) {
this.decisionVersion = decisionVersion;
}
@Override
public String toString() {
return "HistoricDecisionExecutionEntity[" + id + "]";
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\HistoricDecisionExecutionEntityImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getHistoryCleaningCycle() {
return historyCleaningCycle;
}
public void setHistoryCleaningCycle(String historyCleaningCycle) {
this.historyCleaningCycle = historyCleaningCycle;
}
@Deprecated
@DeprecatedConfigurationProperty(replacement = "flowable.history-cleaning-after", reason = "Switched to using a Duration that allows more flexible configuration")
public void setHistoryCleaningAfterDays(int historyCleaningAfterDays) {
this.historyCleaningAfter = Duration.ofDays(historyCleaningAfterDays);
}
public Duration getHistoryCleaningAfter() {
return historyCleaningAfter;
}
public void setHistoryCleaningAfter(Duration historyCleaningAfter) {
this.historyCleaningAfter = historyCleaningAfter;
} | public int getHistoryCleaningBatchSize() {
return historyCleaningBatchSize;
}
public void setHistoryCleaningBatchSize(int historyCleaningBatchSize) {
this.historyCleaningBatchSize = historyCleaningBatchSize;
}
public String getVariableJsonMapper() {
return variableJsonMapper;
}
public void setVariableJsonMapper(String variableJsonMapper) {
this.variableJsonMapper = variableJsonMapper;
}
} | repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\FlowableProperties.java | 2 |
请完成以下Java代码 | public class BankStatementImportFileLoggable implements ILoggable
{
private static final Logger logger = LogManager.getLogger(ApiAuditLoggable.class);
private final BankStatementImportFileLogRepository bankStatementImportFileLogRepository;
private final BankStatementImportFileId bankStatementImportFileId;
private final ClientId clientId;
private final UserId userId;
private final int bufferSize;
@Nullable
private List<BankStatementImportFileRequestLog> buffer;
@Builder
public BankStatementImportFileLoggable(
@NonNull final BankStatementImportFileLogRepository bankStatementImportFileLogRepository,
@NonNull final BankStatementImportFileId bankStatementImportFileId,
@NonNull final ClientId clientId,
@NonNull final UserId userId,
final int bufferSize)
{
Check.assumeGreaterThanZero(bufferSize, "bufferSize");
this.bankStatementImportFileLogRepository = bankStatementImportFileLogRepository;
this.bankStatementImportFileId = bankStatementImportFileId;
this.clientId = clientId;
this.userId = userId;
this.bufferSize = bufferSize;
}
@Override
public ILoggable addLog(@Nullable final String msg, final Object... msgParameters)
{
if (msg == null)
{
logger.warn("Called with msg=null; msgParameters={}; -> ignoring;", msgParameters);
return this;
}
final BankStatementImportFileRequestLog logEntry = createLogEntry(msg, msgParameters);
addToBuffer(logEntry);
return this;
}
@Override
public void flush()
{
final List<BankStatementImportFileRequestLog> logEntries = buffer;
this.buffer = null; | if (logEntries == null || logEntries.isEmpty())
{
return;
}
try
{
bankStatementImportFileLogRepository.insertLogs(logEntries);
}
catch (final Exception ex)
{
// make sure flush never fails
logger.warn("Failed saving {} log entries but IGNORED: {}", logEntries.size(), logEntries, ex);
}
}
@NonNull
private BankStatementImportFileRequestLog createLogEntry(@NonNull final String msg, final Object... msgParameters)
{
final LoggableWithThrowableUtil.FormattedMsgWithAdIssueId msgAndAdIssueId = LoggableWithThrowableUtil.extractMsgAndAdIssue(msg, msgParameters);
return BankStatementImportFileRequestLog.builder()
.message(msgAndAdIssueId.getFormattedMessage())
.adIssueId(msgAndAdIssueId.getAdIsueId().orElse(null))
.timestamp(SystemTime.asInstant())
.bankStatementImportFileId(bankStatementImportFileId)
.clientId(clientId)
.userId(userId)
.build();
}
private void addToBuffer(@NonNull final BankStatementImportFileRequestLog logEntry)
{
List<BankStatementImportFileRequestLog> buffer = this.buffer;
if (buffer == null)
{
buffer = this.buffer = new ArrayList<>(bufferSize);
}
buffer.add(logEntry);
if (buffer.size() >= bufferSize)
{
flush();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\importfile\log\BankStatementImportFileLoggable.java | 1 |
请完成以下Java代码 | public VersionRestService getVersionRestService(String engineName) {
String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString();
VersionRestService subResource = new VersionRestService(engineName, getObjectMapper());
subResource.setRelativeRootResourceUri(rootResourcePath);
return subResource;
}
public SchemaLogRestService getSchemaLogRestService(String engineName) {
String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString();
SchemaLogRestServiceImpl subResource = new SchemaLogRestServiceImpl(engineName, getObjectMapper());
subResource.setRelativeRootResourceUri(rootResourcePath);
return subResource;
}
public EventSubscriptionRestService getEventSubscriptionRestService(String engineName) {
String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString();
EventSubscriptionRestServiceImpl subResource = new EventSubscriptionRestServiceImpl(engineName, getObjectMapper());
subResource.setRelativeRootResourceUri(rootResourcePath); | return subResource;
}
public TelemetryRestService getTelemetryRestService(String engineName) {
String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString();
TelemetryRestServiceImpl subResource = new TelemetryRestServiceImpl(engineName, getObjectMapper());
subResource.setRelativeRootResourceUri(rootResourcePath);
return subResource;
}
protected abstract URI getRelativeEngineUri(String engineName);
protected ObjectMapper getObjectMapper() {
return ProvidersUtil
.resolveFromContext(providers, ObjectMapper.class, MediaType.APPLICATION_JSON_TYPE, this.getClass());
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\AbstractProcessEngineRestServiceImpl.java | 1 |
请完成以下Java代码 | protected void prepare()
{
p_PostingType = getParameterAsIParams().getParameterAsString(PARAM_PostingType);
Check.assumeNotEmpty(p_PostingType, "p_PostingType not empty");
}
@Override
protected String doIt() throws Exception
{
final String tableName = getTableName();
if (I_GL_JournalBatch.Table_Name.equals(tableName))
{
final I_GL_JournalBatch glJournalBatch = getRecord(I_GL_JournalBatch.class);
changePostingType(glJournalBatch);
}
else if (I_GL_Journal.Table_Name.equals(tableName))
{
final I_GL_Journal glJournal = getRecord(I_GL_Journal.class);
changePostingType(glJournal);
}
else
{
throw new AdempiereException("@NotSupported@ @TableName@: " + tableName);
}
return MSG_OK;
}
private void changePostingType(final I_GL_JournalBatch glJournalBatch) | {
glJournalBatch.setPostingType(p_PostingType);
InterfaceWrapperHelper.save(glJournalBatch);
final List<I_GL_Journal> glJournals = glJournalDAO.retrieveJournalsForBatch(glJournalBatch);
for (final I_GL_Journal glJournal : glJournals)
{
changePostingType(glJournal);
}
}
private void changePostingType(final I_GL_Journal glJournal)
{
glJournal.setPostingType(p_PostingType);
glJournalBL.unpost(glJournal);
InterfaceWrapperHelper.save(glJournal);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\process\GL_Journal_ChangePostingType.java | 1 |
请完成以下Java代码 | public class ConsumerStoppedEvent extends KafkaEvent {
private static final long serialVersionUID = 1L;
/**
* Reasons for stopping a consumer.
* @since 2.5.9
*
*/
public enum Reason {
/**
* The consumer was stopped because the container was stopped.
*/
NORMAL,
/**
* The consumer was stopped because the container was stopped abnormally.
* @since 4.0
*
*/
ABNORMAL,
/**
* The transactional producer was fenced and the container
* {@code stopContainerWhenFenced} property is true.
*/
FENCED,
/**
* An authorization exception occurred.
* @since 2.5.10
*/
AUTH,
/**
* No offset found for a partition and no reset policy.
* @since 2.5.10
*/
NO_OFFSET,
/**
* A {@link java.lang.Error} was thrown.
*/
ERROR
}
private final Reason reason;
/**
* Construct an instance with the provided source and container. | * @param source the container instance that generated the event.
* @param container the container or the parent container if the container is a child.
* @param reason the reason.
* @since 2.5.8
*/
public ConsumerStoppedEvent(Object source, Object container, Reason reason) {
super(source, container);
this.reason = reason;
}
/**
* Return the reason why the consumer was stopped.
* @return the reason.
* @since 2.5.8
*/
public Reason getReason() {
return this.reason;
}
@Override
public String toString() {
return "ConsumerStoppedEvent [source=" + getSource() + ", reason=" + this.reason + "]";
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\event\ConsumerStoppedEvent.java | 1 |
请完成以下Java代码 | public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String 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 boolean isEnabled() { | return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Date getLastLogin() {
return lastLogin;
}
public void setLastLogin(Date lastLogin) {
this.lastLogin = lastLogin;
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-boot-3\src\main\java\com\baeldung\relationships\models\AppUser.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Jdk8Module jdk8TimeModule() {
return new Jdk8Module();
}
/*
* Support for Hibernate types in Jackson.
*/
@Bean
public Hibernate5Module hibernate5Module() {
return new Hibernate5Module();
}
/*
* Jackson Afterburner module to speed up serialization/deserialization.
*/
@Bean
public AfterburnerModule afterburnerModule() {
return new AfterburnerModule();
} | /*
* Module for serialization/deserialization of RFC7807 Problem.
*/
@Bean
ProblemModule problemModule() {
return new ProblemModule();
}
/*
* Module for serialization/deserialization of ConstraintViolationProblem.
*/
@Bean
ConstraintViolationProblemModule constraintViolationProblemModule() {
return new ConstraintViolationProblemModule();
}
} | repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\config\JacksonConfiguration.java | 2 |
请完成以下Java代码 | public class GenericRestResponse {
private final Logger logger;
private final Client client;
public GenericRestResponse(Client client, Logger logger) {
this.client = client;
this.logger = logger;
}
public GenericRestResponse() {
this(ClientBuilder.newClient(), LoggerFactory.getLogger(GenericRestResponse.class));
}
public void sendRequest(String url, String jsonPayload) {
WebTarget target = client.target(url);
Response response = target.request(MediaType.APPLICATION_JSON)
.post(Entity.entity(jsonPayload, MediaType.APPLICATION_JSON)); | try {
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
String responseBody = response.readEntity(String.class);
logger.info("Response Body: " + responseBody);
} else {
logger.error("Failed to get a successful response");
}
} catch (RuntimeException e) {
logger.error("Error processing response", e);
} finally {
response.close();
client.close();
}
}
} | repos\tutorials-master\web-modules\jersey-2\src\main\java\com\baeldung\jersey\response\GenericRestResponse.java | 1 |
请完成以下Java代码 | protected java.util.Set<ArrayKey> initialValue()
{
return new HashSet<>();
};
};
private final List<IReceiptScheduleProducer> producers = new ArrayList<IReceiptScheduleProducer>();
private final GenerateReceiptScheduleForModelAggregateFilter modelAggregateFilter;
public CompositeReceiptScheduleProducerExecutor(@NonNull final GenerateReceiptScheduleForModelAggregateFilter modelAggregateFilter)
{
this.modelAggregateFilter = modelAggregateFilter;
}
public void addReceiptScheduleProducer(final IReceiptScheduleProducer producer)
{
Check.assumeNotNull(producer, "producer not null");
producers.add(producer);
}
private ArrayKey createModelKey(final Object model)
{
final String tableName = InterfaceWrapperHelper.getModelTableName(model);
final int id = InterfaceWrapperHelper.getId(model);
return Util.mkKey(tableName, id);
}
@Override
@Nullable
public List<I_M_ReceiptSchedule> createOrUpdateReceiptSchedules(final Object model, final List<I_M_ReceiptSchedule> previousSchedules)
{
if (!modelAggregateFilter.isEligible(model))
{
return null;
}
final ArrayKey modelKey = createModelKey(model);
//
// Add model to current models that are updated.
// If an update is just running for our model, then we shall skip it because we have to avoid recursions
if (!currentUpdatingModelKeys.get().add(modelKey))
{
return null;
}
final List<I_M_ReceiptSchedule> currentPreviousSchedules = new ArrayList<I_M_ReceiptSchedule>(previousSchedules);
final List<I_M_ReceiptSchedule> currentPreviousSchedulesRO = Collections.unmodifiableList(currentPreviousSchedules);
final List<I_M_ReceiptSchedule> schedules = new ArrayList<I_M_ReceiptSchedule>();
try
{
// Iterate all producers and ask them to create/update
for (final IReceiptScheduleProducer producer : producers) | {
final List<I_M_ReceiptSchedule> currentSchedules = producer.createOrUpdateReceiptSchedules(model, currentPreviousSchedulesRO);
// Collect created/updated receipt schedules
if (currentSchedules != null)
{
currentPreviousSchedules.addAll(currentSchedules);
schedules.addAll(currentSchedules);
}
}
}
finally
{
// Remove current model from the list of models that are currently updated
currentUpdatingModelKeys.get().remove(modelKey);
}
return schedules;
}
@Override
public void updateReceiptSchedules(final Object model)
{
for (final IReceiptScheduleProducer producer : producers)
{
producer.updateReceiptSchedules(model);
}
}
@Override
public void inactivateReceiptSchedules(final Object model)
{
for (final IReceiptScheduleProducer producer : producers)
{
producer.inactivateReceiptSchedules(model);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\CompositeReceiptScheduleProducerExecutor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void delete(DeviceProfile deviceProfile, User user) {
ActionType actionType = ActionType.DELETED;
DeviceProfileId deviceProfileId = deviceProfile.getId();
TenantId tenantId = deviceProfile.getTenantId();
try {
deviceProfileService.deleteDeviceProfile(tenantId, deviceProfileId);
logEntityActionService.logEntityAction(tenantId, deviceProfileId, deviceProfile, null,
actionType, user, deviceProfileId.toString());
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.DEVICE_PROFILE), actionType,
user, e, deviceProfileId.toString());
throw e;
}
}
@Override
public DeviceProfile setDefaultDeviceProfile(DeviceProfile deviceProfile, DeviceProfile previousDefaultDeviceProfile, User user) throws ThingsboardException {
TenantId tenantId = deviceProfile.getTenantId();
DeviceProfileId deviceProfileId = deviceProfile.getId();
try {
if (deviceProfileService.setDefaultDeviceProfile(tenantId, deviceProfileId)) { | if (previousDefaultDeviceProfile != null) {
previousDefaultDeviceProfile = deviceProfileService.findDeviceProfileById(tenantId, previousDefaultDeviceProfile.getId());
logEntityActionService.logEntityAction(tenantId, previousDefaultDeviceProfile.getId(), previousDefaultDeviceProfile,
ActionType.UPDATED, user);
}
deviceProfile = deviceProfileService.findDeviceProfileById(tenantId, deviceProfileId);
logEntityActionService.logEntityAction(tenantId, deviceProfileId, deviceProfile, ActionType.UPDATED, user);
}
return deviceProfile;
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.DEVICE_PROFILE), ActionType.UPDATED,
user, e, deviceProfileId.toString());
throw e;
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\device\profile\DefaultTbDeviceProfileService.java | 2 |
请完成以下Java代码 | public class CategoryValueImpl extends BaseElementImpl implements CategoryValue {
protected static Attribute<String> valueAttribute;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CategoryValue.class, BPMN_ELEMENT_CATEGORY_VALUE)
.namespaceUri(BPMN20_NS)
.extendsType(BaseElement.class)
.instanceProvider(new ModelTypeInstanceProvider<CategoryValue>() {
public CategoryValue newInstance(ModelTypeInstanceContext instanceContext) {
return new CategoryValueImpl(instanceContext);
}
});
valueAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_VALUE)
.build(); | typeBuilder.build();
}
public CategoryValueImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getValue() {
return valueAttribute.getValue(this);
}
public void setValue(String name) {
valueAttribute.setValue(this, name);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\CategoryValueImpl.java | 1 |
请完成以下Java代码 | protected void handleProcessConstraints(BpmnModel bpmnModel, Process process, List<ValidationError> errors) {
if (process.getId() != null && process.getId().length() > Constraints.PROCESS_DEFINITION_ID_MAX_LENGTH) {
addError(errors, Problems.PROCESS_DEFINITION_ID_TOO_LONG, process,
"The id of the process definition must not contain more than " + Constraints.PROCESS_DEFINITION_ID_MAX_LENGTH + " characters");
}
if (process.getName() != null && process.getName().length() > Constraints.PROCESS_DEFINITION_NAME_MAX_LENGTH) {
addError(errors, Problems.PROCESS_DEFINITION_NAME_TOO_LONG, process,
"The name of the process definition must not contain more than " + Constraints.PROCESS_DEFINITION_NAME_MAX_LENGTH + " characters");
}
if (process.getDocumentation() != null && process.getDocumentation().length() > Constraints.PROCESS_DEFINITION_DOCUMENTATION_MAX_LENGTH) {
addError(errors, Problems.PROCESS_DEFINITION_DOCUMENTATION_TOO_LONG, process,
"The documentation of the process definition must not contain more than " + Constraints.PROCESS_DEFINITION_DOCUMENTATION_MAX_LENGTH + " characters");
}
}
protected void handleBPMNModelConstraints(BpmnModel bpmnModel, List<ValidationError> errors) {
if (bpmnModel.getTargetNamespace() != null && bpmnModel.getTargetNamespace().length() > Constraints.BPMN_MODEL_TARGET_NAMESPACE_MAX_LENGTH) {
addError(errors, Problems.BPMN_MODEL_TARGET_NAMESPACE_TOO_LONG,
"The targetNamespace of the bpmn model must not contain more than " + Constraints.BPMN_MODEL_TARGET_NAMESPACE_MAX_LENGTH + " characters");
}
}
/**
* Returns 'true' if at least one process definition in the {@link BpmnModel} is executable.
*/
protected boolean validateAtLeastOneExecutable(BpmnModel bpmnModel, List<ValidationError> errors) { | int nrOfExecutableDefinitions = 0;
for (Process process : bpmnModel.getProcesses()) {
if (process.isExecutable()) {
nrOfExecutableDefinitions++;
}
}
if (nrOfExecutableDefinitions == 0) {
addError(errors, Problems.ALL_PROCESS_DEFINITIONS_NOT_EXECUTABLE,
"All process definition are set to be non-executable (property 'isExecutable' on process). This is not allowed.");
}
return nrOfExecutableDefinitions > 0;
}
} | repos\flowable-engine-main\modules\flowable-process-validation\src\main\java\org\flowable\validation\validator\impl\BpmnModelValidator.java | 1 |
请完成以下Java代码 | public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Organization.
@param Org_ID
Organizational entity within client
*/
public void setOrg_ID (int Org_ID)
{
if (Org_ID < 1)
set_Value (COLUMNNAME_Org_ID, null);
else
set_Value (COLUMNNAME_Org_ID, Integer.valueOf(Org_ID));
}
/** Get Organization.
@return Organizational entity within client
*/
public int getOrg_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Org_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_PA_Goal getPA_Goal() throws RuntimeException
{
return (I_PA_Goal)MTable.get(getCtx(), I_PA_Goal.Table_Name)
.getPO(getPA_Goal_ID(), get_TrxName()); }
/** Set Goal. | @param PA_Goal_ID
Performance Goal
*/
public void setPA_Goal_ID (int PA_Goal_ID)
{
if (PA_Goal_ID < 1)
set_Value (COLUMNNAME_PA_Goal_ID, null);
else
set_Value (COLUMNNAME_PA_Goal_ID, Integer.valueOf(PA_Goal_ID));
}
/** Get Goal.
@return Performance Goal
*/
public int getPA_Goal_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Goal_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Goal Restriction.
@param PA_GoalRestriction_ID
Performance Goal Restriction
*/
public void setPA_GoalRestriction_ID (int PA_GoalRestriction_ID)
{
if (PA_GoalRestriction_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_GoalRestriction_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_GoalRestriction_ID, Integer.valueOf(PA_GoalRestriction_ID));
}
/** Get Goal Restriction.
@return Performance Goal Restriction
*/
public int getPA_GoalRestriction_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_GoalRestriction_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_GoalRestriction.java | 1 |
请完成以下Java代码 | public static Builder builderFrom(StartMessageDeploymentDefinitionImpl startMessageEventSubscriptionImpl) {
return new Builder(startMessageEventSubscriptionImpl);
}
/**
* Builder to build {@link StartMessageDeploymentDefinitionImpl}.
*/
public static final class Builder {
private StartMessageSubscription messageSubscription;
private ProcessDefinition processDefinition;
public Builder() {}
private Builder(StartMessageDeploymentDefinitionImpl startMessageEventSubscriptionImpl) {
this.messageSubscription = startMessageEventSubscriptionImpl.messageSubscription;
this.processDefinition = startMessageEventSubscriptionImpl.processDefinition;
}
/**
* Builder method for messageEventSubscription parameter.
* @param messageEventSubscription field to set
* @return builder
*/
public Builder withMessageSubscription(StartMessageSubscription messageEventSubscription) {
this.messageSubscription = messageEventSubscription;
return this;
} | /**
* Builder method for processDefinition parameter.
* @param processDefinition field to set
* @return builder
*/
public Builder withProcessDefinition(ProcessDefinition processDefinition) {
this.processDefinition = processDefinition;
return this;
}
/**
* Builder method of the builder.
* @return built class
*/
public StartMessageDeploymentDefinitionImpl build() {
return new StartMessageDeploymentDefinitionImpl(this);
}
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\StartMessageDeploymentDefinitionImpl.java | 1 |
请完成以下Java代码 | public final class ObjectUtils
{
/**
* Calls {@link #toString(Object, boolean)} with <code>multiLine == true</code>.
*/
public static String toString(final Object obj)
{
return toString(obj, true);
}
/**
* To be used in {@link Object#toString()} implementations.
*
* Might arbitrarily throw exceptions. Therefore, Please consider to reimplement this, or to use e.g. {@link com.google.common.base.MoreObjects#toStringHelper(Object)}.
*
* @param obj the object to be printed
* @param multiLine if <code>true</code> then use {@link RecursiveIndentedMultilineToStringStyle} to display it in multiple lines.
*
*/
public static String toString(final Object obj, final boolean multiLine)
{
if (obj == null)
{
return "<NULL>";
}
try
{
final ToStringStyle toStringStyle;
if (multiLine)
{
toStringStyle = RecursiveIndentedMultilineToStringStyle.instance;
}
else
{
toStringStyle = RecursiveToStringStyle.SHORT_PREFIX_STYLE;
}
return new ExtendedReflectionToStringBuilder(obj, toStringStyle).toString();
}
catch (final Exception e)
{
// task 09493: catching possible errors
// this doesn't work! still invokes the "high-level" toString() method
// return ((Object)obj).toString() + " (WARNING: ExtendedReflectionToStringBuilder threw " + e + ")";
return createFallBackMessage(obj, e);
}
}
/**
*
* @param obj
* @param e
* @return
* @task http://dewiki908/mediawiki/index.php/09493_Error_Processing_Document_bei_Warenannahme_%28100785561740%29
*/
@VisibleForTesting
/* package */static String createFallBackMessage(final Object obj, final Exception e)
{ | return "!!! toString() for "
+ obj.getClass().getName() + "@" + Integer.toHexString(obj.hashCode())
+ ", (IdentityHashCode=" + System.identityHashCode(obj) + ") using ExtendedReflectionToStringBuilder threw " + e
+ ") !!!";
}
/**
* Tests whether two objects are equals.
*
* <p>
* It takes care of the null case. Thus, it is helpful to implement Object.equals.
*
* <p>
* Notice: it uses compareTo if BigDecimal is found. So, in this case, a.equals(b) might not be the same as Objects.equals(a, b).
*
* <p>
* If both a and b are Object[], they are compared item-by-item.
*
* NOTE: this is a copy paste from org.zkoss.lang.Objects.equals(Object, Object)
*
* @see Check#equals(Object, Object)
*/
public boolean equals(final Object a, Object b)
{
return Check.equals(a, b);
}
private ObjectUtils()
{
super();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\lang\ObjectUtils.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Mono<UserData> update(UserData employee) {
data.put(employee.getId(), employee);
return Mono.just(employee);
}
@Override
public Mono<UserData> delete(String id) {
UserData userData = data.remove(id);
if (userData != null) {
return Mono.just(userData);
} else {
return Mono.empty();
}
}
@Override | public void createUsersBulk(Integer n) {
LOG.info("createUsersBulk n={} ...", n);
for (int i=0; i<n; i++) {
String id = "user-id-" + i;
data.put(id, new UserData(id, "email" + i + "@corp.com", "name-" + i));
}
LOG.info("created {} users", n);
}
@Override
public Publisher<UserData> getAllStream() {
LOG.info("getAllStream: ");
return new UserDataPublisher(data.values().stream().collect(Collectors.toUnmodifiableList()));
}
} | repos\spring-examples-java-17\spring-webflux\src\main\java\itx\examples\webflux\services\UserServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Map<String, Object> getTransientVariablesLocal() {
return null;
}
@Override
public Object getTransientVariable(String variableName) {
return null;
}
@Override
public Map<String, Object> getTransientVariables() {
return null;
}
@Override
public void removeTransientVariableLocal(String variableName) {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
@Override
public void removeTransientVariablesLocal() {
throw new UnsupportedOperationException("No execution active, no variables can be removed"); | }
@Override
public void removeTransientVariable(String variableName) {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
@Override
public void removeTransientVariables() {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
@Override
public String getTenantId() {
return null;
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\el\NoExecutionVariableScope.java | 2 |
请完成以下Java代码 | public boolean isCachable() {
return true;
}
public Object getValue(ValueFields valueFields) {
if (valueFields.getLongValue() != null) {
return valueFields.getLongValue() == 1;
}
return null;
}
public void setValue(Object value, ValueFields valueFields) {
if (value == null) {
valueFields.setLongValue(null);
} else {
Boolean booleanValue = (Boolean) value; | if (booleanValue) {
valueFields.setLongValue(1L);
} else {
valueFields.setLongValue(0L);
}
}
}
public boolean isAbleToStore(Object value) {
if (value == null) {
return true;
}
return Boolean.class.isAssignableFrom(value.getClass()) || boolean.class.isAssignableFrom(value.getClass());
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\variable\BooleanType.java | 1 |
请完成以下Java代码 | public BigDecimal getMemberPrice() {
return memberPrice;
}
public void setMemberPrice(BigDecimal memberPrice) {
this.memberPrice = memberPrice;
}
public String getMemberLevelName() {
return memberLevelName;
}
public void setMemberLevelName(String memberLevelName) {
this.memberLevelName = memberLevelName;
}
@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(", productId=").append(productId);
sb.append(", memberLevelId=").append(memberLevelId);
sb.append(", memberPrice=").append(memberPrice);
sb.append(", memberLevelName=").append(memberLevelName);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsMemberPrice.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ShipperConfigId implements RepoIdAware
{
int repoId;
@JsonCreator
public static ShipperConfigId ofRepoId(final int repoId)
{
return new ShipperConfigId(repoId);
}
public static ShipperConfigId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new ShipperConfigId(repoId) : null;
}
public static int toRepoId(final ShipperConfigId productId) | {
return productId != null ? productId.getRepoId() : -1;
}
private ShipperConfigId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "Carrier_Config_Id");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\model\ShipperConfigId.java | 2 |
请完成以下Java代码 | public List<Object> getContent() {
if (content == null) {
content = new ArrayList<Object>();
}
return this.content;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the mimeType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMimeType() { | return mimeType;
}
/**
* Sets the value of the mimeType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMimeType(String value) {
this.mimeType = value;
}
/**
* Gets the value of the encoding property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEncoding() {
return encoding;
}
/**
* Sets the value of the encoding property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEncoding(String value) {
this.encoding = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\ObjectType.java | 1 |
请完成以下Java代码 | public void setPaymentWriteOffAmt (java.math.BigDecimal PaymentWriteOffAmt)
{
set_Value (COLUMNNAME_PaymentWriteOffAmt, PaymentWriteOffAmt);
}
/** Get Abschreibung Betrag.
@return Abschreibung Betrag
*/
@Override
public java.math.BigDecimal getPaymentWriteOffAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PaymentWriteOffAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
@Override
public org.compiere.model.I_C_AllocationLine getReversalLine()
{
return get_ValueAsPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_C_AllocationLine.class);
}
@Override
public void setReversalLine(org.compiere.model.I_C_AllocationLine ReversalLine)
{
set_ValueFromPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_C_AllocationLine.class, ReversalLine);
}
/** Set Storno-Zeile.
@param ReversalLine_ID Storno-Zeile */
@Override
public void setReversalLine_ID (int ReversalLine_ID)
{
if (ReversalLine_ID < 1)
set_Value (COLUMNNAME_ReversalLine_ID, null);
else
set_Value (COLUMNNAME_ReversalLine_ID, Integer.valueOf(ReversalLine_ID));
}
/** Get Storno-Zeile.
@return Storno-Zeile */
@Override | public int getReversalLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ReversalLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Abschreiben.
@param WriteOffAmt
Amount to write-off
*/
@Override
public void setWriteOffAmt (java.math.BigDecimal WriteOffAmt)
{
set_ValueNoCheck (COLUMNNAME_WriteOffAmt, WriteOffAmt);
}
/** Get Abschreiben.
@return Amount to write-off
*/
@Override
public java.math.BigDecimal getWriteOffAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WriteOffAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AllocationLine.java | 1 |
请完成以下Spring Boot application配置 | spring:
# RabbitMQ 配置项,对应 RabbitProperties 配置类
rabbitmq:
host: 127.0.0.1 # RabbitMQ 服务的地址
port: 5672 # RabbitMQ 服务的端口
username: guest # RabbitMQ 服务的账号
password: guest # RabbitMQ | 服务的密码
listener:
simple:
acknowledge-mode: manual # 配置 Consumer 手动提交 | repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-demo-ack\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | public String toString()
{
return String.valueOf(value);
}
@JsonValue
public int toInt()
{
return value;
}
public boolean isZero() { return value == 0; }
public boolean isGreaterThanZero() { return value > 0; }
public boolean isGreaterThanOne() { return value > 1; }
public PrintCopies minimumOne()
{
return isZero() ? ONE : this; | }
public PrintCopies plus(@NonNull final PrintCopies other)
{
if (other.isZero())
{
return this;
}
else if (isZero())
{
return other;
}
else
{
return ofInt(this.value + other.value);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\PrintCopies.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RefundInvoiceCandidate
{
/** May be {@code null} is the candidate is not persisted */
@Nullable
InvoiceCandidateId id;
@NonNull
BPartnerId bpartnerId;
@NonNull
BPartnerLocationId bpartnerLocationId;
@NonNull
LocalDate invoiceableFrom;
@NonNull
RefundContract refundContract;
/**
* If {@link RefundMode} is {@link RefundMode#APPLY_TO_EXCEEDING_QTY}, then there is one config per candidate; if it is {@link RefundMode#APPLY_TO_ALL_QTIES}, then there is one or many.
*/
@NonNull
@Singular
List<RefundConfig> refundConfigs;
@NonNull
Money money;
/** The sum of the quantities of all assigned {@link AssignableInvoiceCandidate}s. */
@NonNull
transient Quantity assignedQuantity;
/** Computes how much can still be assigned to this candidate, according to the given config. */
public Quantity computeAssignableQuantity(@NonNull final RefundConfig refundCondig)
{
final Optional<RefundConfig> nextRefundConfig = getRefundContract()
.getRefundConfigs()
.stream()
.filter(config -> config.getMinQty().compareTo(refundCondig.getMinQty()) > 0)
.min(Comparator.comparing(RefundConfig::getMinQty));
final I_C_UOM uomRecord = assignedQuantity.getUOM();
if (!nextRefundConfig.isPresent())
{
return Quantity.infinite(uomRecord);
} | return Quantity
.of(
nextRefundConfig.get().getMinQty(),
uomRecord)
.subtract(getAssignedQuantity())
.subtract(ONE)
.max(Quantity.zero(uomRecord));
}
public RefundInvoiceCandidate subtractAssignment(@NonNull final AssignmentToRefundCandidate assignmentToRefundCandidate)
{
Check.assume(assignmentToRefundCandidate.getRefundInvoiceCandidate().getId().equals(getId()),
"The given assignmentToRefundCandidate needs to be an assignment to this refund candidate; this={}, assignmentToRefundCandidate={}",
this, assignmentToRefundCandidate);
final RefundInvoiceCandidateBuilder builder = toBuilder();
final Money moneySubtrahent = assignmentToRefundCandidate.getMoneyAssignedToRefundCandidate();
final Money newMoneyAmount = getMoney().subtract(moneySubtrahent);
builder.money(newMoneyAmount);
if (assignmentToRefundCandidate.isUseAssignedQtyInSum())
{
final Quantity assignedQuantitySubtrahent = assignmentToRefundCandidate.getQuantityAssigendToRefundCandidate();
final Quantity newQuantity = getAssignedQuantity().subtract(assignedQuantitySubtrahent);
builder.assignedQuantity(newQuantity);
}
return builder.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\RefundInvoiceCandidate.java | 2 |
请完成以下Java代码 | public boolean isEmpty() {return list.isEmpty();}
public int size() {return list.size();}
public Stream<Packageable> stream() {return list.stream();}
@Override
public @NonNull Iterator<Packageable> iterator() {return list.iterator();}
public ImmutableSet<ShipmentScheduleId> getShipmentScheduleIds()
{
return list.stream().map(Packageable::getShipmentScheduleId).sorted().collect(ImmutableSet.toImmutableSet());
}
public Optional<BPartnerId> getSingleCustomerId() {return getSingleValue(Packageable::getCustomerId);}
public <T> Optional<T> getSingleValue(@NonNull final Function<Packageable, T> mapper)
{
if (list.isEmpty())
{
return Optional.empty();
}
final ImmutableList<T> values = list.stream()
.map(mapper)
.filter(Objects::nonNull)
.distinct()
.collect(ImmutableList.toImmutableList());
if (values.isEmpty())
{
return Optional.empty();
}
else if (values.size() == 1)
{
return Optional.of(values.get(0)); | }
else
{
//throw new AdempiereException("More than one value were extracted (" + values + ") from " + list);
return Optional.empty();
}
}
public Stream<PackageableList> groupBy(Function<Packageable, ?> classifier)
{
return list.stream()
.collect(Collectors.groupingBy(classifier, LinkedHashMap::new, PackageableList.collect()))
.values()
.stream();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\picking\api\PackageableList.java | 1 |
请完成以下Java代码 | protected void prepare()
{
for (ProcessInfoParameter para : getParametersAsArray())
{
if (para.getParameterName().equals("AD_Migration_ID"))
{
migrationId = para.getParameterAsInt();
}
else if (para.getParameterName().equals("FileName"))
{
fileName = (String)para.getParameter();
}
}
// if run from Migration window
if (migrationId <= 0 && I_AD_Migration.Table_Name.equals(getTableName()))
{ | migrationId = getRecord_ID();
}
log.debug("AD_Migration_ID = " + migrationId + ", filename = " + fileName);
}
@Override
protected String doIt() throws Exception
{
final I_AD_Migration migration = InterfaceWrapperHelper.create(getCtx(), migrationId, I_AD_Migration.class, get_TrxName());
final XMLWriter writer = new XMLWriter(fileName);
writer.write(migration);
return "Exported migration to: " + fileName;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\MigrationToXML.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Mono<MongoDatabase> getMongoDatabase() throws DataAccessException {
String gridFsDatabase = getGridFsDatabase();
if (StringUtils.hasText(gridFsDatabase)) {
return this.delegate.getMongoDatabase(gridFsDatabase);
}
return this.delegate.getMongoDatabase();
}
private @Nullable String getGridFsDatabase() {
return this.properties.getGridfs().getDatabase();
}
@Override
public Mono<MongoDatabase> getMongoDatabase(String dbName) throws DataAccessException {
return this.delegate.getMongoDatabase(dbName);
}
@Override
public <T> Optional<Codec<T>> getCodecFor(Class<T> type) {
return this.delegate.getCodecFor(type);
}
@Override
public PersistenceExceptionTranslator getExceptionTranslator() {
return this.delegate.getExceptionTranslator();
} | @Override
public CodecRegistry getCodecRegistry() {
return this.delegate.getCodecRegistry();
}
@Override
public Mono<ClientSession> getSession(ClientSessionOptions options) {
return this.delegate.getSession(options);
}
@Override
public ReactiveMongoDatabaseFactory withSession(ClientSession session) {
return this.delegate.withSession(session);
}
@Override
public boolean isTransactionActive() {
return this.delegate.isTransactionActive();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-data-mongodb\src\main\java\org\springframework\boot\data\mongodb\autoconfigure\DataMongoReactiveAutoConfiguration.java | 2 |
请完成以下Java代码 | public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Schema(description = "Last name of the user", example = "Doe")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Schema(description = "Phone number of the user", example = "38012345123")
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Schema(description = "Additional parameters of the user", implementation = com.fasterxml.jackson.databind.JsonNode.class)
@Override
public JsonNode getAdditionalInfo() {
return super.getAdditionalInfo();
}
@JsonIgnore
public String getTitle() {
return getTitle(email, firstName, lastName);
}
public static String getTitle(String email, String firstName, String lastName) {
String title = "";
if (isNotEmpty(firstName)) {
title += firstName;
}
if (isNotEmpty(lastName)) {
if (!title.isEmpty()) {
title += " ";
}
title += lastName;
}
if (title.isEmpty()) {
title = email;
}
return title;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("User [tenantId=");
builder.append(tenantId);
builder.append(", customerId=");
builder.append(customerId);
builder.append(", email=");
builder.append(email);
builder.append(", authority="); | builder.append(authority);
builder.append(", firstName=");
builder.append(firstName);
builder.append(", lastName=");
builder.append(lastName);
builder.append(", additionalInfo=");
builder.append(getAdditionalInfo());
builder.append(", createdTime=");
builder.append(createdTime);
builder.append(", id=");
builder.append(id);
builder.append("]");
return builder.toString();
}
@JsonIgnore
public boolean isSystemAdmin() {
return tenantId == null || EntityId.NULL_UUID.equals(tenantId.getId());
}
@JsonIgnore
public boolean isTenantAdmin() {
return !isSystemAdmin() && (customerId == null || EntityId.NULL_UUID.equals(customerId.getId()));
}
@JsonIgnore
public boolean isCustomerUser() {
return !isSystemAdmin() && !isTenantAdmin();
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal getStatus() {
return status;
}
public void setStatus(BigDecimal status) {
this.status = status;
}
public PatientNote noteText(String noteText) {
this.noteText = noteText;
return this;
}
/**
* Text der Patientennotiz
* @return noteText
**/
@Schema(example = "MRSA positiv", description = "Text der Patientennotiz")
public String getNoteText() {
return noteText;
}
public void setNoteText(String noteText) {
this.noteText = noteText;
}
public PatientNote patientId(String patientId) {
this.patientId = patientId;
return this;
}
/**
* Id des Patienten in Alberta
* @return patientId
**/
@Schema(example = "a4adecb6-126a-4fa6-8fac-e80165ac4264", description = "Id des Patienten in Alberta")
public String getPatientId() {
return patientId;
}
public void setPatientId(String patientId) {
this.patientId = patientId;
}
public PatientNote archived(Boolean archived) {
this.archived = archived;
return this;
}
/**
* Kennzeichen, ob die Notiz vom Benutzer archiviert wurde
* @return archived
**/
@Schema(example = "false", description = "Kennzeichen, ob die Notiz vom Benutzer archiviert wurde")
public Boolean isArchived() {
return archived;
}
public void setArchived(Boolean archived) {
this.archived = archived;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true; | }
if (o == null || getClass() != o.getClass()) {
return false;
}
PatientNote patientNote = (PatientNote) o;
return Objects.equals(this.status, patientNote.status) &&
Objects.equals(this.noteText, patientNote.noteText) &&
Objects.equals(this.patientId, patientNote.patientId) &&
Objects.equals(this.archived, patientNote.archived);
}
@Override
public int hashCode() {
return Objects.hash(status, noteText, patientId, archived);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PatientNote {\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append(" noteText: ").append(toIndentedString(noteText)).append("\n");
sb.append(" patientId: ").append(toIndentedString(patientId)).append("\n");
sb.append(" archived: ").append(toIndentedString(archived)).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-patient-api\src\main\java\io\swagger\client\model\PatientNote.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public PageBean listPage(PageParam pageParam, PmsPermission pmsPermission) {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("permissionName", pmsPermission.getPermissionName()); // 权限名称(模糊查询)
paramMap.put("permission", pmsPermission.getPermission()); // 权限(精确查询)
return pmsPermissionDao.listPage(pageParam, paramMap);
}
/**
* 检查权限名称是否已存在
*
* @param trim
* @return
*/
public PmsPermission getByPermissionName(String permissionName) {
return pmsPermissionDao.getByPermissionName(permissionName);
}
/**
* 检查权限是否已存在
*
* @param permission
* @return
*/
public PmsPermission getByPermission(String permission) {
return pmsPermissionDao.getByPermission(permission);
}
/**
* 检查权限名称是否已存在(其他id)
*
* @param permissionName
* @param id
* @return
*/
public PmsPermission getByPermissionNameNotEqId(String permissionName, Long id) {
return pmsPermissionDao.getByPermissionNameNotEqId(permissionName, id);
}
/**
* pmsPermissionDao 删除
*
* @param permission
*/
public void delete(Long permissionId) {
pmsPermissionDao.delete(permissionId);
} | /**
* 根据角色查找角色对应的功能权限ID集
*
* @param roleId
* @return
*/
public String getPermissionIdsByRoleId(Long roleId) {
List<PmsRolePermission> rmList = pmsRolePermissionDao.listByRoleId(roleId);
StringBuffer actionIds = new StringBuffer();
if (rmList != null && !rmList.isEmpty()) {
for (PmsRolePermission rm : rmList) {
actionIds.append(rm.getPermissionId()).append(",");
}
}
return actionIds.toString();
}
/**
* 查询所有的权限
*/
public List<PmsPermission> listAll() {
Map<String, Object> paramMap = new HashMap<String, Object>();
return pmsPermissionDao.listBy(paramMap);
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\service\impl\PmsPermissionServiceImpl.java | 2 |
请完成以下Java代码 | public static void forward(HttpServletRequest request, HttpServletResponse response, String page) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/user.check" + page)
.forward(request, response);
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
if (!(req instanceof HttpServletRequest)) {
throw new ServletException("Can only process HttpServletRequest");
}
if (!(res instanceof HttpServletResponse)) {
throw new ServletException("Can only process HttpServletResponse");
}
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res; | request.setAttribute("origin", request.getRequestURI());
if (!request.getRequestURI()
.contains("login") && request.getSession(false) == null) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
forward(request, response, "/login.jsp");
// we return here so the original servlet is not processed
return;
}
chain.doFilter(request, response);
}
public void init(FilterConfig arg) throws ServletException {
}
} | repos\tutorials-master\web-modules\jakarta-servlets-2\src\main\java\com\baeldung\user\check\UserCheckFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ObjectMapper objectMapper() {
return new ObjectMapper();
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
bean.setOrder(2);
return bean;
}
@Bean
public BeanNameViewResolver beanNameViewResolver(){
BeanNameViewResolver beanNameViewResolver = new BeanNameViewResolver();
beanNameViewResolver.setOrder(1);
return beanNameViewResolver;
}
@Bean | public View sample() {
return new JstlView("/WEB-INF/view/sample.jsp");
}
@Bean
public View sample2() {
return new JstlView("/WEB-INF/view2/sample2.jsp");
}
@Bean
public View sample3(){
return new JstlView("/WEB-INF/view3/sample3.jsp");
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-basics-4\src\main\java\com\baeldung\config\WebConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
Resource resource = new ClassPathResource("META-INF/spring.integration.properties");
if (resource.exists()) {
registerIntegrationPropertiesPropertySource(environment, resource);
}
}
protected void registerIntegrationPropertiesPropertySource(ConfigurableEnvironment environment, Resource resource) {
PropertiesPropertySourceLoader loader = new PropertiesPropertySourceLoader();
try {
OriginTrackedMapPropertySource propertyFileSource = (OriginTrackedMapPropertySource) loader
.load("META-INF/spring.integration.properties", resource)
.get(0);
environment.getPropertySources().addLast(new IntegrationPropertiesPropertySource(propertyFileSource));
}
catch (IOException ex) {
throw new IllegalStateException("Failed to load integration properties from " + resource, ex);
}
}
private static final class IntegrationPropertiesPropertySource extends PropertySource<Map<String, Object>>
implements OriginLookup<String> {
private static final String PREFIX = "spring.integration.";
private static final Map<String, String> KEYS_MAPPING;
static {
Map<String, String> mappings = new HashMap<>();
mappings.put(PREFIX + "channel.auto-create", IntegrationProperties.CHANNELS_AUTOCREATE);
mappings.put(PREFIX + "channel.max-unicast-subscribers",
IntegrationProperties.CHANNELS_MAX_UNICAST_SUBSCRIBERS);
mappings.put(PREFIX + "channel.max-broadcast-subscribers", | IntegrationProperties.CHANNELS_MAX_BROADCAST_SUBSCRIBERS);
mappings.put(PREFIX + "error.require-subscribers", IntegrationProperties.ERROR_CHANNEL_REQUIRE_SUBSCRIBERS);
mappings.put(PREFIX + "error.ignore-failures", IntegrationProperties.ERROR_CHANNEL_IGNORE_FAILURES);
mappings.put(PREFIX + "endpoint.default-timeout", IntegrationProperties.ENDPOINTS_DEFAULT_TIMEOUT);
mappings.put(PREFIX + "endpoint.throw-exception-on-late-reply",
IntegrationProperties.THROW_EXCEPTION_ON_LATE_REPLY);
mappings.put(PREFIX + "endpoint.read-only-headers", IntegrationProperties.READ_ONLY_HEADERS);
mappings.put(PREFIX + "endpoint.no-auto-startup", IntegrationProperties.ENDPOINTS_NO_AUTO_STARTUP);
KEYS_MAPPING = Collections.unmodifiableMap(mappings);
}
private final OriginTrackedMapPropertySource delegate;
IntegrationPropertiesPropertySource(OriginTrackedMapPropertySource delegate) {
super("META-INF/spring.integration.properties", delegate.getSource());
this.delegate = delegate;
}
@Override
public @Nullable Object getProperty(String name) {
String mapped = KEYS_MAPPING.get(name);
return (mapped != null) ? this.delegate.getProperty(mapped) : null;
}
@Override
public @Nullable Origin getOrigin(String key) {
String mapped = KEYS_MAPPING.get(key);
return (mapped != null) ? this.delegate.getOrigin(mapped) : null;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-integration\src\main\java\org\springframework\boot\integration\autoconfigure\IntegrationPropertiesEnvironmentPostProcessor.java | 2 |
请在Spring Boot框架中完成以下Java代码 | class ReceiptsScheduleHandlerUtil
{
public CandidatesQuery queryByPurchaseCandidateId(@NonNull final ReceiptScheduleCreatedEvent createdEvent)
{
final int purchaseCandidateRepoId = createdEvent.getPurchaseCandidateRepoId();
if (purchaseCandidateRepoId > 0)
{
return prepareQuery(createdEvent)
.purchaseDetailsQuery(PurchaseDetailsQuery.builder()
.purchaseCandidateRepoId(purchaseCandidateRepoId)
.orderLineRepoIdMustBeNull(true)
.build())
.build();
}
else
{
return CandidatesQuery.FALSE;
}
} | public CandidatesQuery queryByReceiptScheduleId(@NonNull final AbstractReceiptScheduleEvent event)
{
return prepareQuery(event)
.purchaseDetailsQuery(PurchaseDetailsQuery.builder()
.receiptScheduleRepoId(event.getReceiptScheduleId())
.build())
.build();
}
private CandidatesQueryBuilder prepareQuery(@NonNull final AbstractReceiptScheduleEvent event)
{
return CandidatesQuery.builder()
.type(CandidateType.SUPPLY)
.businessCase(CandidateBusinessCase.PURCHASE)
.materialDescriptorQuery(MaterialDescriptorQuery.forDescriptor(event.getMaterialDescriptor()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\receiptschedule\ReceiptsScheduleHandlerUtil.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private H100 mapToH100(final HEADERXbest header)
{
final H100 h100 = new H100();
for (final HADRE1 hadre1 : header.getHADRE1())
{
final AddressQual addressQual = AddressQual.valueOf(hadre1.getADDRESSQUAL());
switch (addressQual)
{
case SUPL:
{
h100.setSupplierID(hadre1.getPARTYIDGLN());
break;
}
case BUYR:
{
h100.setBuyerID(hadre1.getPARTYIDGLN());
break;
}
case DELV:
{
h100.setDeliveryID(hadre1.getPARTYIDGLN());
break;
}
case IVCE:
{
h100.setInvoiceID(hadre1.getPARTYIDGLN());
break;
}
case ULCO:
{
h100.setStoreNumber(hadre1.getPARTYIDGLN());
break;
}
}
}
for (final HDATE1 hdate1 : header.getHDATE1())
{
final DateQual dateQual = DateQual.valueOf(hdate1.getDATEQUAL());
switch (dateQual)
{
case CREA:
{ | h100.setMessageDate(hdate1.getDATEFROM());
break;
}
case DELV:
{
if (hdate1.getDATEFROM() == null)
{
h100.setDeliveryDate(hdate1.getDATETO());
}
else
{
h100.setDeliveryDate(hdate1.getDATEFROM());
}
break;
}
}
}
h100.setDocumentNo(header.getDOCUMENTID());
return h100;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\ordersimport\stepcom\StepComXMLOrdersBean.java | 2 |
请完成以下Java代码 | public class Order {
private final List<OrderLine> orderLines;
private Money totalCost;
public Order(List<OrderLine> orderLines) {
checkNotNull(orderLines);
if (orderLines.isEmpty()) {
throw new IllegalArgumentException("Order must have at least one order line item");
}
this.orderLines = new ArrayList<>(orderLines);
totalCost = calculateTotalCost();
}
public void addLineItem(OrderLine orderLine) {
checkNotNull(orderLine);
orderLines.add(orderLine);
totalCost = totalCost.plus(orderLine.cost());
}
public List<OrderLine> getOrderLines() {
return new ArrayList<>(orderLines);
} | public void removeLineItem(int line) {
OrderLine removedLine = orderLines.remove(line);
totalCost = totalCost.minus(removedLine.cost());
}
public Money totalCost() {
return totalCost;
}
private Money calculateTotalCost() {
return orderLines.stream()
.map(OrderLine::cost)
.reduce(Money::plus)
.get();
}
private static void checkNotNull(Object par) {
if (par == null) {
throw new NullPointerException("Parameter cannot be null");
}
}
} | repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\ddd\order\Order.java | 1 |
请完成以下Java代码 | class PageLoader implements Runnable
{
private JEditorPane html;
private URL url;
private Cursor cursor;
PageLoader( JEditorPane html, URL url, Cursor cursor )
{
this.html = html;
this.url = url;
this.cursor = cursor;
}
@Override
public void run()
{
if( url == null )
{
// restore the original cursor
html.setCursor( cursor );
// PENDING(prinz) remove this hack when
// automatic validation is activated.
Container parent = html.getParent();
parent.repaint();
}
else
{
Document doc = html.getDocument();
try {
html.setPage( url );
} | catch( IOException ioe )
{
html.setDocument( doc );
}
finally
{
// schedule the cursor to revert after
// the paint has happended.
url = null;
SwingUtilities.invokeLater( this );
}
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\apps\graph\HtmlDashboard.java | 1 |
请完成以下Java代码 | public class SignalEventListenerExport extends AbstractPlanItemDefinitionExport<SignalEventListener> {
@Override
protected Class<? extends SignalEventListener> getExportablePlanItemDefinitionClass() {
return SignalEventListener.class;
}
@Override
protected String getPlanItemDefinitionXmlElementValue(SignalEventListener signalEventListener) {
return ELEMENT_GENERIC_EVENT_LISTENER;
}
@Override
protected void writePlanItemDefinitionSpecificAttributes(SignalEventListener signalEventListener, XMLStreamWriter xtw) throws Exception {
super.writePlanItemDefinitionSpecificAttributes(signalEventListener, xtw); | xtw.writeAttribute(FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_EVENT_LISTENER_TYPE, "signal");
if (StringUtils.isNotEmpty(signalEventListener.getSignalRef())) {
xtw.writeAttribute(FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_EVENT_LISTENER_SIGNAL_REF, signalEventListener.getSignalRef());
}
if (StringUtils.isNotEmpty(signalEventListener.getAvailableConditionExpression())) {
xtw.writeAttribute(FLOWABLE_EXTENSIONS_NAMESPACE,
CmmnXmlConstants.ATTRIBUTE_EVENT_LISTENER_AVAILABLE_CONDITION,
signalEventListener.getAvailableConditionExpression());
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\export\SignalEventListenerExport.java | 1 |
请完成以下Java代码 | public void addViewControllers(final ViewControllerRegistry registry) {
registry.addViewController("/anonymous.html");
registry.addViewController("/login.html");
registry.addViewController("/homepage.html");
registry.addViewController("/admin/adminpage.html");
registry.addViewController("/accessDenied");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/WEB-INF/view/react/build/static/");
registry.addResourceHandler("/*.js").addResourceLocations("/WEB-INF/view/react/build/");
registry.addResourceHandler("/*.json").addResourceLocations("/WEB-INF/view/react/build/"); | registry.addResourceHandler("/*.ico").addResourceLocations("/WEB-INF/view/react/build/");
registry.addResourceHandler("/index.html").addResourceLocations("/WEB-INF/view/react/build/index.html");
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-react\src\main\java\com\baeldung\spring\MvcConfig.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Chapter77Application {
public static void main(String[] args) {
SpringApplication.run(Chapter77Application.class, args);
}
@EnableAsync
@Configuration
class TaskPoolConfig {
@Bean
public Executor taskExecutor1() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(10);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("executor-1-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
} | @Bean
public Executor taskExecutor2() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(10);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("executor-2-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}
} | repos\SpringBoot-Learning-master\2.x\chapter7-7\src\main\java\com\didispace\chapter77\Chapter77Application.java | 2 |
请完成以下Java代码 | public MobileApp findAppFromQrCodeSettings(TenantId tenantId, PlatformType platformType) {
log.trace("Executing findAppQrCodeConfig for tenant [{}] ", tenantId);
QrCodeSettings qrCodeSettings = findQrCodeSettings(tenantId);
return qrCodeSettings.getMobileAppBundleId() != null ? mobileAppService.findByBundleIdAndPlatformType(tenantId, qrCodeSettings.getMobileAppBundleId(), platformType) : null;
}
@Override
public void deleteByTenantId(TenantId tenantId) {
log.trace("Executing deleteByTenantId, tenantId [{}]", tenantId);
validateId(tenantId, id -> INCORRECT_TENANT_ID + id);
qrCodeSettingsDao.removeByTenantId(tenantId);
}
@TransactionalEventListener(classes = QrCodeSettingsEvictEvent.class)
@Override
public void handleEvictEvent(QrCodeSettingsEvictEvent event) {
cache.evict(event.getTenantId());
}
private QrCodeSettings constructMobileAppSettings(QrCodeSettings qrCodeSettings) {
if (qrCodeSettings == null) {
qrCodeSettings = new QrCodeSettings();
qrCodeSettings.setUseDefaultApp(true);
qrCodeSettings.setAndroidEnabled(true);
qrCodeSettings.setIosEnabled(true);
QRCodeConfig qrCodeConfig = QRCodeConfig.builder()
.showOnHomePage(true)
.qrCodeLabelEnabled(true)
.qrCodeLabel(DEFAULT_QR_CODE_LABEL)
.badgeEnabled(true)
.badgePosition(BadgePosition.RIGHT)
.badgeEnabled(true) | .build();
qrCodeSettings.setQrCodeConfig(qrCodeConfig);
qrCodeSettings.setMobileAppBundleId(qrCodeSettings.getMobileAppBundleId());
}
if (qrCodeSettings.isUseDefaultApp() || qrCodeSettings.getMobileAppBundleId() == null) {
qrCodeSettings.setGooglePlayLink(googlePlayLink);
qrCodeSettings.setAppStoreLink(appStoreLink);
} else {
MobileApp androidApp = mobileAppService.findByBundleIdAndPlatformType(qrCodeSettings.getTenantId(), qrCodeSettings.getMobileAppBundleId(), ANDROID);
MobileApp iosApp = mobileAppService.findByBundleIdAndPlatformType(qrCodeSettings.getTenantId(), qrCodeSettings.getMobileAppBundleId(), IOS);
if (androidApp != null && androidApp.getStoreInfo() != null) {
qrCodeSettings.setGooglePlayLink(androidApp.getStoreInfo().getStoreLink());
}
if (iosApp != null && iosApp.getStoreInfo() != null) {
qrCodeSettings.setAppStoreLink(iosApp.getStoreInfo().getStoreLink());
}
}
return qrCodeSettings;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\mobile\QrCodeSettingServiceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ExcelController {
@GetMapping("/download-excel")
public ResponseEntity<byte[]> downloadExcel() {
try {
HSSFWorkbook workbook = ExcelCreator.createSampleWorkbook();
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
workbook.write(baos);
byte[] bytes = baos.toByteArray();
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=employee_data.xls")
.contentType(MediaType.parseMediaType("application/vnd.ms-excel")) // More specific MIME type
.body(bytes);
}
} catch (IOException e) {
System.err.println("Error generating or writing Excel workbook: " + e.getMessage());
return ResponseEntity.internalServerError()
.build();
}
}
@PostMapping("/upload-excel")
public ResponseEntity<String> uploadExcel(@RequestParam("file") MultipartFile file) { | if (file.isEmpty()) {
return ResponseEntity.badRequest()
.body("File is empty. Please upload a file.");
}
try {
try (HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream())) {
Sheet sheet = workbook.getSheetAt(0);
return ResponseEntity.ok("Sheet '" + sheet.getSheetName() + "' uploaded successfully!");
}
} catch (IOException e) {
System.err.println("Error processing uploaded Excel file: " + e.getMessage());
return ResponseEntity.internalServerError()
.body("Failed to process the Excel file.");
} catch (Exception e) {
System.err.println("An unexpected error occurred during file upload: " + e.getMessage());
return ResponseEntity.internalServerError()
.body("An unexpected error occurred.");
}
}
} | repos\tutorials-master\apache-poi-3\src\main\java\com\baeldung\hssfworkbook\ExcelController.java | 2 |
请完成以下Java代码 | public SignalEventListenerInstanceQuery stateAvailable() {
innerQuery.planItemInstanceStateAvailable();
return this;
}
@Override
public SignalEventListenerInstanceQuery stateSuspended() {
innerQuery.planItemInstanceState(PlanItemInstanceState.SUSPENDED);
return this;
}
@Override
public SignalEventListenerInstanceQuery orderByName() {
innerQuery.orderByName();
return this;
}
@Override
public SignalEventListenerInstanceQuery asc() {
innerQuery.asc();
return this;
}
@Override
public SignalEventListenerInstanceQuery desc() {
innerQuery.desc();
return this;
}
@Override
public SignalEventListenerInstanceQuery orderBy(QueryProperty property) {
innerQuery.orderBy(property);
return this;
}
@Override
public SignalEventListenerInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) {
innerQuery.orderBy(property, nullHandlingOnOrder); | return this;
}
@Override
public long count() {
return innerQuery.count();
}
@Override
public SignalEventListenerInstance singleResult() {
PlanItemInstance instance = innerQuery.singleResult();
return SignalEventListenerInstanceImpl.fromPlanItemInstance(instance);
}
@Override
public List<SignalEventListenerInstance> list() {
return convertPlanItemInstances(innerQuery.list());
}
@Override
public List<SignalEventListenerInstance> listPage(int firstResult, int maxResults) {
return convertPlanItemInstances(innerQuery.listPage(firstResult, maxResults));
}
protected List<SignalEventListenerInstance> convertPlanItemInstances(List<PlanItemInstance> instances) {
if (instances == null) {
return null;
}
return instances.stream().map(SignalEventListenerInstanceImpl::fromPlanItemInstance).collect(Collectors.toList());
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\SignalEventListenerInstanceQueryImpl.java | 1 |
请完成以下Java代码 | public JSONObject buildQueryString(String query) {
JSONObject queryString = new JSONObject();
queryString.put("query", query);
JSONObject json = new JSONObject();
json.put("query_string", queryString);
return json;
}
/**
* @param field 查询字段
* @param min 最小值
* @param max 最大值
* @param containMin 范围内是否包含最小值
* @param containMax 范围内是否包含最大值
* @return { "range" : { field : { 『 "gt『e』?containMin" : min 』?min!=null , 『 "lt『e』?containMax" : max 』}} }
*/
public JSONObject buildRangeQuery(String field, Object min, Object max, boolean containMin, boolean containMax) {
JSONObject inner = new JSONObject();
if (min != null) {
if (containMin) {
inner.put("gte", min);
} else { | inner.put("gt", min);
}
}
if (max != null) {
if (containMax) {
inner.put("lte", max);
} else {
inner.put("lt", max);
}
}
JSONObject range = new JSONObject();
range.put(field, inner);
JSONObject json = new JSONObject();
json.put("range", range);
return json;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\es\JeecgElasticsearchTemplate.java | 1 |
请完成以下Java代码 | public String getID()
{
return m_value;
} // getID
@Override
public boolean equals(final Object obj)
{
if (obj == this)
{
return true;
}
if (obj instanceof ValueNamePair)
{ | final ValueNamePair other = (ValueNamePair)obj;
return Objects.equals(this.m_value, other.m_value)
&& Objects.equals(this.getName(), other.getName())
&& Objects.equals(this.m_validationInformation, other.m_validationInformation);
}
return false;
} // equals
@Override
public int hashCode()
{
return m_value.hashCode();
} // hashCode
} // KeyValuePair | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\ValueNamePair.java | 1 |
请完成以下Java代码 | void setVocabIndexMap(VocabWord src, int pos)
{
// vocabIndexMap.put(src.word, pos);
trainWords += src.cn;
}
/**
* Create binary Huffman tree using the word counts.
* Frequent words will have short uniqe binary codes
*/
void createBinaryTree()
{
int[] point = new int[VocabWord.MAX_CODE_LENGTH];
char[] code = new char[VocabWord.MAX_CODE_LENGTH];
int[] count = new int[vocabSize * 2 + 1];
char[] binary = new char[vocabSize * 2 + 1];
int[] parentNode = new int[vocabSize * 2 + 1];
for (int i = 0; i < vocabSize; i++)
count[i] = vocab[i].cn;
for (int i = vocabSize; i < vocabSize * 2; i++)
count[i] = Integer.MAX_VALUE;
int pos1 = vocabSize - 1;
int pos2 = vocabSize;
// Following algorithm constructs the Huffman tree by adding one node at a time
int min1i, min2i;
for (int i = 0; i < vocabSize - 1; i++)
{
// First, find two smallest nodes 'min1, min2'
if (pos1 >= 0)
{
if (count[pos1] < count[pos2])
{
min1i = pos1;
pos1--;
}
else
{
min1i = pos2;
pos2++;
}
}
else
{
min1i = pos2;
pos2++;
}
if (pos1 >= 0)
{
if (count[pos1] < count[pos2])
{ | min2i = pos1;
pos1--;
}
else
{
min2i = pos2;
pos2++;
}
}
else
{
min2i = pos2;
pos2++;
}
count[vocabSize + i] = count[min1i] + count[min2i];
parentNode[min1i] = vocabSize + i;
parentNode[min2i] = vocabSize + i;
binary[min2i] = 1;
}
// Now assign binary code to each vocabulary word
for (int j = 0; j < vocabSize; j++)
{
int k = j;
int i = 0;
while (true)
{
code[i] = binary[k];
point[i] = k;
i++;
k = parentNode[k];
if (k == vocabSize * 2 - 2) break;
}
vocab[j].codelen = i;
vocab[j].point[0] = vocabSize - 2;
for (k = 0; k < i; k++)
{
vocab[j].code[i - k - 1] = code[k];
vocab[j].point[i - k] = point[k] - vocabSize;
}
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\Corpus.java | 1 |
请完成以下Java代码 | static MethodParameterRuntimeHintsRegistrar fromMethodParameter(
HandlerMethodArgumentResolverComposite resolvers, MethodParameter parameter) {
HandlerMethodArgumentResolver resolver = resolvers.getArgumentResolver(parameter);
if (resolver instanceof ArgumentMethodArgumentResolver
|| resolver instanceof ArgumentsMethodArgumentResolver) {
return new ArgumentBindingHints(parameter);
}
if (resolver instanceof DataLoaderMethodArgumentResolver) {
return new DataLoaderHints(parameter);
}
if (springDataPresent) {
if (resolver instanceof ProjectedPayloadMethodArgumentResolver) {
return new ProjectedPayloadHints(parameter);
}
}
return new NoHintsRequired();
}
}
private static final class NoHintsRequired implements MethodParameterRuntimeHintsRegistrar {
@Override
public void apply(RuntimeHints runtimeHints) {
// no runtime hints are required for this type of argument
}
}
private static class ArgumentBindingHints implements MethodParameterRuntimeHintsRegistrar {
private final MethodParameter methodParameter;
ArgumentBindingHints(MethodParameter methodParameter) {
this.methodParameter = methodParameter;
}
@Override
public void apply(RuntimeHints runtimeHints) {
Type parameterType = this.methodParameter.getGenericParameterType();
if (ArgumentValue.class.isAssignableFrom(this.methodParameter.getParameterType())) {
parameterType = this.methodParameter.nested().getNestedGenericParameterType();
}
bindingRegistrar.registerReflectionHints(runtimeHints.reflection(), parameterType);
}
}
private static class DataLoaderHints implements MethodParameterRuntimeHintsRegistrar {
private final MethodParameter methodParameter; | DataLoaderHints(MethodParameter methodParameter) {
this.methodParameter = methodParameter;
}
@Override
public void apply(RuntimeHints hints) {
bindingRegistrar.registerReflectionHints(
hints.reflection(), this.methodParameter.nested().getNestedGenericParameterType());
}
}
private static class ProjectedPayloadHints implements MethodParameterRuntimeHintsRegistrar {
private final MethodParameter methodParameter;
ProjectedPayloadHints(MethodParameter methodParameter) {
this.methodParameter = methodParameter;
}
@Override
public void apply(RuntimeHints hints) {
Class<?> parameterType = this.methodParameter.nestedIfOptional().getNestedParameterType();
hints.reflection().registerType(parameterType);
hints.proxies().registerJdkProxy(parameterType, TargetAware.class, SpringProxy.class, DecoratingProxy.class);
}
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\data\method\annotation\support\SchemaMappingBeanFactoryInitializationAotProcessor.java | 1 |
请完成以下Java代码 | protected String doIt()
{
final ImmutableList<PrintableQRCode> qrCodes = streamSelectedDevices()
.map(PrintDeviceQRCodes::toDeviceQRCode)
.map(DeviceQRCode::toPrintableQRCode)
.collect(ImmutableList.toImmutableList());
final QRCodePDFResource pdf = globalQRCodeService.createPDF(qrCodes);
getResult().setReportData(pdf, pdf.getFilename(), pdf.getContentType());
return MSG_OK;
}
private Stream<DeviceAccessor> streamSelectedDevices()
{
final DeviceId onlyDeviceId = StringUtils.trimBlankToOptional(p_deviceIdStr)
.map(DeviceId::ofString)
.orElse(null);
if (onlyDeviceId != null)
{
final DeviceAccessor deviceAccessor = deviceAccessorsHubFactory.getDefaultDeviceAccessorsHub() | .getDeviceAccessorById(onlyDeviceId)
.orElseThrow(() -> new AdempiereException("No device found for id: " + onlyDeviceId));
return Stream.of(deviceAccessor);
}
else
{
return deviceAccessorsHubFactory.getDefaultDeviceAccessorsHub()
.streamAllDeviceAccessors();
}
}
private static DeviceQRCode toDeviceQRCode(final DeviceAccessor deviceAccessor)
{
return DeviceQRCode.builder()
.deviceId(deviceAccessor.getId())
.caption(deviceAccessor.getDisplayName().getDefaultValue())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\devices\webui\process\PrintDeviceQRCodes.java | 1 |
请完成以下Java代码 | public int getM_HU_PI_Attribute_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PI_Attribute_ID);
}
@Override
public de.metas.handlingunits.model.I_M_HU_PI_Version getM_HU_PI_Version()
{
return get_ValueAsPO(COLUMNNAME_M_HU_PI_Version_ID, de.metas.handlingunits.model.I_M_HU_PI_Version.class);
}
@Override
public void setM_HU_PI_Version(final de.metas.handlingunits.model.I_M_HU_PI_Version M_HU_PI_Version)
{
set_ValueFromPO(COLUMNNAME_M_HU_PI_Version_ID, de.metas.handlingunits.model.I_M_HU_PI_Version.class, M_HU_PI_Version);
}
@Override
public void setM_HU_PI_Version_ID (final int M_HU_PI_Version_ID)
{
if (M_HU_PI_Version_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_PI_Version_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_PI_Version_ID, M_HU_PI_Version_ID);
}
@Override
public int getM_HU_PI_Version_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PI_Version_ID);
}
/**
* PropagationType AD_Reference_ID=540404
* Reference name: M_HU_PI_Attribute_PropagationType
*/
public static final int PROPAGATIONTYPE_AD_Reference_ID=540404;
/** TopDown = TOPD */
public static final String PROPAGATIONTYPE_TopDown = "TOPD";
/** BottomUp = BOTU */
public static final String PROPAGATIONTYPE_BottomUp = "BOTU";
/** NoPropagation = NONE */
public static final String PROPAGATIONTYPE_NoPropagation = "NONE";
@Override
public void setPropagationType (final java.lang.String PropagationType)
{
set_Value (COLUMNNAME_PropagationType, PropagationType);
}
@Override
public java.lang.String getPropagationType()
{
return get_ValueAsString(COLUMNNAME_PropagationType); | }
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setSplitterStrategy_JavaClass_ID (final int SplitterStrategy_JavaClass_ID)
{
if (SplitterStrategy_JavaClass_ID < 1)
set_Value (COLUMNNAME_SplitterStrategy_JavaClass_ID, null);
else
set_Value (COLUMNNAME_SplitterStrategy_JavaClass_ID, SplitterStrategy_JavaClass_ID);
}
@Override
public int getSplitterStrategy_JavaClass_ID()
{
return get_ValueAsInt(COLUMNNAME_SplitterStrategy_JavaClass_ID);
}
@Override
public void setUseInASI (final boolean UseInASI)
{
set_Value (COLUMNNAME_UseInASI, UseInASI);
}
@Override
public boolean isUseInASI()
{
return get_ValueAsBoolean(COLUMNNAME_UseInASI);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PI_Attribute.java | 1 |
请完成以下Java代码 | protected final Properties getCtx()
{
return Env.getCtx();
}
/**
*
* @param valueObj
* @return {@link BigDecimal} value or {@link BigDecimal#ZERO} if the value is null or cannot be converted
*/
protected final BigDecimal toBigDecimalOrZero(final Object valueObj)
{
if (valueObj == null)
{
return BigDecimal.ZERO;
}
else if (valueObj instanceof BigDecimal)
{
return (BigDecimal)valueObj;
}
else
{
try
{
return new BigDecimal(valueObj.toString());
}
catch (Exception e)
{
logger.warn("Failed converting " + valueObj
+ " (class " + valueObj.getClass() + ")"
+ " to BigDecimal. Returning ZERO.", e);
}
return BigDecimal.ZERO;
}
}
protected final boolean setRowValueOrNull(final IRModelMetadata metadata, final List<Object> row, final String columnName, final Object value)
{
final int columnIndex = metadata.getRColumnIndex(columnName);
if (columnIndex < 0)
{
return false;
}
if (columnIndex >= row.size())
{
return false;
}
row.set(columnIndex, value);
return true;
}
protected final Object getRowValueOrNull(final IRModelMetadata metadata, final List<Object> row, final String columnName)
{
if (row == null)
{
return null;
}
final int columnIndex = metadata.getRColumnIndex(columnName);
if (columnIndex < 0)
{
return null;
}
if (columnIndex >= row.size())
{
return null;
} | final Object value = row.get(columnIndex);
return value;
}
protected final <T> T getRowValueOrNull(final IRModelMetadata metadata, final List<Object> row, final String columnName, final Class<T> valueClass)
{
final Object valueObj = getRowValueOrNull(metadata, row, columnName);
if (valueObj == null)
{
return null;
}
if (!valueClass.isAssignableFrom(valueObj.getClass()))
{
return null;
}
final T value = valueClass.cast(valueObj);
return value;
}
/**
*
* @param calculationCtx
* @param columnName
* @return true if the status of current calculation is about calculating the row for "columnName" group (subtotals)
*/
protected final boolean isGroupBy(final RModelCalculationContext calculationCtx, final String columnName)
{
final int groupColumnIndex = calculationCtx.getGroupColumnIndex();
if (groupColumnIndex < 0)
{
// no grouping
return false;
}
final IRModelMetadata metadata = calculationCtx.getMetadata();
final int columnIndex = metadata.getRColumnIndex(columnName);
if (columnIndex < 0)
{
return false;
}
return columnIndex == groupColumnIndex;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\compiere\report\core\AbstractRModelAggregatedValue.java | 1 |
请完成以下Java代码 | public class PaymentBatchFactory implements IPaymentBatchFactory
{
private final CopyOnWriteArrayList<IPaymentBatchProvider> providers = new CopyOnWriteArrayList<>();
public PaymentBatchFactory()
{
super();
addPaymentBatchProvider(new PaySelectionPaymentBatchProvider());
}
@Override
public IPaymentBatch retrievePaymentBatch(final I_C_Payment payment)
{
Check.assumeNotNull(payment, "payment not null");
for (final IPaymentBatchProvider provider : providers)
{ | final IPaymentBatch paymentBatch = provider.retrievePaymentBatch(payment);
if (paymentBatch != null)
{
return paymentBatch;
}
}
return null;
}
@Override
public void addPaymentBatchProvider(final IPaymentBatchProvider provider)
{
Check.assumeNotNull(provider, "provider not null");
providers.addIfAbsent(provider);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\bankstatement\match\api\impl\PaymentBatchFactory.java | 1 |
请完成以下Java代码 | public class MD5Util {
private static final String SALT = "tamboo";
public static String encode(String password) {
password = password + SALT;
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {
throw new RuntimeException(e);
}
char[] charArray = password.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++)
byteArray[i] = (byte) charArray[i];
byte[] md5Bytes = md5.digest(byteArray); | StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
public static void main(String[] args) {
System.out.println(MD5Util.encode("abel"));
}
} | repos\springBoot-master\springboot-SpringSecurity0\src\main\java\com\us\example\util\MD5Util.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static MethodSecurityMetadataSourceAdvisor methodSecurityInterceptor(AbstractMethodSecurityMetadataSource source,
ReactiveMethodSecurityConfiguration configuration) {
MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor(
"securityMethodInterceptor", source, "methodMetadataSource");
advisor.setOrder(configuration.advisorOrder);
return advisor;
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
static DelegatingMethodSecurityMetadataSource methodMetadataSource(
MethodSecurityExpressionHandler methodSecurityExpressionHandler) {
ExpressionBasedAnnotationAttributeFactory attributeFactory = new ExpressionBasedAnnotationAttributeFactory(
methodSecurityExpressionHandler);
PrePostAnnotationSecurityMetadataSource prePostSource = new PrePostAnnotationSecurityMetadataSource(
attributeFactory);
return new DelegatingMethodSecurityMetadataSource(Arrays.asList(prePostSource));
}
@Bean
static PrePostAdviceReactiveMethodInterceptor securityMethodInterceptor(AbstractMethodSecurityMetadataSource source,
MethodSecurityExpressionHandler handler) {
ExpressionBasedPostInvocationAdvice postAdvice = new ExpressionBasedPostInvocationAdvice(handler);
ExpressionBasedPreInvocationAdvice preAdvice = new ExpressionBasedPreInvocationAdvice();
preAdvice.setExpressionHandler(handler);
return new PrePostAdviceReactiveMethodInterceptor(source, preAdvice, postAdvice);
} | @Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
@Fallback
static DefaultMethodSecurityExpressionHandler methodSecurityExpressionHandler(
ReactiveMethodSecurityConfiguration configuration) {
DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
if (configuration.grantedAuthorityDefaults != null) {
handler.setDefaultRolePrefix(configuration.grantedAuthorityDefaults.getRolePrefix());
}
return handler;
}
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
this.advisorOrder = (int) importMetadata.getAnnotationAttributes(EnableReactiveMethodSecurity.class.getName())
.get("order");
}
@Autowired(required = false)
void setGrantedAuthorityDefaults(GrantedAuthorityDefaults grantedAuthorityDefaults) {
this.grantedAuthorityDefaults = grantedAuthorityDefaults;
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\ReactiveMethodSecurityConfiguration.java | 2 |
请完成以下Java代码 | public class CircularLinkedList {
final Logger logger = LoggerFactory.getLogger(CircularLinkedList.class);
private Node head = null;
private Node tail = null;
public void addNode(int value) {
Node newNode = new Node(value);
if (head == null) {
head = newNode;
} else {
tail.nextNode = newNode;
}
tail = newNode;
tail.nextNode = head;
}
public boolean containsNode(int searchValue) {
Node currentNode = head;
if (head == null) {
return false;
} else {
do {
if (currentNode.value == searchValue) {
return true;
}
currentNode = currentNode.nextNode;
} while (currentNode != head);
return false;
}
}
public void deleteNode(int valueToDelete) {
Node currentNode = head;
if (head == null) {
return;
}
do {
Node nextNode = currentNode.nextNode;
if (nextNode.value == valueToDelete) {
if (tail == head) {
head = null;
tail = null;
} else {
currentNode.nextNode = nextNode.nextNode;
if (head == nextNode) {
head = head.nextNode;
}
if (tail == nextNode) {
tail = currentNode;
}
}
break; | }
currentNode = nextNode;
} while (currentNode != head);
}
public void traverseList() {
Node currentNode = head;
if (head != null) {
do {
logger.info(currentNode.value + " ");
currentNode = currentNode.nextNode;
} while (currentNode != head);
}
}
}
class Node {
int value;
Node nextNode;
public Node(int value) {
this.value = value;
}
} | repos\tutorials-master\data-structures-2\src\main\java\com\baeldung\circularlinkedlist\CircularLinkedList.java | 1 |
请完成以下Java代码 | public final DefaultPaymentBuilder orderExternalId(@Nullable final String orderExternalId)
{
assertNotBuilt();
if (Check.isNotBlank(orderExternalId))
{
payment.setExternalOrderId(orderExternalId);
}
return this;
}
public final DefaultPaymentBuilder isAutoAllocateAvailableAmt(final boolean isAutoAllocateAvailableAmt)
{
assertNotBuilt();
payment.setIsAutoAllocateAvailableAmt(isAutoAllocateAvailableAmt);
return this; | }
private DefaultPaymentBuilder fromOrder(@NonNull final I_C_Order order)
{
adOrgId(OrgId.ofRepoId(order.getAD_Org_ID()));
orderId(OrderId.ofRepoId(order.getC_Order_ID()));
bpartnerId(BPartnerId.ofRepoId(order.getC_BPartner_ID()));
currencyId(CurrencyId.ofRepoId(order.getC_Currency_ID()));
final SOTrx soTrx = SOTrx.ofBoolean(order.isSOTrx());
direction(PaymentDirection.ofSOTrxAndCreditMemo(soTrx, false));
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\api\DefaultPaymentBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void validateSigningCredentials(Registration properties, boolean signRequest) {
if (signRequest) {
Assert.state(!properties.getSigning().getCredentials().isEmpty(),
"Signing credentials must not be empty when authentication requests require signing.");
}
}
private Saml2X509Credential asSigningCredential(Signing.Credential properties) {
RSAPrivateKey privateKey = readPrivateKey(properties.getPrivateKeyLocation());
X509Certificate certificate = readCertificate(properties.getCertificateLocation());
return new Saml2X509Credential(privateKey, certificate, Saml2X509CredentialType.SIGNING);
}
private Saml2X509Credential asDecryptionCredential(Decryption.Credential properties) {
RSAPrivateKey privateKey = readPrivateKey(properties.getPrivateKeyLocation());
X509Certificate certificate = readCertificate(properties.getCertificateLocation());
return new Saml2X509Credential(privateKey, certificate, Saml2X509CredentialType.DECRYPTION);
}
private Saml2X509Credential asVerificationCredential(Verification.Credential properties) {
X509Certificate certificate = readCertificate(properties.getCertificateLocation());
return new Saml2X509Credential(certificate, Saml2X509Credential.Saml2X509CredentialType.ENCRYPTION,
Saml2X509Credential.Saml2X509CredentialType.VERIFICATION);
}
private RSAPrivateKey readPrivateKey(@Nullable Resource location) {
Assert.state(location != null, "No private key location specified");
Assert.state(location.exists(), () -> "Private key location '" + location + "' does not exist");
try (InputStream inputStream = location.getInputStream()) {
PemContent pemContent = PemContent.load(inputStream);
PrivateKey privateKey = pemContent.getPrivateKey();
Assert.state(privateKey instanceof RSAPrivateKey,
() -> "PrivateKey in resource '" + location + "' must be an RSAPrivateKey");
return (RSAPrivateKey) privateKey;
}
catch (Exception ex) { | throw new IllegalArgumentException(ex);
}
}
private X509Certificate readCertificate(@Nullable Resource location) {
Assert.state(location != null, "No certificate location specified");
Assert.state(location.exists(), () -> "Certificate location '" + location + "' does not exist");
try (InputStream inputStream = location.getInputStream()) {
PemContent pemContent = PemContent.load(inputStream);
List<X509Certificate> certificates = pemContent.getCertificates();
return certificates.get(0);
}
catch (Exception ex) {
throw new IllegalArgumentException(ex);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-security-saml2\src\main\java\org\springframework\boot\security\saml2\autoconfigure\Saml2RelyingPartyRegistrationConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static Object getSQLValueObjectEx(String trxName, String sql, Object... params)
{
Object retValue = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, trxName);
DB.setParameters(pstmt, params);
rs = pstmt.executeQuery();
if (rs.next())
{
retValue = rs.getObject(1);
}
else
{ | logger.info("No Value " + sql);
}
}
catch (SQLException e)
{
throw new DBException(e, sql);
}
finally
{
DB.close(rs, pstmt);
rs = null;
pstmt = null;
}
return retValue;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\service\impl\TableColumnPathBL.java | 2 |
请完成以下Java代码 | void processValueChanges(final List<JSONDocumentChangedEvent> events, final ReasonSupplier reason)
{
assertNotCompleted();
data.processValueChanges(events, reason);
}
public Collection<IDocumentFieldView> getFieldViews()
{
return data.getFieldViews();
}
public JSONASIDocument toJSONASIDocument(
final JSONDocumentOptions docOpts,
final JSONDocumentLayoutOptions layoutOpts)
{
return JSONASIDocument.builder()
.id(data.getDocumentId())
.layout(JSONASILayout.of(getLayout(), layoutOpts))
.fieldsByName(JSONDocument.ofDocument(data, docOpts).getFieldsByName())
.build();
}
public LookupValuesPage getFieldLookupValuesForQuery(final String attributeName, final String query)
{
return data.getFieldLookupValuesForQuery(attributeName, query);
}
public LookupValuesList getFieldLookupValues(final String attributeName)
{
return data.getFieldLookupValues(attributeName);
}
public boolean isCompleted()
{
return completed;
}
IntegerLookupValue complete()
{
assertNotCompleted();
final I_M_AttributeSetInstance asiRecord = createM_AttributeSetInstance(this);
final IntegerLookupValue lookupValue = IntegerLookupValue.of(asiRecord.getM_AttributeSetInstance_ID(), asiRecord.getDescription());
completed = true;
return lookupValue;
} | private static I_M_AttributeSetInstance createM_AttributeSetInstance(final ASIDocument asiDoc)
{
//
// Create M_AttributeSetInstance
final AttributeSetId attributeSetId = asiDoc.getAttributeSetId();
final I_M_AttributeSetInstance asiRecord = InterfaceWrapperHelper.newInstance(I_M_AttributeSetInstance.class);
asiRecord.setM_AttributeSet_ID(attributeSetId.getRepoId());
InterfaceWrapperHelper.save(asiRecord);
//
// Create M_AttributeInstances
asiDoc.getFieldViews()
.forEach(asiField -> asiField
.getDescriptor()
.getDataBindingNotNull(ASIAttributeFieldBinding.class)
.createAndSaveM_AttributeInstance(asiRecord, asiField));
//
// Update the ASI description
Services.get(IAttributeSetInstanceBL.class).setDescription(asiRecord);
InterfaceWrapperHelper.save(asiRecord);
return asiRecord;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pattribute\ASIDocument.java | 1 |
请完成以下Java代码 | public void setServletConfig(@Nullable ServletConfig servletConfig) {
this.servletConfig = servletConfig;
}
@Override
public @Nullable ServletConfig getServletConfig() {
return this.servletConfig;
}
/**
* Returns the {@link WebServer} that was created by the context or {@code null} if
* the server has not yet been created.
* @return the embedded web server
*/
@Override
public @Nullable WebServer getWebServer() {
return this.webServer;
}
/**
* Utility class to store and restore any user defined scopes. This allows scopes to
* be registered in an ApplicationContextInitializer in the same way as they would in
* a classic non-embedded web application context.
*/
public static class ExistingWebApplicationScopes {
private static final Set<String> SCOPES;
static {
Set<String> scopes = new LinkedHashSet<>();
scopes.add(WebApplicationContext.SCOPE_REQUEST);
scopes.add(WebApplicationContext.SCOPE_SESSION);
SCOPES = Collections.unmodifiableSet(scopes);
}
private final ConfigurableListableBeanFactory beanFactory; | private final Map<String, Scope> scopes = new HashMap<>();
public ExistingWebApplicationScopes(ConfigurableListableBeanFactory beanFactory) {
this.beanFactory = beanFactory;
for (String scopeName : SCOPES) {
Scope scope = beanFactory.getRegisteredScope(scopeName);
if (scope != null) {
this.scopes.put(scopeName, scope);
}
}
}
public void restore() {
this.scopes.forEach((key, value) -> {
if (logger.isInfoEnabled()) {
logger.info("Restoring user defined scope " + key);
}
this.beanFactory.registerScope(key, value);
});
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\context\ServletWebServerApplicationContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setTaskAssignee(String taskAssignee) {
this.taskAssignee = taskAssignee;
}
public String getTaskCompletedBy() {
return taskCompletedBy;
}
public void setTaskCompletedBy(String taskCompletedBy) {
this.taskCompletedBy = taskCompletedBy;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
} | public String getTenantIdLike() {
return tenantIdLike;
}
public void setTenantIdLike(String tenantIdLike) {
this.tenantIdLike = tenantIdLike;
}
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Set<String> getProcessInstanceIds() {
return processInstanceIds;
}
public void setProcessInstanceIds(Set<String> processInstanceIds) {
this.processInstanceIds = processInstanceIds;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ActivityInstanceQueryRequest.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.