instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
private void releaseLock()
{
lock.unlock();
log.debug(" {} GithubImporterService: lock released!", IMPORT_LOG_MESSAGE_PREFIX);
}
private void processLabels(final List<Label> labelList,
@NonNull final ImportIssueInfo.ImportIssueInfoBuilder importIssueInfoBuilder,
@NonNull final OrgId orgId)
{
final ImmutableList<ProcessedLabel> processedLabels = labelService.processLabels(labelList);
final List<IssueLabel> issueLabelList = new ArrayList<>();
final List<String> deliveryPlatformList = new ArrayList<>();
BigDecimal budget = BigDecimal.ZERO;
BigDecimal estimation = BigDecimal.ZERO;
BigDecimal roughEstimation = BigDecimal.ZERO;
Optional<Status> status = Optional.empty();
Optional<LocalDate> plannedUATDate = Optional.empty();
Optional<LocalDate> deliveredDate = Optional.empty();
for (final ProcessedLabel label : processedLabels)
{
switch (label.getLabelType())
{
case ESTIMATION:
estimation = estimation.add(NumberUtils.asBigDecimal(label.getExtractedValue(), BigDecimal.ZERO));
break;
case ROUGH_EST:
roughEstimation = roughEstimation.add(NumberUtils.asBigDecimal(label.getExtractedValue(), BigDecimal.ZERO));
break;
case BUDGET:
budget = budget.add(NumberUtils.asBigDecimal(label.getExtractedValue(), BigDecimal.ZERO));
break;
case STATUS:
status = status.isPresent() ? status : Status.ofCodeOptional(label.getExtractedValue());
break;
case DELIVERY_PLATFORM:
deliveryPlatformList.add(label.getExtractedValue());
break;
case PLANNED_UAT:
plannedUATDate = plannedUATDate.isPresent() ? plannedUATDate : getDateFromLabel(label.getExtractedValue());
break;
case DELIVERED_DATE:
deliveredDate = deliveredDate.isPresent() ? deliveredDate : getDateFromLabel(label.getExtractedValue());
|
break;
default:
// nothing to do for UNKNOWN label types
}
issueLabelList.add(IssueLabel.builder().value(label.getLabel()).orgId(orgId).build());
}
importIssueInfoBuilder.budget(budget);
importIssueInfoBuilder.estimation(estimation);
importIssueInfoBuilder.roughEstimation(roughEstimation);
importIssueInfoBuilder.issueLabels(ImmutableList.copyOf(issueLabelList));
status.ifPresent(importIssueInfoBuilder::status);
plannedUATDate.ifPresent(importIssueInfoBuilder::plannedUATDate);
deliveredDate.ifPresent(importIssueInfoBuilder::deliveredDate);
if (!deliveryPlatformList.isEmpty())
{
importIssueInfoBuilder.deliveryPlatform(Joiner.on(",").join(deliveryPlatformList));
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\github\GithubImporterService.java
| 2
|
请完成以下Java代码
|
private static final String getLogicOperatorOrNull(final ILogicExpression expression)
{
if (expression instanceof LogicExpression)
{
final LogicExpression logicExpression = (LogicExpression)expression;
return logicExpression.getOperator();
}
return null;
}
private static final int getOperatorStrength(final String operator)
{
if (operator == null)
{
return -100;
}
else if (LOGIC_OPERATOR_AND.equals(operator))
{
return 20;
}
else if (LOGIC_OPERATOR_OR.equals(operator))
{
return 10;
}
else
{
// unknown operator
throw ExpressionEvaluationException.newWithTranslatableMessage("Unknown operator: " + operator);
}
}
@Override
public Set<CtxName> getParameters()
{
if (_parameters == null)
{
if (isConstant())
{
_parameters = ImmutableSet.of();
}
else
{
final Set<CtxName> result = new LinkedHashSet<>(left.getParameters());
result.addAll(right.getParameters());
_parameters = ImmutableSet.copyOf(result);
}
}
return _parameters;
}
/**
* @return left expression; never null
*/
public ILogicExpression getLeft()
{
return left;
}
/**
|
* @return right expression; never null
*/
public ILogicExpression getRight()
{
return right;
}
/**
* @return logic operator; never null
*/
public String getOperator()
{
return operator;
}
@Override
public String toString()
{
return getExpressionString();
}
@Override
public ILogicExpression evaluatePartial(final Evaluatee ctx)
{
if (isConstant())
{
return this;
}
final ILogicExpression leftExpression = getLeft();
final ILogicExpression newLeftExpression = leftExpression.evaluatePartial(ctx);
final ILogicExpression rightExpression = getRight();
final ILogicExpression newRightExpression = rightExpression.evaluatePartial(ctx);
final String logicOperator = getOperator();
if (newLeftExpression.isConstant() && newRightExpression.isConstant())
{
final BooleanEvaluator logicExprEvaluator = LogicExpressionEvaluator.getBooleanEvaluatorByOperator(logicOperator);
final boolean result = logicExprEvaluator.evaluateOrNull(newLeftExpression::constantValue, newRightExpression::constantValue);
return ConstantLogicExpression.of(result);
}
else if (Objects.equals(leftExpression, newLeftExpression)
&& Objects.equals(rightExpression, newRightExpression))
{
return this;
}
else
{
return LogicExpression.of(newLeftExpression, logicOperator, newRightExpression);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\LogicExpression.java
| 1
|
请完成以下Java代码
|
private boolean isExisting() {
try {
return transactionManager.getStatus() != Status.STATUS_NO_TRANSACTION;
} catch (SystemException e) {
throw new TransactionException("Unable to retrieve transaction status", e);
}
}
private Transaction doSuspend() {
try {
return transactionManager.suspend();
} catch (SystemException e) {
throw new TransactionException("Unable to suspend transaction", e);
}
}
private void doResume(Transaction tx) {
if (tx != null) {
try {
transactionManager.resume(tx);
} catch (SystemException e) {
throw new TransactionException("Unable to resume transaction", e);
} catch (InvalidTransactionException e) {
throw new TransactionException("Unable to resume transaction", e);
}
}
}
private void doCommit() {
try {
transactionManager.commit();
} catch (HeuristicMixedException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (HeuristicRollbackException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (RollbackException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (SystemException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (RuntimeException e) {
doRollback(true, e);
throw e;
} catch (Error e) {
doRollback(true, e);
throw e;
}
}
private void doRollback(boolean isNew, Throwable originalException) {
Throwable rollbackEx = null;
try {
if (isNew) {
transactionManager.rollback();
} else {
|
transactionManager.setRollbackOnly();
}
} catch (SystemException e) {
LOGGER.debug("Error when rolling back transaction", e);
} catch (RuntimeException e) {
rollbackEx = e;
throw e;
} catch (Error e) {
rollbackEx = e;
throw e;
} finally {
if (rollbackEx != null && originalException != null) {
LOGGER.error("Error when rolling back transaction, original exception was:", originalException);
}
}
}
private static class TransactionException extends RuntimeException {
private static final long serialVersionUID = 1L;
private TransactionException() {}
private TransactionException(String s) {
super(s);
}
private TransactionException(String s, Throwable throwable) {
super(s, throwable);
}
private TransactionException(Throwable throwable) {
super(throwable);
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\interceptor\JtaTransactionInterceptor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setResource(String resource) {
this.resource = resource;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-repository/deployments/2/resources/testCase.cmmn", value = "Contains the actual deployed CMMN 1.1 xml.")
public String getResource() {
return resource;
}
@ApiModelProperty(example = "This is a case for testing purposes")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setDiagramResource(String diagramResource) {
this.diagramResource = diagramResource;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-repository/deployments/2/resources/testProcess.png", value = "Contains a graphical representation of the case, null when no diagram is available.")
public String getDiagramResource() {
return diagramResource;
|
}
public void setGraphicalNotationDefined(boolean graphicalNotationDefined) {
this.graphicalNotationDefined = graphicalNotationDefined;
}
@ApiModelProperty(value = "Indicates the case definition contains graphical information (CMMN DI).")
public boolean isGraphicalNotationDefined() {
return graphicalNotationDefined;
}
public void setStartFormDefined(boolean startFormDefined) {
this.startFormDefined = startFormDefined;
}
public boolean isStartFormDefined() {
return startFormDefined;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\CaseDefinitionResponse.java
| 2
|
请完成以下Java代码
|
public void startProcessInstanceByKeyForm() {
if (FacesContext.getCurrentInstance().isPostback()) {
// if this is an AJAX request ignore it, since we will receive multiple calls to this bean if it is added
// as preRenderView event
// see http://stackoverflow.com/questions/2830834/jsf-fevent-prerenderview-is-triggered-by-fajax-calls-and-partial-renders-some
return;
}
Map<String, String> requestParameterMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
String processDefinitionKey = requestParameterMap.get("processDefinitionKey");
String callbackUrl = requestParameterMap.get("callbackUrl");
this.url = callbackUrl;
this.processDefinitionKey = processDefinitionKey;
beginConversation();
}
public void completeProcessInstanceForm() throws IOException {
// start the process instance
if (processDefinitionId!=null) {
businessProcess.startProcessById(processDefinitionId);
processDefinitionId = null;
} else {
businessProcess.startProcessByKey(processDefinitionKey);
processDefinitionKey = null;
}
// End the conversation
conversationInstance.get().end();
|
// and redirect
FacesContext.getCurrentInstance().getExternalContext().redirect(url);
}
public ProcessDefinition getProcessDefinition() {
// TODO cache result to avoid multiple queries within one page request
if (processDefinitionId!=null) {
return repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult();
} else {
return repositoryService.createProcessDefinitionQuery().processDefinitionKey(processDefinitionKey).latestVersion().singleResult();
}
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
|
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\jsf\TaskForm.java
| 1
|
请完成以下Java代码
|
protected Edge makeEdge(Node[] nodeArray, int from, int to)
{
LinkedList<String> context = new LinkedList<String>();
int index = from;
for (int i = index - 2; i < index + 2 + 1; ++i)
{
Node w = i >= 0 && i < nodeArray.length ? nodeArray[i] : Node.NULL;
context.add(w.compiledWord + "i" + (i - index)); // 在尾巴上做个标记,不然特征冲突了
context.add(w.label + "i" + (i - index));
}
index = to;
for (int i = index - 2; i < index + 2 + 1; ++i)
{
Node w = i >= 0 && i < nodeArray.length ? nodeArray[i] : Node.NULL;
context.add(w.compiledWord + "j" + (i - index)); // 在尾巴上做个标记,不然特征冲突了
context.add(w.label + "j" + (i - index));
}
context.add(nodeArray[from].compiledWord + '→' + nodeArray[to].compiledWord);
context.add(nodeArray[from].label + '→' + nodeArray[to].label);
context.add(nodeArray[from].compiledWord + '→' + nodeArray[to].compiledWord + (from - to));
context.add(nodeArray[from].label + '→' + nodeArray[to].label + (from - to));
Node wordBeforeI = from - 1 >= 0 ? nodeArray[from - 1] : Node.NULL;
Node wordBeforeJ = to - 1 >= 0 ? nodeArray[to - 1] : Node.NULL;
|
context.add(wordBeforeI.compiledWord + '@' + nodeArray[from].compiledWord + '→' + nodeArray[to].compiledWord);
context.add(nodeArray[from].compiledWord + '→' + wordBeforeJ.compiledWord + '@' + nodeArray[to].compiledWord);
context.add(wordBeforeI.label + '@' + nodeArray[from].label + '→' + nodeArray[to].label);
context.add(nodeArray[from].label + '→' + wordBeforeJ.label + '@' + nodeArray[to].label);
List<Pair<String, Double>> pairList = model.predict(context.toArray(new String[0]));
Pair<String, Double> maxPair = new Pair<String, Double>("null", -1.0);
// System.out.println(context);
// System.out.println(pairList);
for (Pair<String, Double> pair : pairList)
{
if (pair.getValue() > maxPair.getValue() && !"null".equals(pair.getKey()))
{
maxPair = pair;
}
}
// System.out.println(nodeArray[from].word + "→" + nodeArray[to].word + " : " + maxPair);
return new Edge(from, to, maxPair.getKey(), (float) - Math.log(maxPair.getValue()));
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\MaxEntDependencyParser.java
| 1
|
请完成以下Java代码
|
protected ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
}
protected CommandExecutor getCommandExecutor() {
return getProcessEngineConfiguration().getCommandExecutor();
}
protected Clock getClock() {
return getProcessEngineConfiguration().getClock();
}
protected AsyncExecutor getAsyncExecutor() {
return getProcessEngineConfiguration().getAsyncExecutor();
}
protected FlowableEventDispatcher getEventDispatcher() {
return getProcessEngineConfiguration().getEventDispatcher();
}
protected HistoryManager getHistoryManager() {
return getProcessEngineConfiguration().getHistoryManager();
}
protected DeploymentEntityManager getDeploymentEntityManager() {
return getProcessEngineConfiguration().getDeploymentEntityManager();
}
protected ResourceEntityManager getResourceEntityManager() {
return getProcessEngineConfiguration().getResourceEntityManager();
}
protected ByteArrayEntityManager getByteArrayEntityManager() {
return getProcessEngineConfiguration().getByteArrayEntityManager();
}
protected ProcessDefinitionEntityManager getProcessDefinitionEntityManager() {
return getProcessEngineConfiguration().getProcessDefinitionEntityManager();
}
protected ProcessDefinitionInfoEntityManager getProcessDefinitionInfoEntityManager() {
return getProcessEngineConfiguration().getProcessDefinitionInfoEntityManager();
}
protected ModelEntityManager getModelEntityManager() {
return getProcessEngineConfiguration().getModelEntityManager();
}
protected ExecutionEntityManager getExecutionEntityManager() {
return getProcessEngineConfiguration().getExecutionEntityManager();
}
|
protected ActivityInstanceEntityManager getActivityInstanceEntityManager() {
return getProcessEngineConfiguration().getActivityInstanceEntityManager();
}
protected HistoricProcessInstanceEntityManager getHistoricProcessInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricProcessInstanceEntityManager();
}
protected HistoricDetailEntityManager getHistoricDetailEntityManager() {
return getProcessEngineConfiguration().getHistoricDetailEntityManager();
}
protected HistoricActivityInstanceEntityManager getHistoricActivityInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricActivityInstanceEntityManager();
}
protected AttachmentEntityManager getAttachmentEntityManager() {
return getProcessEngineConfiguration().getAttachmentEntityManager();
}
protected CommentEntityManager getCommentEntityManager() {
return getProcessEngineConfiguration().getCommentEntityManager();
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\AbstractManager.java
| 1
|
请完成以下Java代码
|
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public Date getRemovalTime() {
return removalTime;
}
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", processDefinitionKey=" + processDefinitionKey
|
+ ", processDefinitionId=" + processDefinitionId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", removalTime=" + removalTime
+ ", processInstanceId=" + processInstanceId
+ ", taskId=" + taskId
+ ", executionId=" + executionId
+ ", tenantId=" + tenantId
+ ", activityInstanceId=" + activityInstanceId
+ ", caseDefinitionKey=" + caseDefinitionKey
+ ", caseDefinitionId=" + caseDefinitionId
+ ", caseInstanceId=" + caseInstanceId
+ ", caseExecutionId=" + caseExecutionId
+ ", name=" + name
+ ", createTime=" + createTime
+ ", revision=" + revision
+ ", serializerName=" + getSerializerName()
+ ", longValue=" + longValue
+ ", doubleValue=" + doubleValue
+ ", textValue=" + textValue
+ ", textValue2=" + textValue2
+ ", state=" + state
+ ", byteArrayId=" + getByteArrayId()
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricVariableInstanceEntity.java
| 1
|
请完成以下Java代码
|
public boolean hasInstructionReports() {
return !instructionReports.isEmpty();
}
public List<MigrationInstructionValidationReport> getInstructionReports() {
return instructionReports;
}
@Override
public boolean hasVariableReports() {
return !variableReports.isEmpty();
}
@Override
public Map<String, MigrationVariableValidationReport> getVariableReports() {
return variableReports;
}
public void writeTo(StringBuilder sb) {
sb.append("Migration plan for process definition '")
.append(migrationPlan.getSourceProcessDefinitionId())
.append("' to '")
.append(migrationPlan.getTargetProcessDefinitionId())
.append("' is not valid:\n");
|
for (MigrationInstructionValidationReport instructionReport : instructionReports) {
sb.append("\t Migration instruction ").append(instructionReport.getMigrationInstruction()).append(" is not valid:\n");
for (String failure : instructionReport.getFailures()) {
sb.append("\t\t").append(failure).append("\n");
}
}
variableReports.forEach((name, report) -> {
sb.append("\t Migration variable ").append(name).append(" is not valid:\n");
for (String failure : report.getFailures()) {
sb.append("\t\t").append(failure).append("\n");
}
});
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\validation\instruction\MigrationPlanValidationReportImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
DefaultCodecCustomizer defaultCodecCustomizer(HttpCodecsProperties httpCodecProperties) {
return new DefaultCodecCustomizer(httpCodecProperties.isLogRequestDetails(),
httpCodecProperties.getMaxInMemorySize());
}
static final class DefaultCodecCustomizer implements CodecCustomizer, Ordered {
private final boolean logRequestDetails;
private final @Nullable DataSize maxInMemorySize;
DefaultCodecCustomizer(boolean logRequestDetails, @Nullable DataSize maxInMemorySize) {
this.logRequestDetails = logRequestDetails;
this.maxInMemorySize = maxInMemorySize;
}
@Override
public void customize(CodecConfigurer configurer) {
PropertyMapper map = PropertyMapper.get();
CodecConfigurer.DefaultCodecs defaultCodecs = configurer.defaultCodecs();
defaultCodecs.enableLoggingRequestDetails(this.logRequestDetails);
map.from(this.maxInMemorySize).asInt(DataSize::toBytes).to(defaultCodecs::maxInMemorySize);
}
@Override
public int getOrder() {
|
return 0;
}
}
}
static class NoJacksonOrJackson2Preferred extends AnyNestedCondition {
NoJacksonOrJackson2Preferred() {
super(ConfigurationPhase.PARSE_CONFIGURATION);
}
@ConditionalOnMissingClass("tools.jackson.databind.json.JsonMapper")
static class NoJackson {
}
@ConditionalOnProperty(name = "spring.http.codecs.preferred-json-mapper", havingValue = "jackson2")
static class Jackson2Preferred {
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-http-codec\src\main\java\org\springframework\boot\http\codec\autoconfigure\CodecsAutoConfiguration.java
| 2
|
请完成以下Java代码
|
protected static DmnTypeDefinition createTypeDefinition(DmnElementTransformContext context, String typeRef) {
if (typeRef != null) {
DmnDataTypeTransformer transformer = context.getDataTypeTransformerRegistry().getTransformer(typeRef);
return new DmnTypeDefinitionImpl(typeRef, transformer);
}
else {
return new DefaultTypeDefinition();
}
}
public static String getExpressionLanguage(DmnElementTransformContext context, LiteralExpression expression) {
return getExpressionLanguage(context, expression.getExpressionLanguage());
}
public static String getExpressionLanguage(DmnElementTransformContext context, UnaryTests expression) {
return getExpressionLanguage(context, expression.getExpressionLanguage());
}
protected static String getExpressionLanguage(DmnElementTransformContext context, String expressionLanguage) {
if (expressionLanguage != null) {
return expressionLanguage;
}
else {
return getGlobalExpressionLanguage(context);
}
}
protected static String getGlobalExpressionLanguage(DmnElementTransformContext context) {
String expressionLanguage = context.getModelInstance().getDefinitions().getExpressionLanguage();
if (!DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE.equals(expressionLanguage) &&
!DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN12.equals(expressionLanguage) &&
!DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN13.equals(expressionLanguage) &&
!DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN14.equals(expressionLanguage) &&
!DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN15.equals(expressionLanguage)) {
return expressionLanguage;
}
else {
return null;
}
}
|
public static String getExpression(LiteralExpression expression) {
return getExpression(expression.getText());
}
public static String getExpression(UnaryTests expression) {
return getExpression(expression.getText());
}
protected static String getExpression(Text text) {
if (text != null) {
String textContent = text.getTextContent();
if (textContent != null && !textContent.isEmpty()) {
return textContent;
}
}
return null;
}
}
|
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\transform\DmnExpressionTransformHelper.java
| 1
|
请完成以下Java代码
|
public void generateShipperDeliveryOrderIfPossible(
@NonNull final ShipperId shipperId,
@NonNull final ShipperTransportationId shipperTransportationId,
@NonNull final Collection<I_M_Package> packages,
@Nullable final AsyncBatchId asyncBatchId)
{
final ShipperGatewayId shipperGatewayId = shipperDAO.getShipperGatewayId(shipperId).orElse(null);
// no ShipperGateway, so no API to call/no courier to request
if (shipperGatewayId == null)
{
return;
}
if (!shipperGatewayFacade.hasServiceSupport(shipperGatewayId))
{
return;
}
final Set<Integer> mPackageIds = packages.stream()
.map(I_M_Package::getM_Package_ID)
.collect(ImmutableSet.toImmutableSet());
final I_M_ShipperTransportation shipperTransportation = load(shipperTransportationId, I_M_ShipperTransportation.class);
final DeliveryOrderCreateRequest request = DeliveryOrderCreateRequest.builder()
.pickupDate(getPickupDate(shipperTransportation))
.timeFrom(TimeUtil.asLocalTime(shipperTransportation.getPickupTimeFrom()))
.timeTo(TimeUtil.asLocalTime(shipperTransportation.getPickupTimeTo()))
.packageIds(mPackageIds)
|
.shipperTransportationId(shipperTransportationId)
.shipperGatewayId(shipperGatewayId)
.asyncBatchId(asyncBatchId)
.build();
shipperGatewayFacade.createAndSendDeliveryOrdersForPackages(request);
}
private LocalDate getPickupDate(@NonNull final I_M_ShipperTransportation shipperTransportation)
{
final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(shipperTransportation.getAD_Org_ID()));
return CoalesceUtil.coalesceNotNull(
TimeUtil.asLocalDate(shipperTransportation.getDateToBeFetched(), timeZone),
TimeUtil.asLocalDate(shipperTransportation.getDateDoc(), timeZone));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\inoutcandidate\shippertransportation\ShipperDeliveryService.java
| 1
|
请完成以下Java代码
|
public class KafkaTopicApplication {
private final Properties properties;
public KafkaTopicApplication(Properties properties) {
this.properties = properties;
}
public void createTopic(String topicName) throws Exception {
try (Admin admin = Admin.create(properties)) {
int partitions = 1;
short replicationFactor = 1;
NewTopic newTopic = new NewTopic(topicName, partitions, replicationFactor);
CreateTopicsResult result = admin.createTopics(Collections.singleton(newTopic));
// get the async result for the new topic creation
KafkaFuture<Void> future = result.values()
.get(topicName);
// call get() to block until topic creation has completed or failed
future.get();
}
}
public void createTopicWithOptions(String topicName) throws Exception {
Properties props = new Properties();
props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
try (Admin admin = Admin.create(props)) {
int partitions = 1;
short replicationFactor = 1;
NewTopic newTopic = new NewTopic(topicName, partitions, replicationFactor);
CreateTopicsOptions topicOptions = new CreateTopicsOptions().validateOnly(true)
.retryOnQuotaViolation(true);
|
CreateTopicsResult result = admin.createTopics(Collections.singleton(newTopic), topicOptions);
KafkaFuture<Void> future = result.values()
.get(topicName);
future.get();
}
}
public void createCompactedTopicWithCompression(String topicName) throws Exception {
Properties props = new Properties();
props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
try (Admin admin = Admin.create(props)) {
int partitions = 1;
short replicationFactor = 1;
// Create a compacted topic with 'lz4' compression codec
Map<String, String> newTopicConfig = new HashMap<>();
newTopicConfig.put(TopicConfig.CLEANUP_POLICY_CONFIG, TopicConfig.CLEANUP_POLICY_COMPACT);
newTopicConfig.put(TopicConfig.COMPRESSION_TYPE_CONFIG, "lz4");
NewTopic newTopic = new NewTopic(topicName, partitions, replicationFactor).configs(newTopicConfig);
CreateTopicsResult result = admin.createTopics(Collections.singleton(newTopic));
KafkaFuture<Void> future = result.values()
.get(topicName);
future.get();
}
}
}
|
repos\tutorials-master\apache-kafka-2\src\main\java\com\baeldung\kafka\admin\KafkaTopicApplication.java
| 1
|
请完成以下Java代码
|
public class Person {
private int id;
private String name;
public Person(String json) {
Gson gson = new Gson();
Person request = gson.fromJson(json, Person.class);
this.id = request.getId();
this.name = request.getName();
}
public String toString() {
final Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(this);
}
|
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
repos\tutorials-master\aws-modules\aws-lambda-modules\lambda-function\src\main\java\com\baeldung\lambda\apigateway\model\Person.java
| 1
|
请完成以下Java代码
|
public Quantity getQtyInSourceUOM()
{
return pickFromHUs.stream()
.map(PickFromHU::getQtyToPick)
.reduce(Quantity::add)
.orElseThrow(() -> new AdempiereException("No HUs"));
}
public Quantity getQtyInStockingUOM()
{
return pickFromHUs.stream()
.map(PickFromHU::getQtyToPickInStockingUOM)
.reduce(Quantity::add)
.orElseThrow(() -> new AdempiereException("No HUs"));
}
public I_M_HU_PI_Item_Product getM_HU_PI_Item_Product()
{
return piItemProduct;
}
public List<PickFromHU> getPickFromHUs()
{
return pickFromHUs;
}
public String getDescription()
{
final StringBuilder description = new StringBuilder();
for (final PickFromHU pickFromHU : pickFromHUs)
{
final String huValue = String.valueOf(pickFromHU.getHuId().getRepoId());
if (description.length() > 0)
{
description.append(", ");
}
description.append(huValue);
}
description.insert(0, Services.get(IMsgBL.class).translate(Env.getCtx(), "M_HU_ID") + ": ");
|
return description.toString();
}
public LotNumberQuarantine getLotNumberQuarantine()
{
return lotNoQuarantine;
}
public Map<I_M_Attribute, Object> getAttributes()
{
return attributes;
}
//
// ---------------------------------------------------------------
//
@Value
@Builder
public static class PickFromHU
{
@NonNull HuId huId;
@NonNull Quantity qtyToPick;
@NonNull Quantity qtyToPickInStockingUOM;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\producer\DDOrderLineCandidate.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SpringProcessEngineServicesConfiguration implements ProcessEngineServices {
@Autowired
private ProcessEngine processEngine;
@Bean(name = "runtimeService")
@Override
public RuntimeService getRuntimeService() {
return processEngine.getRuntimeService();
}
@Bean(name = "repositoryService")
@Override
public RepositoryService getRepositoryService() {
return processEngine.getRepositoryService();
}
@Bean(name = "formService")
@Override
public FormService getFormService() {
return processEngine.getFormService();
}
@Bean(name = "taskService")
@Override
public TaskService getTaskService() {
return processEngine.getTaskService();
}
@Bean(name = "historyService")
@Override
public HistoryService getHistoryService() {
return processEngine.getHistoryService();
}
@Bean(name = "identityService")
@Override
public IdentityService getIdentityService() {
return processEngine.getIdentityService();
}
@Bean(name = "managementService")
|
@Override
public ManagementService getManagementService() {
return processEngine.getManagementService();
}
@Bean(name = "authorizationService")
@Override
public AuthorizationService getAuthorizationService() {
return processEngine.getAuthorizationService();
}
@Bean(name = "caseService")
@Override
public CaseService getCaseService() {
return processEngine.getCaseService();
}
@Bean(name = "filterService")
@Override
public FilterService getFilterService() {
return processEngine.getFilterService();
}
@Bean(name = "externalTaskService")
@Override
public ExternalTaskService getExternalTaskService() {
return processEngine.getExternalTaskService();
}
@Bean(name = "decisionService")
@Override
public DecisionService getDecisionService() {
return processEngine.getDecisionService();
}
}
|
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\SpringProcessEngineServicesConfiguration.java
| 2
|
请完成以下Java代码
|
public class Code implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@Schema(description = "主键")
@TableId(value = "id", type = IdType.ASSIGN_ID)
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
/**
* 数据源主键
*/
@Schema(description = "数据源主键")
@JsonSerialize(using = ToStringSerializer.class)
private Long datasourceId;
/**
* 模块名称
*/
@Schema(description = "服务名称")
private String serviceName;
/**
* 模块名称
*/
@Schema(description = "模块名称")
private String codeName;
/**
* 表名
*/
@Schema(description = "表名")
private String tableName;
/**
* 实体名
*/
@Schema(description = "表前缀")
private String tablePrefix;
/**
* 主键名
*/
@Schema(description = "主键名")
private String pkName;
/**
* 基础业务模式
*/
@Schema(description = "基础业务模式")
|
private Integer baseMode;
/**
* 包装器模式
*/
@Schema(description = "包装器模式")
private Integer wrapMode;
/**
* 后端包名
*/
@Schema(description = "后端包名")
private String packageName;
/**
* 后端路径
*/
@Schema(description = "后端路径")
private String apiPath;
/**
* 前端路径
*/
@Schema(description = "前端路径")
private String webPath;
/**
* 是否已删除
*/
@TableLogic
@Schema(description = "是否已删除")
private Integer isDeleted;
}
|
repos\SpringBlade-master\blade-ops\blade-develop\src\main\java\org\springblade\develop\entity\Code.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static class NettyDriverConfiguration {
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
NettyDriverMongoClientSettingsBuilderCustomizer nettyDriverCustomizer(
ObjectProvider<MongoClientSettings> settings) {
return new NettyDriverMongoClientSettingsBuilderCustomizer(settings);
}
}
/**
* {@link MongoClientSettingsBuilderCustomizer} to apply Mongo client settings.
*/
static final class NettyDriverMongoClientSettingsBuilderCustomizer
implements MongoClientSettingsBuilderCustomizer, DisposableBean {
private final ObjectProvider<MongoClientSettings> settings;
private volatile @Nullable EventLoopGroup eventLoopGroup;
NettyDriverMongoClientSettingsBuilderCustomizer(ObjectProvider<MongoClientSettings> settings) {
this.settings = settings;
}
@Override
public void customize(Builder builder) {
if (!isCustomTransportConfiguration(this.settings.getIfAvailable())) {
|
EventLoopGroup eventLoopGroup = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory());
this.eventLoopGroup = eventLoopGroup;
builder.transportSettings(TransportSettings.nettyBuilder().eventLoopGroup(eventLoopGroup).build());
}
}
@Override
public void destroy() {
EventLoopGroup eventLoopGroup = this.eventLoopGroup;
if (eventLoopGroup != null) {
eventLoopGroup.shutdownGracefully().awaitUninterruptibly();
this.eventLoopGroup = null;
}
}
private boolean isCustomTransportConfiguration(@Nullable MongoClientSettings settings) {
return settings != null && settings.getTransportSettings() != null;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-mongodb\src\main\java\org\springframework\boot\mongodb\autoconfigure\MongoReactiveAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public CmmnDiShape getCurrentDiShape() {
return currentDiShape;
}
public void setCurrentDiShape(CmmnDiShape currentDiShape) {
this.currentDiShape = currentDiShape;
}
public CmmnDiEdge getCurrentDiEdge() {
return currentDiEdge;
}
public void setCurrentDiEdge(CmmnDiEdge currentDiEdge) {
this.currentDiEdge = currentDiEdge;
}
public List<Stage> getStages() {
return stages;
}
public List<PlanFragment> getPlanFragments() {
return planFragments;
}
public List<Criterion> getEntryCriteria() {
return entryCriteria;
}
public List<Criterion> getExitCriteria() {
return exitCriteria;
}
public List<Sentry> getSentries() {
return sentries;
}
public List<SentryOnPart> getSentryOnParts() {
return sentryOnParts;
}
public List<SentryIfPart> getSentryIfParts() {
|
return sentryIfParts;
}
public List<PlanItem> getPlanItems() {
return planItems;
}
public List<PlanItemDefinition> getPlanItemDefinitions() {
return planItemDefinitions;
}
public List<CmmnDiShape> getDiShapes() {
return diShapes;
}
public List<CmmnDiEdge> getDiEdges() {
return diEdges;
}
public GraphicInfo getCurrentLabelGraphicInfo() {
return currentLabelGraphicInfo;
}
public void setCurrentLabelGraphicInfo(GraphicInfo labelGraphicInfo) {
this.currentLabelGraphicInfo = labelGraphicInfo;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\ConversionHelper.java
| 1
|
请完成以下Java代码
|
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParentid() {
return parentid;
}
public void setParentid(String parentid) {
this.parentid = parentid;
}
public String getFinancial() {
return financial;
}
public void setFinancial(String financial) {
this.financial = financial;
}
public String getContactman() {
return contactman;
}
public void setContactman(String contactman) {
this.contactman = contactman;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCantonlev() {
return cantonlev;
}
public void setCantonlev(String cantonlev) {
this.cantonlev = cantonlev;
}
public String getTaxorgcode() {
return taxorgcode;
|
}
public void setTaxorgcode(String taxorgcode) {
this.taxorgcode = taxorgcode;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public String getUsing() {
return using;
}
public void setUsing(String using) {
this.using = using;
}
public String getUsingdate() {
return usingdate;
}
public void setUsingdate(String usingdate) {
this.usingdate = usingdate;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public String getEnd() {
return end;
}
public void setEnd(String end) {
this.end = end;
}
public String getQrcantonid() {
return qrcantonid;
}
public void setQrcantonid(String qrcantonid) {
this.qrcantonid = qrcantonid;
}
public String getDeclare() {
return declare;
}
public void setDeclare(String declare) {
this.declare = declare;
}
public String getDeclareisend() {
return declareisend;
}
public void setDeclareisend(String declareisend) {
this.declareisend = declareisend;
}
}
|
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\canton\Canton.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SysDepartRolePermissionServiceImpl extends ServiceImpl<SysDepartRolePermissionMapper, SysDepartRolePermission> implements ISysDepartRolePermissionService {
@Override
public void saveDeptRolePermission(String roleId, String permissionIds, String lastPermissionIds) {
String ip = "";
try {
//获取request
HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
//获取IP地址
ip = IpUtils.getIpAddr(request);
} catch (Exception e) {
ip = "127.0.0.1";
}
List<String> add = getDiff(lastPermissionIds,permissionIds);
if(add!=null && add.size()>0) {
List<SysDepartRolePermission> list = new ArrayList<SysDepartRolePermission>();
for (String p : add) {
if(oConvertUtils.isNotEmpty(p)) {
SysDepartRolePermission rolepms = new SysDepartRolePermission(roleId, p);
rolepms.setOperateDate(new Date());
rolepms.setOperateIp(ip);
list.add(rolepms);
}
}
this.saveBatch(list);
}
List<String> delete = getDiff(permissionIds,lastPermissionIds);
if(delete!=null && delete.size()>0) {
for (String permissionId : delete) {
this.remove(new QueryWrapper<SysDepartRolePermission>().lambda().eq(SysDepartRolePermission::getRoleId, roleId).eq(SysDepartRolePermission::getPermissionId, permissionId));
}
}
}
/**
* 从diff中找出main中没有的元素
* @param main
* @param diff
|
* @return
*/
private List<String> getDiff(String main, String diff){
if(oConvertUtils.isEmpty(diff)) {
return null;
}
if(oConvertUtils.isEmpty(main)) {
return Arrays.asList(diff.split(","));
}
String[] mainArr = main.split(",");
String[] diffArr = diff.split(",");
Map<String, Integer> map = new HashMap(5);
for (String string : mainArr) {
map.put(string, 1);
}
List<String> res = new ArrayList<String>();
for (String key : diffArr) {
if(oConvertUtils.isNotEmpty(key) && !map.containsKey(key)) {
res.add(key);
}
}
return res;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysDepartRolePermissionServiceImpl.java
| 2
|
请完成以下Java代码
|
public DDOrderCandidateId getIdNotNull() {return Check.assumeNotNull(getId(), "candidate shall be saved: {}", this);}
public OrgId getOrgId() {return getClientAndOrgId().getOrgId();}
public DDOrderCandidate withForwardPPOrderId(@Nullable final PPOrderId newPPOrderId)
{
final PPOrderRef forwardPPOrderRefNew = PPOrderRef.withPPOrderId(forwardPPOrderRef, newPPOrderId);
if (Objects.equals(this.forwardPPOrderRef, forwardPPOrderRefNew))
{
return this;
}
return toBuilder().forwardPPOrderRef(forwardPPOrderRefNew).build();
}
public Quantity getQtyToProcess() {return getQtyEntered().subtract(getQtyProcessed());}
public void setQtyProcessed(final @NonNull Quantity qtyProcessed)
{
Quantity.assertSameUOM(this.qtyEntered, qtyProcessed);
this.qtyProcessed = qtyProcessed;
|
updateProcessed();
}
@Nullable
public OrderId getSalesOrderId()
{
return salesOrderLineId != null ? salesOrderLineId.getOrderId() : null;
}
private void updateProcessed()
{
this.processed = getQtyToProcess().signum() == 0;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddordercandidate\DDOrderCandidate.java
| 1
|
请完成以下Java代码
|
public class ConfigurationException extends AdempiereException
{
public static final ConfigurationException wrapIfNeeded(final Throwable throwable)
{
if (throwable == null)
{
return null;
}
else if (throwable instanceof ConfigurationException)
{
return (ConfigurationException)throwable;
}
final Throwable cause = extractCause(throwable);
if (cause != throwable)
{
return wrapIfNeeded(cause);
}
|
// default
return new ConfigurationException(cause.getLocalizedMessage(), cause);
}
/**
*
*/
private static final long serialVersionUID = -5463410167655542710L;
public ConfigurationException(String message)
{
super(message);
}
public ConfigurationException(String message, Throwable cause)
{
super(message, cause);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\exceptions\ConfigurationException.java
| 1
|
请完成以下Java代码
|
public class User {
private Long uid; // 用户id
private String uname; // 登录名,不可改
private String nick; // 用户昵称,可改
private String pwd; // 已加密的登录密码
private String salt; // 加密盐值
private Date created; // 创建时间
private Date updated; // 修改时间
private Set<String> roles = new HashSet<>(); //用户所有角色值,用于shiro做角色权限的判断
private Set<String> perms = new HashSet<>(); //用户所有权限值,用于shiro做资源权限的判断
public Long getUid() {
return uid;
}
public void setUid(Long uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getNick() {
return nick;
}
public void setNick(String nick) {
this.nick = nick;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public Date getCreated() {
|
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
public Set<String> getRoles() {
return roles;
}
public void setRoles(Set<String> roles) {
this.roles = roles;
}
public Set<String> getPerms() {
return perms;
}
public void setPerms(Set<String> perms) {
this.perms = perms;
}
}
|
repos\spring-boot-quick-master\quick-spring-shiro\src\main\java\com\shiro\entity\User.java
| 1
|
请完成以下Java代码
|
public void addInOut(final I_M_InOut inOut)
{
if (storeInOuts)
{
// Avoid an internal transaction name to slip out to external world
InterfaceWrapperHelper.setTrxName(inOut, ITrx.TRXNAME_ThreadInherited);
inouts.add(inOut);
}
inoutCount++;
}
@Override
public List<I_M_InOut> getInOuts()
{
if (!storeInOuts)
{
|
throw new AdempiereException("Cannot provide the generated shipments because the result was not configured to retain them");
}
return inoutsRO;
}
@Override
public int getInOutCount()
{
if (storeInOuts)
{
return inouts.size();
}
return inoutCount;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\DefaultInOutGenerateResult.java
| 1
|
请完成以下Java代码
|
public long findProcessDefinitionCountByQueryCriteria(ProcessDefinitionQueryImpl processDefinitionQuery) {
return processDefinitionDataManager.findProcessDefinitionCountByQueryCriteria(processDefinitionQuery);
}
@Override
public ProcessDefinitionEntity findProcessDefinitionByDeploymentAndKey(
String deploymentId,
String processDefinitionKey
) {
return processDefinitionDataManager.findProcessDefinitionByDeploymentAndKey(deploymentId, processDefinitionKey);
}
@Override
public ProcessDefinitionEntity findProcessDefinitionByDeploymentAndKeyAndTenantId(
String deploymentId,
String processDefinitionKey,
String tenantId
) {
return processDefinitionDataManager.findProcessDefinitionByDeploymentAndKeyAndTenantId(
deploymentId,
processDefinitionKey,
tenantId
);
}
@Override
public ProcessDefinition findProcessDefinitionByKeyAndVersionAndTenantId(
String processDefinitionKey,
Integer processDefinitionVersion,
String tenantId
) {
if (tenantId == null || ProcessEngineConfiguration.NO_TENANT_ID.equals(tenantId)) {
return processDefinitionDataManager.findProcessDefinitionByKeyAndVersion(
processDefinitionKey,
processDefinitionVersion
);
} else {
return processDefinitionDataManager.findProcessDefinitionByKeyAndVersionAndTenantId(
processDefinitionKey,
processDefinitionVersion,
tenantId
);
}
}
@Override
public List<ProcessDefinition> findProcessDefinitionsByNativeQuery(
|
Map<String, Object> parameterMap,
int firstResult,
int maxResults
) {
return processDefinitionDataManager.findProcessDefinitionsByNativeQuery(parameterMap, firstResult, maxResults);
}
@Override
public long findProcessDefinitionCountByNativeQuery(Map<String, Object> parameterMap) {
return processDefinitionDataManager.findProcessDefinitionCountByNativeQuery(parameterMap);
}
@Override
public void updateProcessDefinitionTenantIdForDeployment(String deploymentId, String newTenantId) {
processDefinitionDataManager.updateProcessDefinitionTenantIdForDeployment(deploymentId, newTenantId);
}
public ProcessDefinitionDataManager getProcessDefinitionDataManager() {
return processDefinitionDataManager;
}
public void setProcessDefinitionDataManager(ProcessDefinitionDataManager processDefinitionDataManager) {
this.processDefinitionDataManager = processDefinitionDataManager;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ProcessDefinitionEntityManagerImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private @Nullable Properties loadCommonMessages(@Nullable List<Resource> resources) {
if (CollectionUtils.isEmpty(resources)) {
return null;
}
Properties properties = CollectionFactory.createSortedProperties(false);
for (Resource resource : resources) {
try {
PropertiesLoaderUtils.fillProperties(properties, resource);
}
catch (IOException ex) {
throw new UncheckedIOException("Failed to load common messages from '%s'".formatted(resource), ex);
}
}
return properties;
}
protected static class ResourceBundleCondition extends SpringBootCondition {
private static final ConcurrentReferenceHashMap<String, ConditionOutcome> cache = new ConcurrentReferenceHashMap<>();
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
String basename = context.getEnvironment().getProperty("spring.messages.basename", "messages");
ConditionOutcome outcome = cache.get(basename);
if (outcome == null) {
outcome = getMatchOutcomeForBasename(context, basename);
cache.put(basename, outcome);
}
return outcome;
}
private ConditionOutcome getMatchOutcomeForBasename(ConditionContext context, String basename) {
ConditionMessage.Builder message = ConditionMessage.forCondition("ResourceBundle");
for (String name : StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(basename))) {
for (Resource resource : getResources(context.getClassLoader(), name)) {
if (resource.exists()) {
return ConditionOutcome.match(message.found("bundle").items(resource));
}
}
|
}
return ConditionOutcome.noMatch(message.didNotFind("bundle with basename " + basename).atAll());
}
private Resource[] getResources(@Nullable ClassLoader classLoader, String name) {
String target = name.replace('.', '/');
try {
return new PathMatchingResourcePatternResolver(classLoader)
.getResources("classpath*:" + target + ".properties");
}
catch (Exception ex) {
return NO_RESOURCES;
}
}
}
static class MessageSourceRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.resources().registerPattern("messages.properties").registerPattern("messages_*.properties");
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\context\MessageSourceAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public Builder setInternalName(final String internalName)
{
this.internalName = internalName;
return this;
}
private String getInternalName()
{
if (Check.isEmpty(internalName, true))
{
return getRelatedDocumentsId().toJson();
}
return internalName;
}
public Builder setSource_Reference_ID(final int sourceReferenceId)
{
this.sourceReferenceId = ReferenceId.ofRepoIdOrNull(sourceReferenceId);
sourceTableRefInfo = null; // reset
return this;
}
private ReferenceId getSource_Reference_ID()
{
return Check.assumeNotNull(sourceReferenceId, "sourceReferenceId is set");
}
@Nullable
private ADRefTable getSourceTableRefInfoOrNull()
{
if (sourceTableRefInfo == null)
{
sourceTableRefInfo = retrieveTableRefInfo(getSource_Reference_ID());
}
return sourceTableRefInfo;
}
@Nullable
private ADRefTable retrieveTableRefInfo(final ReferenceId adReferenceId)
{
final ADRefTable tableRefInfo = adReferenceService.retrieveTableRefInfo(adReferenceId);
if (tableRefInfo == null)
{
return null;
}
return tableRefInfo.mapWindowIds(this::getCustomizationWindowId);
}
@Nullable
private AdWindowId getCustomizationWindowId(@Nullable final AdWindowId adWindowId)
{
return adWindowId != null
? customizedWindowInfoMap.getCustomizedWindowInfo(adWindowId).map(CustomizedWindowInfo::getCustomizationWindowId).orElse(adWindowId)
: null;
}
public Builder setSourceRoleDisplayName(final ITranslatableString sourceRoleDisplayName)
{
this.sourceRoleDisplayName = sourceRoleDisplayName;
return this;
}
public Builder setTarget_Reference_AD(final int targetReferenceId)
{
|
this.targetReferenceId = ReferenceId.ofRepoIdOrNull(targetReferenceId);
targetTableRefInfo = null; // lazy
return this;
}
private ReferenceId getTarget_Reference_ID()
{
return Check.assumeNotNull(targetReferenceId, "targetReferenceId is set");
}
private ADRefTable getTargetTableRefInfoOrNull()
{
if (targetTableRefInfo == null)
{
targetTableRefInfo = retrieveTableRefInfo(getTarget_Reference_ID());
}
return targetTableRefInfo;
}
public Builder setTargetRoleDisplayName(final ITranslatableString targetRoleDisplayName)
{
this.targetRoleDisplayName = targetRoleDisplayName;
return this;
}
public ITranslatableString getTargetRoleDisplayName()
{
return targetRoleDisplayName;
}
public Builder setIsTableRecordIdTarget(final boolean isReferenceTarget)
{
isTableRecordIDTarget = isReferenceTarget;
return this;
}
private boolean isTableRecordIdTarget()
{
return isTableRecordIDTarget;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\related_documents\relation_type\SpecificRelationTypeRelatedDocumentsProvider.java
| 1
|
请完成以下Java代码
|
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Zahldatum.
@param PayDate
Date Payment made
*/
@Override
public void setPayDate (java.sql.Timestamp PayDate)
{
set_Value (COLUMNNAME_PayDate, PayDate);
}
/** Get Zahldatum.
@return Date Payment made
*/
@Override
public java.sql.Timestamp getPayDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_PayDate);
}
/** Set PaySelection_includedTab.
@param PaySelection_includedTab PaySelection_includedTab */
@Override
public void setPaySelection_includedTab (java.lang.String PaySelection_includedTab)
{
set_Value (COLUMNNAME_PaySelection_includedTab, PaySelection_includedTab);
}
/** Get PaySelection_includedTab.
@return PaySelection_includedTab */
@Override
public java.lang.String getPaySelection_includedTab ()
{
return (java.lang.String)get_Value(COLUMNNAME_PaySelection_includedTab);
}
/**
* PaySelectionTrxType AD_Reference_ID=541109
* Reference name: PaySelectionTrxType
*/
public static final int PAYSELECTIONTRXTYPE_AD_Reference_ID=541109;
/** Direct Debit = DD */
public static final String PAYSELECTIONTRXTYPE_DirectDebit = "DD";
/** Credit Transfer = CT */
public static final String PAYSELECTIONTRXTYPE_CreditTransfer = "CT";
/** Set Transaktionsart.
@param PaySelectionTrxType Transaktionsart */
@Override
public void setPaySelectionTrxType (java.lang.String PaySelectionTrxType)
{
set_Value (COLUMNNAME_PaySelectionTrxType, PaySelectionTrxType);
}
/** Get Transaktionsart.
@return Transaktionsart */
@Override
public java.lang.String getPaySelectionTrxType ()
{
return (java.lang.String)get_Value(COLUMNNAME_PaySelectionTrxType);
|
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Datensatz verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Datensatz verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Gesamtbetrag.
@param TotalAmt Gesamtbetrag */
@Override
public void setTotalAmt (java.math.BigDecimal TotalAmt)
{
set_Value (COLUMNNAME_TotalAmt, TotalAmt);
}
/** Get Gesamtbetrag.
@return Gesamtbetrag */
@Override
public java.math.BigDecimal getTotalAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalAmt);
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_PaySelection.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Map<String, ConfigurationMetadataGroup> getAllGroups() {
return Collections.unmodifiableMap(this.allGroups);
}
@Override
public Map<String, ConfigurationMetadataProperty> getAllProperties() {
Map<String, ConfigurationMetadataProperty> properties = new HashMap<>();
for (ConfigurationMetadataGroup group : this.allGroups.values()) {
properties.putAll(group.getProperties());
}
return properties;
}
/**
* Register the specified {@link ConfigurationMetadataSource sources}.
* @param sources the sources to add
*/
public void add(Collection<ConfigurationMetadataSource> sources) {
for (ConfigurationMetadataSource source : sources) {
String groupId = source.getGroupId();
ConfigurationMetadataGroup group = this.allGroups.computeIfAbsent(groupId,
(key) -> new ConfigurationMetadataGroup(groupId));
String sourceType = source.getType();
if (sourceType != null) {
addOrMergeSource(group.getSources(), sourceType, source);
}
}
}
/**
* Add a {@link ConfigurationMetadataProperty} with the
* {@link ConfigurationMetadataSource source} that defines it, if any.
* @param property the property to add
* @param source the source
*/
public void add(ConfigurationMetadataProperty property, ConfigurationMetadataSource source) {
if (source != null) {
source.getProperties().putIfAbsent(property.getId(), property);
}
getGroup(source).getProperties().putIfAbsent(property.getId(), property);
}
|
/**
* Merge the content of the specified repository to this repository.
* @param repository the repository to include
*/
public void include(ConfigurationMetadataRepository repository) {
for (ConfigurationMetadataGroup group : repository.getAllGroups().values()) {
ConfigurationMetadataGroup existingGroup = this.allGroups.get(group.getId());
if (existingGroup == null) {
this.allGroups.put(group.getId(), group);
}
else {
// Merge properties
group.getProperties().forEach((name, value) -> existingGroup.getProperties().putIfAbsent(name, value));
// Merge sources
group.getSources().forEach((name, value) -> addOrMergeSource(existingGroup.getSources(), name, value));
}
}
}
private ConfigurationMetadataGroup getGroup(ConfigurationMetadataSource source) {
if (source == null) {
return this.allGroups.computeIfAbsent(ROOT_GROUP, (key) -> new ConfigurationMetadataGroup(ROOT_GROUP));
}
return this.allGroups.get(source.getGroupId());
}
private void addOrMergeSource(Map<String, ConfigurationMetadataSource> sources, String name,
ConfigurationMetadataSource source) {
ConfigurationMetadataSource existingSource = sources.get(name);
if (existingSource == null) {
sources.put(name, source);
}
else {
source.getProperties().forEach((k, v) -> existingSource.getProperties().putIfAbsent(k, v));
}
}
}
|
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-metadata\src\main\java\org\springframework\boot\configurationmetadata\SimpleConfigurationMetadataRepository.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void setHIERARCHICALPARENT(String value) {
this.hierarchicalparent = value;
}
/**
* Gets the value of the packagingunit property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPACKAGINGUNIT() {
return packagingunit;
}
/**
* Sets the value of the packagingunit property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPACKAGINGUNIT(String value) {
this.packagingunit = value;
}
/**
* Gets the value of the packagingunitcode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPACKAGINGUNITCODE() {
return packagingunitcode;
}
/**
* Sets the value of the packagingunitcode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPACKAGINGUNITCODE(String value) {
this.packagingunitcode = value;
}
/**
* Gets the value of the pmesu1 property.
*
* @return
* possible object is
* {@link PMESU1 }
*
*/
public PMESU1 getPMESU1() {
return pmesu1;
}
/**
* Sets the value of the pmesu1 property.
*
* @param value
* allowed object is
* {@link PMESU1 }
*
*/
public void setPMESU1(PMESU1 value) {
this.pmesu1 = value;
}
/**
* Gets the value of the phand1 property.
*
|
* @return
* possible object is
* {@link PHAND1 }
*
*/
public PHAND1 getPHAND1() {
return phand1;
}
/**
* Sets the value of the phand1 property.
*
* @param value
* allowed object is
* {@link PHAND1 }
*
*/
public void setPHAND1(PHAND1 value) {
this.phand1 = value;
}
/**
* Gets the value of the detail property.
*
* @return
* possible object is
* {@link DETAILXbest }
*
*/
public DETAILXbest getDETAIL() {
return detail;
}
/**
* Sets the value of the detail property.
*
* @param value
* allowed object is
* {@link DETAILXbest }
*
*/
public void setDETAIL(DETAILXbest value) {
this.detail = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_orders\de\metas\edi\esb\jaxb\stepcom\orders\PPACK1.java
| 2
|
请完成以下Java代码
|
public HistoricExternalTaskLogQuery orderByExecutionId() {
orderBy(HistoricExternalTaskLogQueryProperty.EXECUTION_ID);
return this;
}
@Override
public HistoricExternalTaskLogQuery orderByProcessInstanceId() {
orderBy(HistoricExternalTaskLogQueryProperty.PROCESS_INSTANCE_ID);
return this;
}
@Override
public HistoricExternalTaskLogQuery orderByProcessDefinitionId() {
orderBy(HistoricExternalTaskLogQueryProperty.PROCESS_DEFINITION_ID);
return this;
}
@Override
public HistoricExternalTaskLogQuery orderByProcessDefinitionKey() {
orderBy(HistoricExternalTaskLogQueryProperty.PROCESS_DEFINITION_KEY);
return this;
}
@Override
public HistoricExternalTaskLogQuery orderByTenantId() {
orderBy(HistoricExternalTaskLogQueryProperty.TENANT_ID);
return this;
}
|
// results //////////////////////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getHistoricExternalTaskLogManager()
.findHistoricExternalTaskLogsCountByQueryCriteria(this);
}
@Override
public List<HistoricExternalTaskLog> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getHistoricExternalTaskLogManager()
.findHistoricExternalTaskLogsByQueryCriteria(this, page);
}
// getters & setters ////////////////////////////////////////////////////////////
protected void setState(ExternalTaskState state) {
this.state = state;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricExternalTaskLogQueryImpl.java
| 1
|
请完成以下Java代码
|
public void setEXP_FormatLine_ID (final int EXP_FormatLine_ID)
{
if (EXP_FormatLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_EXP_FormatLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_EXP_FormatLine_ID, EXP_FormatLine_ID);
}
@Override
public int getEXP_FormatLine_ID()
{
return get_ValueAsInt(COLUMNNAME_EXP_FormatLine_ID);
}
/**
* FilterOperator AD_Reference_ID=541875
* Reference name: FilterOperator_for_EXP_FormatLine
*/
public static final int FILTEROPERATOR_AD_Reference_ID=541875;
/** Equals = E */
public static final String FILTEROPERATOR_Equals = "E";
/** Like = L */
public static final String FILTEROPERATOR_Like = "L";
@Override
public void setFilterOperator (final java.lang.String FilterOperator)
{
set_Value (COLUMNNAME_FilterOperator, FilterOperator);
}
@Override
public java.lang.String getFilterOperator()
{
return get_ValueAsString(COLUMNNAME_FilterOperator);
}
@Override
public void setHelp (final @Nullable java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
@Override
public java.lang.String getHelp()
{
return get_ValueAsString(COLUMNNAME_Help);
}
@Override
public void setIsMandatory (final boolean IsMandatory)
{
set_Value (COLUMNNAME_IsMandatory, IsMandatory);
}
@Override
public boolean isMandatory()
{
return get_ValueAsBoolean(COLUMNNAME_IsMandatory);
}
@Override
public void setIsPartUniqueIndex (final boolean IsPartUniqueIndex)
{
set_Value (COLUMNNAME_IsPartUniqueIndex, IsPartUniqueIndex);
}
@Override
public boolean isPartUniqueIndex()
{
return get_ValueAsBoolean(COLUMNNAME_IsPartUniqueIndex);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setPosition (final int Position)
{
set_Value (COLUMNNAME_Position, Position);
}
@Override
public int getPosition()
|
{
return get_ValueAsInt(COLUMNNAME_Position);
}
/**
* Type AD_Reference_ID=53241
* Reference name: EXP_Line_Type
*/
public static final int TYPE_AD_Reference_ID=53241;
/** XML Element = E */
public static final String TYPE_XMLElement = "E";
/** XML Attribute = A */
public static final String TYPE_XMLAttribute = "A";
/** Embedded EXP Format = M */
public static final String TYPE_EmbeddedEXPFormat = "M";
/** Referenced EXP Format = R */
public static final String TYPE_ReferencedEXPFormat = "R";
@Override
public void setType (final java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_EXP_FormatLine.java
| 1
|
请完成以下Java代码
|
public int getId() {
return id;
}
public String getPost() {
return post;
}
public void setPost(String post) {
this.post = post;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
|
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
@Override
public String toString() {
return "title: " + this.title
+ "\npost: " + this.post
+ "\nauthor: " + this.author
+"\ncreatetdAt: " + this.createdAt
+ "\nupdatedAt: " + this.updatedAt;
}
}
|
repos\tutorials-master\web-modules\vraptor\src\main\java\com\baeldung\models\Post.java
| 1
|
请完成以下Java代码
|
public class ActivitiSequenceFlowTakenEventImpl extends ActivitiEventImpl implements ActivitiSequenceFlowTakenEvent {
protected String id;
protected String sourceActivityId;
protected String sourceActivityName;
protected String sourceActivityType;
protected String targetActivityId;
protected String targetActivityName;
protected String targetActivityType;
protected String sourceActivityBehaviorClass;
protected String targetActivityBehaviorClass;
public ActivitiSequenceFlowTakenEventImpl(ActivitiEventType type) {
super(type);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSourceActivityId() {
return sourceActivityId;
}
public void setSourceActivityId(String sourceActivityId) {
this.sourceActivityId = sourceActivityId;
}
public String getSourceActivityName() {
return sourceActivityName;
}
public void setSourceActivityName(String sourceActivityName) {
this.sourceActivityName = sourceActivityName;
}
public String getSourceActivityType() {
return sourceActivityType;
}
public void setSourceActivityType(String sourceActivityType) {
this.sourceActivityType = sourceActivityType;
}
public String getTargetActivityId() {
return targetActivityId;
}
public void setTargetActivityId(String targetActivityId) {
this.targetActivityId = targetActivityId;
}
public String getTargetActivityName() {
return targetActivityName;
}
|
public void setTargetActivityName(String targetActivityName) {
this.targetActivityName = targetActivityName;
}
public String getTargetActivityType() {
return targetActivityType;
}
public void setTargetActivityType(String targetActivityType) {
this.targetActivityType = targetActivityType;
}
public String getSourceActivityBehaviorClass() {
return sourceActivityBehaviorClass;
}
public void setSourceActivityBehaviorClass(String sourceActivityBehaviorClass) {
this.sourceActivityBehaviorClass = sourceActivityBehaviorClass;
}
public String getTargetActivityBehaviorClass() {
return targetActivityBehaviorClass;
}
public void setTargetActivityBehaviorClass(String targetActivityBehaviorClass) {
this.targetActivityBehaviorClass = targetActivityBehaviorClass;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\delegate\event\impl\ActivitiSequenceFlowTakenEventImpl.java
| 1
|
请完成以下Java代码
|
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 Benchmark.
@param PA_Benchmark_ID
Performance Benchmark
*/
public void setPA_Benchmark_ID (int PA_Benchmark_ID)
{
|
if (PA_Benchmark_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_Benchmark_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_Benchmark_ID, Integer.valueOf(PA_Benchmark_ID));
}
/** Get Benchmark.
@return Performance Benchmark
*/
public int getPA_Benchmark_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Benchmark_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_Benchmark.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void importCostsFromRepairOrderAndMarkTaskCompleted(@NonNull final RepairManufacturingOrderInfo repairOrder)
{
ImportProjectCostsFromRepairOrderCommand.builder()
.projectTaskRepository(projectTaskRepository)
.projectCostCollectorRepository(projectCostCollectorRepository)
.serviceRepairProjectService(this)
.handlingUnitsBL(handlingUnitsBL)
//
.repairOrder(repairOrder)
//
.build()
.execute();
}
public void unimportCostsFromRepairOrder(@NonNull final RepairManufacturingOrderInfo repairOrder)
{
final ServiceRepairProjectTaskId taskId = projectTaskRepository
.getTaskIdByRepairOrderId(repairOrder.getProjectId(), repairOrder.getId())
.orElseThrow(() -> new AdempiereException("No task found for " + repairOrder));
final ImmutableList<ServiceRepairProjectCostCollector> costCollectorsToDelete = projectCostCollectorRepository
.getByTaskId(taskId)
.stream()
.filter(ServiceRepairProjectCostCollector::isNotIncludedInCustomerQuotation)
.collect(ImmutableList.toImmutableList());
deleteCostCollectors(costCollectorsToDelete, false);
projectTaskRepository.save(
projectTaskRepository.getById(taskId)
.withRepairOrderNotDone());
}
private void deleteCostCollectors(
@NonNull final Collection<ServiceRepairProjectCostCollector> costCollectors,
final boolean deleteHUReservations)
{
if (costCollectors.isEmpty())
{
return;
}
|
final HashSet<HuId> reservedVHUIds = new HashSet<>();
final HashSet<ServiceRepairProjectCostCollectorId> costCollectorIdsToDelete = new HashSet<>();
final ArrayList<AddQtyToProjectTaskRequest> addQtyToProjectTaskRequests = new ArrayList<>();
for (final ServiceRepairProjectCostCollector costCollector : costCollectors)
{
if (deleteHUReservations && costCollector.getVhuId() != null)
{
reservedVHUIds.add(costCollector.getVhuId());
}
addQtyToProjectTaskRequests.add(extractAddQtyToProjectTaskRequest(costCollector).negate());
costCollectorIdsToDelete.add(costCollector.getId());
}
huReservationService.deleteReservationsByVHUIds(reservedVHUIds);
projectCostCollectorRepository.deleteByIds(costCollectorIdsToDelete);
addQtyToProjectTaskRequests.forEach(this::addQtyToProjectTask);
}
public void unlinkQuotationFromProject(@NonNull final ProjectId projectId, @NonNull final OrderId quotationId)
{
projectCostCollectorRepository.unsetCustomerQuotation(projectId, quotationId);
}
public void unlinkProposalLineFromProject(@NonNull final OrderAndLineId proposalLineId)
{
projectCostCollectorRepository.unsetCustomerQuotationLine(proposalLineId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\service\ServiceRepairProjectService.java
| 2
|
请完成以下Java代码
|
public Set<CarrierService> getAssignedServicesByDeliveryOrderId(@NonNull final DeliveryOrderId carrierShipmentOrderId)
{
return queryBL.createQueryBuilder(I_Carrier_ShipmentOrder_Service.class)
.addEqualsFilter(I_Carrier_ShipmentOrder_Service.COLUMNNAME_Carrier_ShipmentOrder_ID, carrierShipmentOrderId)
.andCollect(I_Carrier_ShipmentOrder_Service.COLUMN_Carrier_Service_ID)
.create()
.stream()
.map(CarrierShipmentOrderServiceRepository::fromRecord)
.collect(ImmutableSet.toImmutableSet());
}
public void assignServiceToDeliveryOrder(@NonNull final DeliveryOrderId deliveryOrderId, @NonNull final ShipperId shipperId, @NonNull final CarrierService service)
{
final CarrierService actualService = getOrCreateService(shipperId, service.getExternalId(), service.getName());
final I_Carrier_ShipmentOrder_Service po = InterfaceWrapperHelper.newInstance(I_Carrier_ShipmentOrder_Service.class);
po.setCarrier_ShipmentOrder_ID(deliveryOrderId.getRepoId());
po.setCarrier_Service_ID(CarrierServiceId.toRepoId(actualService.getId()));
InterfaceWrapperHelper.saveRecord(po);
}
@NonNull
public CarrierService getOrCreateService(@NonNull final ShipperId shipperId, @NonNull final String externalId, @NonNull final String name)
{
final CarrierService cachedService = getCachedServiceByShipperExternalId(shipperId, externalId);
if (cachedService != null)
{
return cachedService;
}
return createShipperService(shipperId, externalId, name);
}
@Nullable
private CarrierService getCachedServiceByShipperExternalId(@NonNull final ShipperId shipperId, @Nullable final String externalId)
{
if (externalId == null)
|
{
return null;
}
return carrierServicesByExternalId.getOrLoad(shipperId + externalId, () ->
queryBL.createQueryBuilder(I_Carrier_Service.class)
.addEqualsFilter(I_Carrier_Goods_Type.COLUMNNAME_M_Shipper_ID, shipperId)
.addEqualsFilter(I_Carrier_Goods_Type.COLUMNNAME_ExternalId, externalId)
.firstOptional()
.map(CarrierShipmentOrderServiceRepository::fromRecord)
.orElse(null));
}
private static CarrierService fromRecord(@NotNull final I_Carrier_Service service)
{
return CarrierService.builder()
.id(CarrierServiceId.ofRepoId(service.getCarrier_Service_ID()))
.externalId(service.getExternalId())
.name(service.getName())
.build();
}
private CarrierService createShipperService(@NonNull final ShipperId shipperId, @NonNull final String externalId, @NonNull final String name)
{
final I_Carrier_Service po = InterfaceWrapperHelper.newInstance(I_Carrier_Service.class);
po.setM_Shipper_ID(shipperId.getRepoId());
po.setExternalId(externalId);
po.setName(name);
InterfaceWrapperHelper.saveRecord(po);
return fromRecord(po);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\model\CarrierShipmentOrderServiceRepository.java
| 1
|
请完成以下Java代码
|
public void setC_Region_ID (final int C_Region_ID)
{
if (C_Region_ID < 1)
set_Value (COLUMNNAME_C_Region_ID, null);
else
set_Value (COLUMNNAME_C_Region_ID, C_Region_ID);
}
@Override
public int getC_Region_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Region_ID);
}
@Override
public void setCity (final @Nullable java.lang.String City)
{
set_Value (COLUMNNAME_City, City);
}
@Override
public java.lang.String getCity()
{
return get_ValueAsString(COLUMNNAME_City);
}
@Override
public void setDistrict (final @Nullable java.lang.String District)
{
set_Value (COLUMNNAME_District, District);
}
@Override
public java.lang.String getDistrict()
{
return get_ValueAsString(COLUMNNAME_District);
}
@Override
public void setIsManual (final boolean IsManual)
{
set_Value (COLUMNNAME_IsManual, IsManual);
}
@Override
public boolean isManual()
{
return get_ValueAsBoolean(COLUMNNAME_IsManual);
}
@Override
public void setIsValidDPD (final boolean IsValidDPD)
{
set_Value (COLUMNNAME_IsValidDPD, IsValidDPD);
}
@Override
public boolean isValidDPD()
{
return get_ValueAsBoolean(COLUMNNAME_IsValidDPD);
}
@Override
public void setNonStdAddress (final boolean NonStdAddress)
{
set_Value (COLUMNNAME_NonStdAddress, NonStdAddress);
}
@Override
public boolean isNonStdAddress()
{
return get_ValueAsBoolean(COLUMNNAME_NonStdAddress);
}
@Override
public void setPostal (final @Nullable java.lang.String Postal)
{
set_Value (COLUMNNAME_Postal, Postal);
}
|
@Override
public java.lang.String getPostal()
{
return get_ValueAsString(COLUMNNAME_Postal);
}
@Override
public void setPostal_Add (final @Nullable java.lang.String Postal_Add)
{
set_Value (COLUMNNAME_Postal_Add, Postal_Add);
}
@Override
public java.lang.String getPostal_Add()
{
return get_ValueAsString(COLUMNNAME_Postal_Add);
}
@Override
public void setRegionName (final @Nullable java.lang.String RegionName)
{
set_Value (COLUMNNAME_RegionName, RegionName);
}
@Override
public java.lang.String getRegionName()
{
return get_ValueAsString(COLUMNNAME_RegionName);
}
@Override
public void setTownship (final @Nullable java.lang.String Township)
{
set_Value (COLUMNNAME_Township, Township);
}
@Override
public java.lang.String getTownship()
{
return get_ValueAsString(COLUMNNAME_Township);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Postal.java
| 1
|
请完成以下Java代码
|
public final class MicrometerHolder {
private final ConcurrentMap<String, Timer> timers = new ConcurrentHashMap<>();
@SuppressWarnings("NullAway.Init")
private final MeterRegistry registry;
private final Map<String, String> tags;
private final String listenerId;
@SuppressWarnings("NullAway") // Dataflow analysis limitation
MicrometerHolder(@Nullable ApplicationContext context, String listenerId, Map<String, String> tags) {
Assert.notNull(context, "'context' must not be null");
try {
this.registry = context.getBeanProvider(MeterRegistry.class).getIfUnique();
}
catch (NoUniqueBeanDefinitionException ex) {
throw new IllegalStateException(ex);
}
if (this.registry != null) {
this.listenerId = listenerId;
this.tags = tags;
}
else {
throw new IllegalStateException("No micrometer registry present (or more than one and "
+ "there is not exactly one marked with @Primary)");
}
}
public Object start() {
return Timer.start(this.registry);
}
public void success(Object sample, String queue) {
Timer timer = this.timers.get(queue + "none");
if (timer == null) {
timer = buildTimer(this.listenerId, "success", queue, "none");
}
((Sample) sample).stop(timer);
}
public void failure(Object sample, String queue, String exception) {
Timer timer = this.timers.get(queue + exception);
if (timer == null) {
timer = buildTimer(this.listenerId, "failure", queue, exception);
}
((Sample) sample).stop(timer);
}
|
private Timer buildTimer(String aListenerId, String result, String queue, String exception) {
Builder builder = Timer.builder("spring.rabbitmq.listener")
.description("Spring RabbitMQ Listener")
.tag("listener.id", aListenerId)
.tag("queue", queue)
.tag("result", result)
.tag("exception", exception);
if (!CollectionUtils.isEmpty(this.tags)) {
this.tags.forEach(builder::tag);
}
Timer registeredTimer = builder.register(this.registry);
this.timers.put(queue + exception, registeredTimer);
return registeredTimer;
}
void destroy() {
this.timers.values().forEach(this.registry::remove);
this.timers.clear();
}
}
|
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\listener\MicrometerHolder.java
| 1
|
请完成以下Java代码
|
public String determineHistoryLevel() {
Integer historyLevelFromDb = null;
try {
historyLevelFromDb = jdbcTemplate.queryForObject(getSql(), Integer.class);
log.debug("found history '{}' in database", historyLevelFromDb);
} catch (DataAccessException e) {
if (ignoreDataAccessException) {
log.warn("unable to fetch history level from database: {}", e.getMessage());
log.debug("unable to fetch history level from database", e);
} else {
throw e;
}
}
return getHistoryLevelFrom(historyLevelFromDb);
}
protected String getSql() {
String tablePrefix = camundaBpmProperties.getDatabase().getTablePrefix();
if (tablePrefix == null) {
tablePrefix = "";
}
return SQL_TEMPLATE.replace(TABLE_PREFIX_PLACEHOLDER, tablePrefix);
}
|
protected String getHistoryLevelFrom(Integer historyLevelFromDb) {
String result = defaultHistoryLevel;
if (historyLevelFromDb != null) {
for (HistoryLevel historyLevel : historyLevels) {
if (historyLevel.getId() == historyLevelFromDb.intValue()) {
result = historyLevel.getName();
log.debug("found matching history level '{}'", result);
break;
}
}
}
return result;
}
public void addCustomHistoryLevels(Collection<HistoryLevel> customHistoryLevels) {
historyLevels.addAll(customHistoryLevels);
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\jdbc\HistoryLevelDeterminatorJdbcTemplateImpl.java
| 1
|
请完成以下Java代码
|
public static void checkPositionIndexes(int start, int end, int size)
{
// Carefully optimized for execution by hotspot (explanatory comment above)
if (start < 0 || end < start || end > size)
{
throw new IndexOutOfBoundsException(badPositionIndexes(start, end, size));
}
}
private static String badPositionIndexes(int start, int end, int size)
{
if (start < 0 || start > size)
{
return badPositionIndex(start, size, "start index");
}
if (end < 0 || end > size)
{
return badPositionIndex(end, size, "end index");
}
// end < start
return format("end index (%s) must not be less than start index (%s)", end, start);
}
/**
* Substitutes each {@code %s} in {@code template} with an argument. These are matched by
* position: the first {@code %s} gets {@code args[0]}, etc. If there are more arguments than
* placeholders, the unmatched arguments will be appended to the end of the formatted message in
* square braces.
*
* @param template a non-null string containing 0 or more {@code %s} placeholders.
* @param args the arguments to be substituted into the message template. Arguments are converted
* to strings using {@link String#valueOf(Object)}. Arguments can be null.
*/
// Note that this is somewhat-improperly used from Verify.java as well.
static String format(String template, Object... args)
{
template = String.valueOf(template); // null -> "null"
// start substituting the arguments into the '%s' placeholders
StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
int templateStart = 0;
|
int i = 0;
while (i < args.length)
{
int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1)
{
break;
}
builder.append(template.substring(templateStart, placeholderStart));
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template.substring(templateStart));
// if we run out of placeholders, append the extra args in square braces
if (i < args.length)
{
builder.append(" [");
builder.append(args[i++]);
while (i < args.length)
{
builder.append(", ");
builder.append(args[i++]);
}
builder.append(']');
}
return builder.toString();
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\Preconditions.java
| 1
|
请完成以下Java代码
|
public class DestroyScopeOperation extends AbstractOperation {
public DestroyScopeOperation(CommandContext commandContext, ExecutionEntity execution) {
super(commandContext, execution);
}
@Override
public void run() {
// Find the actual scope that needs to be destroyed.
// This could be the incoming execution, or the first parent execution where isScope = true
// Find parent scope execution
ExecutionEntity scopeExecution = execution.isScope() ? execution : findFirstParentScopeExecution(execution);
if (scopeExecution == null) {
|
throw new FlowableException("Programmatic error: no parent scope execution found for boundary event for " + execution);
}
ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);
// Delete all child executions
executionEntityManager.deleteChildExecutions(scopeExecution, execution.getDeleteReason(), true);
executionEntityManager.deleteExecutionAndRelatedData(scopeExecution, execution.getDeleteReason(), false, false, true, null);
if (scopeExecution.isActive()) {
CommandContextUtil.getActivityInstanceEntityManager(commandContext).recordActivityEnd(scopeExecution, scopeExecution.getDeleteReason());
}
executionEntityManager.delete(scopeExecution);
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\agenda\DestroyScopeOperation.java
| 1
|
请完成以下Java代码
|
public String toString()
{
StringBuffer sb = new StringBuffer ("X_ImpEx_ConnectorType[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Classname.
@param Classname
Java Classname
*/
public void setClassname (String Classname)
{
set_Value (COLUMNNAME_Classname, Classname);
}
/** Get Classname.
@return Java Classname
*/
public String getClassname ()
{
return (String)get_Value(COLUMNNAME_Classname);
}
/** Set Beschreibung.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Direction AD_Reference_ID=540086 */
public static final int DIRECTION_AD_Reference_ID=540086;
/** Import = I */
public static final String DIRECTION_Import = "I";
/** Export = E */
public static final String DIRECTION_Export = "E";
/** Set Richtung.
@param Direction Richtung */
public void setDirection (String Direction)
{
set_Value (COLUMNNAME_Direction, Direction);
}
/** Get Richtung.
@return Richtung */
public String getDirection ()
{
return (String)get_Value(COLUMNNAME_Direction);
}
/** Set Konnektor-Typ.
@param ImpEx_ConnectorType_ID Konnektor-Typ */
public void setImpEx_ConnectorType_ID (int ImpEx_ConnectorType_ID)
{
if (ImpEx_ConnectorType_ID < 1)
set_ValueNoCheck (COLUMNNAME_ImpEx_ConnectorType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ImpEx_ConnectorType_ID, Integer.valueOf(ImpEx_ConnectorType_ID));
}
/** Get Konnektor-Typ.
|
@return Konnektor-Typ */
public int getImpEx_ConnectorType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ImpEx_ConnectorType_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());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\impex\model\X_ImpEx_ConnectorType.java
| 1
|
请完成以下Java代码
|
public Mono<CsrfToken> generateToken(ServerWebExchange exchange) {
return Mono.fromCallable(() -> createCsrfToken()).subscribeOn(Schedulers.boundedElastic());
}
@Override
public Mono<Void> saveToken(ServerWebExchange exchange, @Nullable CsrfToken token) {
return exchange.getSession()
.doOnNext((session) -> putToken(session.getAttributes(), token))
.flatMap((session) -> session.changeSessionId());
}
private void putToken(Map<String, Object> attributes, @Nullable CsrfToken token) {
if (token == null) {
attributes.remove(this.sessionAttributeName);
}
else {
attributes.put(this.sessionAttributeName, token);
}
}
@Override
@SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290
public Mono<CsrfToken> loadToken(ServerWebExchange exchange) {
return exchange.getSession()
.filter((session) -> session.getAttributes().containsKey(this.sessionAttributeName))
.mapNotNull((session) -> session.getAttribute(this.sessionAttributeName));
}
/**
* Sets the {@link ServerWebExchange} parameter name that the {@link CsrfToken} is
* expected to appear on
* @param parameterName the new parameter name to use
*/
public void setParameterName(String parameterName) {
Assert.hasLength(parameterName, "parameterName cannot be null or empty");
this.parameterName = parameterName;
}
/**
* Sets the header name that the {@link CsrfToken} is expected to appear on and the
* header that the response will contain the {@link CsrfToken}.
* @param headerName the new header name to use
*/
public void setHeaderName(String headerName) {
Assert.hasLength(headerName, "headerName cannot be null or empty");
|
this.headerName = headerName;
}
/**
* Sets the {@link WebSession} attribute name that the {@link CsrfToken} is stored in
* @param sessionAttributeName the new attribute name to use
*/
public void setSessionAttributeName(String sessionAttributeName) {
Assert.hasLength(sessionAttributeName, "sessionAttributeName cannot be null or empty");
this.sessionAttributeName = sessionAttributeName;
}
private CsrfToken createCsrfToken() {
return new DefaultCsrfToken(this.headerName, this.parameterName, createNewToken());
}
private String createNewToken() {
return UUID.randomUUID().toString();
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\csrf\WebSessionServerCsrfTokenRepository.java
| 1
|
请完成以下Java代码
|
public List<Integer> getResult_()
{
return result_;
}
public void setResult_(List<Integer> result_)
{
this.result_ = result_;
}
public static void main(String[] args) throws Exception
{
if (args.length < 1)
{
return;
}
TaggerImpl tagger = new TaggerImpl(Mode.TEST);
InputStream stream = null;
try
{
stream = IOUtil.newInputStream(args[0]);
}
catch (IOException e)
{
System.err.printf("model not exits for %s", args[0]);
return;
}
if (stream != null && !tagger.open(stream, 2, 0, 1.0))
{
System.err.println("open error");
return;
}
System.out.println("Done reading model");
if (args.length >= 2)
{
InputStream fis = IOUtil.newInputStream(args[1]);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader br = new BufferedReader(isr);
while (true)
|
{
ReadStatus status = tagger.read(br);
if (ReadStatus.ERROR == status)
{
System.err.println("read error");
return;
}
else if (ReadStatus.EOF == status)
{
break;
}
if (tagger.getX_().isEmpty())
{
break;
}
if (!tagger.parse())
{
System.err.println("parse error");
return;
}
System.out.print(tagger.toString());
}
br.close();
}
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\TaggerImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class InputDataSourceId implements RepoIdAware
{
int repoId;
@JsonCreator
public static InputDataSourceId ofRepoId(final int repoId)
{
return new InputDataSourceId(repoId);
}
@Nullable
public static InputDataSourceId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new InputDataSourceId(repoId) : null;
}
public static Optional<InputDataSourceId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static int toRepoId(@Nullable final InputDataSourceId inputDataSourceId)
{
|
return toRepoIdOr(inputDataSourceId, -1);
}
public static int toRepoIdOr(@Nullable final InputDataSourceId inputDataSourceId, final int defaultValue)
{
return inputDataSourceId != null ? inputDataSourceId.getRepoId() : defaultValue;
}
private InputDataSourceId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "repoId");
}
@JsonValue
public int toJson()
{
return getRepoId();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\InputDataSourceId.java
| 2
|
请完成以下Java代码
|
private File findInJavaHome(String javaHome) {
File bin = new File(new File(javaHome), "bin");
File command = new File(bin, "java.exe");
command = command.exists() ? command : new File(bin, "java");
Assert.state(command.exists(), () -> "Unable to find java in " + javaHome);
return command;
}
/**
* Create a new {@link ProcessBuilder} that will run with the Java executable.
* @param arguments the command arguments
* @return a {@link ProcessBuilder}
*/
public ProcessBuilder processBuilder(String... arguments) {
ProcessBuilder processBuilder = new ProcessBuilder(toString());
|
processBuilder.command().addAll(Arrays.asList(arguments));
return processBuilder;
}
@Override
public String toString() {
try {
return this.file.getCanonicalPath();
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\JavaExecutable.java
| 1
|
请完成以下Java代码
|
public static Graph calculateShortestPathFromSource(Graph graph, Node source) {
source.setDistance(0);
Set<Node> settledNodes = new HashSet<>();
Set<Node> unsettledNodes = new HashSet<>();
unsettledNodes.add(source);
while (unsettledNodes.size() != 0) {
Node currentNode = getLowestDistanceNode(unsettledNodes);
unsettledNodes.remove(currentNode);
for (Entry<Node, Integer> adjacencyPair : currentNode.getAdjacentNodes().entrySet()) {
Node adjacentNode = adjacencyPair.getKey();
Integer edgeWeigh = adjacencyPair.getValue();
if (!settledNodes.contains(adjacentNode)) {
CalculateMinimumDistance(adjacentNode, edgeWeigh, currentNode);
unsettledNodes.add(adjacentNode);
}
}
settledNodes.add(currentNode);
}
return graph;
}
private static void CalculateMinimumDistance(Node evaluationNode, Integer edgeWeigh, Node sourceNode) {
|
Integer sourceDistance = sourceNode.getDistance();
if (sourceDistance + edgeWeigh < evaluationNode.getDistance()) {
evaluationNode.setDistance(sourceDistance + edgeWeigh);
LinkedList<Node> shortestPath = new LinkedList<>(sourceNode.getShortestPath());
shortestPath.add(sourceNode);
evaluationNode.setShortestPath(shortestPath);
}
}
private static Node getLowestDistanceNode(Set<Node> unsettledNodes) {
Node lowestDistanceNode = null;
int lowestDistance = Integer.MAX_VALUE;
for (Node node : unsettledNodes) {
int nodeDistance = node.getDistance();
if (nodeDistance < lowestDistance) {
lowestDistance = nodeDistance;
lowestDistanceNode = node;
}
}
return lowestDistanceNode;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-1\src\main\java\com\baeldung\algorithms\dijkstra\Dijkstra.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class DeviceToCreate {\n");
sb.append(" patientId: ").append(toIndentedString(patientId)).append("\n");
sb.append(" articleId: ").append(toIndentedString(articleId)).append("\n");
sb.append(" articleNumber: ").append(toIndentedString(articleNumber)).append("\n");
sb.append(" serialNumber: ").append(toIndentedString(serialNumber)).append("\n");
sb.append(" registerNumber: ").append(toIndentedString(registerNumber)).append("\n");
sb.append(" description: ").append(toIndentedString(description)).append("\n");
sb.append(" additionalDescription: ").append(toIndentedString(additionalDescription)).append("\n");
sb.append(" locked: ").append(toIndentedString(locked)).append("\n");
sb.append(" commissioningDate: ").append(toIndentedString(commissioningDate)).append("\n");
sb.append(" repairEstimateRequired: ").append(toIndentedString(repairEstimateRequired)).append("\n");
sb.append(" repairEstimateLimit: ").append(toIndentedString(repairEstimateLimit)).append("\n");
sb.append(" lastBookingCode: ").append(toIndentedString(lastBookingCode)).append("\n");
sb.append(" lastLocationCode: ").append(toIndentedString(lastLocationCode)).append("\n");
sb.append(" ownerName: ").append(toIndentedString(ownerName)).append("\n");
sb.append(" deviceNumber: ").append(toIndentedString(deviceNumber)).append("\n");
sb.append(" maintenances: ").append(toIndentedString(maintenances)).append("\n");
sb.append(" deviceInfomationLines: ").append(toIndentedString(deviceInfomationLines)).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-article-api\src\main\java\io\swagger\client\model\DeviceToCreate.java
| 2
|
请完成以下Java代码
|
public int getC_DunningRun_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DunningRun_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 Dunning Date.
@param DunningDate
Date of Dunning
*/
public void setDunningDate (Timestamp DunningDate)
{
set_Value (COLUMNNAME_DunningDate, DunningDate);
}
/** Get Dunning Date.
@return Date of Dunning
*/
public Timestamp getDunningDate ()
{
return (Timestamp)get_Value(COLUMNNAME_DunningDate);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getDunningDate()));
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
|
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Send.
@param SendIt Send */
public void setSendIt (String SendIt)
{
set_Value (COLUMNNAME_SendIt, SendIt);
}
/** Get Send.
@return Send */
public String getSendIt ()
{
return (String)get_Value(COLUMNNAME_SendIt);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DunningRun.java
| 1
|
请完成以下Java代码
|
public abstract class AbstractMessageMatcherComposite<T> implements MessageMatcher<T> {
protected final Log logger = LogFactory.getLog(getClass());
/**
* @deprecated since 5.4 in favor of {@link #logger}
*/
@Deprecated
protected final Log LOGGER = this.logger;
private final List<MessageMatcher<T>> messageMatchers;
/**
* Creates a new instance
* @param messageMatchers the {@link MessageMatcher} instances to try
*/
AbstractMessageMatcherComposite(List<MessageMatcher<T>> messageMatchers) {
Assert.notEmpty(messageMatchers, "messageMatchers must contain a value");
Assert.isTrue(!messageMatchers.contains(null), "messageMatchers cannot contain null values");
this.messageMatchers = messageMatchers;
}
/**
* Creates a new instance
|
* @param messageMatchers the {@link MessageMatcher} instances to try
*/
@SafeVarargs
AbstractMessageMatcherComposite(MessageMatcher<T>... messageMatchers) {
this(Arrays.asList(messageMatchers));
}
public List<MessageMatcher<T>> getMessageMatchers() {
return this.messageMatchers;
}
@Override
public String toString() {
return getClass().getSimpleName() + "[messageMatchers=" + this.messageMatchers + "]";
}
}
|
repos\spring-security-main\messaging\src\main\java\org\springframework\security\messaging\util\matcher\AbstractMessageMatcherComposite.java
| 1
|
请完成以下Java代码
|
public void destroy() throws Exception {
if (appEngine != null) {
appEngine.close();
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public AppEngine getObject() throws Exception {
configureExternallyManagedTransactions();
if (appEngineConfiguration.getBeans() == null) {
appEngineConfiguration.setBeans(new SpringBeanFactoryProxyMap(applicationContext));
}
this.appEngine = appEngineConfiguration.buildAppEngine();
return this.appEngine;
}
protected void configureExternallyManagedTransactions() {
if (appEngineConfiguration instanceof SpringAppEngineConfiguration) { // remark: any config can be injected, so we cannot have SpringConfiguration as member
SpringAppEngineConfiguration engineConfiguration = (SpringAppEngineConfiguration) appEngineConfiguration;
if (engineConfiguration.getTransactionManager() != null) {
appEngineConfiguration.setTransactionsExternallyManaged(true);
}
}
}
@Override
public Class<AppEngine> getObjectType() {
return AppEngine.class;
|
}
@Override
public boolean isSingleton() {
return true;
}
public AppEngineConfiguration getAppEngineConfiguration() {
return appEngineConfiguration;
}
public void setAppEngineConfiguration(AppEngineConfiguration appEngineConfiguration) {
this.appEngineConfiguration = appEngineConfiguration;
}
}
|
repos\flowable-engine-main\modules\flowable-app-engine-spring\src\main\java\org\flowable\app\spring\AppEngineFactoryBean.java
| 1
|
请完成以下Java代码
|
public List<TenantDto> queryTenants(UriInfo uriInfo, Integer firstResult, Integer maxResults) {
TenantQueryDto queryDto = new TenantQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
TenantQuery query = queryDto.toQuery(getProcessEngine());
List<Tenant> tenants = QueryUtil.list(query, firstResult, maxResults);
return TenantDto.fromTenantList(tenants );
}
@Override
public CountResultDto getTenantCount(UriInfo uriInfo) {
TenantQueryDto queryDto = new TenantQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
TenantQuery query = queryDto.toQuery(getProcessEngine());
long count = query.count();
return new CountResultDto(count);
}
@Override
public void createTenant(TenantDto dto) {
if (getIdentityService().isReadOnly()) {
throw new InvalidRequestException(Status.FORBIDDEN, "Identity service implementation is read-only.");
}
Tenant newTenant = getIdentityService().newTenant(dto.getId());
dto.update(newTenant);
getIdentityService().saveTenant(newTenant);
}
@Override
|
public ResourceOptionsDto availableOperations(UriInfo context) {
UriBuilder baseUriBuilder = context.getBaseUriBuilder()
.path(relativeRootResourcePath)
.path(TenantRestService.PATH);
ResourceOptionsDto resourceOptionsDto = new ResourceOptionsDto();
// GET /
URI baseUri = baseUriBuilder.build();
resourceOptionsDto.addReflexiveLink(baseUri, HttpMethod.GET, "list");
// GET /count
URI countUri = baseUriBuilder.clone().path("/count").build();
resourceOptionsDto.addReflexiveLink(countUri, HttpMethod.GET, "count");
// POST /create
if (!getIdentityService().isReadOnly() && isAuthorized(CREATE)) {
URI createUri = baseUriBuilder.clone().path("/create").build();
resourceOptionsDto.addReflexiveLink(createUri, HttpMethod.POST, "create");
}
return resourceOptionsDto;
}
protected IdentityService getIdentityService() {
return getProcessEngine().getIdentityService();
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\TenantRestServiceImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
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 getScopeId() {
return scopeId;
}
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
public String getSubScopeId() {
return subScopeId;
}
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
|
public Date getFrom() {
return from;
}
public void setFrom(Date from) {
this.from = from;
}
public Date getTo() {
return to;
}
public void setTo(Date to) {
this.to = to;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public Long getFromLogNumber() {
return fromLogNumber;
}
public void setFromLogNumber(Long fromLogNumber) {
this.fromLogNumber = fromLogNumber;
}
public Long getToLogNumber() {
return toLogNumber;
}
public void setToLogNumber(Long toLogNumber) {
this.toLogNumber = toLogNumber;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskLogEntryQueryRequest.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public T findById(Long id) {
return allRules.get(id);
}
@Override
public List<T> findAllByMachine(MachineInfo machineInfo) {
Map<Long, T> entities = machineRules.get(machineInfo);
if (entities == null) {
return new ArrayList<>();
}
return new ArrayList<>(entities.values());
}
@Override
public List<T> findAllByApp(String appName) {
AssertUtil.notEmpty(appName, "appName cannot be empty");
Map<Long, T> entities = appRules.get(appName);
if (entities == null) {
return new ArrayList<>();
}
return new ArrayList<>(entities.values());
}
public void clearAll() {
allRules.clear();
|
machineRules.clear();
appRules.clear();
}
protected T preProcess(T entity) {
return entity;
}
/**
* Get next unused id.
*
* @return next unused id
*/
abstract protected long nextId();
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\repository\rule\InMemoryRuleRepositoryAdapter.java
| 2
|
请完成以下Java代码
|
public final class ClientAuthenticationMethod implements Serializable {
private static final long serialVersionUID = 620L;
/**
* @since 5.5
*/
public static final ClientAuthenticationMethod CLIENT_SECRET_BASIC = new ClientAuthenticationMethod(
"client_secret_basic");
/**
* @since 5.5
*/
public static final ClientAuthenticationMethod CLIENT_SECRET_POST = new ClientAuthenticationMethod(
"client_secret_post");
/**
* @since 5.5
*/
public static final ClientAuthenticationMethod CLIENT_SECRET_JWT = new ClientAuthenticationMethod(
"client_secret_jwt");
/**
* @since 5.5
*/
public static final ClientAuthenticationMethod PRIVATE_KEY_JWT = new ClientAuthenticationMethod("private_key_jwt");
/**
* @since 5.2
*/
public static final ClientAuthenticationMethod NONE = new ClientAuthenticationMethod("none");
/**
* @since 6.3
*/
public static final ClientAuthenticationMethod TLS_CLIENT_AUTH = new ClientAuthenticationMethod("tls_client_auth");
/**
* @since 6.3
*/
public static final ClientAuthenticationMethod SELF_SIGNED_TLS_CLIENT_AUTH = new ClientAuthenticationMethod(
"self_signed_tls_client_auth");
private final String value;
/**
* Constructs a {@code ClientAuthenticationMethod} using the provided value.
* @param value the value of the client authentication method
*/
public ClientAuthenticationMethod(String value) {
Assert.hasText(value, "value cannot be empty");
this.value = value;
}
/**
* Returns the value of the client authentication method.
* @return the value of the client authentication method
*/
public String getValue() {
return this.value;
}
static ClientAuthenticationMethod[] methods() {
return new ClientAuthenticationMethod[] { CLIENT_SECRET_BASIC, CLIENT_SECRET_POST, CLIENT_SECRET_JWT,
PRIVATE_KEY_JWT, NONE, TLS_CLIENT_AUTH, SELF_SIGNED_TLS_CLIENT_AUTH };
}
/**
* A factory to construct a {@link ClientAuthenticationMethod} based on a string,
* returning any constant value that matches.
|
* @param method the client authentication method
* @return a {@link ClientAuthenticationMethod}; specifically the corresponding
* constant, if any
* @since 6.5
*/
@NonNull
public static ClientAuthenticationMethod valueOf(String method) {
for (ClientAuthenticationMethod m : methods()) {
if (m.getValue().equals(method)) {
return m;
}
}
return new ClientAuthenticationMethod(method);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || this.getClass() != obj.getClass()) {
return false;
}
ClientAuthenticationMethod that = (ClientAuthenticationMethod) obj;
return getValue().equals(that.getValue());
}
@Override
public int hashCode() {
return getValue().hashCode();
}
@Override
public String toString() {
return this.value;
}
}
|
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\ClientAuthenticationMethod.java
| 1
|
请完成以下Java代码
|
public long findJobDefinitionCountByQueryCriteria(JobDefinitionQueryImpl jobDefinitionQuery) {
configureQuery(jobDefinitionQuery);
return (Long) getDbEntityManager().selectOne("selectJobDefinitionCountByQueryCriteria", jobDefinitionQuery);
}
public void updateJobDefinitionSuspensionStateById(String jobDefinitionId, SuspensionState suspensionState) {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("jobDefinitionId", jobDefinitionId);
parameters.put("suspensionState", suspensionState.getStateCode());
getDbEntityManager().update(JobDefinitionEntity.class, "updateJobDefinitionSuspensionStateByParameters", configureParameterizedQuery(parameters));
}
public void updateJobDefinitionSuspensionStateByProcessDefinitionId(String processDefinitionId, SuspensionState suspensionState) {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("processDefinitionId", processDefinitionId);
parameters.put("suspensionState", suspensionState.getStateCode());
getDbEntityManager().update(JobDefinitionEntity.class, "updateJobDefinitionSuspensionStateByParameters", configureParameterizedQuery(parameters));
}
public void updateJobDefinitionSuspensionStateByProcessDefinitionKey(String processDefinitionKey, SuspensionState suspensionState) {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("processDefinitionKey", processDefinitionKey);
parameters.put("isProcessDefinitionTenantIdSet", false);
parameters.put("suspensionState", suspensionState.getStateCode());
getDbEntityManager().update(JobDefinitionEntity.class, "updateJobDefinitionSuspensionStateByParameters", configureParameterizedQuery(parameters));
}
|
public void updateJobDefinitionSuspensionStateByProcessDefinitionKeyAndTenantId(String processDefinitionKey, String processDefinitionTenantId, SuspensionState suspensionState) {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("processDefinitionKey", processDefinitionKey);
parameters.put("isProcessDefinitionTenantIdSet", true);
parameters.put("processDefinitionTenantId", processDefinitionTenantId);
parameters.put("suspensionState", suspensionState.getStateCode());
getDbEntityManager().update(JobDefinitionEntity.class, "updateJobDefinitionSuspensionStateByParameters", configureParameterizedQuery(parameters));
}
protected void configureQuery(JobDefinitionQueryImpl query) {
getAuthorizationManager().configureJobDefinitionQuery(query);
getTenantManager().configureQuery(query);
}
protected ListQueryParameterObject configureParameterizedQuery(Object parameter) {
return getTenantManager().configureQuery(parameter);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\JobDefinitionManager.java
| 1
|
请完成以下Java代码
|
public int getAD_BusinessRule_Trigger_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_BusinessRule_Trigger_ID);
}
@Override
public void setAD_Issue_ID (final int AD_Issue_ID)
{
if (AD_Issue_ID < 1)
set_Value (COLUMNNAME_AD_Issue_ID, null);
else
set_Value (COLUMNNAME_AD_Issue_ID, AD_Issue_ID);
}
@Override
public int getAD_Issue_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Issue_ID);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessingTag (final @Nullable java.lang.String ProcessingTag)
{
set_Value (COLUMNNAME_ProcessingTag, ProcessingTag);
}
@Override
public java.lang.String getProcessingTag()
{
return get_ValueAsString(COLUMNNAME_ProcessingTag);
}
@Override
public void setSource_Record_ID (final int Source_Record_ID)
{
if (Source_Record_ID < 1)
set_ValueNoCheck (COLUMNNAME_Source_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Source_Record_ID, Source_Record_ID);
}
@Override
public int getSource_Record_ID()
{
return get_ValueAsInt(COLUMNNAME_Source_Record_ID);
}
@Override
|
public void setSource_Table_ID (final int Source_Table_ID)
{
if (Source_Table_ID < 1)
set_ValueNoCheck (COLUMNNAME_Source_Table_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Source_Table_ID, Source_Table_ID);
}
@Override
public int getSource_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_Source_Table_ID);
}
@Override
public void setTriggering_User_ID (final int Triggering_User_ID)
{
if (Triggering_User_ID < 1)
set_Value (COLUMNNAME_Triggering_User_ID, null);
else
set_Value (COLUMNNAME_Triggering_User_ID, Triggering_User_ID);
}
@Override
public int getTriggering_User_ID()
{
return get_ValueAsInt(COLUMNNAME_Triggering_User_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_BusinessRule_Event.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class BaseEventDefinitionResource {
@Autowired
protected EventRegistryRestResponseFactory restResponseFactory;
@Autowired
protected EventRepositoryService repositoryService;
@Autowired(required=false)
protected EventRegistryRestApiInterceptor restApiInterceptor;
/**
* Returns the {@link EventDefinition} that is requested. Throws the right exceptions when bad request was made or definition was not found.
*/
protected EventDefinition getEventDefinitionFromRequest(String eventDefinitionId) {
EventDefinition eventDefinition = repositoryService.getEventDefinition(eventDefinitionId);
if (eventDefinition == null) {
throw new FlowableObjectNotFoundException("Could not find an event definition with id '" + eventDefinitionId + "'.", EventDefinition.class);
}
if (restApiInterceptor != null) {
restApiInterceptor.accessEventDefinitionById(eventDefinition);
}
return eventDefinition;
}
/**
* Returns the {@link ChannelDefinition} that is requested. Throws the right exceptions when bad request was made or definition was not found.
|
*/
protected ChannelDefinition getChannelDefinitionFromRequest(String channelDefinitionId) {
ChannelDefinition channelDefinition = repositoryService.getChannelDefinition(channelDefinitionId);
if (channelDefinition == null) {
throw new FlowableObjectNotFoundException("Could not find a channel definition with id '" + channelDefinitionId + "'.", ChannelDefinition.class);
}
if (restApiInterceptor != null) {
restApiInterceptor.accessChannelDefinitionById(channelDefinition);
}
return channelDefinition;
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry-rest\src\main\java\org\flowable\eventregistry\rest\service\api\repository\BaseEventDefinitionResource.java
| 2
|
请完成以下Java代码
|
public int getEXP_Format_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_EXP_Format_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Request handler.
@param IMP_RequestHandler_ID Request handler */
@Override
public void setIMP_RequestHandler_ID (int IMP_RequestHandler_ID)
{
if (IMP_RequestHandler_ID < 1)
set_ValueNoCheck (COLUMNNAME_IMP_RequestHandler_ID, null);
else
set_ValueNoCheck (COLUMNNAME_IMP_RequestHandler_ID, Integer.valueOf(IMP_RequestHandler_ID));
}
/** Get Request handler.
@return Request handler */
@Override
public int getIMP_RequestHandler_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_IMP_RequestHandler_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.adempiere.process.rpl.requesthandler.model.I_IMP_RequestHandlerType getIMP_RequestHandlerType() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_IMP_RequestHandlerType_ID, org.adempiere.process.rpl.requesthandler.model.I_IMP_RequestHandlerType.class);
}
@Override
public void setIMP_RequestHandlerType(org.adempiere.process.rpl.requesthandler.model.I_IMP_RequestHandlerType IMP_RequestHandlerType)
{
set_ValueFromPO(COLUMNNAME_IMP_RequestHandlerType_ID, org.adempiere.process.rpl.requesthandler.model.I_IMP_RequestHandlerType.class, IMP_RequestHandlerType);
}
/** Set Request handler type.
@param IMP_RequestHandlerType_ID Request handler type */
@Override
public void setIMP_RequestHandlerType_ID (int IMP_RequestHandlerType_ID)
{
if (IMP_RequestHandlerType_ID < 1)
set_Value (COLUMNNAME_IMP_RequestHandlerType_ID, null);
else
set_Value (COLUMNNAME_IMP_RequestHandlerType_ID, Integer.valueOf(IMP_RequestHandlerType_ID));
}
/** Get Request handler type.
@return Request handler type */
@Override
public int getIMP_RequestHandlerType_ID ()
{
|
Integer ii = (Integer)get_Value(COLUMNNAME_IMP_RequestHandlerType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Suchschlüssel.
@param Value
Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\process\rpl\requesthandler\model\X_IMP_RequestHandler.java
| 1
|
请完成以下Java代码
|
private Class<?> loadModelClassForClassname(final String className)
{
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try
{
final Class<?> clazz = classLoader.loadClass(className);
// Make sure that it is a PO class
if (!PO.class.isAssignableFrom(clazz))
{
log.debug("Skip {} because it does not have PO class as supertype", clazz);
return null;
}
return clazz;
}
catch (ClassNotFoundException e)
{
if (log.isDebugEnabled())
{
log.debug("No class found for " + className + " (classloader: " + classLoader + ")", e);
}
}
return null;
}
private final Constructor<?> findIDConstructor(final Class<?> modelClass) throws NoSuchMethodException, SecurityException
{
return modelClass.getDeclaredConstructor(new Class[] { Properties.class, int.class, String.class });
}
public Constructor<?> getIDConstructor(final Class<?> modelClass)
{
try
{
return class2idConstructor.get(modelClass);
}
catch (ExecutionException e)
{
throw new AdempiereException("Cannot get ID constructor for " + modelClass, e);
}
}
|
private final Constructor<?> findResultSetConstructor(final Class<?> modelClass) throws NoSuchMethodException, SecurityException
{
return modelClass.getDeclaredConstructor(new Class[] { Properties.class, ResultSet.class, String.class });
}
public Constructor<?> getResultSetConstructor(final Class<?> modelClass)
{
try
{
return class2resultSetConstructor.get(modelClass);
}
catch (ExecutionException e)
{
throw new AdempiereException("Cannot get ResultSet constructor for " + modelClass, e);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\TableModelClassLoader.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
boolean isEmptyDirectory() {
return this.emptyDirectory;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
StandardConfigDataResource other = (StandardConfigDataResource) obj;
return (this.emptyDirectory == other.emptyDirectory) && isSameUnderlyingResource(this.resource, other.resource);
}
private boolean isSameUnderlyingResource(Resource ours, Resource other) {
return ours.equals(other) || isSameFile(getUnderlyingFile(ours), getUnderlyingFile(other));
}
private boolean isSameFile(@Nullable File ours, @Nullable File other) {
return (ours != null) && ours.equals(other);
}
@Override
public int hashCode() {
File underlyingFile = getUnderlyingFile(this.resource);
return (underlyingFile != null) ? underlyingFile.hashCode() : this.resource.hashCode();
}
@Override
public String toString() {
if (this.resource instanceof FileSystemResource || this.resource instanceof FileUrlResource) {
|
try {
return "file [" + this.resource.getFile() + "]";
}
catch (IOException ex) {
// Ignore
}
}
return this.resource.toString();
}
private @Nullable File getUnderlyingFile(Resource resource) {
try {
if (resource instanceof ClassPathResource || resource instanceof FileSystemResource
|| resource instanceof FileUrlResource) {
return resource.getFile().getAbsoluteFile();
}
}
catch (IOException ex) {
// Ignore
}
return null;
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\StandardConfigDataResource.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class DataSourceConfiguration {
/**
* 创建 user 数据源的配置对象
*/
@Primary
@Bean(name = "userDataSourceProperties")
@ConfigurationProperties(prefix = "spring.datasource.user") // 读取 spring.datasource.user 配置到 DataSourceProperties 对象
public DataSourceProperties userDataSourceProperties() {
return new DataSourceProperties();
}
/**
* 创建 user 数据源
*/
@Primary
@Bean(name = "userDataSource")
@ConfigurationProperties(prefix = "spring.datasource.user.hikari") // 读取 spring.datasource.user 配置到 HikariDataSource 对象
public DataSource userDataSource() {
// 获得 DataSourceProperties 对象
DataSourceProperties properties = this.userDataSourceProperties();
// 创建 HikariDataSource 对象
return createHikariDataSource(properties);
}
/**
* 创建 quartz 数据源的配置对象
*/
@Bean(name = "quartzDataSourceProperties")
|
@ConfigurationProperties(prefix = "spring.datasource.quartz") // 读取 spring.datasource.quartz 配置到 DataSourceProperties 对象
public DataSourceProperties quartzDataSourceProperties() {
return new DataSourceProperties();
}
/**
* 创建 quartz 数据源
*/
@Bean(name = "quartzDataSource")
@ConfigurationProperties(prefix = "spring.datasource.quartz.hikari")
@QuartzDataSource
public DataSource quartzDataSource() {
// 获得 DataSourceProperties 对象
DataSourceProperties properties = this.quartzDataSourceProperties();
// 创建 HikariDataSource 对象
return createHikariDataSource(properties);
}
private static HikariDataSource createHikariDataSource(DataSourceProperties properties) {
// 创建 HikariDataSource 对象
HikariDataSource dataSource = properties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
// 设置线程池名
if (StringUtils.hasText(properties.getName())) {
dataSource.setPoolName(properties.getName());
}
return dataSource;
}
}
|
repos\SpringBoot-Labs-master\lab-28\lab-28-task-quartz-jdbc\src\main\java\cn\iocoder\springboot\lab28\task\config\DataSourceConfiguration.java
| 2
|
请完成以下Java代码
|
public class AbstractTypedValue<T> implements TypedValue {
private static final long serialVersionUID = 1L;
protected T value;
protected ValueType type;
protected boolean isTransient;
public AbstractTypedValue(T value, ValueType type) {
this.value = value;
this.type = type;
}
public T getValue() {
return value;
}
|
public ValueType getType() {
return type;
}
public String toString() {
return "Value '" + value + "' of type '" + type + "', isTransient=" + isTransient;
}
@Override
public boolean isTransient() {
return isTransient;
}
public void setTransient(boolean isTransient) {
this.isTransient = isTransient;
}
}
|
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\value\AbstractTypedValue.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public final class OtlpMetricsExportAutoConfiguration {
private final OtlpMetricsProperties properties;
OtlpMetricsExportAutoConfiguration(OtlpMetricsProperties properties) {
this.properties = properties;
}
@Bean
@ConditionalOnMissingBean
OtlpMetricsConnectionDetails otlpMetricsConnectionDetails() {
return new PropertiesOtlpMetricsConnectionDetails(this.properties);
}
@Bean
@ConditionalOnMissingBean
OtlpConfig otlpConfig(OpenTelemetryProperties openTelemetryProperties,
OtlpMetricsConnectionDetails connectionDetails, Environment environment) {
return new OtlpMetricsPropertiesConfigAdapter(this.properties, openTelemetryProperties, connectionDetails,
environment);
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnThreading(Threading.PLATFORM)
OtlpMeterRegistry otlpMeterRegistry(OtlpConfig otlpConfig, Clock clock,
ObjectProvider<OtlpMetricsSender> metricsSender) {
return builder(otlpConfig, clock, metricsSender).build();
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnThreading(Threading.VIRTUAL)
OtlpMeterRegistry otlpMeterRegistryVirtualThreads(OtlpConfig otlpConfig, Clock clock,
ObjectProvider<OtlpMetricsSender> metricsSender) {
VirtualThreadTaskExecutor executor = new VirtualThreadTaskExecutor("otlp-meter-registry-");
return builder(otlpConfig, clock, metricsSender).threadFactory(executor.getVirtualThreadFactory()).build();
}
|
private OtlpMeterRegistry.Builder builder(OtlpConfig otlpConfig, Clock clock,
ObjectProvider<OtlpMetricsSender> metricsSender) {
OtlpMeterRegistry.Builder builder = OtlpMeterRegistry.builder(otlpConfig).clock(clock);
metricsSender.ifAvailable(builder::metricsSender);
return builder;
}
/**
* Adapts {@link OtlpMetricsProperties} to {@link OtlpMetricsConnectionDetails}.
*/
static class PropertiesOtlpMetricsConnectionDetails implements OtlpMetricsConnectionDetails {
private final OtlpMetricsProperties properties;
PropertiesOtlpMetricsConnectionDetails(OtlpMetricsProperties properties) {
this.properties = properties;
}
@Override
public @Nullable String getUrl() {
return this.properties.getUrl();
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\otlp\OtlpMetricsExportAutoConfiguration.java
| 2
|
请完成以下Spring Boot application配置
|
server:
port: 8080
tomcat:
max-threads: 100
spring:
application:
name: demo
logging:
level:
ROOT: WARN
com.giraone.sb3.demo: INFO
# To have some logs
com.giraone.sb3.demo.controller.filter.SimpleRequestLoggingFilter: DEBUG
# traceID and spanId are predefined MDC keys - we want the logs to include them
pattern.level: '%5p [${spring.application.name:},%X{traceId:-},%X{spanId:-}]'
management:
endpoints:
web:
exposure:
# health,prometheus is needed; the others are for troubleshooting
include: 'health,prometheus,loggers,metrics,env'
endpoint:
loggers:
enabled: true
env:
show-values: ALWAYS # Show values - do not use in production (may leak passwords)
metrics:
distribution:
percentiles-histogram:
# For exemplars to work, we need histogram buckets
|
http.server.requests: true
tracing:
sampling:
# All traces should be sent to latency analysis tool
probability: 1.0
application:
show-config-on-startup: true
# URL for second service
client:
host: 127.0.0.1
port: 8080
propagated-headers:
- Authorization
# - traceparent
# - tracestate
# - X-B3-TraceId
# - X-B3-SpanId
|
repos\spring-boot3-demo-master\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
protected void formatPage(final Sheet sheet)
{
super.formatPage(sheet);
MPrintPaper paper = MPrintPaper.get(this.m_printFormat.getAD_PrintPaper_ID());
//
// Set paper size:
short paperSize = -1;
MediaSizeName mediaSizeName = paper.getMediaSize().getMediaSizeName();
if (MediaSizeName.NA_LETTER.equals(mediaSizeName))
{
paperSize = PrintSetup.LETTER_PAPERSIZE;
}
else if (MediaSizeName.NA_LEGAL.equals(mediaSizeName))
{
paperSize = PrintSetup.LEGAL_PAPERSIZE;
}
else if (MediaSizeName.EXECUTIVE.equals(mediaSizeName))
{
paperSize = PrintSetup.EXECUTIVE_PAPERSIZE;
}
else if (MediaSizeName.ISO_A4.equals(mediaSizeName))
{
paperSize = PrintSetup.A4_PAPERSIZE;
}
else if (MediaSizeName.ISO_A5.equals(mediaSizeName))
{
paperSize = PrintSetup.A5_PAPERSIZE;
}
else if (MediaSizeName.NA_NUMBER_10_ENVELOPE.equals(mediaSizeName))
{
paperSize = PrintSetup.ENVELOPE_10_PAPERSIZE;
}
// else if (MediaSizeName..equals(mediaSizeName)) {
// paperSize = PrintSetup.ENVELOPE_DL_PAPERSIZE;
// }
// else if (MediaSizeName..equals(mediaSizeName)) {
// paperSize = PrintSetup.ENVELOPE_CS_PAPERSIZE;
// }
else if (MediaSizeName.MONARCH_ENVELOPE.equals(mediaSizeName))
{
paperSize = PrintSetup.ENVELOPE_MONARCH_PAPERSIZE;
}
if (paperSize != -1)
{
sheet.getPrintSetup().setPaperSize(paperSize);
}
//
// Set Landscape/Portrait:
sheet.getPrintSetup().setLandscape(paper.isLandscape());
//
|
// Set Paper Margin:
sheet.setMargin(Sheet.TopMargin, ((double)paper.getMarginTop()) / 72);
sheet.setMargin(Sheet.RightMargin, ((double)paper.getMarginRight()) / 72);
sheet.setMargin(Sheet.LeftMargin, ((double)paper.getMarginLeft()) / 72);
sheet.setMargin(Sheet.BottomMargin, ((double)paper.getMarginBottom()) / 72);
//
}
@Override
protected List<CellValue> getNextRow()
{
final ArrayList<CellValue> result = new ArrayList<>();
for (int i = 0; i < getColumnCount(); i++)
{
result.add(getValueAt(rowNumber, i));
}
rowNumber++;
return result;
}
@Override
protected boolean hasNextRow()
{
return rowNumber < getRowCount();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\print\export\PrintDataExcelExporter.java
| 1
|
请完成以下Java代码
|
public Builder trackField(final DocumentFieldDescriptor.Builder field)
{
documentFieldBuilder = field;
return this;
}
public boolean isSpecialFieldToExcludeFromLayout()
{
return documentFieldBuilder != null && documentFieldBuilder.isSpecialFieldToExcludeFromLayout();
}
public Builder setDevices(@NonNull final DeviceDescriptorsList devices)
{
this._devices = devices;
return this;
}
private DeviceDescriptorsList getDevices()
{
return _devices;
}
public Builder setSupportZoomInto(final boolean supportZoomInto)
{
this.supportZoomInto = supportZoomInto;
return this;
}
private boolean isSupportZoomInto()
|
{
return supportZoomInto;
}
public Builder setForbidNewRecordCreation(final boolean forbidNewRecordCreation)
{
this.forbidNewRecordCreation = forbidNewRecordCreation;
return this;
}
private boolean isForbidNewRecordCreation()
{
return forbidNewRecordCreation;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutElementFieldDescriptor.java
| 1
|
请完成以下Java代码
|
public String getSql()
{
buildSql();
return sqlWhereClause;
}
@Override
public List<Object> getSqlParams(Properties ctx)
{
buildSql();
return sqlParams;
}
@Override
public boolean accept(T model)
{
final Object value = InterfaceWrapperHelper.getValueOrNull(model, columnName);
if (value == null)
{
return false;
}
else if (value instanceof String)
{
return ((String)value).endsWith(endsWithString);
}
else
|
{
throw new IllegalArgumentException("Invalid '" + columnName + "' value for " + model);
}
}
private boolean sqlBuilt = false;
private String sqlWhereClause = null;
private List<Object> sqlParams = null;
private void buildSql()
{
if (sqlBuilt)
{
return;
}
final String sqlWhereClause = columnName
+ " LIKE "
+ "'%'||? ";
this.sqlParams = Collections.singletonList(endsWithString);
this.sqlWhereClause = sqlWhereClause;
this.sqlBuilt = true;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\EndsWithQueryFilter.java
| 1
|
请完成以下Java代码
|
public boolean isJsonVariableTypeTrackObjects() {
return jsonVariableTypeTrackObjects;
}
public AppEngineConfiguration setJsonVariableTypeTrackObjects(boolean jsonVariableTypeTrackObjects) {
this.jsonVariableTypeTrackObjects = jsonVariableTypeTrackObjects;
return this;
}
@Override
public VariableJsonMapper getVariableJsonMapper() {
return variableJsonMapper;
}
@Override
public AppEngineConfiguration setVariableJsonMapper(VariableJsonMapper variableJsonMapper) {
this.variableJsonMapper = variableJsonMapper;
return this;
}
public boolean isDisableIdmEngine() {
return disableIdmEngine;
}
public AppEngineConfiguration setDisableIdmEngine(boolean disableIdmEngine) {
this.disableIdmEngine = disableIdmEngine;
return this;
}
public boolean isDisableEventRegistry() {
return disableEventRegistry;
}
|
public AppEngineConfiguration setDisableEventRegistry(boolean disableEventRegistry) {
this.disableEventRegistry = disableEventRegistry;
return this;
}
public BusinessCalendarManager getBusinessCalendarManager() {
return businessCalendarManager;
}
public AppEngineConfiguration setBusinessCalendarManager(BusinessCalendarManager businessCalendarManager) {
this.businessCalendarManager = businessCalendarManager;
return this;
}
}
|
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\AppEngineConfiguration.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Employee {
@Id
private Long id;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parking_spot_id")
private ParkingSpot parkingSpot;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "department_id")
private Department department;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
|
public ParkingSpot getParkingSpot() {
return parkingSpot;
}
public void setParkingSpot(ParkingSpot parkingSpot) {
this.parkingSpot = parkingSpot;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\associations\unidirectional\Employee.java
| 2
|
请完成以下Java代码
|
public class CalculatedFieldTbelScriptEngine implements CalculatedFieldScriptEngine {
private final TbelInvokeService tbelInvokeService;
private final UUID scriptId;
private final TenantId tenantId;
public CalculatedFieldTbelScriptEngine(TenantId tenantId, TbelInvokeService tbelInvokeService, String script, String... argNames) {
this.tenantId = tenantId;
this.tbelInvokeService = tbelInvokeService;
try {
this.scriptId = this.tbelInvokeService.eval(tenantId, ScriptType.CALCULATED_FIELD_SCRIPT, script, argNames).get();
} catch (Exception e) {
Throwable t = e;
if (e instanceof ExecutionException) {
t = e.getCause();
}
throw new IllegalArgumentException("Can't compile script: " + t.getMessage(), t);
}
}
@Override
public ListenableFuture<Object> executeScriptAsync(Object[] args) {
log.trace("Executing script async, args {}", args);
return Futures.transformAsync(tbelInvokeService.invokeScript(tenantId, null, this.scriptId, args),
o -> {
try {
return Futures.immediateFuture(o);
} catch (Exception e) {
if (e.getCause() instanceof ScriptException) {
return Futures.immediateFailedFuture(e.getCause());
} else if (e.getCause() instanceof RuntimeException) {
return Futures.immediateFailedFuture(new ScriptException(e.getCause().getMessage()));
} else {
|
return Futures.immediateFailedFuture(new ScriptException(e));
}
}
}, MoreExecutors.directExecutor());
}
@Override
public ListenableFuture<JsonNode> executeJsonAsync(Object[] args) {
return Futures.transform(executeScriptAsync(args), JacksonUtil::valueToTree, MoreExecutors.directExecutor());
}
@Override
public void destroy() {
tbelInvokeService.release(this.scriptId);
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\cf\ctx\state\CalculatedFieldTbelScriptEngine.java
| 1
|
请完成以下Java代码
|
public String getR_AuthCode ()
{
return (String)get_Value(COLUMNNAME_R_AuthCode);
}
// /** TenderType AD_Reference_ID=214 */
// public static final int TENDERTYPE_AD_Reference_ID=214;
// /** Kreditkarte = C */
// public static final String TENDERTYPE_Kreditkarte = "C";
// /** Scheck = K */
// public static final String TENDERTYPE_Scheck = "K";
// /** ueberweisung = A */
// public static final String TENDERTYPE_ueberweisung = "A";
// /** Bankeinzug = D */
// public static final String TENDERTYPE_Bankeinzug = "D";
// /** Account = T */
// public static final String TENDERTYPE_Account = "T";
// /** Bar = X */
// public static final String TENDERTYPE_Bar = "X";
/** Set Tender type.
@param TenderType
Method of Payment
*/
@Override
public void setTenderType (String TenderType)
{
set_Value (COLUMNNAME_TenderType, TenderType);
}
/** Get Tender type.
@return Method of Payment
*/
@Override
public String getTenderType ()
{
return (String)get_Value(COLUMNNAME_TenderType);
}
// /** TrxType AD_Reference_ID=215 */
// public static final int TRXTYPE_AD_Reference_ID=215;
// /** Verkauf = S */
// public static final String TRXTYPE_Verkauf = "S";
|
// /** Delayed Capture = D */
// public static final String TRXTYPE_DelayedCapture = "D";
// /** Kredit (Zahlung) = C */
// public static final String TRXTYPE_KreditZahlung = "C";
// /** Voice Authorization = F */
// public static final String TRXTYPE_VoiceAuthorization = "F";
// /** Autorisierung = A */
// public static final String TRXTYPE_Autorisierung = "A";
// /** Loeschen = V */
// public static final String TRXTYPE_Loeschen = "V";
// /** Rueckzahlung = R */
// public static final String TRXTYPE_Rueckzahlung = "R";
/** Set Transaction Type.
@param TrxType
Type of credit card transaction
*/
@Override
public void setTrxType (String TrxType)
{
set_Value (COLUMNNAME_TrxType, TrxType);
}
/** Get Transaction Type.
@return Type of credit card transaction
*/
@Override
public String getTrxType ()
{
return (String)get_Value(COLUMNNAME_TrxType);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\schaeffer\pay\model\X_Pay_OnlinePaymentHistory.java
| 1
|
请完成以下Java代码
|
public void updateCurrencyRateIfNotSet()
{
if (getCurrencyRate().signum() == 0 || getCurrencyRate().compareTo(BigDecimal.ONE) == 0)
{
updateCurrencyRate();
}
}
public void updateCurrencyRate()
{
setCurrencyRate(computeCurrencyRate());
}
public void setTaxIdAndUpdateVatCode(@Nullable final TaxId taxId)
{
if (TaxId.equals(this.taxId, taxId))
{
return;
}
this.taxId = taxId;
this.vatCode = computeVATCode().map(VATCode::getCode).orElse(null);
}
private Optional<VATCode> computeVATCode()
{
if (taxId == null)
{
return Optional.empty();
}
final boolean isSOTrx = m_docLine != null ? m_docLine.isSOTrx() : m_doc.isSOTrx();
return services.findVATCode(VATCodeMatchingRequest.builder()
.setC_AcctSchema_ID(getAcctSchemaId().getRepoId())
.setC_Tax_ID(taxId.getRepoId())
.setIsSOTrx(isSOTrx)
.setDate(this.dateAcct)
.build());
}
public void updateFAOpenItemTrxInfo()
{
|
if (openItemTrxInfo != null)
{
return;
}
this.openItemTrxInfo = services.computeOpenItemTrxInfo(this).orElse(null);
}
void setOpenItemTrxInfo(@Nullable final FAOpenItemTrxInfo openItemTrxInfo)
{
this.openItemTrxInfo = openItemTrxInfo;
}
public void updateFrom(@NonNull FactAcctChanges changes)
{
setAmtSource(changes.getAmtSourceDr(), changes.getAmtSourceCr());
setAmtAcct(changes.getAmtAcctDr(), changes.getAmtAcctCr());
updateCurrencyRate();
if (changes.getAccountId() != null)
{
this.accountId = changes.getAccountId();
}
setTaxIdAndUpdateVatCode(changes.getTaxId());
setDescription(changes.getDescription());
this.M_Product_ID = changes.getProductId();
this.userElementString1 = changes.getUserElementString1();
this.C_OrderSO_ID = changes.getSalesOrderId();
this.C_Activity_ID = changes.getActivityId();
this.appliedUserChanges = changes;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\FactLine.java
| 1
|
请完成以下Java代码
|
public void setC_TaxType_ID (int C_TaxType_ID)
{
if (C_TaxType_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_TaxType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_TaxType_ID, Integer.valueOf(C_TaxType_ID));
}
/** Get Tax Type.
@return Tax Type */
public int getC_TaxType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_TaxType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
|
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_C_TaxType.java
| 1
|
请完成以下Java代码
|
public class SimpleSavedRequest implements SavedRequest {
@Serial
private static final long serialVersionUID = 807650604272166969L;
private String redirectUrl;
private List<Cookie> cookies = new ArrayList<>();
private String method = "GET";
private Map<String, List<String>> headers = new HashMap<>();
private List<Locale> locales = new ArrayList<>();
private Map<String, String[]> parameters = new HashMap<>();
public SimpleSavedRequest() {
this.redirectUrl = "/";
this.method = "GET";
}
public SimpleSavedRequest(String redirectUrl) {
this.redirectUrl = redirectUrl;
}
public SimpleSavedRequest(SavedRequest request) {
this.redirectUrl = request.getRedirectUrl();
this.cookies = request.getCookies();
for (String headerName : request.getHeaderNames()) {
this.headers.put(headerName, request.getHeaderValues(headerName));
}
this.locales = request.getLocales();
this.parameters = request.getParameterMap();
this.method = request.getMethod();
}
@Override
public String getRedirectUrl() {
return this.redirectUrl;
}
@Override
public List<Cookie> getCookies() {
return this.cookies;
}
@Override
public String getMethod() {
return this.method;
}
@Override
public List<String> getHeaderValues(String name) {
return this.headers.getOrDefault(name, new ArrayList<>());
}
@Override
public Collection<String> getHeaderNames() {
return this.headers.keySet();
}
@Override
public List<Locale> getLocales() {
return this.locales;
}
@Override
public String[] getParameterValues(String name) {
return this.parameters.getOrDefault(name, new String[0]);
}
@Override
public Map<String, String[]> getParameterMap() {
|
return this.parameters;
}
public void setRedirectUrl(String redirectUrl) {
Assert.notNull(redirectUrl, "redirectUrl cannot be null");
this.redirectUrl = redirectUrl;
}
public void setCookies(List<Cookie> cookies) {
Assert.notNull(cookies, "cookies cannot be null");
this.cookies = cookies;
}
public void setMethod(String method) {
Assert.notNull(method, "method cannot be null");
this.method = method;
}
public void setHeaders(Map<String, List<String>> headers) {
Assert.notNull(headers, "headers cannot be null");
this.headers = headers;
}
public void setLocales(List<Locale> locales) {
Assert.notNull(locales, "locales cannot be null");
this.locales = locales;
}
public void setParameters(Map<String, String[]> parameters) {
Assert.notNull(parameters, "parameters cannot be null");
this.parameters = parameters;
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\savedrequest\SimpleSavedRequest.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PageHelperAutoConfiguration implements InitializingBean {
private final List<SqlSessionFactory> sqlSessionFactoryList;
private final PageHelperProperties properties;
public PageHelperAutoConfiguration(List<SqlSessionFactory> sqlSessionFactoryList, PageHelperStandardProperties standardProperties) {
this.sqlSessionFactoryList = sqlSessionFactoryList;
this.properties = standardProperties.getProperties();
}
@Override
public void afterPropertiesSet() throws Exception {
PageInterceptor interceptor = new PageInterceptor();
interceptor.setProperties(this.properties);
for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
org.apache.ibatis.session.Configuration configuration = sqlSessionFactory.getConfiguration();
if (!containsInterceptor(configuration, interceptor)) {
configuration.addInterceptor(interceptor);
}
|
}
}
/**
* 是否已经存在相同的拦截器
*
* @param configuration
* @param interceptor
* @return
*/
private boolean containsInterceptor(org.apache.ibatis.session.Configuration configuration, Interceptor interceptor) {
try {
// getInterceptors since 3.2.2
return configuration.getInterceptors().stream().anyMatch(config->interceptor.getClass().isAssignableFrom(config.getClass()));
} catch (Exception e) {
return false;
}
}
}
|
repos\pagehelper-spring-boot-master\pagehelper-spring-boot-autoconfigure\src\main\java\com\github\pagehelper\autoconfigure\PageHelperAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public void setAD_Table(org.compiere.model.I_AD_Table AD_Table)
{
set_ValueFromPO(COLUMNNAME_AD_Table_ID, org.compiere.model.I_AD_Table.class, AD_Table);
}
/** Set DB-Tabelle.
@param AD_Table_ID
Database Table information
*/
@Override
public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get DB-Tabelle.
@return Database Table information
*/
@Override
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Referenced Document.
@param C_ReferenceNo_Doc_ID Referenced Document */
@Override
public void setC_ReferenceNo_Doc_ID (int C_ReferenceNo_Doc_ID)
{
if (C_ReferenceNo_Doc_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_Doc_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_Doc_ID, Integer.valueOf(C_ReferenceNo_Doc_ID));
}
/** Get Referenced Document.
@return Referenced Document */
@Override
public int getC_ReferenceNo_Doc_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_ReferenceNo_Doc_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.document.refid.model.I_C_ReferenceNo getC_ReferenceNo() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_ReferenceNo_ID, de.metas.document.refid.model.I_C_ReferenceNo.class);
}
@Override
public void setC_ReferenceNo(de.metas.document.refid.model.I_C_ReferenceNo C_ReferenceNo)
{
set_ValueFromPO(COLUMNNAME_C_ReferenceNo_ID, de.metas.document.refid.model.I_C_ReferenceNo.class, C_ReferenceNo);
}
/** Set Reference No.
@param C_ReferenceNo_ID Reference No */
@Override
public void setC_ReferenceNo_ID (int C_ReferenceNo_ID)
{
if (C_ReferenceNo_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_ID, Integer.valueOf(C_ReferenceNo_ID));
}
|
/** Get Reference No.
@return Reference No */
@Override
public int getC_ReferenceNo_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_ReferenceNo_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java-gen\de\metas\document\refid\model\X_C_ReferenceNo_Doc.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class StockEstimateCreatedHandler implements MaterialEventHandler<AbstractStockEstimateEvent>
{
private final CandidateChangeService candidateChangeHandler;
private final StockEstimateEventService stockEstimateEventService;
public StockEstimateCreatedHandler(
@NonNull final CandidateChangeService candidateChangeHandler,
@NonNull final StockEstimateEventService stockEstimateEventService)
{
this.candidateChangeHandler = candidateChangeHandler;
this.stockEstimateEventService = stockEstimateEventService;
}
@Override
public Collection<Class<? extends AbstractStockEstimateEvent>> getHandledEventType()
{
return ImmutableList.of(StockEstimateCreatedEvent.class);
}
@Override
public void handleEvent(final AbstractStockEstimateEvent event)
{
final Candidate existingStockEstimateCandidate = stockEstimateEventService.retrieveExistingStockEstimateCandidateOrNull(event);
if (existingStockEstimateCandidate != null)
{
throw new AdempiereException("No candidate should exist for event, but an actual candidate was returned")
.appendParametersToMessage()
.setParameter("StockEstimateCreatedEvent", event);
}
final Candidate previousStockOrNull = stockEstimateEventService.retrievePreviousStockCandidateOrNull(event);
|
final BigDecimal currentATP = previousStockOrNull != null ? previousStockOrNull.getQuantity() : BigDecimal.ZERO;
final BigDecimal deltaATP = currentATP.subtract(event.getQuantityDelta());
final StockChangeDetail stockChangeDetail = StockChangeDetail.builder()
.eventDate(event.getEventDate())
.freshQuantityOnHandRepoId(event.getFreshQtyOnHandId())
.freshQuantityOnHandLineRepoId(event.getFreshQtyOnHandLineId())
.isReverted(false)
.build();
final Candidate.CandidateBuilder supplyCandidateBuilder = Candidate.builder()
.clientAndOrgId(event.getClientAndOrgId())
.materialDescriptor(event.getMaterialDescriptor())
.businessCase(CandidateBusinessCase.STOCK_CHANGE)
.businessCaseDetail(stockChangeDetail);
if (deltaATP.signum() > 0)
{
supplyCandidateBuilder
.type(CandidateType.INVENTORY_DOWN)
.quantity(deltaATP);
}
else
{
supplyCandidateBuilder
.type(CandidateType.INVENTORY_UP)
.quantity(deltaATP.negate());
}
candidateChangeHandler.onCandidateNewOrChange(supplyCandidateBuilder.build());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\stockchange\StockEstimateCreatedHandler.java
| 2
|
请完成以下Java代码
|
public void collectDocumentValidStatusChanged(final DocumentPath documentPath, final DocumentValidStatus documentValidStatus)
{
documentChanges(documentPath)
.collectDocumentValidStatusChanged(documentValidStatus);
}
@Override
public void collectValidStatus(final IDocumentFieldView documentField)
{
documentChanges(documentField)
.collectValidStatusChanged(documentField);
}
@Override
public void collectDocumentSaveStatusChanged(final DocumentPath documentPath, final DocumentSaveStatus documentSaveStatus)
{
documentChanges(documentPath)
.collectDocumentSaveStatusChanged(documentSaveStatus);
}
@Override
public void collectDeleted(final DocumentPath documentPath)
{
documentChanges(documentPath)
.collectDeleted();
}
@Override
public void collectStaleDetailId(final DocumentPath rootDocumentPath, final DetailId detailId)
{
rootDocumentChanges(rootDocumentPath)
.includedDetailInfo(detailId)
.setStale();
}
@Override
public void collectAllowNew(final DocumentPath rootDocumentPath, final DetailId detailId, final LogicExpressionResult allowNew)
{
rootDocumentChanges(rootDocumentPath)
.includedDetailInfo(detailId)
.setAllowNew(allowNew);
}
@Override
public void collectAllowDelete(final DocumentPath rootDocumentPath, final DetailId detailId, final LogicExpressionResult allowDelete)
{
rootDocumentChanges(rootDocumentPath)
.includedDetailInfo(detailId)
.setAllowDelete(allowDelete);
}
|
private boolean isStaleDocumentChanges(final DocumentChanges documentChanges)
{
final DocumentPath documentPath = documentChanges.getDocumentPath();
if (!documentPath.isSingleIncludedDocument())
{
return false;
}
final DocumentPath rootDocumentPath = documentPath.getRootDocumentPath();
final DetailId detailId = documentPath.getDetailId();
return documentChangesIfExists(rootDocumentPath)
.flatMap(rootDocumentChanges -> rootDocumentChanges.includedDetailInfoIfExists(detailId))
.map(IncludedDetailInfo::isStale)
.orElse(false);
}
@Override
public void collectEvent(final IDocumentFieldChangedEvent event)
{
documentChanges(event.getDocumentPath())
.collectEvent(event);
}
@Override
public void collectFieldWarning(final IDocumentFieldView documentField, final DocumentFieldWarning fieldWarning)
{
documentChanges(documentField)
.collectFieldWarning(documentField, fieldWarning);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentChangesCollector.java
| 1
|
请完成以下Java代码
|
public void setPath(String path) {
this.path = path;
}
public String getGeom() {
return geom;
}
public void setGeom(String geom) {
this.geom = geom;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDes() {
|
return des;
}
public void setDes(String des) {
this.des = des;
}
public boolean isAppendWrite() {
return appendWrite;
}
public void setAppendWrite(boolean appendWrite) {
this.appendWrite = appendWrite;
}
}
|
repos\springboot-demo-master\GeoTools\src\main\java\com\et\geotools\pojos\ShpInfo.java
| 1
|
请完成以下Java代码
|
public DemandDetail getDemandDetail()
{
return CoalesceUtil.coalesce(DemandDetail.castOrNull(businessCaseDetail), additionalDemandDetail);
}
public BigDecimal getBusinessCaseDetailQty()
{
if (businessCaseDetail == null)
{
return BigDecimal.ZERO;
}
return businessCaseDetail.getQty();
}
@Nullable
public OrderAndLineId getSalesOrderLineId()
{
final DemandDetail demandDetail = getDemandDetail();
if (demandDetail == null)
{
return null;
}
return OrderAndLineId.ofRepoIdsOrNull(demandDetail.getOrderId(), demandDetail.getOrderLineId());
}
@NonNull
public BusinessCaseDetail getBusinessCaseDetailNotNull()
{
return Check.assumeNotNull(getBusinessCaseDetail(), "businessCaseDetail is not null: {}", this);
}
public <T extends BusinessCaseDetail> Optional<T> getBusinessCaseDetail(@NonNull final Class<T> type)
{
return type.isInstance(businessCaseDetail) ? Optional.of(type.cast(businessCaseDetail)) : Optional.empty();
}
public <T extends BusinessCaseDetail> T getBusinessCaseDetailNotNull(@NonNull final Class<T> type)
{
if (type.isInstance(businessCaseDetail))
{
return type.cast(businessCaseDetail);
}
else
{
throw new AdempiereException("businessCaseDetail is not matching " + type.getSimpleName() + ": " + this);
}
}
public <T extends BusinessCaseDetail> Candidate withBusinessCaseDetail(@NonNull final Class<T> type, @NonNull final UnaryOperator<T> mapper)
{
final T businessCaseDetail = getBusinessCaseDetailNotNull(type);
final T businessCaseDetailChanged = mapper.apply(businessCaseDetail);
if (Objects.equals(businessCaseDetail, businessCaseDetailChanged))
{
return this;
}
return withBusinessCaseDetail(businessCaseDetailChanged);
}
@Nullable
public String getTraceId()
{
|
final DemandDetail demandDetail = getDemandDetail();
return demandDetail != null ? demandDetail.getTraceId() : null;
}
/**
* This is enabled by the current usage of {@link #parentId}
*/
public boolean isStockCandidateOfThisCandidate(@NonNull final Candidate potentialStockCandidate)
{
if (potentialStockCandidate.type != CandidateType.STOCK)
{
return false;
}
switch (type)
{
case DEMAND:
return potentialStockCandidate.getParentId().equals(id);
case SUPPLY:
return potentialStockCandidate.getId().equals(parentId);
default:
return false;
}
}
/**
* The qty is always stored as an absolute value on the candidate, but we're interested if the candidate is adding or subtracting qty to the stock.
*/
public BigDecimal getStockImpactPlannedQuantity()
{
switch (getType())
{
case DEMAND:
case UNEXPECTED_DECREASE:
case INVENTORY_DOWN:
return getQuantity().negate();
default:
return getQuantity();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\Candidate.java
| 1
|
请完成以下Java代码
|
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
public String getRePassword() {
return rePassword;
}
public void setRePassword(String rePassword) {
this.rePassword = rePassword;
}
public String getHistoryPassword() {
return historyPassword;
}
public void setHistoryPassword(String historyPassword) {
this.historyPassword = historyPassword;
}
public Role getRole() {
return role;
|
}
public void setRole(Role role) {
this.role = role;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", cnname=" + cnname +
", username=" + username +
", password=" + password +
", email=" + email +
", telephone=" + telephone +
", mobilePhone=" + mobilePhone +
'}';
}
}
|
repos\springBoot-master\springboot-springSecurity4\src\main\java\com\yy\example\bean\User.java
| 1
|
请完成以下Java代码
|
protected DataManager<HistoricIdentityLinkEntity> getDataManager() {
return historicIdentityLinkDataManager;
}
@Override
public List<HistoricIdentityLinkEntity> findHistoricIdentityLinksByTaskId(String taskId) {
return historicIdentityLinkDataManager.findHistoricIdentityLinksByTaskId(taskId);
}
@Override
public List<HistoricIdentityLinkEntity> findHistoricIdentityLinksByProcessInstanceId(String processInstanceId) {
return historicIdentityLinkDataManager.findHistoricIdentityLinksByProcessInstanceId(processInstanceId);
}
@Override
public void deleteHistoricIdentityLinksByTaskId(String taskId) {
List<HistoricIdentityLinkEntity> identityLinks = findHistoricIdentityLinksByTaskId(taskId);
for (HistoricIdentityLinkEntity identityLink : identityLinks) {
delete(identityLink);
}
}
|
@Override
public void deleteHistoricIdentityLinksByProcInstance(final String processInstanceId) {
List<HistoricIdentityLinkEntity> identityLinks =
historicIdentityLinkDataManager.findHistoricIdentityLinksByProcessInstanceId(processInstanceId);
for (HistoricIdentityLinkEntity identityLink : identityLinks) {
delete(identityLink);
}
}
public HistoricIdentityLinkDataManager getHistoricIdentityLinkDataManager() {
return historicIdentityLinkDataManager;
}
public void setHistoricIdentityLinkDataManager(HistoricIdentityLinkDataManager historicIdentityLinkDataManager) {
this.historicIdentityLinkDataManager = historicIdentityLinkDataManager;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricIdentityLinkEntityManagerImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected BuildVersion getBuildVersion(List<Instance> instances) {
List<BuildVersion> versions = instances.stream()
.map(Instance::getBuildVersion)
.filter(Objects::nonNull)
.distinct()
.sorted()
.toList();
if (versions.isEmpty()) {
return null;
}
else if (versions.size() == 1) {
return versions.get(0);
}
else {
return BuildVersion.valueOf(versions.get(0) + " ... " + versions.get(versions.size() - 1));
}
}
protected Tuple2<String, Instant> getStatus(List<Instance> instances) {
// TODO: Correct is just a second readmodel for groups
Map<String, Instant> statusWithTime = instances.stream()
.collect(toMap((instance) -> instance.getStatusInfo().getStatus(), Instance::getStatusTimestamp,
this::getMax));
if (statusWithTime.size() == 1) {
Map.Entry<String, Instant> e = statusWithTime.entrySet().iterator().next();
return Tuples.of(e.getKey(), e.getValue());
}
if (statusWithTime.containsKey(StatusInfo.STATUS_UP)) {
Instant oldestNonUp = statusWithTime.entrySet()
.stream()
|
.filter((e) -> !StatusInfo.STATUS_UP.equals(e.getKey()))
.map(Map.Entry::getValue)
.min(naturalOrder())
.orElse(Instant.EPOCH);
Instant latest = getMax(oldestNonUp, statusWithTime.getOrDefault(StatusInfo.STATUS_UP, Instant.EPOCH));
return Tuples.of(StatusInfo.STATUS_RESTRICTED, latest);
}
return statusWithTime.entrySet()
.stream()
.min(Map.Entry.comparingByKey(StatusInfo.severity()))
.map((e) -> Tuples.of(e.getKey(), e.getValue()))
.orElse(Tuples.of(STATUS_UNKNOWN, Instant.EPOCH));
}
protected Instant getMax(Instant t1, Instant t2) {
return (t1.compareTo(t2) >= 0) ? t1 : t2;
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\services\ApplicationRegistry.java
| 2
|
请完成以下Java代码
|
public static void writePools(BpmnModel model, XMLStreamWriter xtw) throws Exception {
if (!model.getPools().isEmpty()) {
xtw.writeStartElement(ELEMENT_COLLABORATION);
xtw.writeAttribute(ATTRIBUTE_ID, "Collaboration");
for (Pool pool : model.getPools()) {
xtw.writeStartElement(ELEMENT_PARTICIPANT);
xtw.writeAttribute(ATTRIBUTE_ID, pool.getId());
if (StringUtils.isNotEmpty(pool.getName())) {
xtw.writeAttribute(ATTRIBUTE_NAME, pool.getName());
}
if (StringUtils.isNotEmpty(pool.getProcessRef())) {
xtw.writeAttribute(ATTRIBUTE_PROCESS_REF, pool.getProcessRef());
}
xtw.writeEndElement();
}
for (MessageFlow messageFlow : model.getMessageFlows().values()) {
xtw.writeStartElement(ELEMENT_MESSAGE_FLOW);
xtw.writeAttribute(ATTRIBUTE_ID, messageFlow.getId());
if (StringUtils.isNotEmpty(messageFlow.getName())) {
xtw.writeAttribute(ATTRIBUTE_NAME, messageFlow.getName());
}
|
if (StringUtils.isNotEmpty(messageFlow.getSourceRef())) {
xtw.writeAttribute(ATTRIBUTE_FLOW_SOURCE_REF, messageFlow.getSourceRef());
}
if (StringUtils.isNotEmpty(messageFlow.getTargetRef())) {
xtw.writeAttribute(ATTRIBUTE_FLOW_TARGET_REF, messageFlow.getTargetRef());
}
if (StringUtils.isNotEmpty(messageFlow.getMessageRef())) {
xtw.writeAttribute(ATTRIBUTE_MESSAGE_REF, messageFlow.getMessageRef());
}
xtw.writeEndElement();
}
xtw.writeEndElement();
}
}
}
|
repos\flowable-engine-main\modules\flowable-bpmn-converter\src\main\java\org\flowable\bpmn\converter\export\CollaborationExport.java
| 1
|
请完成以下Java代码
|
public boolean isMatchingClientId(@NonNull final ClientId clientIdToMatch)
{
return clientId.isSystem() || ClientId.equals(clientId, clientIdToMatch);
}
public boolean isUnconditional()
{
return !isStdUserWorkflow() && getConditions().isEmpty();
} // isUnconditional
public BooleanWithReason checkAllowGoingAwayFrom(final WFActivity fromActivity)
{
if (isStdUserWorkflow())
{
final IDocument document = fromActivity.getDocumentOrNull();
if (document != null)
{
final String docStatus = document.getDocStatus();
final String docAction = document.getDocAction();
if (!IDocument.ACTION_Complete.equals(docAction)
|| IDocument.STATUS_Completed.equals(docStatus)
|| IDocument.STATUS_WaitingConfirmation.equals(docStatus)
|| IDocument.STATUS_WaitingPayment.equals(docStatus)
|| IDocument.STATUS_Voided.equals(docStatus)
|| IDocument.STATUS_Closed.equals(docStatus)
|| IDocument.STATUS_Reversed.equals(docStatus))
{
return BooleanWithReason.falseBecause("document state is not valid for a standard workflow transition (docStatus=" + docStatus + ", docAction=" + docAction + ")");
}
}
}
// No Conditions
final ImmutableList<WFNodeTransitionCondition> conditions = getConditions();
if (conditions.isEmpty())
{
return BooleanWithReason.trueBecause("no conditions");
}
// First condition always AND
|
boolean ok = conditions.get(0).evaluate(fromActivity);
for (int i = 1; i < conditions.size(); i++)
{
final WFNodeTransitionCondition condition = conditions.get(i);
if (condition.isOr())
{
ok = ok || condition.evaluate(fromActivity);
}
else
{
ok = ok && condition.evaluate(fromActivity);
}
} // for all conditions
return ok
? BooleanWithReason.trueBecause("transition conditions matched")
: BooleanWithReason.falseBecause("transition conditions NOT matched");
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\WFNodeTransition.java
| 1
|
请完成以下Java代码
|
public OAuth2ClientRegistrationTemplate saveClientRegistrationTemplate(OAuth2ClientRegistrationTemplate clientRegistrationTemplate) {
log.trace("Executing saveClientRegistrationTemplate [{}]", clientRegistrationTemplate);
clientRegistrationTemplateValidator.validate(clientRegistrationTemplate, o -> TenantId.SYS_TENANT_ID);
OAuth2ClientRegistrationTemplate savedClientRegistrationTemplate;
try {
savedClientRegistrationTemplate = clientRegistrationTemplateDao.save(TenantId.SYS_TENANT_ID, clientRegistrationTemplate);
} catch (Exception t) {
ConstraintViolationException e = extractConstraintViolationException(t).orElse(null);
if (e != null && e.getConstraintName() != null && e.getConstraintName().equalsIgnoreCase("oauth2_template_provider_id_unq_key")) {
throw new DataValidationException("Client registration template with such providerId already exists!");
} else {
throw t;
}
}
return savedClientRegistrationTemplate;
}
@Override
public Optional<OAuth2ClientRegistrationTemplate> findClientRegistrationTemplateByProviderId(String providerId) {
log.trace("Executing findClientRegistrationTemplateByProviderId [{}]", providerId);
validateString(providerId, id -> INCORRECT_CLIENT_REGISTRATION_PROVIDER_ID + id);
return clientRegistrationTemplateDao.findByProviderId(providerId);
}
@Override
public OAuth2ClientRegistrationTemplate findClientRegistrationTemplateById(OAuth2ClientRegistrationTemplateId templateId) {
|
log.trace("Executing findClientRegistrationTemplateById [{}]", templateId);
validateId(templateId, id -> INCORRECT_CLIENT_REGISTRATION_TEMPLATE_ID + id);
return clientRegistrationTemplateDao.findById(TenantId.SYS_TENANT_ID, templateId.getId());
}
@Override
public List<OAuth2ClientRegistrationTemplate> findAllClientRegistrationTemplates() {
log.trace("Executing findAllClientRegistrationTemplates");
return clientRegistrationTemplateDao.findAll();
}
@Override
public void deleteClientRegistrationTemplateById(OAuth2ClientRegistrationTemplateId templateId) {
log.trace("Executing deleteClientRegistrationTemplateById [{}]", templateId);
validateId(templateId, id -> INCORRECT_CLIENT_REGISTRATION_TEMPLATE_ID + id);
clientRegistrationTemplateDao.removeById(TenantId.SYS_TENANT_ID, templateId.getId());
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\oauth2\OAuth2ConfigTemplateServiceImpl.java
| 1
|
请完成以下Java代码
|
public class ChangeEDI_ExportStatus_C_Invoice_SingleView
extends JavaProcess
implements IProcessPrecondition, IProcessDefaultParametersProvider
{
private final EDIDocOutBoundLogService ediDocOutBoundLogService = SpringContextHolder.instance.getBean(EDIDocOutBoundLogService.class);
protected static final String PARAM_TargetExportStatus = I_EDI_Desadv.COLUMNNAME_EDI_ExportStatus;
@Param(parameterName = PARAM_TargetExportStatus)
private String p_TargetExportStatus;
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
final de.metas.edi.model.I_C_Invoice invoice = ediDocOutBoundLogService.retreiveById(InvoiceId.ofRepoId(context.getSingleSelectedRecordId()));
final EDIExportStatus fromExportStatus = EDIExportStatus.ofNullableCode(invoice.getEDI_ExportStatus());
if (fromExportStatus == null)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Selected record is not an EDI Invoice: " + invoice);
}
if (ChangeEDI_ExportStatusHelper.getAvailableTargetExportStatuses(fromExportStatus).isEmpty())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Cannot change ExportStatus from the current one: " + fromExportStatus);
}
return ProcessPreconditionsResolution.accept();
}
@ProcessParamLookupValuesProvider(parameterName = PARAM_TargetExportStatus, numericKey = false, lookupSource = LookupSource.list)
private LookupValuesList getTargetExportStatusLookupValues(final LookupDataSourceContext context)
{
final de.metas.edi.model.I_C_Invoice invoice = ediDocOutBoundLogService.retreiveById(InvoiceId.ofRepoId(getRecord_ID()));
final EDIExportStatus fromExportStatus = EDIExportStatus.ofCode(invoice.getEDI_ExportStatus());
return ChangeEDI_ExportStatusHelper.computeTargetExportStatusLookupValues(fromExportStatus);
|
}
@Override
@Nullable
public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
final de.metas.edi.model.I_C_Invoice invoice = ediDocOutBoundLogService.retreiveById(InvoiceId.ofRepoId(getRecord_ID()));
final EDIExportStatus fromExportStatus = EDIExportStatus.ofCode(invoice.getEDI_ExportStatus());
return ChangeEDI_ExportStatusHelper.computeParameterDefaultValue(fromExportStatus);
}
@Override
protected String doIt() throws Exception
{
final InvoiceId invoiceId = InvoiceId.ofRepoId(getRecord_ID());
final EDIExportStatus targetExportStatus = EDIExportStatus.ofCode(p_TargetExportStatus);
ChangeEDI_ExportStatusHelper.C_InvoiceDoIt(invoiceId, targetExportStatus);
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\edi_desadv\ChangeEDI_ExportStatus_C_Invoice_SingleView.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean matchesFilter(RuleEngineComponentLifecycleEventTrigger trigger, RuleEngineComponentLifecycleEventNotificationRuleTriggerConfig triggerConfig) {
if (CollectionUtils.isNotEmpty(triggerConfig.getRuleChains())) {
if (!triggerConfig.getRuleChains().contains(trigger.getRuleChainId().getId())) {
return false;
}
}
if (!partitionService.isMyPartition(ServiceType.TB_RULE_ENGINE, trigger.getTenantId(), trigger.getComponentId())) {
return false;
}
EntityType componentType = trigger.getComponentId().getEntityType();
Set<ComponentLifecycleEvent> trackedEvents;
boolean onlyFailures;
if (componentType == EntityType.RULE_CHAIN) {
trackedEvents = triggerConfig.getRuleChainEvents();
onlyFailures = triggerConfig.isOnlyRuleChainLifecycleFailures();
} else if (componentType == EntityType.RULE_NODE && triggerConfig.isTrackRuleNodeEvents()) {
trackedEvents = triggerConfig.getRuleNodeEvents();
onlyFailures = triggerConfig.isOnlyRuleNodeLifecycleFailures();
} else {
return false;
}
if (CollectionUtils.isEmpty(trackedEvents)) {
trackedEvents = Set.of(ComponentLifecycleEvent.STARTED, ComponentLifecycleEvent.UPDATED, ComponentLifecycleEvent.STOPPED);
}
if (!trackedEvents.contains(trigger.getEventType())) {
return false;
}
if (onlyFailures) {
return trigger.getError() != null;
}
return true;
}
@Override
public RuleOriginatedNotificationInfo constructNotificationInfo(RuleEngineComponentLifecycleEventTrigger trigger) {
return RuleEngineComponentLifecycleEventNotificationInfo.builder()
.ruleChainId(trigger.getRuleChainId())
|
.ruleChainName(trigger.getRuleChainName())
.componentId(trigger.getComponentId())
.componentName(trigger.getComponentName())
.action(trigger.getEventType() == ComponentLifecycleEvent.STARTED ? "start" :
trigger.getEventType() == ComponentLifecycleEvent.UPDATED ? "update" :
trigger.getEventType() == ComponentLifecycleEvent.STOPPED ? "stop" : null)
.eventType(trigger.getEventType())
.error(getErrorMsg(trigger.getError()))
.build();
}
private String getErrorMsg(Throwable error) {
if (error == null) return null;
StringWriter sw = new StringWriter();
error.printStackTrace(new PrintWriter(sw));
return StringUtils.abbreviate(ExceptionUtils.getStackTrace(error), 200);
}
@Override
public NotificationRuleTriggerType getTriggerType() {
return NotificationRuleTriggerType.RULE_ENGINE_COMPONENT_LIFECYCLE_EVENT;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\rule\trigger\RuleEngineComponentLifecycleEventTriggerProcessor.java
| 2
|
请完成以下Java代码
|
void run(String... args) {
run(dequeOf(args));
}
private void run(Deque<String> args) {
if (!args.isEmpty()) {
String commandName = args.removeFirst();
Command command = Command.find(this.commands, commandName);
if (command != null) {
runCommand(command, args);
return;
}
printError("Unknown command \"" + commandName + "\"");
}
this.help.run(this.out, args);
}
private void runCommand(Command command, Deque<String> args) {
if (command.isDeprecated()) {
printWarning("This command is deprecated. " + command.getDeprecationMessage());
}
try {
command.run(this.out, args);
}
catch (UnknownOptionException ex) {
|
printError("Unknown option \"" + ex.getMessage() + "\" for the " + command.getName() + " command");
this.help.printCommandHelp(this.out, command, false);
}
catch (MissingValueException ex) {
printError("Option \"" + ex.getMessage() + "\" for the " + command.getName() + " command requires a value");
this.help.printCommandHelp(this.out, command, false);
}
}
private void printWarning(String message) {
this.out.println("Warning: " + message);
this.out.println();
}
private void printError(String message) {
this.out.println("Error: " + message);
this.out.println();
}
private Deque<String> dequeOf(String... args) {
return new ArrayDeque<>(Arrays.asList(args));
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-jarmode-tools\src\main\java\org\springframework\boot\jarmode\tools\Runner.java
| 1
|
请完成以下Java代码
|
public class Customer {
private Integer id;
private String name;
private String emailId;
private Long phoneNumber;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", emailId=" + emailId + ", phoneNumber=" +
phoneNumber + "]";
}
|
Customer(Integer id, String name, String emailId, Long phoneNumber) {
super();
this.id = id;
this.name = name;
this.emailId = emailId;
this.phoneNumber = phoneNumber;
}
public Long getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(Long phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
|
repos\tutorials-master\core-java-modules\core-java-streams-6\src\main\java\com\baeldung\streams\gettersreturningnull\Customer.java
| 1
|
请完成以下Java代码
|
public StartingExecution getStartingExecution() {
return startingExecution;
}
@Override
public void disposeStartingExecution() {
startingExecution = null;
}
public String updateProcessBusinessKey(String bzKey) {
return getProcessInstance().updateProcessBusinessKey(bzKey);
}
@Override
public String getTenantId() {
return null; // Not implemented
}
// NOT IN V5
@Override
public boolean isMultiInstanceRoot() {
return false;
}
@Override
public void setMultiInstanceRoot(boolean isMultiInstanceRoot) {
}
@Override
public String getPropagatedStageInstanceId() {
return null;
}
// No support for transient variables in v5
@Override
public void setTransientVariablesLocal(Map<String, Object> transientVariables) {
throw new UnsupportedOperationException();
}
@Override
public void setTransientVariableLocal(String variableName, Object variableValue) {
throw new UnsupportedOperationException();
}
@Override
public void setTransientVariables(Map<String, Object> transientVariables) {
throw new UnsupportedOperationException();
}
@Override
public void setTransientVariable(String variableName, Object variableValue) {
throw new UnsupportedOperationException();
}
@Override
public Object getTransientVariableLocal(String variableName) {
throw new UnsupportedOperationException();
}
@Override
public Map<String, Object> getTransientVariablesLocal() {
throw new UnsupportedOperationException();
}
@Override
|
public Object getTransientVariable(String variableName) {
throw new UnsupportedOperationException();
}
@Override
public Map<String, Object> getTransientVariables() {
throw new UnsupportedOperationException();
}
@Override
public void removeTransientVariableLocal(String variableName) {
throw new UnsupportedOperationException();
}
@Override
public void removeTransientVariablesLocal() {
throw new UnsupportedOperationException();
}
@Override
public void removeTransientVariable(String variableName) {
throw new UnsupportedOperationException();
}
@Override
public void removeTransientVariables() {
throw new UnsupportedOperationException();
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\runtime\ExecutionImpl.java
| 1
|
请完成以下Java代码
|
public java.lang.String getPassword ()
{
return (java.lang.String)get_Value(COLUMNNAME_Password);
}
/** Set Grund der Anfrage.
@param RequestReason Grund der Anfrage */
@Override
public void setRequestReason (java.lang.String RequestReason)
{
set_Value (COLUMNNAME_RequestReason, RequestReason);
}
/** Get Grund der Anfrage.
@return Grund der Anfrage */
@Override
public java.lang.String getRequestReason ()
{
return (java.lang.String)get_Value(COLUMNNAME_RequestReason);
}
/** Set REST API URL.
@param RestApiBaseURL REST API URL */
@Override
public void setRestApiBaseURL (java.lang.String RestApiBaseURL)
{
set_Value (COLUMNNAME_RestApiBaseURL, RestApiBaseURL);
}
/** Get REST API URL.
@return REST API URL */
@Override
public java.lang.String getRestApiBaseURL ()
{
return (java.lang.String)get_Value(COLUMNNAME_RestApiBaseURL);
}
/** Set Creditpass-Prüfung wiederholen .
@param RetryAfterDays Creditpass-Prüfung wiederholen */
@Override
public void setRetryAfterDays (java.math.BigDecimal RetryAfterDays)
{
set_Value (COLUMNNAME_RetryAfterDays, RetryAfterDays);
|
}
/** Get Creditpass-Prüfung wiederholen .
@return Creditpass-Prüfung wiederholen */
@Override
public java.math.BigDecimal getRetryAfterDays ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RetryAfterDays);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** 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();
}
/** 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));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java-gen\de\metas\vertical\creditscore\creditpass\model\X_CS_Creditpass_Config.java
| 1
|
请完成以下Java代码
|
public void createOrderCosts(@NonNull final I_PP_Order ppOrder)
{
new CreatePPOrderCostsCommand(ppOrder)
.execute();
}
@Override
public boolean hasPPOrderCosts(@NonNull final PPOrderId orderId)
{
return orderCostsRepo.hasPPOrderCosts(orderId);
}
@Override
public PPOrderCosts getByOrderId(@NonNull final PPOrderId orderId)
{
|
return orderCostsRepo.getByOrderId(orderId);
}
@Override
public void deleteByOrderId(@NonNull final PPOrderId orderId)
{
orderCostsRepo.deleteByOrderId(orderId);
}
@Override
public void save(@NonNull final PPOrderCosts orderCosts)
{
orderCostsRepo.save(orderCosts);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\impl\PPOrderCostBL.java
| 1
|
请完成以下Java代码
|
public ICalloutExecutor getCurrentCalloutExecutor()
{
final GridTab gridTab = getGridTab();
if (gridTab == null)
{
return null;
}
return gridTab.getCalloutExecutor();
}
public int getTabNo()
{
return m_vo.TabNo;
}
/**
* Enable events delaying.
* So, from now on, all events will be enqueued instead of directly fired.
* Later, when {@link #releaseDelayedEvents()} is called, all enqueued events will be fired.
*/
public void delayEvents()
{
m_propertyChangeListeners.blockEvents();
}
/**
* Fire all enqueued events (if any) and disable events delaying.
*
* @see #delayEvents().
*/
public void releaseDelayedEvents()
{
m_propertyChangeListeners.releaseEvents();
}
@Override
public boolean isRecordCopyingMode()
{
final GridTab gridTab = getGridTab();
// If there was no GridTab set for this field, consider as we are not copying the record
if (gridTab == null)
{
return false;
}
return gridTab.isDataNewCopy();
}
@Override
public boolean isRecordCopyingModeIncludingDetails()
{
final GridTab gridTab = getGridTab();
// If there was no GridTab set for this field, consider as we are not copying the record
if (gridTab == null)
{
return false;
}
return gridTab.getTableModel().isCopyWithDetails();
}
@Override
public void fireDataStatusEEvent(final String AD_Message, final String info, final boolean isError)
{
final GridTab gridTab = getGridTab();
if(gridTab == null)
{
log.warn("Could not fire EEvent on {} because gridTab is not set. The event was: AD_Message={}, info={}, isError={}", this, AD_Message, info, isError);
return;
}
|
gridTab.fireDataStatusEEvent(AD_Message, info, isError);
}
@Override
public void fireDataStatusEEvent(final ValueNamePair errorLog)
{
final GridTab gridTab = getGridTab();
if(gridTab == null)
{
log.warn("Could not fire EEvent on {} because gridTab is not set. The event was: errorLog={}", this, errorLog);
return;
}
gridTab.fireDataStatusEEvent(errorLog);
}
@Override
public boolean isLookupValuesContainingId(@NonNull final RepoIdAware id)
{
throw new UnsupportedOperationException();
}
@Override
public ICalloutRecord getCalloutRecord()
{
final GridTab gridTab = getGridTab();
Check.assumeNotNull(gridTab, "gridTab not null");
return gridTab;
}
@Override
public int getContextAsInt(String name)
{
return Env.getContextAsInt(getCtx(), getWindowNo(), name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridField.java
| 1
|
请完成以下Java代码
|
private CategoryChart buildChart(List xData, List yData) {
// Create Chart
CategoryChart chart = new CategoryChartBuilder().width(800).height(600)
.title("Age Distribution")
.xAxisTitle("Age Group")
.yAxisTitle("Frequency")
.build();
chart.getStyler().setLegendPosition(Styler.LegendPosition.InsideNW);
chart.getStyler().setAvailableSpaceFill(0.99);
chart.getStyler().setOverlapped(true);
chart.addSeries("age group", xData, yData);
return chart;
}
private Map processRawData() {
List<Integer> datasetList = Arrays.asList(
36, 25, 38, 46, 55, 68, 72,
55, 36, 38, 67, 45, 22, 48,
91, 46, 52, 61, 58, 55);
Frequency frequency = new Frequency();
datasetList.forEach(d -> frequency.addValue(Double.parseDouble(d.toString())));
datasetList.stream()
.map(d -> Double.parseDouble(d.toString()))
.distinct()
.forEach(observation -> {
long observationFrequency = frequency.getCount(observation);
int upperBoundary = (observation > classWidth)
? Math.multiplyExact( (int) Math.ceil(observation / classWidth), classWidth)
: classWidth;
int lowerBoundary = (upperBoundary > classWidth)
? Math.subtractExact(upperBoundary, classWidth)
: 0;
|
String bin = lowerBoundary + "-" + upperBoundary;
updateDistributionMap(lowerBoundary, bin, observationFrequency);
});
return distributionMap;
}
private void updateDistributionMap(int lowerBoundary, String bin, long observationFrequency) {
int prevLowerBoundary = (lowerBoundary > classWidth) ? lowerBoundary - classWidth : 0;
String prevBin = prevLowerBoundary + "-" + lowerBoundary;
if(!distributionMap.containsKey(prevBin))
distributionMap.put(prevBin, 0);
if(!distributionMap.containsKey(bin)) {
distributionMap.put(bin, observationFrequency);
}
else {
long oldFrequency = Long.parseLong(distributionMap.get(bin).toString());
distributionMap.replace(bin, oldFrequency + observationFrequency);
}
}
public static void main(String[] args) {
new Histogram();
}
}
|
repos\tutorials-master\libraries-apache-commons\src\main\java\com\baeldung\commons\math3\Histogram.java
| 1
|
请完成以下Java代码
|
public String getPaymentRule()
{
return paymentRule;
}
@Override
public String getExternalId()
{
return externalId;
}
@Override
public int getC_Async_Batch_ID()
{
return C_Async_Batch_ID;
}
public void setC_Async_Batch_ID(final int C_Async_Batch_ID)
{
this.C_Async_Batch_ID = C_Async_Batch_ID;
}
public String setExternalId(String externalId)
{
return this.externalId = externalId;
}
@Override
public int getC_Incoterms_ID()
{
return C_Incoterms_ID;
}
public void setC_Incoterms_ID(final int C_Incoterms_ID)
{
|
this.C_Incoterms_ID = C_Incoterms_ID;
}
@Override
public String getIncotermLocation()
{
return incotermLocation;
}
public void setIncotermLocation(final String incotermLocation)
{
this.incotermLocation = incotermLocation;
}
@Override
public InputDataSourceId getAD_InputDataSource_ID() { return inputDataSourceId;}
public void setAD_InputDataSource_ID(final InputDataSourceId inputDataSourceId){this.inputDataSourceId = inputDataSourceId;}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceHeaderImpl.java
| 1
|
请完成以下Java代码
|
public Integer getPriviledgeSignIn() {
return priviledgeSignIn;
}
public void setPriviledgeSignIn(Integer priviledgeSignIn) {
this.priviledgeSignIn = priviledgeSignIn;
}
public Integer getPriviledgeComment() {
return priviledgeComment;
}
public void setPriviledgeComment(Integer priviledgeComment) {
this.priviledgeComment = priviledgeComment;
}
public Integer getPriviledgePromotion() {
return priviledgePromotion;
}
public void setPriviledgePromotion(Integer priviledgePromotion) {
this.priviledgePromotion = priviledgePromotion;
}
public Integer getPriviledgeMemberPrice() {
return priviledgeMemberPrice;
}
public void setPriviledgeMemberPrice(Integer priviledgeMemberPrice) {
this.priviledgeMemberPrice = priviledgeMemberPrice;
}
public Integer getPriviledgeBirthday() {
return priviledgeBirthday;
}
public void setPriviledgeBirthday(Integer priviledgeBirthday) {
this.priviledgeBirthday = priviledgeBirthday;
}
public String getNote() {
|
return note;
}
public void setNote(String note) {
this.note = note;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", growthPoint=").append(growthPoint);
sb.append(", defaultStatus=").append(defaultStatus);
sb.append(", freeFreightPoint=").append(freeFreightPoint);
sb.append(", commentGrowthPoint=").append(commentGrowthPoint);
sb.append(", priviledgeFreeFreight=").append(priviledgeFreeFreight);
sb.append(", priviledgeSignIn=").append(priviledgeSignIn);
sb.append(", priviledgeComment=").append(priviledgeComment);
sb.append(", priviledgePromotion=").append(priviledgePromotion);
sb.append(", priviledgeMemberPrice=").append(priviledgeMemberPrice);
sb.append(", priviledgeBirthday=").append(priviledgeBirthday);
sb.append(", note=").append(note);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberLevel.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.