instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public JobEntity findJobByCorrelationId(String correlationId) {
return dataManager.findJobByCorrelationId(correlationId);
}
@Override
public List<Job> findJobsByQueryCriteria(JobQueryImpl jobQuery) {
return dataManager.findJobsByQueryCriteria(jobQuery);
}
@Override
public long findJobCountByQueryCriteria(JobQueryImpl jobQuery) {
return dataManager.findJobCountByQueryCriteria(jobQuery);
}
@Override
public void delete(JobEntity jobEntity) {
delete(jobEntity, false);
deleteByteArrayRef(jobEntity.getExceptionByteArrayRef());
deleteByteArrayRef(jobEntity.getCustomValuesByteArrayRef());
// Send event
FlowableEventDispatcher eventDispatcher = getEventDispatcher();
if (eventDispatcher != null && eventDispatcher.isEnabled()) {
eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, jobEntity),
serviceConfiguration.getEngineName());
}
} | @Override
public void delete(JobEntity entity, boolean fireDeleteEvent) {
if (serviceConfiguration.getInternalJobManager() != null) {
serviceConfiguration.getInternalJobManager().handleJobDelete(entity);
}
super.delete(entity, fireDeleteEvent);
}
@Override
public void deleteJobsByExecutionId(String executionId) {
dataManager.deleteJobsByExecutionId(executionId);
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\JobEntityManagerImpl.java | 2 |
请完成以下Java代码 | public void deleteHistoricProcessInstance(String processInstanceId) {
commandExecutor.execute(new DeleteHistoricProcessInstanceCmd(processInstanceId));
}
public NativeHistoricProcessInstanceQuery createNativeHistoricProcessInstanceQuery() {
return new NativeHistoricProcessInstanceQueryImpl(commandExecutor);
}
public NativeHistoricTaskInstanceQuery createNativeHistoricTaskInstanceQuery() {
return new NativeHistoricTaskInstanceQueryImpl(commandExecutor);
}
public NativeHistoricActivityInstanceQuery createNativeHistoricActivityInstanceQuery() {
return new NativeHistoricActivityInstanceQueryImpl(commandExecutor);
} | @Override
public List<HistoricIdentityLink> getHistoricIdentityLinksForProcessInstance(String processInstanceId) {
return commandExecutor.execute(new GetHistoricIdentityLinksForTaskCmd(null, processInstanceId));
}
@Override
public List<HistoricIdentityLink> getHistoricIdentityLinksForTask(String taskId) {
return commandExecutor.execute(new GetHistoricIdentityLinksForTaskCmd(taskId, null));
}
@Override
public ProcessInstanceHistoryLogQuery createProcessInstanceHistoryLogQuery(String processInstanceId) {
return new ProcessInstanceHistoryLogQueryImpl(commandExecutor, processInstanceId);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoryServiceImpl.java | 1 |
请完成以下Java代码 | public int getM_Inventory_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Inventory_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Securpharm Aktion Ergebnise.
@param M_Securpharm_Action_Result_ID Securpharm Aktion Ergebnise */
@Override
public void setM_Securpharm_Action_Result_ID (int M_Securpharm_Action_Result_ID)
{
if (M_Securpharm_Action_Result_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Securpharm_Action_Result_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Securpharm_Action_Result_ID, Integer.valueOf(M_Securpharm_Action_Result_ID));
}
/** Get Securpharm Aktion Ergebnise.
@return Securpharm Aktion Ergebnise */
@Override
public int getM_Securpharm_Action_Result_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Securpharm_Action_Result_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.vertical.pharma.securpharm.model.I_M_Securpharm_Productdata_Result getM_Securpharm_Productdata_Result()
{
return get_ValueAsPO(COLUMNNAME_M_Securpharm_Productdata_Result_ID, de.metas.vertical.pharma.securpharm.model.I_M_Securpharm_Productdata_Result.class);
}
@Override
public void setM_Securpharm_Productdata_Result(de.metas.vertical.pharma.securpharm.model.I_M_Securpharm_Productdata_Result M_Securpharm_Productdata_Result)
{
set_ValueFromPO(COLUMNNAME_M_Securpharm_Productdata_Result_ID, de.metas.vertical.pharma.securpharm.model.I_M_Securpharm_Productdata_Result.class, M_Securpharm_Productdata_Result);
}
/** Set Securpharm Produktdaten Ergebnise.
@param M_Securpharm_Productdata_Result_ID Securpharm Produktdaten Ergebnise */
@Override
public void setM_Securpharm_Productdata_Result_ID (int M_Securpharm_Productdata_Result_ID)
{
if (M_Securpharm_Productdata_Result_ID < 1)
set_Value (COLUMNNAME_M_Securpharm_Productdata_Result_ID, null);
else
set_Value (COLUMNNAME_M_Securpharm_Productdata_Result_ID, Integer.valueOf(M_Securpharm_Productdata_Result_ID)); | }
/** Get Securpharm Produktdaten Ergebnise.
@return Securpharm Produktdaten Ergebnise */
@Override
public int getM_Securpharm_Productdata_Result_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Securpharm_Productdata_Result_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set TransaktionsID Server.
@param TransactionIDServer TransaktionsID Server */
@Override
public void setTransactionIDServer (java.lang.String TransactionIDServer)
{
set_Value (COLUMNNAME_TransactionIDServer, TransactionIDServer);
}
/** Get TransaktionsID Server.
@return TransaktionsID Server */
@Override
public java.lang.String getTransactionIDServer ()
{
return (java.lang.String)get_Value(COLUMNNAME_TransactionIDServer);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java-gen\de\metas\vertical\pharma\securpharm\model\X_M_Securpharm_Action_Result.java | 1 |
请完成以下Java代码 | public void visit(ScopeImpl obj) {
PvmExecutionImpl execution = scopeExecutionMapping.get(obj);
subscriptions.addAll(((ExecutionEntity) execution).getCompensateEventSubscriptions());
}
};
new FlowScopeWalker(activity).addPostVisitor(eventSubscriptionCollector).walkUntil(new ReferenceWalker.WalkCondition<ScopeImpl>() {
@Override
public boolean isFulfilled(ScopeImpl element) {
Boolean consumesCompensationProperty = (Boolean) element.getProperty(BpmnParse.PROPERTYNAME_CONSUMES_COMPENSATION);
return consumesCompensationProperty == null || consumesCompensationProperty == Boolean.TRUE;
}
});
return new ArrayList<EventSubscriptionEntity>(subscriptions);
}
/**
* Collect all compensate event subscriptions for activity on the scope of
* given execution.
*/
public static List<EventSubscriptionEntity> collectCompensateEventSubscriptionsForActivity(ActivityExecution execution, String activityRef) {
final List<EventSubscriptionEntity> eventSubscriptions = collectCompensateEventSubscriptionsForScope(execution);
final String subscriptionActivityId = getSubscriptionActivityId(execution, activityRef);
List<EventSubscriptionEntity> eventSubscriptionsForActivity = new ArrayList<EventSubscriptionEntity>();
for (EventSubscriptionEntity subscription : eventSubscriptions) {
if (subscriptionActivityId.equals(subscription.getActivityId())) {
eventSubscriptionsForActivity.add(subscription);
}
}
return eventSubscriptionsForActivity;
}
public static ExecutionEntity getCompensatingExecution(EventSubscriptionEntity eventSubscription) {
String configuration = eventSubscription.getConfiguration();
if (configuration != null) {
return Context.getCommandContext().getExecutionManager().findExecutionById(configuration);
}
else {
return null;
} | }
private static String getSubscriptionActivityId(ActivityExecution execution, String activityRef) {
ActivityImpl activityToCompensate = ((ExecutionEntity) execution).getProcessDefinition().findActivity(activityRef);
if (activityToCompensate.isMultiInstance()) {
ActivityImpl flowScope = (ActivityImpl) activityToCompensate.getFlowScope();
return flowScope.getActivityId();
} else {
ActivityImpl compensationHandler = activityToCompensate.findCompensationHandler();
if (compensationHandler != null) {
return compensationHandler.getActivityId();
} else {
// if activityRef = subprocess and subprocess has no compensation handler
return activityRef;
}
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\helper\CompensationUtil.java | 1 |
请完成以下Java代码 | public void handleGetByParam(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
JSONObject responseJson = new JSONObject();
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient();
DynamoDB dynamoDb = new DynamoDB(client);
Item result = null;
try {
JSONObject event = (JSONObject) parser.parse(reader);
JSONObject responseBody = new JSONObject();
if (event.get("pathParameters") != null) {
JSONObject pps = (JSONObject) event.get("pathParameters");
if (pps.get("id") != null) {
int id = Integer.parseInt((String) pps.get("id"));
result = dynamoDb.getTable(DYNAMODB_TABLE_NAME)
.getItem("id", id);
}
} else if (event.get("queryStringParameters") != null) {
JSONObject qps = (JSONObject) event.get("queryStringParameters");
if (qps.get("id") != null) {
int id = Integer.parseInt((String) qps.get("id"));
result = dynamoDb.getTable(DYNAMODB_TABLE_NAME)
.getItem("id", id);
}
}
if (result != null) { | Person person = new Person(result.toJSON());
responseBody.put("Person", person);
responseJson.put("statusCode", 200);
} else {
responseBody.put("message", "No item found");
responseJson.put("statusCode", 404);
}
JSONObject headerJson = new JSONObject();
headerJson.put("x-custom-header", "my custom header value");
responseJson.put("headers", headerJson);
responseJson.put("body", responseBody.toString());
} catch (ParseException pex) {
responseJson.put("statusCode", 400);
responseJson.put("exception", pex);
}
OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
writer.write(responseJson.toString());
writer.close();
}
} | repos\tutorials-master\aws-modules\aws-lambda-modules\lambda-function\src\main\java\com\baeldung\lambda\apigateway\APIDemoHandler.java | 1 |
请完成以下Java代码 | public static final class Builder {
private String id;
private String eventName;
private String processDefinitionId;
private String configuration;
private String activityId;
private Date created;
public Builder() {}
private Builder(StartMessageSubscriptionImpl startMessageSubscriptionImpl) {
this.id = startMessageSubscriptionImpl.id;
this.eventName = startMessageSubscriptionImpl.eventName;
this.processDefinitionId = startMessageSubscriptionImpl.processDefinitionId;
this.configuration = startMessageSubscriptionImpl.configuration;
this.activityId = startMessageSubscriptionImpl.activityId;
this.created = startMessageSubscriptionImpl.created;
}
/**
* Builder method for id parameter.
* @param id field to set
* @return builder
*/
public Builder withId(String id) {
this.id = id;
return this;
}
/**
* Builder method for eventName parameter.
* @param eventName field to set
* @return builder
*/
public Builder withEventName(String eventName) {
this.eventName = eventName;
return this;
}
/**
* Builder method for processDefinitionId parameter.
* @param processDefinitionId field to set
* @return builder
*/
public Builder withProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
return this;
} | /**
* Builder method for configuration parameter.
* @param configuration field to set
* @return builder
*/
public Builder withConfiguration(String configuration) {
this.configuration = configuration;
return this;
}
/**
* Builder method for activityId parameter.
* @param activityId field to set
* @return builder
*/
public Builder withActivityId(String activityId) {
this.activityId = activityId;
return this;
}
/**
* Builder method for created parameter.
* @param created field to set
* @return builder
*/
public Builder withCreated(Date created) {
this.created = created;
return this;
}
/**
* Builder method of the builder.
* @return built class
*/
public StartMessageSubscriptionImpl build() {
return new StartMessageSubscriptionImpl(this);
}
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\StartMessageSubscriptionImpl.java | 1 |
请完成以下Java代码 | public class CacheSourceModelFactory
{
public static ICacheSourceModel ofPO(@NonNull final PO po)
{
return new POCacheSourceModel(po);
}
public static ICacheSourceModel ofObject(@NonNull final Object obj)
{
final PO po = unwrapPOOrNull(obj);
if (po != null)
{
return ofPO((PO)obj);
}
else
{ | return new ModelCacheSourceModel(obj);
}
}
@Nullable
private static PO unwrapPOOrNull(@NonNull final Object obj)
{
if (obj instanceof PO)
{
return (PO)obj;
}
return POWrapper.getStrictPO(obj);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\CacheSourceModelFactory.java | 1 |
请完成以下Java代码 | public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public Publisher getPublisher() {
return publisher;
}
public void setPublisher(Publisher publisher) {
this.publisher = publisher;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true; | }
if (getClass() != obj.getClass()) {
return false;
}
return id != null && id.equals(((Book) obj).id);
}
@Override
public int hashCode() {
return 2021;
}
@Override
public String toString() {
return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootNamedSubgraph\src\main\java\com\bookstore\entity\Book.java | 1 |
请完成以下Java代码 | public static VersionReference ofValue(String value) {
return new VersionReference(null, value);
}
/**
* Specify if this reference defines a property.
* @return {@code true} if this version is backed by a property
*/
public boolean isProperty() {
return this.property != null;
}
/**
* Return the {@link VersionProperty} or {@code null} if this reference is not a
* property.
* @return the version property or {@code null}
*/
public VersionProperty getProperty() {
return this.property;
}
/**
* Return the version or {@code null} if this reference is backed by a property.
* @return the version or {@code null}
*/
public String getValue() {
return this.value;
} | @Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
VersionReference that = (VersionReference) o;
return Objects.equals(this.property, that.property) && Objects.equals(this.value, that.value);
}
@Override
public int hashCode() {
return Objects.hash(this.property, this.value);
}
@Override
public String toString() {
return (this.property != null) ? "${" + this.property.toStandardFormat() + "}" : this.value;
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\version\VersionReference.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<Message> list() {
List<Message> messages = this.messageRepository.findAll();
return messages;
}
@ApiOperation(
value = "添加消息",
notes = "根据参数创建消息"
)
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "消息 ID", required = true, dataType = "Long", paramType = "query"),
@ApiImplicitParam(name = "text", value = "正文", required = true, dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "summary", value = "摘要", required = false, dataType = "String", paramType = "query"),
})
@PostMapping(value = "message")
public Message create(Message message) {
System.out.println("message===="+message.toString());
message = this.messageRepository.save(message);
return message;
}
@ApiOperation(
value = "修改消息",
notes = "根据参数修改消息"
)
@PutMapping(value = "message")
@ApiResponses({
@ApiResponse(code = 100, message = "请求参数有误"),
@ApiResponse(code = 101, message = "未授权"),
@ApiResponse(code = 103, message = "禁止访问"),
@ApiResponse(code = 104, message = "请求路径不存在"),
@ApiResponse(code = 200, message = "服务器内部错误")
})
public Message modify(Message message) { | Message messageResult=this.messageRepository.update(message);
return messageResult;
}
@PatchMapping(value="/message/text")
public BaseResult<Message> patch(Message message) {
Message messageResult=this.messageRepository.updateText(message);
return BaseResult.successWithData(messageResult);
}
@GetMapping(value = "message/{id}")
public Message get(@PathVariable Long id) {
Message message = this.messageRepository.findMessage(id);
return message;
}
@DeleteMapping(value = "message/{id}")
public void delete(@PathVariable("id") Long id) {
this.messageRepository.deleteMessage(id);
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 2-9 课:Spring Boot 中使用 Swagger2 构建 RESTful APIs\spring-boot-swagger\src\main\java\com\neo\controller\MessageController.java | 2 |
请完成以下Java代码 | private boolean isStatsPrintRequired() {
return log.isInfoEnabled();
}
private List<GroupTopicStats> getTopicsStatsWithLag(Map<TopicPartition, OffsetAndMetadata> groupOffsets, Map<TopicPartition, Long> endOffsets) {
List<GroupTopicStats> consumerGroupStats = new ArrayList<>();
for (TopicPartition topicPartition : groupOffsets.keySet()) {
long endOffset = endOffsets.get(topicPartition);
long committedOffset = groupOffsets.get(topicPartition).offset();
long lag = endOffset - committedOffset;
if (lag != 0) {
GroupTopicStats groupTopicStats = GroupTopicStats.builder()
.topic(topicPartition.topic())
.partition(topicPartition.partition())
.committedOffset(committedOffset)
.endOffset(endOffset)
.lag(lag)
.build();
consumerGroupStats.add(groupTopicStats);
}
}
return consumerGroupStats;
}
public void registerClientGroup(String groupId) {
if (statsConfig.getEnabled() && !StringUtils.isEmpty(groupId)) {
monitoredGroups.add(groupId);
}
}
public void unregisterClientGroup(String groupId) {
if (statsConfig.getEnabled() && !StringUtils.isEmpty(groupId)) {
monitoredGroups.remove(groupId);
}
}
@PreDestroy
public void destroy() {
if (statsPrintScheduler != null) {
statsPrintScheduler.shutdownNow();
}
if (consumer != null) {
consumer.close();
}
} | @Builder
@Data
private static class GroupTopicStats {
private String topic;
private int partition;
private long committedOffset;
private long endOffset;
private long lag;
@Override
public String toString() {
return "[" +
"topic=[" + topic + ']' +
", partition=[" + partition + "]" +
", committedOffset=[" + committedOffset + "]" +
", endOffset=[" + endOffset + "]" +
", lag=[" + lag + "]" +
"]";
}
}
} | repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\kafka\TbKafkaConsumerStatsService.java | 1 |
请完成以下Java代码 | public class GenericMapOutputConverter<V> implements StructuredOutputConverter<Map<String, V>> {
private final ObjectMapper objectMapper;
private final String jsonSchema;
private final TypeReference<Map<String, V>> typeRef;
public GenericMapOutputConverter(Class<V> valueType) {
this.objectMapper = this.getObjectMapper();
this.typeRef = new TypeReference<>() {};
this.jsonSchema = generateJsonSchemaForValueType(valueType);
}
public Map<String, V> convert(@NonNull String text) {
try {
text = trimMarkdown(text);
return objectMapper.readValue(text, typeRef);
} catch (JsonProcessingException e) {
throw new RuntimeException("Failed to convert JSON to Map<String, V>", e);
}
}
public String getFormat() {
String raw = "Your response should be in JSON format.\nThe data structure for the JSON should match this Java class: %s\n" +
"For the map values, here is the JSON Schema instance your output must adhere to:\n```%s```\n" +
"Do not include any explanations, only provide a RFC8259 compliant JSON response following this format without deviation.\n";
return String.format(raw, HashMap.class.getName(), this.jsonSchema);
}
protected ObjectMapper getObjectMapper() {
return JsonMapper.builder()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.build(); | }
private String trimMarkdown(String text) {
if (text.startsWith("```json") && text.endsWith("```")) {
text = text.substring(7, text.length() - 3);
}
return text;
}
private String generateJsonSchemaForValueType(Class<V> valueType) {
try {
JacksonModule jacksonModule = new JacksonModule();
SchemaGeneratorConfig config = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2020_12, OptionPreset.PLAIN_JSON)
.with(jacksonModule)
.build();
SchemaGenerator generator = new SchemaGenerator(config);
JsonNode jsonNode = generator.generateSchema(valueType);
ObjectWriter objectWriter = new ObjectMapper().writer(new DefaultPrettyPrinter().withObjectIndenter(new DefaultIndenter().withLinefeed(System.lineSeparator())));
return objectWriter.writeValueAsString(jsonNode);
} catch (JsonProcessingException e) {
throw new RuntimeException("Could not generate JSON schema for value type: " + valueType.getName(), e);
}
}
} | repos\tutorials-master\spring-ai-modules\spring-ai-3\src\main\java\com\baeldung\springaistructuredoutput\converters\GenericMapOutputConverter.java | 1 |
请完成以下Java代码 | public void setRltdAcct(CashAccount24 value) {
this.rltdAcct = value;
}
/**
* Gets the value of the intrst property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the intrst property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getIntrst().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AccountInterest3 }
*
*
*/
public List<AccountInterest3> getIntrst() {
if (intrst == null) {
intrst = new ArrayList<AccountInterest3>();
}
return this.intrst;
}
/**
* Gets the value of the txsSummry property.
*
* @return
* possible object is
* {@link TotalTransactions5 }
*
*/
public TotalTransactions5 getTxsSummry() {
return txsSummry;
}
/**
* Sets the value of the txsSummry property.
*
* @param value
* allowed object is
* {@link TotalTransactions5 }
*
*/
public void setTxsSummry(TotalTransactions5 value) {
this.txsSummry = value;
}
/**
* Gets the value of the ntry property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the ntry property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre> | * getNtry().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ReportEntry8 }
*
*
*/
public List<ReportEntry8> getNtry() {
if (ntry == null) {
ntry = new ArrayList<ReportEntry8>();
}
return this.ntry;
}
/**
* Gets the value of the addtlNtfctnInf property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAddtlNtfctnInf() {
return addtlNtfctnInf;
}
/**
* Sets the value of the addtlNtfctnInf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAddtlNtfctnInf(String value) {
this.addtlNtfctnInf = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\AccountNotification12.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getInputVariable() {
return inputVariable;
}
public void setInputVariable(String inputVariable) {
this.inputVariable = inputVariable;
}
public TypedValue getValue() {
return value;
}
public void setValue(TypedValue value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DmnEvaluatedInputImpl that = (DmnEvaluatedInputImpl) o; | if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
if (inputVariable != null ? !inputVariable.equals(that.inputVariable) : that.inputVariable != null) return false;
return !(value != null ? !value.equals(that.value) : that.value != null);
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (inputVariable != null ? inputVariable.hashCode() : 0);
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "DmnEvaluatedInputImpl{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", inputVariable='" + inputVariable + '\'' +
", value=" + value +
'}';
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\delegate\DmnEvaluatedInputImpl.java | 1 |
请完成以下Java代码 | public CleanableHistoricCaseInstanceReport compact() {
this.isCompact = true;
return this;
}
@Override
public CleanableHistoricCaseInstanceReport orderByFinished() {
orderBy(CleanableHistoricInstanceReportProperty.FINISHED_AMOUNT);
return this;
}
@Override
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getHistoricCaseInstanceManager()
.findCleanableHistoricCaseInstancesReportCountByCriteria(this);
}
@Override
public List<CleanableHistoricCaseInstanceReportResult> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getHistoricCaseInstanceManager()
.findCleanableHistoricCaseInstancesReportByCriteria(this, page);
}
public String[] getCaseDefinitionIdIn() {
return caseDefinitionIdIn;
}
public void setCaseDefinitionIdIn(String[] caseDefinitionIdIn) {
this.caseDefinitionIdIn = caseDefinitionIdIn;
} | public String[] getCaseDefinitionKeyIn() {
return caseDefinitionKeyIn;
}
public void setCaseDefinitionKeyIn(String[] caseDefinitionKeyIn) {
this.caseDefinitionKeyIn = caseDefinitionKeyIn;
}
public Date getCurrentTimestamp() {
return currentTimestamp;
}
public void setCurrentTimestamp(Date currentTimestamp) {
this.currentTimestamp = currentTimestamp;
}
public String[] getTenantIdIn() {
return tenantIdIn;
}
public void setTenantIdIn(String[] tenantIdIn) {
this.tenantIdIn = tenantIdIn;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
public boolean isCompact() {
return isCompact;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\CleanableHistoricCaseInstanceReportImpl.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_M_Warehouse getM_Warehouse() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Warehouse_ID, org.compiere.model.I_M_Warehouse.class);
}
@Override
public void setM_Warehouse(org.compiere.model.I_M_Warehouse M_Warehouse)
{
set_ValueFromPO(COLUMNNAME_M_Warehouse_ID, org.compiere.model.I_M_Warehouse.class, M_Warehouse);
}
/** Set Lager.
@param M_Warehouse_ID
Lager oder Ort für Dienstleistung
*/
@Override
public void setM_Warehouse_ID (int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID));
}
/** Get Lager.
@return Lager oder Ort für Dienstleistung
*/
@Override
public int getM_Warehouse_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_ID);
if (ii == null) | return 0;
return ii.intValue();
}
/** Set Lagerzuordnung.
@param M_Warehouse_Routing_ID Lagerzuordnung */
@Override
public void setM_Warehouse_Routing_ID (int M_Warehouse_Routing_ID)
{
if (M_Warehouse_Routing_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Warehouse_Routing_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Warehouse_Routing_ID, Integer.valueOf(M_Warehouse_Routing_ID));
}
/** Get Lagerzuordnung.
@return Lagerzuordnung */
@Override
public int getM_Warehouse_Routing_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_Routing_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\eevolution\model\X_M_Warehouse_Routing.java | 1 |
请完成以下Java代码 | public Set<OrderDetail> lazyLoaded() {
final Session sessionLazy = HibernateUtil.getHibernateSession("lazy");
List<UserLazy> users = sessionLazy.createQuery("From UserLazy").list();
UserLazy userLazyLoaded = users.get(0);
// since data is lazyloaded so data won't be initialized
return (userLazyLoaded.getOrderDetail());
}
// eagerly loaded
public Set<OrderDetail> eagerLoaded() {
final Session sessionEager = HibernateUtil.getHibernateSession();
// data should be loaded in the following line
// also note the queries generated
List<UserEager> user = sessionEager.createQuery("From UserEager").list();
UserEager userEagerLoaded = user.get(0);
return userEagerLoaded.getOrderDetail();
}
// creates test data
// call this method to create the data in the database
public void createTestData() {
final Session session = HibernateUtil.getHibernateSession("lazy");
Transaction tx = session.beginTransaction();
final UserLazy user1 = new UserLazy();
final UserLazy user2 = new UserLazy();
final UserLazy user3 = new UserLazy(); | session.save(user1);
session.save(user2);
session.save(user3);
final OrderDetail order1 = new OrderDetail();
final OrderDetail order2 = new OrderDetail();
final OrderDetail order3 = new OrderDetail();
final OrderDetail order4 = new OrderDetail();
final OrderDetail order5 = new OrderDetail();
session.saveOrUpdate(order1);
session.saveOrUpdate(order2);
session.saveOrUpdate(order3);
session.saveOrUpdate(order4);
session.saveOrUpdate(order5);
tx.commit();
session.close();
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\hibernate\fetching\view\FetchingAppView.java | 1 |
请完成以下Java代码 | public class CamundaBpmRunLdapProperties extends LdapIdentityProviderPlugin {
public static final String PREFIX = CamundaBpmRunProperties.PREFIX + ".ldap";
boolean enabled = true;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
public String toString() {
return "CamundaBpmRunLdapProperty [enabled=" + enabled +
", initialContextFactory=" + initialContextFactory +
", securityAuthentication=" + securityAuthentication +
", contextProperties=" + contextProperties +
", serverUrl=******" + // sensitive for logging
", managerDn=******" + // sensitive for logging
", managerPassword=******" + // sensitive for logging
", baseDn=" + baseDn +
", userDnPattern=" + userDnPattern +
", userSearchBase=" + userSearchBase + | ", userSearchFilter=" + userSearchFilter +
", groupSearchBase=" + groupSearchBase +
", groupSearchFilter=" + groupSearchFilter +
", userIdAttribute=" + userIdAttribute +
", userFirstnameAttribute=" + userFirstnameAttribute +
", userLastnameAttribute=" + userLastnameAttribute +
", userEmailAttribute=" + userEmailAttribute +
", userPasswordAttribute=" + userPasswordAttribute +
", groupIdAttribute=" + groupIdAttribute +
", groupNameAttribute=" + groupNameAttribute +
", groupTypeAttribute=" + groupTypeAttribute +
", groupMemberAttribute=" + groupMemberAttribute +
", sortControlSupported=" + sortControlSupported +
", useSsl=" + useSsl +
", usePosixGroups=" + usePosixGroups +
", allowAnonymousLogin=" + allowAnonymousLogin +
", authorizationCheckEnabled=" + authorizationCheckEnabled +
", passwordCheckCatchAuthenticationException=" + passwordCheckCatchAuthenticationException + "]";
}
} | repos\camunda-bpm-platform-master\distro\run\core\src\main\java\org\camunda\bpm\run\property\CamundaBpmRunLdapProperties.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Employee {
@EmbeddedId
private EmployeeIdentity id;
private String name;
private String email;
@Column(name = "phone_number")
private String phoneNumber;
public Employee() {
}
public Employee(EmployeeIdentity id, String name, String email, String phoneNumber) {
super();
this.id = id;
this.name = name;
this.email = email;
this.phoneNumber = phoneNumber;
}
public EmployeeIdentity getId() {
return id;
}
public void setId(EmployeeIdentity id) {
this.id = id;
}
public String getName() {
return name;
} | public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
} | repos\Spring-Boot-Advanced-Projects-main\springboot-hibernate-composite-key-demo\src\main\java\net\alanbinu\springboot\entity\Employee.java | 2 |
请完成以下Java代码 | private void releaseAndSave(final I_M_PickingSlot pickingSlot)
{
pickingSlot.setC_BPartner_ID(-1);
pickingSlot.setC_BPartner_Location_ID(-1);
pickingSlot.setM_Picking_Job_ID(-1);
pickingSlotDAO.save(pickingSlot);
}
@Override
public void releasePickingSlotIfPossible(final PickingSlotId pickingSlotId)
{
final I_M_PickingSlot pickingSlot = pickingSlotDAO.getById(pickingSlotId, I_M_PickingSlot.class);
releasePickingSlotIfPossible(pickingSlot);
}
@Override
public void releasePickingSlotsIfPossible(@NonNull final Collection<PickingSlotId> pickingSlotIds)
{
// tolerate empty
if (pickingSlotIds.isEmpty())
{
return;
}
pickingSlotIds.forEach(this::releasePickingSlotIfPossible);
}
@Override
public List<I_M_HU> retrieveAvailableSourceHUs(@NonNull final PickingHUsQuery query)
{
final SourceHUsService sourceHuService = SourceHUsService.get();
return RetrieveAvailableHUsToPick.retrieveAvailableHUsToPick(query, sourceHuService::retrieveParentHusThatAreSourceHUs);
}
@Override
@NonNull
public List<I_M_HU> retrieveAvailableHUsToPick(@NonNull final PickingHUsQuery query)
{
return RetrieveAvailableHUsToPick.retrieveAvailableHUsToPick(query, RetrieveAvailableHUsToPickFilters::retrieveFullTreeAndExcludePickingHUs);
}
@Override
public ImmutableList<HuId> retrieveAvailableHUIdsToPick(@NonNull final PickingHUsQuery query)
{
return retrieveAvailableHUsToPick(query)
.stream()
.map(I_M_HU::getM_HU_ID)
.map(HuId::ofRepoId)
.collect(ImmutableList.toImmutableList());
} | @Override
public ImmutableList<HuId> retrieveAvailableHUIdsToPickForShipmentSchedule(@NonNull final RetrieveAvailableHUIdsToPickRequest request)
{
final I_M_ShipmentSchedule schedule = loadOutOfTrx(request.getScheduleId(), I_M_ShipmentSchedule.class);
final PickingHUsQuery query = PickingHUsQuery
.builder()
.onlyTopLevelHUs(request.isOnlyTopLevel())
.shipmentSchedule(schedule)
.onlyIfAttributesMatchWithShipmentSchedules(request.isConsiderAttributes())
.build();
return retrieveAvailableHUIdsToPick(query);
}
public boolean clearPickingSlotQueue(@NonNull final PickingSlotId pickingSlotId, final boolean removeQueuedHUsFromSlot)
{
final I_M_PickingSlot slot = pickingSlotDAO.getById(pickingSlotId, I_M_PickingSlot.class);
if (removeQueuedHUsFromSlot)
{
huPickingSlotDAO.retrieveAllHUs(slot)
.stream()
.map(hu -> HuId.ofRepoId(hu.getM_HU_ID()))
.forEach(queuedHU -> removeFromPickingSlotQueue(slot, queuedHU));
}
return huPickingSlotDAO.isEmpty(slot);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\slot\impl\HUPickingSlotBL.java | 1 |
请完成以下Java代码 | public boolean apply(IInvoiceCandidateRow row)
{
return row.isSelected();
}
};
public InvoiceCandidatesTableModel()
{
super(IInvoiceCandidateRow.class);
}
public final List<IInvoiceCandidateRow> getRowsSelected()
{
return FluentIterable.from(getRowsInnerList())
.filter(PREDICATE_Selected)
.toList();
}
public final Set<Integer> getSelectedInvoiceCandidateIds()
{
final Set<Integer> invoiceCandidateIds = new HashSet<>();
for (final IInvoiceCandidateRow row : getRowsSelected())
{
final int invoiceCandidateId = row.getC_Invoice_Candidate_ID();
if (invoiceCandidateId <= 0)
{
continue;
}
invoiceCandidateIds.add(invoiceCandidateId);
}
return invoiceCandidateIds;
}
public final void selectRowsByInvoiceCandidateIds(final Collection<Integer> invoiceCandidateIds)
{
if (invoiceCandidateIds == null || invoiceCandidateIds.isEmpty())
{
return;
}
final List<IInvoiceCandidateRow> rowsChanged = new ArrayList<>();
for (final IInvoiceCandidateRow row : getRowsInnerList())
{
// Skip if already selected
if (row.isSelected())
{
continue;
}
if (invoiceCandidateIds.contains(row.getC_Invoice_Candidate_ID()))
{
row.setSelected(true);
rowsChanged.add(row);
}
}
fireTableRowsUpdated(rowsChanged); | }
/** @return latest {@link IInvoiceCandidateRow#getDocumentDate()} of selected rows */
public final Date getLatestDocumentDateOfSelectedRows()
{
Date latestDocumentDate = null;
for (final IInvoiceCandidateRow row : getRowsSelected())
{
final Date documentDate = row.getDocumentDate();
latestDocumentDate = TimeUtil.max(latestDocumentDate, documentDate);
}
return latestDocumentDate;
}
/**
* @return latest {@link IInvoiceCandidateRow#getDateAcct()} of selected rows
*/
public final Date getLatestDateAcctOfSelectedRows()
{
Date latestDateAcct = null;
for (final IInvoiceCandidateRow row : getRowsSelected())
{
final Date dateAcct = row.getDateAcct();
latestDateAcct = TimeUtil.max(latestDateAcct, dateAcct);
}
return latestDateAcct;
}
public final BigDecimal getTotalNetAmtToInvoiceOfSelectedRows()
{
BigDecimal totalNetAmtToInvoiced = BigDecimal.ZERO;
for (final IInvoiceCandidateRow row : getRowsSelected())
{
final BigDecimal netAmtToInvoice = row.getNetAmtToInvoice();
totalNetAmtToInvoiced = totalNetAmtToInvoiced.add(netAmtToInvoice);
}
return totalNetAmtToInvoiced;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\InvoiceCandidatesTableModel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ConfigurableBootstrapContext getBootstrapContext() {
return this.contributors.getBootstrapContext();
}
}
private class InactiveSourceChecker implements BindHandler {
private final @Nullable ConfigDataActivationContext activationContext;
InactiveSourceChecker(@Nullable ConfigDataActivationContext activationContext) {
this.activationContext = activationContext;
}
@Override
public Object onSuccess(ConfigurationPropertyName name, Bindable<?> target, BindContext context,
Object result) {
for (ConfigDataEnvironmentContributor contributor : ConfigDataEnvironmentContributors.this) {
if (!contributor.isActive(this.activationContext)) {
InactiveConfigDataAccessException.throwIfPropertyFound(contributor, name);
}
}
return result;
} | }
/**
* Binder options that can be used with
* {@link ConfigDataEnvironmentContributors#getBinder(ConfigDataActivationContext, BinderOption...)}.
*/
enum BinderOption {
/**
* Throw an exception if an inactive contributor contains a bound value.
*/
FAIL_ON_BIND_TO_INACTIVE_SOURCE
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigDataEnvironmentContributors.java | 2 |
请完成以下Java代码 | public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** ReplicationType AD_Reference_ID=126 */
public static final int REPLICATIONTYPE_AD_Reference_ID=126;
/** Local = L */
public static final String REPLICATIONTYPE_Local = "L";
/** Merge = M */
public static final String REPLICATIONTYPE_Merge = "M";
/** Reference = R */
public static final String REPLICATIONTYPE_Reference = "R";
/** Broadcast = B */
public static final String REPLICATIONTYPE_Broadcast = "B";
/** Set Replication Type.
@param ReplicationType
Type of Data Replication
*/
public void setReplicationType (String ReplicationType)
{
set_Value (COLUMNNAME_ReplicationType, ReplicationType);
}
/** Get Replication Type.
@return Type of Data Replication
*/
public String getReplicationType () | {
return (String)get_Value(COLUMNNAME_ReplicationType);
}
public I_EXP_Format getEXP_Format() throws RuntimeException
{
return (I_EXP_Format)MTable.get(getCtx(), I_EXP_Format.Table_Name)
.getPO(getEXP_Format_ID(), get_TrxName());
}
public void setEXP_Format_ID (int EXP_Format_ID)
{
if (EXP_Format_ID < 1)
set_ValueNoCheck (COLUMNNAME_EXP_Format_ID, null);
else
set_ValueNoCheck (COLUMNNAME_EXP_Format_ID, Integer.valueOf(EXP_Format_ID));
}
public int getEXP_Format_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_EXP_Format_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ReplicationTable.java | 1 |
请完成以下Java代码 | public String getTitle() {
return title;
}
public Book setTitle(String title) {
this.title = title;
return this;
}
public String getAuthor() {
return author;
}
public Book setAuthor(String author) {
this.author = author;
return this;
}
public Publisher getPublisher() {
return publisher;
}
public Book setPublisher(Publisher publisher) {
this.publisher = publisher;
return this;
}
public double getCost() {
return cost;
}
public Book setCost(double cost) {
this.cost = cost;
return this;
}
public LocalDateTime getPublishDate() {
return publishDate;
}
public Book setPublishDate(LocalDateTime publishDate) {
this.publishDate = publishDate;
return this;
}
public Set<Book> getCompanionBooks() {
return companionBooks;
}
public Book addCompanionBooks(Book book) {
if (companionBooks != null)
this.companionBooks.add(book);
return this;
}
@Override
public String toString() {
return "Book [isbn=" + isbn + ", title=" + title + ", author=" + author + ", publisher=" + publisher + ", cost=" + cost + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((author == null) ? 0 : author.hashCode());
long temp;
temp = Double.doubleToLongBits(cost);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((isbn == null) ? 0 : isbn.hashCode());
result = prime * result + ((publisher == null) ? 0 : publisher.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object obj) { | if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Book other = (Book) obj;
if (author == null) {
if (other.author != null)
return false;
} else if (!author.equals(other.author))
return false;
if (Double.doubleToLongBits(cost) != Double.doubleToLongBits(other.cost))
return false;
if (isbn == null) {
if (other.isbn != null)
return false;
} else if (!isbn.equals(other.isbn))
return false;
if (publisher == null) {
if (other.publisher != null)
return false;
} else if (!publisher.equals(other.publisher))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
} | repos\tutorials-master\persistence-modules\java-mongodb\src\main\java\com\baeldung\bsontojson\Book.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OAuthFeignConfig {
public static final String CLIENT_REGISTRATION_ID = "keycloak";
private final OAuth2AuthorizedClientService oAuth2AuthorizedClientService;
private final ClientRegistrationRepository clientRegistrationRepository;
public OAuthFeignConfig(OAuth2AuthorizedClientService oAuth2AuthorizedClientService,
ClientRegistrationRepository clientRegistrationRepository) {
this.oAuth2AuthorizedClientService = oAuth2AuthorizedClientService;
this.clientRegistrationRepository = clientRegistrationRepository;
}
@Bean
public RequestInterceptor requestInterceptor() {
ClientRegistration clientRegistration = clientRegistrationRepository.findByRegistrationId(CLIENT_REGISTRATION_ID);
OAuthClientCredentialsFeignManager clientCredentialsFeignManager =
new OAuthClientCredentialsFeignManager(authorizedClientManager(), clientRegistration);
return requestTemplate -> {
requestTemplate.header("Authorization", "Bearer " + clientCredentialsFeignManager.getAccessToken());
}; | }
@Bean
OAuth2AuthorizedClientManager authorizedClientManager() {
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.clientCredentials()
.build();
AuthorizedClientServiceOAuth2AuthorizedClientManager authorizedClientManager =
new AuthorizedClientServiceOAuth2AuthorizedClientManager(clientRegistrationRepository, oAuth2AuthorizedClientService);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
return authorizedClientManager;
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-openfeign\src\main\java\com\baeldung\cloud\openfeign\oauthfeign\OAuthFeignConfig.java | 2 |
请完成以下Java代码 | abstract class StdConverters {
static final class AccessTokenTypeConverter extends StdConverter<JsonNode, OAuth2AccessToken.TokenType> {
@Override
public OAuth2AccessToken.TokenType convert(JsonNode jsonNode) {
String value = JsonNodeUtils.findStringValue(jsonNode, "value");
if (OAuth2AccessToken.TokenType.BEARER.getValue().equalsIgnoreCase(value)) {
return OAuth2AccessToken.TokenType.BEARER;
}
return null;
}
}
static final class ClientAuthenticationMethodConverter extends StdConverter<JsonNode, ClientAuthenticationMethod> {
@Override
public ClientAuthenticationMethod convert(JsonNode jsonNode) {
String value = JsonNodeUtils.findStringValue(jsonNode, "value");
return ClientAuthenticationMethod.valueOf(value);
}
}
static final class AuthorizationGrantTypeConverter extends StdConverter<JsonNode, AuthorizationGrantType> {
@Override
public AuthorizationGrantType convert(JsonNode jsonNode) {
String value = JsonNodeUtils.findStringValue(jsonNode, "value");
if (AuthorizationGrantType.AUTHORIZATION_CODE.getValue().equalsIgnoreCase(value)) {
return AuthorizationGrantType.AUTHORIZATION_CODE; | }
if (AuthorizationGrantType.CLIENT_CREDENTIALS.getValue().equalsIgnoreCase(value)) {
return AuthorizationGrantType.CLIENT_CREDENTIALS;
}
return new AuthorizationGrantType(value);
}
}
static final class AuthenticationMethodConverter extends StdConverter<JsonNode, AuthenticationMethod> {
@Override
public AuthenticationMethod convert(JsonNode jsonNode) {
String value = JsonNodeUtils.findStringValue(jsonNode, "value");
if (AuthenticationMethod.HEADER.getValue().equalsIgnoreCase(value)) {
return AuthenticationMethod.HEADER;
}
if (AuthenticationMethod.FORM.getValue().equalsIgnoreCase(value)) {
return AuthenticationMethod.FORM;
}
if (AuthenticationMethod.QUERY.getValue().equalsIgnoreCase(value)) {
return AuthenticationMethod.QUERY;
}
return null;
}
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\jackson\StdConverters.java | 1 |
请完成以下Java代码 | public boolean supportsParameter(MethodParameter parameter) {
return findMethodAnnotation(parameter) != null;
}
/**
* Sets the {@link BeanResolver} to be used on the expressions
* @param beanResolver the {@link BeanResolver} to use
*/
public void setBeanResolver(BeanResolver beanResolver) {
this.beanResolver = beanResolver;
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
/**
* Configure AuthenticationPrincipal template resolution
* <p>
* By default, this value is <code>null</code>, which indicates that templates should
* not be resolved.
* @param templateDefaults - whether to resolve AuthenticationPrincipal templates
* parameters
* @since 6.4
*/
public void setTemplateDefaults(AnnotationTemplateExpressionDefaults templateDefaults) {
this.scanner = SecurityAnnotationScanners.requireUnique(AuthenticationPrincipal.class, templateDefaults); | this.useAnnotationTemplate = templateDefaults != null;
}
/**
* Obtains the specified {@link Annotation} on the specified {@link MethodParameter}.
* {@link MethodParameter}
* @param parameter the {@link MethodParameter} to search for an {@link Annotation}
* @return the {@link Annotation} that was found or null.
*/
@SuppressWarnings("unchecked")
private @Nullable AuthenticationPrincipal findMethodAnnotation(MethodParameter parameter) {
if (this.useAnnotationTemplate) {
return this.scanner.scan(parameter.getParameter());
}
AuthenticationPrincipal annotation = parameter.getParameterAnnotation(this.annotationType);
if (annotation != null) {
return annotation;
}
Annotation[] annotationsToSearch = parameter.getParameterAnnotations();
for (Annotation toSearch : annotationsToSearch) {
annotation = AnnotationUtils.findAnnotation(toSearch.annotationType(), this.annotationType);
if (annotation != null) {
return MergedAnnotations.from(toSearch).get(this.annotationType).synthesize();
}
}
return null;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\method\annotation\AuthenticationPrincipalArgumentResolver.java | 1 |
请完成以下Java代码 | public void setProductNo(final String productNo)
{
this.productNo = productNo;
productNoSet = true;
}
public void setDescription(final String description)
{
this.description = description;
descriptionSet = true;
}
public void setCuEAN(final String cuEAN)
{
this.cuEAN = cuEAN;
cuEANSet = true;
}
public void setGtin(final String gtin)
{
this.gtin = gtin;
gtinSet = true;
}
public void setCustomerLabelName(final String customerLabelName)
{
this.customerLabelName = customerLabelName;
customerLabelNameSet = true;
}
public void setIngredients(final String ingredients)
{
this.ingredients = ingredients;
ingredientsSet = true;
}
public void setCurrentVendor(final Boolean currentVendor)
{
this.currentVendor = currentVendor;
currentVendorSet = true; | }
public void setExcludedFromSales(final Boolean excludedFromSales)
{
this.excludedFromSales = excludedFromSales;
excludedFromSalesSet = true;
}
public void setExclusionFromSalesReason(final String exclusionFromSalesReason)
{
this.exclusionFromSalesReason = exclusionFromSalesReason;
exclusionFromSalesReasonSet = true;
}
public void setDropShip(final Boolean dropShip)
{
this.dropShip = dropShip;
dropShipSet = true;
}
public void setUsedForVendor(final Boolean usedForVendor)
{
this.usedForVendor = usedForVendor;
usedForVendorSet = true;
}
public void setExcludedFromPurchase(final Boolean excludedFromPurchase)
{
this.excludedFromPurchase = excludedFromPurchase;
excludedFromPurchaseSet = true;
}
public void setExclusionFromPurchaseReason(final String exclusionFromPurchaseReason)
{
this.exclusionFromPurchaseReason = exclusionFromPurchaseReason;
exclusionFromPurchaseReasonSet = true;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-product\src\main\java\de\metas\common\product\v2\request\JsonRequestBPartnerProductUpsert.java | 1 |
请完成以下Java代码 | public ImmutableList<ProductPrice> getProductPrices(@NonNull final PriceListVersionId priceListVersionId)
{
return priceListsRepo.retrieveProductPrices(priceListVersionId)
.map(productPriceRepository::toProductPrice)
.collect(ImmutableList.toImmutableList());
}
@NonNull
public ImmutableList<I_M_ProductPrice> getProductPricesByPLVAndProduct(@NonNull final PriceListVersionId priceListVersionId, @NonNull final ProductId productId)
{
return priceListsRepo.retrieveProductPrices(priceListVersionId, productId);
}
@NonNull
public ImmutableMap<ProductId, String> getProductValues(final ImmutableSet<ProductId> productIds)
{
return productsService.getProductValues(productIds);
}
@NonNull
public String getProductValue(@NonNull final ProductId productId)
{
return productsService.getProductValue(productId);
}
// TODO move this method to de.metas.bpartner.service.IBPartnerDAO since it has nothing to do with price list
// TODO: IdentifierString must also be moved to the module containing IBPartnerDAO
public Optional<BPartnerId> getBPartnerId(final IdentifierString bpartnerIdentifier, final OrgId orgId)
{
final BPartnerQuery query = createBPartnerQuery(bpartnerIdentifier, orgId);
return bpartnersRepo.retrieveBPartnerIdBy(query);
}
private static BPartnerQuery createBPartnerQuery(@NonNull final IdentifierString bpartnerIdentifier, final OrgId orgId)
{
final Type type = bpartnerIdentifier.getType();
final BPartnerQuery.BPartnerQueryBuilder builder = BPartnerQuery.builder();
if (orgId != null)
{
builder.onlyOrgId(orgId);
} | if (Type.METASFRESH_ID.equals(type))
{
return builder
.bPartnerId(bpartnerIdentifier.asMetasfreshId(BPartnerId::ofRepoId))
.build();
}
else if (Type.EXTERNAL_ID.equals(type))
{
return builder
.externalId(bpartnerIdentifier.asExternalId())
.build();
}
else if (Type.VALUE.equals(type))
{
return builder
.bpartnerValue(bpartnerIdentifier.asValue())
.build();
}
else if (Type.GLN.equals(type))
{
return builder
.gln(bpartnerIdentifier.asGLN())
.build();
}
else
{
throw new AdempiereException("Invalid bpartnerIdentifier: " + bpartnerIdentifier);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\bpartner_pricelist\BpartnerPriceListServicesFacade.java | 1 |
请完成以下Java代码 | public class PersonName {
public String getName(String firstName, String lastName) throws RuntimeException {
return firstName + " " + lastName;
}
public String getName(String firstName, String middleName, String lastName) {
if (!middleName.equals("")) {
return firstName + " " + lastName;
}
return firstName + " " + middleName + " " + lastName;
}
public void printFullName(String firstName, String lastName) {
System.out.println(firstName + " " + lastName); | }
public void writeName(String name) throws IOException {
PrintWriter out = new PrintWriter(new FileWriter("OutFile.txt"));
out.println("Name: " + name);
out.close();
}
public static String getNameStatic(String firstName, String lastName) {
return firstName + " " + lastName;
}
public static void callToStaticMethod() {
System.out.println("Name is: " + PersonName.getNameStatic("Alan", "Turing"));
}
} | repos\tutorials-master\core-java-modules\core-java-lang-oop-methods-2\src\main\java\com\baeldung\methods\PersonName.java | 1 |
请完成以下Java代码 | public long length() {
return this.delegate.length();
}
@Override
public URI getURI() {
return this.delegate.getURI();
}
@Override
public String getName() {
return this.delegate.getName();
}
@Override
public String getFileName() {
return this.delegate.getFileName();
}
@Override
public InputStream newInputStream() throws IOException {
return this.delegate.newInputStream();
}
@Override
@SuppressWarnings({ "deprecation", "removal" })
public ReadableByteChannel newReadableByteChannel() throws IOException {
return this.delegate.newReadableByteChannel();
}
@Override
public List<Resource> list() {
return asLoaderHidingResources(this.delegate.list());
}
private boolean nonLoaderResource(Resource resource) {
return !resource.getPath().startsWith(this.loaderBasePath);
}
private List<Resource> asLoaderHidingResources(Collection<Resource> resources) {
return resources.stream().filter(this::nonLoaderResource).map(this::asLoaderHidingResource).toList();
}
private Resource asLoaderHidingResource(Resource resource) {
return (resource instanceof LoaderHidingResource) ? resource : new LoaderHidingResource(this.base, resource);
}
@Override
public @Nullable Resource resolve(String subUriPath) {
if (subUriPath.startsWith(LOADER_RESOURCE_PATH_PREFIX)) {
return null;
}
Resource resolved = this.delegate.resolve(subUriPath);
return (resolved != null) ? new LoaderHidingResource(this.base, resolved) : null;
} | @Override
public boolean isAlias() {
return this.delegate.isAlias();
}
@Override
public URI getRealURI() {
return this.delegate.getRealURI();
}
@Override
public void copyTo(Path destination) throws IOException {
this.delegate.copyTo(destination);
}
@Override
public Collection<Resource> getAllResources() {
return asLoaderHidingResources(this.delegate.getAllResources());
}
@Override
public String toString() {
return this.delegate.toString();
}
} | repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\servlet\LoaderHidingResource.java | 1 |
请完成以下Java代码 | public class ToCleanString implements Operator<String, String> {
public static ToCleanString toCleanString() {
return new ToCleanString();
}
private ToCleanString() {
super();
}
@Override
public Subscriber<? super String> call(final Subscriber<? super String> subscriber) {
return new Subscriber<String>(subscriber) {
@Override
public void onCompleted() {
if (!subscriber.isUnsubscribed()) {
subscriber.onCompleted();
}
} | @Override
public void onError(Throwable t) {
if (!subscriber.isUnsubscribed()) {
subscriber.onError(t);
}
}
@Override
public void onNext(String item) {
if (!subscriber.isUnsubscribed()) {
final String result = item.replaceAll("[^A-Za-z0-9]", "");
subscriber.onNext(result);
}
}
};
}
} | repos\tutorials-master\rxjava-modules\rxjava-operators\src\main\java\com\baeldung\rxjava\operator\ToCleanString.java | 1 |
请完成以下Java代码 | public String toString()
{
StringBuffer sb = new StringBuffer ("X_C_OrgAssignment[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_AD_User getAD_User() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getAD_User_ID(), get_TrxName()); }
/** Set User/Contact.
@param AD_User_ID
User within the system - Internal or Business Partner Contact
*/
public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 1)
set_Value (COLUMNNAME_AD_User_ID, null);
else
set_Value (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID));
}
/** Get User/Contact.
@return User within the system - Internal or Business Partner Contact
*/
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Org Assignment.
@param C_OrgAssignment_ID
Assigment to (transaction) Organization
*/
public void setC_OrgAssignment_ID (int C_OrgAssignment_ID)
{
if (C_OrgAssignment_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_OrgAssignment_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_OrgAssignment_ID, Integer.valueOf(C_OrgAssignment_ID));
}
/** Get Org Assignment.
@return Assigment to (transaction) Organization
*/
public int getC_OrgAssignment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_OrgAssignment_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 Valid from. | @param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_OrgAssignment.java | 1 |
请完成以下Java代码 | public void setDescription(String description) {
this.description = description;
}
@Override
public String getApplicationName() {
return this.applicationName;
}
/**
* Sets the application name.
* @param applicationName the application name
*/
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
@Override
public String getPackageName() {
if (StringUtils.hasText(this.packageName)) {
return this.packageName;
}
if (StringUtils.hasText(this.groupId) && StringUtils.hasText(this.artifactId)) {
return this.groupId + "." + this.artifactId;
}
return null; | }
/**
* Sets the package name.
* @param packageName the package name
*/
public void setPackageName(String packageName) {
this.packageName = packageName;
}
@Override
public String getBaseDirectory() {
return this.baseDirectory;
}
/**
* Sets the base directory.
* @param baseDirectory the base directory
*/
public void setBaseDirectory(String baseDirectory) {
this.baseDirectory = baseDirectory;
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\project\MutableProjectDescription.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ForecastService
{
private final static AdMessageKey FORECAST_COMPLETED_NOTIFICATION = AdMessageKey.of("ForecastDocumentCompleted");
@NonNull private final IForecastDAO forecastDAO = Services.get(IForecastDAO.class);
@NonNull private final IDocumentBL docActionBL = Services.get(IDocumentBL.class);
@NonNull private final INotificationBL userNotifications = Services.get(INotificationBL.class);
@NonNull
public ImmutableSet<ForecastId> createForecasts(@NonNull final List<ForecastRequest> requests)
{
return requests.stream()
.map(forecastDAO::createForecast)
.collect(ImmutableSet.toImmutableSet());
}
public void completeAndNotifyUser(@NonNull final ImmutableSet<ForecastId> ids, @NonNull final UserId userId)
{
forecastDAO.streamRecordsByIds(ids).forEach(forecast -> {
complete(forecast); | sendForecastCompleteNotification(forecast, userId);
});
}
private void complete(@NonNull final I_M_Forecast forecast)
{
docActionBL.processEx(forecast, IDocument.ACTION_Complete, IDocument.STATUS_Completed);
}
private void sendForecastCompleteNotification(@NonNull final I_M_Forecast forecast, @NonNull final UserId userId)
{
final UserNotificationRequest userNotificationRequest = UserNotificationRequest.builder()
.recipientUserId(userId)
.contentADMessage(FORECAST_COMPLETED_NOTIFICATION)
.contentADMessageParam(forecast.getName() + "|" + forecast.getM_Forecast_ID())
.targetAction(UserNotificationRequest.TargetRecordAction.of(TableRecordReference.of(forecast)))
.build();
userNotifications.send(userNotificationRequest);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\mforecast\impl\ForecastService.java | 2 |
请完成以下Java代码 | public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getCredentialType() {
return credentialType;
}
public void setCredentialType(String credentialType) {
this.credentialType = credentialType;
}
public String getCredentialId() {
return credentialId;
}
public void setCredentialId(String credentialId) {
this.credentialId = credentialId;
}
public String getPublicKeyCose() {
return publicKeyCose;
}
public void setPublicKeyCose(String publicKeyCose) {
this.publicKeyCose = publicKeyCose;
}
public Long getSignatureCount() {
return signatureCount;
}
public void setSignatureCount(Long signatureCount) {
this.signatureCount = signatureCount;
}
public Boolean getUvInitialized() {
return uvInitialized;
}
public void setUvInitialized(Boolean uvInitialized) {
this.uvInitialized = uvInitialized;
}
public String getTransports() {
return transports;
} | public void setTransports(String transports) {
this.transports = transports;
}
public Boolean getBackupEligible() {
return backupEligible;
}
public void setBackupEligible(Boolean backupEligible) {
this.backupEligible = backupEligible;
}
public Boolean getBackupState() {
return backupState;
}
public void setBackupState(Boolean backupState) {
this.backupState = backupState;
}
public String getAttestationObject() {
return attestationObject;
}
public void setAttestationObject(String attestationObject) {
this.attestationObject = attestationObject;
}
public Instant getLastUsed() {
return lastUsed;
}
public void setLastUsed(Instant lastUsed) {
this.lastUsed = lastUsed;
}
public Instant getCreated() {
return created;
}
public void setCreated(Instant created) {
this.created = created;
}
} | repos\tutorials-master\spring-security-modules\spring-security-passkey\src\main\java\com\baeldung\tutorials\passkey\domain\PasskeyCredential.java | 1 |
请完成以下Java代码 | public class ListDemo {
private List<Passenger> passengers = new ArrayList<>(20);
// private List<Passenger> passengers = new LinkedList<>(); // No compile time error
public List<Passenger> addPassenger(Passenger passenger) {
passengers.add(passenger);
return passengers;
}
public List<Passenger> removePassenger(Passenger passenger) {
passengers.remove(passenger);
return passengers;
}
public List<Passenger> getPassengersBySource(String source) {
return passengers.stream()
.filter(it -> it.getSource().equals(source))
.collect(Collectors.toList());
}
public List<Passenger> getPassengersByDestination(String destination) { | return passengers.stream()
.filter(it -> it.getDestination().equals(destination))
.collect(Collectors.toList());
}
public long getKidsCount(List<Passenger> passengerList) {
return passengerList.stream()
.filter(it -> (it.getAge() <= 10))
.count();
}
public List<Passenger> getFinalPassengersList() {
return Collections.unmodifiableList(passengers);
}
public List<String> getServicedCountries() {
return Stream.of(Locale.getISOCountries())
.collect(Collectors.toList());
}
} | repos\tutorials-master\core-java-modules\core-java-collections-list-3\src\main\java\com\baeldung\list\listvsarraylist\ListDemo.java | 1 |
请完成以下Java代码 | public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Percent.
@param Percent
Percentage
*/
@Override
public void setPercent (int Percent)
{
set_Value (COLUMNNAME_Percent, Integer.valueOf(Percent));
}
/** Get Percent.
@return Percentage
*/
@Override
public int getPercent ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Percent);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Verarbeitet.
@param Processed | Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
throw new IllegalArgumentException ("Processed is virtual column"); }
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg 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;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Cost.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class ServletApiConfigurer<H extends HttpSecurityBuilder<H>>
extends AbstractHttpConfigurer<ServletApiConfigurer<H>, H> {
private SecurityContextHolderAwareRequestFilter securityContextRequestFilter = new SecurityContextHolderAwareRequestFilter();
/**
* Creates a new instance
* @see HttpSecurity#servletApi(Customizer)
*/
public ServletApiConfigurer() {
}
public ServletApiConfigurer<H> rolePrefix(String rolePrefix) {
this.securityContextRequestFilter.setRolePrefix(rolePrefix);
return this;
}
@Override
@SuppressWarnings("unchecked")
public void configure(H http) {
this.securityContextRequestFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
ExceptionHandlingConfigurer<H> exceptionConf = http.getConfigurer(ExceptionHandlingConfigurer.class);
AuthenticationEntryPoint authenticationEntryPoint = (exceptionConf != null)
? exceptionConf.getAuthenticationEntryPoint(http) : null;
this.securityContextRequestFilter.setAuthenticationEntryPoint(authenticationEntryPoint);
LogoutConfigurer<H> logoutConf = http.getConfigurer(LogoutConfigurer.class); | List<LogoutHandler> logoutHandlers = (logoutConf != null) ? logoutConf.getLogoutHandlers() : null;
this.securityContextRequestFilter.setLogoutHandlers(logoutHandlers);
AuthenticationTrustResolver trustResolver = http.getSharedObject(AuthenticationTrustResolver.class);
if (trustResolver != null) {
this.securityContextRequestFilter.setTrustResolver(trustResolver);
}
ApplicationContext context = http.getSharedObject(ApplicationContext.class);
if (context != null) {
context.getBeanProvider(GrantedAuthorityDefaults.class)
.ifUnique((grantedAuthorityDefaults) -> this.securityContextRequestFilter
.setRolePrefix(grantedAuthorityDefaults.getRolePrefix()));
this.securityContextRequestFilter.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy());
}
this.securityContextRequestFilter = postProcess(this.securityContextRequestFilter);
http.addFilter(this.securityContextRequestFilter);
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\ServletApiConfigurer.java | 2 |
请完成以下Java代码 | public Map<String, Object> getCaseVariables() {
return null;
}
@Override
public List<? extends IdentityLinkInfo> getIdentityLinks() {
return null;
}
@Override
public Date getClaimTime() {
return null;
}
@Override
public void setName(String name) {
activiti5Task.setName(name);
}
@Override
public void setLocalizedName(String name) {
activiti5Task.setLocalizedName(name);
}
@Override
public void setDescription(String description) {
activiti5Task.setDescription(description);
}
@Override
public void setLocalizedDescription(String description) {
activiti5Task.setLocalizedDescription(description);
}
@Override
public void setPriority(int priority) {
activiti5Task.setPriority(priority);
}
@Override
public void setOwner(String owner) {
activiti5Task.setOwner(owner);
}
@Override
public void setAssignee(String assignee) { | activiti5Task.setAssignee(assignee);
}
@Override
public DelegationState getDelegationState() {
return activiti5Task.getDelegationState();
}
@Override
public void setDelegationState(DelegationState delegationState) {
activiti5Task.setDelegationState(delegationState);
}
@Override
public void setDueDate(Date dueDate) {
activiti5Task.setDueDate(dueDate);
}
@Override
public void setCategory(String category) {
activiti5Task.setCategory(category);
}
@Override
public void setParentTaskId(String parentTaskId) {
activiti5Task.setParentTaskId(parentTaskId);
}
@Override
public void setTenantId(String tenantId) {
activiti5Task.setTenantId(tenantId);
}
@Override
public void setFormKey(String formKey) {
activiti5Task.setFormKey(formKey);
}
@Override
public boolean isSuspended() {
return activiti5Task.isSuspended();
}
} | repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5TaskWrapper.java | 1 |
请完成以下Java代码 | public void setA_Term (String A_Term)
{
set_Value (COLUMNNAME_A_Term, A_Term);
}
/** Get Period/Yearly.
@return Period/Yearly */
public String getA_Term ()
{
return (String)get_Value(COLUMNNAME_A_Term);
}
/** 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 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;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Table_Header.java | 1 |
请完成以下Java代码 | public class AggregationKeyRegistry implements IAggregationKeyRegistry
{
private static final Map<String, List<String>> dependsOnColumnNames = new HashMap<>();
private static final Map<String, CompositeAggregationKeyValueHandler> _valueHandlers = new HashMap<>();
@Override
public void registerDependsOnColumnnames(final String registrationKey, final String... columnNames)
{
dependsOnColumnNames.put(registrationKey, Arrays.asList(columnNames));
}
@Override
public List<String> getDependsOnColumnNames(final String registrationKey)
{
return dependsOnColumnNames.get(registrationKey);
}
private CompositeAggregationKeyValueHandler getCompositeKeyValueHandler(@NonNull final String registrationKey)
{
CompositeAggregationKeyValueHandler compositeKeyValueHandler = _valueHandlers.get(registrationKey);
if (compositeKeyValueHandler == null)
{
compositeKeyValueHandler = new CompositeAggregationKeyValueHandler();
_valueHandlers.put(registrationKey, compositeKeyValueHandler);
}
return compositeKeyValueHandler;
} | @Override
public void registerAggregationKeyValueHandler(final String registrationKey, final IAggregationKeyValueHandler<?> aggregationKeyValueHandler)
{
final CompositeAggregationKeyValueHandler compositeKeyValueHandler = getCompositeKeyValueHandler(registrationKey);
@SuppressWarnings("unchecked")
final IAggregationKeyValueHandler<Object> aggregationKeyValueHandlerCast = (IAggregationKeyValueHandler<Object>)aggregationKeyValueHandler;
compositeKeyValueHandler.registerAggregationKeyValueHandler(aggregationKeyValueHandlerCast);
}
@Override
public <T> List<Object> getValuesForModel(final String registrationKey, final T model)
{
final CompositeAggregationKeyValueHandler compositeKeyValueHandler = getCompositeKeyValueHandler(registrationKey);
return compositeKeyValueHandler.getValues(model);
}
@Override
public void clearHandlers(final String registrationKey)
{
_valueHandlers.remove(registrationKey);
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\agg\key\impl\AggregationKeyRegistry.java | 1 |
请完成以下Java代码 | public String getElementName() {
return ELEMENT_CALL_ACTIVITY_IN_PARAMETERS;
}
public void parseChildElement(XMLStreamReader xtr, BaseElement parentElement, BpmnModel model)
throws Exception {
String source = xtr.getAttributeValue(null, ATTRIBUTE_IOPARAMETER_SOURCE);
String sourceExpression = xtr.getAttributeValue(null, ATTRIBUTE_IOPARAMETER_SOURCE_EXPRESSION);
String target = xtr.getAttributeValue(null, ATTRIBUTE_IOPARAMETER_TARGET);
if (
(StringUtils.isNotEmpty(source) || StringUtils.isNotEmpty(sourceExpression)) &&
StringUtils.isNotEmpty(target)
) {
IOParameter parameter = new IOParameter();
if (StringUtils.isNotEmpty(sourceExpression)) {
parameter.setSourceExpression(sourceExpression);
} else {
parameter.setSource(source);
}
parameter.setTarget(target);
((CallActivity) parentElement).getInParameters().add(parameter);
}
}
}
public class OutParameterParser extends BaseChildElementParser {
public String getElementName() {
return ELEMENT_CALL_ACTIVITY_OUT_PARAMETERS;
}
public void parseChildElement(XMLStreamReader xtr, BaseElement parentElement, BpmnModel model)
throws Exception {
String source = xtr.getAttributeValue(null, ATTRIBUTE_IOPARAMETER_SOURCE);
String sourceExpression = xtr.getAttributeValue(null, ATTRIBUTE_IOPARAMETER_SOURCE_EXPRESSION);
String target = xtr.getAttributeValue(null, ATTRIBUTE_IOPARAMETER_TARGET);
if ( | (StringUtils.isNotEmpty(source) || StringUtils.isNotEmpty(sourceExpression)) &&
StringUtils.isNotEmpty(target)
) {
IOParameter parameter = new IOParameter();
if (StringUtils.isNotEmpty(sourceExpression)) {
parameter.setSourceExpression(sourceExpression);
} else {
parameter.setSource(source);
}
parameter.setTarget(target);
((CallActivity) parentElement).getOutParameters().add(parameter);
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\CallActivityXMLConverter.java | 1 |
请完成以下Java代码 | public void init(TbContext tbContext, TbNodeConfiguration configuration) throws TbNodeException {
this.config = TbNodeUtils.convert(configuration, TbCheckMessageNodeConfiguration.class);
messageNamesList = config.getMessageNames();
metadataNamesList = config.getMetadataNames();
}
@Override
public void onMsg(TbContext ctx, TbMsg msg) {
try {
String relationType = config.isCheckAllKeys() ?
allKeysData(msg) && allKeysMetadata(msg) ? TbNodeConnectionType.TRUE : TbNodeConnectionType.FALSE :
atLeastOneData(msg) || atLeastOneMetadata(msg) ? TbNodeConnectionType.TRUE : TbNodeConnectionType.FALSE;
ctx.tellNext(msg, relationType);
} catch (Exception e) {
ctx.tellFailure(msg, e);
}
}
private boolean allKeysData(TbMsg msg) {
if (!messageNamesList.isEmpty()) {
Map<String, String> dataMap = dataToMap(msg);
return processAllKeys(messageNamesList, dataMap);
}
return true;
}
private boolean allKeysMetadata(TbMsg msg) {
if (!metadataNamesList.isEmpty()) {
Map<String, String> metadataMap = metadataToMap(msg);
return processAllKeys(metadataNamesList, metadataMap);
}
return true;
}
private boolean atLeastOneData(TbMsg msg) {
if (!messageNamesList.isEmpty()) {
Map<String, String> dataMap = dataToMap(msg);
return processAtLeastOne(messageNamesList, dataMap);
}
return false;
}
private boolean atLeastOneMetadata(TbMsg msg) { | if (!metadataNamesList.isEmpty()) {
Map<String, String> metadataMap = metadataToMap(msg);
return processAtLeastOne(metadataNamesList, metadataMap);
}
return false;
}
private boolean processAllKeys(List<String> data, Map<String, String> map) {
for (String field : data) {
if (!map.containsKey(field)) {
return false;
}
}
return true;
}
private boolean processAtLeastOne(List<String> data, Map<String, String> map) {
for (String field : data) {
if (map.containsKey(field)) {
return true;
}
}
return false;
}
private Map<String, String> metadataToMap(TbMsg msg) {
return msg.getMetaData().getData();
}
@SuppressWarnings("unchecked")
private Map<String, String> dataToMap(TbMsg msg) {
return (Map<String, String>) gson.fromJson(msg.getData(), Map.class);
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\filter\TbCheckMessageNode.java | 1 |
请完成以下Java代码 | public Collection<HUProcessDescriptor> getHUProcessDescriptors()
{
return getIndexedHUProcessDescriptors().getAsCollection();
}
@Override
public HUProcessDescriptor getByProcessIdOrNull(@NonNull final AdProcessId processId)
{
return getIndexedHUProcessDescriptors().getByProcessIdOrNull(processId);
}
private IndexedHUProcessDescriptors getIndexedHUProcessDescriptors()
{
return huProcessDescriptors.getOrLoad(0, this::retrieveIndexedHUProcessDescriptors);
}
private IndexedHUProcessDescriptors retrieveIndexedHUProcessDescriptors()
{
final ImmutableList<HUProcessDescriptor> huProcessDescriptors = Services.get(IQueryBL.class)
.createQueryBuilderOutOfTrx(I_M_HU_Process.class)
.addOnlyActiveRecordsFilter()
.create()
.stream(I_M_HU_Process.class)
.map(MHUProcessDAO::toHUProcessDescriptor)
.collect(ImmutableList.toImmutableList());
return new IndexedHUProcessDescriptors(huProcessDescriptors);
}
private static HUProcessDescriptor toHUProcessDescriptor(final I_M_HU_Process huProcessRecord)
{
final HUProcessDescriptorBuilder builder = HUProcessDescriptor.builder()
.processId(AdProcessId.ofRepoId(huProcessRecord.getAD_Process_ID()))
.internalName(huProcessRecord.getAD_Process().getValue());
if (huProcessRecord.isApplyToLUs())
{
builder.acceptHUUnitType(HuUnitType.LU);
}
if (huProcessRecord.isApplyToTUs()) | {
builder.acceptHUUnitType(HuUnitType.TU);
}
if (huProcessRecord.isApplyToCUs())
{
builder.acceptHUUnitType(HuUnitType.VHU);
}
builder.provideAsUserAction(huProcessRecord.isProvideAsUserAction());
builder.acceptOnlyTopLevelHUs(huProcessRecord.isApplyToTopLevelHUsOnly());
return builder.build();
}
private static final class IndexedHUProcessDescriptors
{
private final ImmutableMap<AdProcessId, HUProcessDescriptor> huProcessDescriptorsByProcessId;
private IndexedHUProcessDescriptors(final List<HUProcessDescriptor> huProcessDescriptors)
{
huProcessDescriptorsByProcessId = Maps.uniqueIndex(huProcessDescriptors, HUProcessDescriptor::getProcessId);
}
public Collection<HUProcessDescriptor> getAsCollection()
{
return huProcessDescriptorsByProcessId.values();
}
public HUProcessDescriptor getByProcessIdOrNull(final AdProcessId processId)
{
return huProcessDescriptorsByProcessId.get(processId);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\process\api\impl\MHUProcessDAO.java | 1 |
请完成以下Java代码 | public static void printJsonString(@NonNull final JsonOLCandCreateBulkRequest object)
{
System.out.println(writeValueAsString(object));
}
private static String writeValueAsString(@NonNull final JsonOLCandCreateBulkRequest object)
{
final ObjectMapper jsonObjectMapper = JsonObjectMapperHolder.newJsonObjectMapper()
.enable(SerializationFeature.INDENT_OUTPUT);
try
{
final String json = jsonObjectMapper.writeValueAsString(object);
return json;
}
catch (final JsonProcessingException e)
{
throw new JsonOLCandUtilException("JsonProcessingException", e);
}
}
public static class JsonOLCandUtilException extends RuntimeException
{
private static final long serialVersionUID = -626001461757553239L;
public JsonOLCandUtilException(final String msg, final Throwable cause)
{
super(msg, cause);
}
}
public static JsonOLCandCreateBulkRequest loadJsonOLCandCreateBulkRequest(@NonNull final String resourceName)
{
return fromRessource(resourceName, JsonOLCandCreateBulkRequest.class);
}
public static JsonOLCandCreateRequest loadJsonOLCandCreateRequest(@NonNull final String resourceName) | {
return fromRessource(resourceName, JsonOLCandCreateRequest.class);
}
private static <T> T fromRessource(@NonNull final String resourceName, @NonNull final Class<T> clazz)
{
final InputStream inputStream = Check.assumeNotNull(
JsonOLCandUtil.class.getResourceAsStream(resourceName),
"There needs to be a loadable resource with name={}", resourceName);
final ObjectMapper jsonObjectMapper = JsonObjectMapperHolder.sharedJsonObjectMapper();
try
{
return jsonObjectMapper.readValue(inputStream, clazz);
}
catch (final JsonParseException e)
{
throw new JsonOLCandUtilException("JsonParseException", e);
}
catch (final JsonMappingException e)
{
throw new JsonOLCandUtilException("JsonMappingException", e);
}
catch (final IOException e)
{
throw new JsonOLCandUtilException("IOException", e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\ordercandidates\impl\JsonOLCandUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public CurrencyId getCurrencyId()
{
return amountToAllocateInitial.getCurrencyId();
}
@Override
public void addAllocatedAmt(@NonNull final Money allocatedAmtToAdd)
{
allocatedAmt = allocatedAmt.add(allocatedAmtToAdd);
amountToAllocate = amountToAllocate.subtract(allocatedAmtToAdd);
}
@Override
public LocalDate getDate()
{
return dateTrx;
}
@Override
public boolean isFullyAllocated()
{
return getAmountToAllocate().signum() == 0;
}
private Money getOpenAmtRemaining()
{
final Money totalAllocated = allocatedAmt;
return openAmtInitial.subtract(totalAllocated);
}
@Override | public Money calculateProjectedOverUnderAmt(@NonNull final Money amountToAllocate)
{
return getOpenAmtRemaining().subtract(amountToAllocate);
}
@Override
public boolean canPay(@NonNull final PayableDocument payable)
{
return true;
}
@Override
public Money getPaymentDiscountAmt()
{
return amountToAllocate.toZero();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\service\PaymentDocument.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Book {
@Id
@GeneratedValue
private Long id;
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
public Book() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() { | return author;
}
public void setAuthor(String author) {
this.author = author;
}
static Specification<Book> hasAuthor(String author) {
return (book, cq, cb) -> cb.equal(book.get("author"), author);
}
static Specification<Book> titleContains(String title) {
return (book, cq, cb) -> cb.like(book.get("title"), "%" + title + "%");
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\criteriaquery\Book.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
} | public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getTaskUrl() {
return taskUrl;
}
public void setTaskUrl(String taskUrl) {
this.taskUrl = taskUrl;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessInstanceUrl() {
return processInstanceUrl;
}
public void setProcessInstanceUrl(String processInstanceUrl) {
this.processInstanceUrl = processInstanceUrl;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\engine\CommentResponse.java | 2 |
请完成以下Spring Boot application配置 | server.port=8088
spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=root
#Spring Boot 2.0 includes HikariDataSource by default
#spring.datasource.type = com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.connection-timeout=20000
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.maximum-pool-size=12
spring.datasource.hikari.idle-timeout=300000
spring.datasource.hikari.max-lifetime=1200000
spring.datasource.hikari. | auto-commit=true
spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
#use mysql database
spring.jpa.database=mysql
# show sql
spring.jpa.show-sql=true | repos\springboot-demo-master\hikari\src\main\resources\application.properties | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setPhone(String phone) {
this.phone = phone;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getLicencePic() {
return licencePic;
}
public void setLicencePic(String licencePic) {
this.licencePic = licencePic;
}
public Timestamp getRegisterTime() {
return registerTime;
}
public void setRegisterTime(Timestamp registerTime) {
this.registerTime = registerTime;
}
public UserTypeEnum getUserTypeEnum() {
return userTypeEnum;
}
public void setUserTypeEnum(UserTypeEnum userTypeEnum) {
this.userTypeEnum = userTypeEnum;
}
public UserStateEnum getUserStateEnum() {
return userStateEnum;
}
public void setUserStateEnum(UserStateEnum userStateEnum) {
this.userStateEnum = userStateEnum;
} | public RoleEntity getRoleEntity() {
return roleEntity;
}
public void setRoleEntity(RoleEntity roleEntity) {
this.roleEntity = roleEntity;
}
@Override
public String toString() {
return "UserEntity{" +
"id='" + id + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
", phone='" + phone + '\'' +
", mail='" + mail + '\'' +
", licencePic='" + licencePic + '\'' +
", registerTime=" + registerTime +
", userTypeEnum=" + userTypeEnum +
", userStateEnum=" + userStateEnum +
", roleEntity=" + roleEntity +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\user\UserEntity.java | 2 |
请完成以下Java代码 | public DeviceProfile findDefaultEntityByTenantId(UUID tenantId) {
return findDefaultDeviceProfile(TenantId.fromUUID(tenantId));
}
@Override
public List<DeviceProfileInfo> findByTenantAndImageLink(TenantId tenantId, String imageLink, int limit) {
return deviceProfileRepository.findByTenantAndImageLink(tenantId.getId(), imageLink, PageRequest.of(0, limit));
}
@Override
public List<DeviceProfileInfo> findByImageLink(String imageLink, int limit) {
return deviceProfileRepository.findByImageLink(imageLink, PageRequest.of(0, limit));
}
@Override | public PageData<DeviceProfile> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findDeviceProfiles(tenantId, pageLink);
}
@Override
public List<DeviceProfileFields> findNextBatch(UUID id, int batchSize) {
return deviceProfileRepository.findNextBatch(id, Limit.of(batchSize));
}
@Override
public EntityType getEntityType() {
return EntityType.DEVICE_PROFILE;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\device\JpaDeviceProfileDao.java | 1 |
请完成以下Java代码 | private String cleanMavenCoordinate(String coordinate, String delimiter) {
String[] elements = coordinate.split("[^\\w\\-.]+");
if (elements.length == 1) {
return coordinate;
}
StringBuilder builder = new StringBuilder();
for (String element : elements) {
if (shouldAppendDelimiter(element, builder)) {
builder.append(delimiter);
}
builder.append(element);
}
return builder.toString();
}
private boolean shouldAppendDelimiter(String element, StringBuilder builder) {
if (builder.isEmpty()) {
return false; | }
for (char c : VALID_MAVEN_SPECIAL_CHARACTERS) {
int prevIndex = builder.length() - 1;
if (element.charAt(0) == c || builder.charAt(prevIndex) == c) {
return false;
}
}
return true;
}
private String determineValue(String candidate, Supplier<String> fallback) {
return (StringUtils.hasText(candidate)) ? candidate : fallback.get();
}
} | repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\project\MetadataProjectDescriptionCustomizer.java | 1 |
请完成以下Java代码 | public class WorkflowEngineImpl implements WorkflowEngine {
@Override
public ProcessInstance runjBPMEngineForProcess(String processId, Context<String> initialContext, String kbaseId, String persistenceUnit) {
RuntimeManager manager = null;
RuntimeEngine engine = null;
ProcessInstance pInstance = null;
try {
KieBase kbase = getKieBase(kbaseId);
manager = createJBPMRuntimeManager(kbase, persistenceUnit);
engine = manager.getRuntimeEngine(initialContext);
pInstance = executeProcessInstance(processId, manager, initialContext, engine);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (manager != null && engine != null)
manager.disposeRuntimeEngine(engine);
System.exit(0);
}
return pInstance;
}
private ProcessInstance executeProcessInstance(String processId, RuntimeManager manager, Context<String> initialContext, RuntimeEngine engine) {
KieSession ksession = engine.getKieSession();
ProcessInstance pInstance = ksession.startProcess(processId);
return pInstance;
} | private KieBase getKieBase(String kbaseId) {
KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieBase kbase = kContainer.getKieBase(kbaseId);
return kbase;
}
private RuntimeManager createJBPMRuntimeManager(KieBase kbase, String persistenceUnit) {
JBPMHelper.startH2Server();
JBPMHelper.setupDataSource();
EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit);
RuntimeEnvironmentBuilder runtimeEnvironmentBuilder = RuntimeEnvironmentBuilder.Factory.get()
.newDefaultBuilder();
RuntimeEnvironment runtimeEnvironment = runtimeEnvironmentBuilder.entityManagerFactory(emf)
.knowledgeBase(kbase)
.get();
return RuntimeManagerFactory.Factory.get()
.newSingletonRuntimeManager(runtimeEnvironment);
}
} | repos\tutorials-master\libraries-2\src\main\java\com\baeldung\jbpm\engine\WorkflowEngineImpl.java | 1 |
请完成以下Java代码 | public void setOvertimeCost (BigDecimal OvertimeCost)
{
set_Value (COLUMNNAME_OvertimeCost, OvertimeCost);
}
/** Get Overtime Cost.
@return Hourly Overtime Cost
*/
public BigDecimal getOvertimeCost ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OvertimeCost);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom); | }
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_UserRemuneration.java | 1 |
请完成以下Java代码 | private C getContext(WebApplicationContext webApplicationContext) {
if (this.contextClass.isInstance(webApplicationContext)) {
return (C) webApplicationContext;
}
return webApplicationContext.getBean(this.contextClass);
}
/**
* Returns if the {@link WebApplicationContext} should be ignored and not used for
* matching. If this method returns {@code true} then the context will not be used and
* the {@link #matches(HttpServletRequest) matches} method will return {@code false}.
* @param webApplicationContext the candidate web application context
* @return if the application context should be ignored
*/
protected boolean ignoreApplicationContext(WebApplicationContext webApplicationContext) {
return false;
}
/**
* Method that can be implemented by subclasses that wish to initialize items the
* first time that the matcher is called. This method will be called only once and
* only if {@link #ignoreApplicationContext(WebApplicationContext)} returns
* {@code false}. Note that the supplied context will be based on the
* <strong>first</strong> request sent to the matcher.
* @param context a supplier for the initialized context (may throw an exception)
* @see #ignoreApplicationContext(WebApplicationContext)
*/
protected void initialized(Supplier<C> context) {
}
/**
* Decides whether the rule implemented by the strategy matches the supplied request.
* @param request the source request
* @param context a supplier for the initialized context (may throw an exception)
* @return if the request matches
*/
protected abstract boolean matches(HttpServletRequest request, Supplier<C> context); | /**
* Returns {@code true} if the specified context is a
* {@link WebServerApplicationContext} with a matching server namespace.
* @param context the context to check
* @param serverNamespace the server namespace to match against
* @return {@code true} if the server namespace of the context matches
* @since 4.0.1
*/
protected final boolean hasServerNamespace(@Nullable ApplicationContext context, String serverNamespace) {
if (!ClassUtils.isPresent(WEB_SERVER_CONTEXT_CLASS, null)) {
return false;
}
return WebServerApplicationContext.hasServerNamespace(context, serverNamespace);
}
/**
* Returns the server namespace if the specified context is a
* {@link WebServerApplicationContext}.
* @param context the context
* @return the server namespace or {@code null} if the context is not a
* {@link WebServerApplicationContext}
* @since 4.0.1
*/
protected final @Nullable String getServerNamespace(@Nullable ApplicationContext context) {
if (!ClassUtils.isPresent(WEB_SERVER_CONTEXT_CLASS, null)) {
return null;
}
return WebServerApplicationContext.getServerNamespace(context);
}
} | repos\spring-boot-4.0.1\module\spring-boot-security\src\main\java\org\springframework\boot\security\web\servlet\ApplicationContextRequestMatcher.java | 1 |
请完成以下Java代码 | public static Builder withAuthorizedClient(OAuth2AuthorizedClient authorizedClient) {
return new Builder(authorizedClient);
}
/**
* A builder for {@link OAuth2AuthorizationContext}.
*/
public static final class Builder {
private ClientRegistration clientRegistration;
private OAuth2AuthorizedClient authorizedClient;
private Authentication principal;
private Map<String, Object> attributes;
private Builder(ClientRegistration clientRegistration) {
Assert.notNull(clientRegistration, "clientRegistration cannot be null");
this.clientRegistration = clientRegistration;
}
private Builder(OAuth2AuthorizedClient authorizedClient) {
Assert.notNull(authorizedClient, "authorizedClient cannot be null");
this.authorizedClient = authorizedClient;
}
/**
* Sets the {@code Principal} (to be) associated to the authorized client.
* @param principal the {@code Principal} (to be) associated to the authorized
* client
* @return the {@link Builder}
*/
public Builder principal(Authentication principal) {
this.principal = principal;
return this;
}
/**
* Provides a {@link Consumer} access to the attributes associated to the context.
* @param attributesConsumer a {@link Consumer} of the attributes associated to
* the context
* @return the {@link OAuth2AuthorizeRequest.Builder}
*/
public Builder attributes(Consumer<Map<String, Object>> attributesConsumer) {
if (this.attributes == null) {
this.attributes = new HashMap<>();
}
attributesConsumer.accept(this.attributes);
return this;
} | /**
* Sets an attribute associated to the context.
* @param name the name of the attribute
* @param value the value of the attribute
* @return the {@link Builder}
*/
public Builder attribute(String name, Object value) {
if (this.attributes == null) {
this.attributes = new HashMap<>();
}
this.attributes.put(name, value);
return this;
}
/**
* Builds a new {@link OAuth2AuthorizationContext}.
* @return a {@link OAuth2AuthorizationContext}
*/
public OAuth2AuthorizationContext build() {
Assert.notNull(this.principal, "principal cannot be null");
OAuth2AuthorizationContext context = new OAuth2AuthorizationContext();
if (this.authorizedClient != null) {
context.clientRegistration = this.authorizedClient.getClientRegistration();
context.authorizedClient = this.authorizedClient;
}
else {
context.clientRegistration = this.clientRegistration;
}
context.principal = this.principal;
context.attributes = Collections.unmodifiableMap(CollectionUtils.isEmpty(this.attributes)
? Collections.emptyMap() : new LinkedHashMap<>(this.attributes));
return context;
}
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\OAuth2AuthorizationContext.java | 1 |
请完成以下Java代码 | public static void main(String[] args) {
if (args.length < 2) {
System.err.println("Usage: `java TranslationPruner <source folder> <dest folder>`, where dest folder must contain the locale.constant-en_US.json for reference structure.");
System.exit(1);
}
try {
File sourceFolder = new File(args[0]);
File destFolder = new File(args[1]);
File referenceFile = new File(destFolder, "locale.constant-en_US.json");
ObjectMapper mapper = new ObjectMapper();
JsonNode usRoot = mapper.readTree(referenceFile);
Set<String> validKeys = new HashSet<>();
collectKeys(usRoot, "", validKeys);
for (File sourceFile : sourceFolder.listFiles()) {
File destFile = new File(destFolder, sourceFile.getName());
JsonNode sourceRoot = mapper.readTree(sourceFile);
if (!sourceRoot.isObject()) { | throw new IllegalArgumentException("Source JSON must be an object at root");
}
ObjectNode pruned = pruneNode((ObjectNode) sourceRoot, validKeys, "", mapper);
Separators seps = Separators.createDefaultInstance()
.withObjectFieldValueSpacing(Spacing.AFTER);
mapper.writer(new DefaultPrettyPrinter().withSeparators(seps)).writeValue(destFile, pruned);
System.out.println("Pruned translation written to " + destFile.getPath());
}
} catch (IOException e) {
e.printStackTrace();
System.exit(2);
}
}
} | repos\thingsboard-master\tools\src\main\java\org\thingsboard\client\tools\i18n\TranslationPruner.java | 1 |
请完成以下Java代码 | public void updateActivity(final I_M_InOutLine inOutLine)
{
if (inOutLine.getC_Activity_ID() > 0)
{
return; // was already set, so don't try to auto-fill it
}
final ProductId productId = ProductId.ofRepoIdOrNull(inOutLine.getM_Product_ID());
if (productId == null)
{
return;
}
final ActivityId productActivityId = productAcctDAO.retrieveActivityForAcct(
ClientId.ofRepoId(inOutLine.getAD_Client_ID()),
OrgId.ofRepoId(inOutLine.getAD_Org_ID()),
productId); | if (productActivityId == null)
{
return;
}
final Dimension orderLineDimension = dimensionService.getFromRecord(inOutLine);
if (orderLineDimension == null)
{
//nothing to do
return;
}
dimensionService.updateRecord(inOutLine, orderLineDimension.withActivityId(productActivityId));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\activity\model\validator\M_InOutLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static class Provider {
/**
* Authorization URI for the provider.
*/
private @Nullable String authorizationUri;
/**
* Token URI for the provider.
*/
private @Nullable String tokenUri;
/**
* User info URI for the provider.
*/
private @Nullable String userInfoUri;
/**
* User info authentication method for the provider.
*/
private @Nullable String userInfoAuthenticationMethod;
/**
* Name of the attribute that will be used to extract the username from the call
* to 'userInfoUri'.
*/
private @Nullable String userNameAttribute;
/**
* JWK set URI for the provider.
*/
private @Nullable String jwkSetUri;
/**
* URI that can either be an OpenID Connect discovery endpoint or an OAuth 2.0
* Authorization Server Metadata endpoint defined by RFC 8414.
*/
private @Nullable String issuerUri;
public @Nullable String getAuthorizationUri() {
return this.authorizationUri;
}
public void setAuthorizationUri(@Nullable String authorizationUri) {
this.authorizationUri = authorizationUri;
}
public @Nullable String getTokenUri() {
return this.tokenUri;
}
public void setTokenUri(@Nullable String tokenUri) {
this.tokenUri = tokenUri;
}
public @Nullable String getUserInfoUri() { | return this.userInfoUri;
}
public void setUserInfoUri(@Nullable String userInfoUri) {
this.userInfoUri = userInfoUri;
}
public @Nullable String getUserInfoAuthenticationMethod() {
return this.userInfoAuthenticationMethod;
}
public void setUserInfoAuthenticationMethod(@Nullable String userInfoAuthenticationMethod) {
this.userInfoAuthenticationMethod = userInfoAuthenticationMethod;
}
public @Nullable String getUserNameAttribute() {
return this.userNameAttribute;
}
public void setUserNameAttribute(@Nullable String userNameAttribute) {
this.userNameAttribute = userNameAttribute;
}
public @Nullable String getJwkSetUri() {
return this.jwkSetUri;
}
public void setJwkSetUri(@Nullable String jwkSetUri) {
this.jwkSetUri = jwkSetUri;
}
public @Nullable String getIssuerUri() {
return this.issuerUri;
}
public void setIssuerUri(@Nullable String issuerUri) {
this.issuerUri = issuerUri;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-security-oauth2-client\src\main\java\org\springframework\boot\security\oauth2\client\autoconfigure\OAuth2ClientProperties.java | 2 |
请完成以下Java代码 | public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getRemote_Addr());
}
/** Set Remote Host.
@param Remote_Host
Remote host Info
*/
public void setRemote_Host (String Remote_Host)
{
set_Value (COLUMNNAME_Remote_Host, Remote_Host);
}
/** Get Remote Host.
@return Remote host Info
*/
public String getRemote_Host ()
{
return (String)get_Value(COLUMNNAME_Remote_Host);
}
/** Set Target URL.
@param TargetURL
URL for the Target
*/
public void setTargetURL (String TargetURL)
{
set_Value (COLUMNNAME_TargetURL, TargetURL);
}
/** Get Target URL.
@return URL for the Target
*/
public String getTargetURL ()
{
return (String)get_Value(COLUMNNAME_TargetURL);
}
/** Set User Agent.
@param UserAgent
Browser Used
*/
public void setUserAgent (String UserAgent)
{
set_Value (COLUMNNAME_UserAgent, UserAgent);
}
/** Get User Agent.
@return Browser Used
*/
public String getUserAgent ()
{
return (String)get_Value(COLUMNNAME_UserAgent);
}
public I_W_ClickCount getW_ClickCount() throws RuntimeException
{
return (I_W_ClickCount)MTable.get(getCtx(), I_W_ClickCount.Table_Name)
.getPO(getW_ClickCount_ID(), get_TrxName()); }
/** Set Click Count.
@param W_ClickCount_ID
Web Click Management
*/
public void setW_ClickCount_ID (int W_ClickCount_ID)
{
if (W_ClickCount_ID < 1) | set_ValueNoCheck (COLUMNNAME_W_ClickCount_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_ClickCount_ID, Integer.valueOf(W_ClickCount_ID));
}
/** Get Click Count.
@return Web Click Management
*/
public int getW_ClickCount_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_ClickCount_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Web Click.
@param W_Click_ID
Individual Web Click
*/
public void setW_Click_ID (int W_Click_ID)
{
if (W_Click_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_Click_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_Click_ID, Integer.valueOf(W_Click_ID));
}
/** Get Web Click.
@return Individual Web Click
*/
public int getW_Click_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_Click_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_Click.java | 1 |
请完成以下Java代码 | public int getAD_Role_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_DocType getC_DocType() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_DocType_ID, org.compiere.model.I_C_DocType.class);
}
@Override
public void setC_DocType(org.compiere.model.I_C_DocType C_DocType)
{
set_ValueFromPO(COLUMNNAME_C_DocType_ID, org.compiere.model.I_C_DocType.class, C_DocType);
}
/** Set Belegart.
@param C_DocType_ID
Document type or rules
*/
@Override
public void setC_DocType_ID (int C_DocType_ID)
{
if (C_DocType_ID < 0)
set_ValueNoCheck (COLUMNNAME_C_DocType_ID, null); | else
set_ValueNoCheck (COLUMNNAME_C_DocType_ID, Integer.valueOf(C_DocType_ID));
}
/** Get Belegart.
@return Document type or rules
*/
@Override
public int getC_DocType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Document_Action_Access.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void configureGlobalSecurity(
final AuthenticationManagerBuilder auth,
final MSV3ServerAuthenticationService msv3authService) throws Exception
{
auth.userDetailsService(msv3authService);
}
@Override
protected void configure(final HttpSecurity http) throws Exception
{
http
.csrf().disable()
.authorizeRequests()
.antMatchers(MSV3ServerConstants.WEBSERVICE_ENDPOINT_PATH + "/**").hasAuthority(ROLE_CLIENT)
.antMatchers(MSV3ServerConstants.REST_ENDPOINT_PATH + "/**").hasAuthority(ROLE_SERVER_ADMIN)
.and().httpBasic().realmName(REALM).authenticationEntryPoint(getBasicAuthEntryPoint())
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); | }
@Bean
public BasicAuthenticationEntryPoint getBasicAuthEntryPoint()
{
final BasicAuthenticationEntryPoint authenticationEntryPoint = new BasicAuthenticationEntryPoint();
authenticationEntryPoint.setRealmName(REALM);
return authenticationEntryPoint;
}
/* To allow Pre-flight [OPTIONS] request from browser */
@Override
public void configure(final WebSecurity web) throws Exception
{
web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\security\SecurityConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable String getAuthorityPrefix() {
return this.authorityPrefix;
}
public void setAuthorityPrefix(@Nullable String authorityPrefix) {
this.authorityPrefix = authorityPrefix;
}
public @Nullable String getAuthoritiesClaimDelimiter() {
return this.authoritiesClaimDelimiter;
}
public void setAuthoritiesClaimDelimiter(@Nullable String authoritiesClaimDelimiter) {
this.authoritiesClaimDelimiter = authoritiesClaimDelimiter;
}
public @Nullable String getAuthoritiesClaimName() {
return this.authoritiesClaimName;
}
public void setAuthoritiesClaimName(@Nullable String authoritiesClaimName) {
this.authoritiesClaimName = authoritiesClaimName;
}
public @Nullable String getPrincipalClaimName() {
return this.principalClaimName;
}
public void setPrincipalClaimName(@Nullable String principalClaimName) {
this.principalClaimName = principalClaimName;
}
public String readPublicKey() throws IOException {
String key = "spring.security.oauth2.resourceserver.jwt.public-key-location";
if (this.publicKeyLocation == null) {
throw new InvalidConfigurationPropertyValueException(key, this.publicKeyLocation,
"No public key location specified");
}
if (!this.publicKeyLocation.exists()) {
throw new InvalidConfigurationPropertyValueException(key, this.publicKeyLocation,
"Public key location does not exist");
}
try (InputStream inputStream = this.publicKeyLocation.getInputStream()) {
return StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
}
}
}
public static class Opaquetoken {
/**
* Client id used to authenticate with the token introspection endpoint.
*/
private @Nullable String clientId;
/**
* Client secret used to authenticate with the token introspection endpoint.
*/
private @Nullable String clientSecret;
/** | * OAuth 2.0 endpoint through which token introspection is accomplished.
*/
private @Nullable String introspectionUri;
public @Nullable String getClientId() {
return this.clientId;
}
public void setClientId(@Nullable String clientId) {
this.clientId = clientId;
}
public @Nullable String getClientSecret() {
return this.clientSecret;
}
public void setClientSecret(@Nullable String clientSecret) {
this.clientSecret = clientSecret;
}
public @Nullable String getIntrospectionUri() {
return this.introspectionUri;
}
public void setIntrospectionUri(@Nullable String introspectionUri) {
this.introspectionUri = introspectionUri;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-security-oauth2-resource-server\src\main\java\org\springframework\boot\security\oauth2\server\resource\autoconfigure\OAuth2ResourceServerProperties.java | 2 |
请完成以下Java代码 | public class UmsAdminPermissionRelation implements Serializable {
private Long id;
private Long adminId;
private Long permissionId;
private Integer type;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getAdminId() {
return adminId;
}
public void setAdminId(Long adminId) {
this.adminId = adminId;
}
public Long getPermissionId() {
return permissionId;
}
public void setPermissionId(Long permissionId) {
this.permissionId = permissionId;
}
public Integer getType() {
return type;
}
public void setType(Integer type) { | this.type = type;
}
@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(", adminId=").append(adminId);
sb.append(", permissionId=").append(permissionId);
sb.append(", type=").append(type);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsAdminPermissionRelation.java | 1 |
请完成以下Java代码 | public List<ActivityImpl> getInitialActivityStack() {
return getInitialActivityStack(initial);
}
public synchronized List<ActivityImpl> getInitialActivityStack(ActivityImpl startActivity) {
List<ActivityImpl> initialActivityStack = initialActivityStacks.get(startActivity);
if(initialActivityStack == null) {
initialActivityStack = new ArrayList<ActivityImpl>();
ActivityImpl activity = startActivity;
while (activity!=null) {
initialActivityStack.add(0, activity);
activity = activity.getParentFlowScopeActivity();
}
initialActivityStacks.put(startActivity, initialActivityStack);
}
return initialActivityStack;
}
public String getDiagramResourceName() {
return null;
}
public String getDeploymentId() {
return null;
}
public void addLaneSet(LaneSet newLaneSet) {
getLaneSets().add(newLaneSet);
}
public Lane getLaneForId(String id) {
if(laneSets != null && laneSets.size() > 0) {
Lane lane;
for(LaneSet set : laneSets) {
lane = set.getLaneForId(id);
if(lane != null) {
return lane;
}
}
}
return null;
}
@Override
public CoreActivityBehavior<? extends BaseDelegateExecution> getActivityBehavior() {
// unsupported in PVM
return null;
}
// getters and setters //////////////////////////////////////////////////////
public ActivityImpl getInitial() {
return initial;
}
public void setInitial(ActivityImpl initial) {
this.initial = initial;
}
@Override
public String toString() {
return "ProcessDefinition("+id+")";
}
public String getDescription() {
return (String) getProperty("documentation");
}
/**
* @return all lane-sets defined on this process-instance. Returns an empty list if none are defined. | */
public List<LaneSet> getLaneSets() {
if(laneSets == null) {
laneSets = new ArrayList<LaneSet>();
}
return laneSets;
}
public void setParticipantProcess(ParticipantProcess participantProcess) {
this.participantProcess = participantProcess;
}
public ParticipantProcess getParticipantProcess() {
return participantProcess;
}
public boolean isScope() {
return true;
}
public PvmScope getEventScope() {
return null;
}
public ScopeImpl getFlowScope() {
return null;
}
public PvmScope getLevelOfSubprocessScope() {
return null;
}
@Override
public boolean isSubProcessScope() {
return true;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\process\ProcessDefinitionImpl.java | 1 |
请完成以下Spring Boot application配置 | spring:
datasource:
dynamic:
datasource:
master:
username: root
password: root
url: jdbc:mysql://127.0.0.1:3306/spring-boot-demo?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
driver-class-name: com.mysql.cj.jdbc.Driver
slave:
username: root
password: root
url: jdbc:mysql://127.0.0.1:3306/spring-boot-demo-2?useUnicode=true&characterEncoding=UTF-8 | &useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
driver-class-name: com.mysql.cj.jdbc.Driver
mp-enabled: true
logging:
level:
com.xkcoding.multi.datasource.mybatis: debug | repos\spring-boot-demo-master\demo-multi-datasource-mybatis\src\main\resources\application.yml | 2 |
请在Spring Boot框架中完成以下Java代码 | private Saml2X509Credential asSigningCredential(Signing.Credential properties) {
RSAPrivateKey privateKey = readPrivateKey(properties.getPrivateKeyLocation());
X509Certificate certificate = readCertificate(properties.getCertificateLocation());
return new Saml2X509Credential(privateKey, certificate, Saml2X509CredentialType.SIGNING);
}
private Saml2X509Credential asDecryptionCredential(Decryption.Credential properties) {
RSAPrivateKey privateKey = readPrivateKey(properties.getPrivateKeyLocation());
X509Certificate certificate = readCertificate(properties.getCertificateLocation());
return new Saml2X509Credential(privateKey, certificate, Saml2X509CredentialType.DECRYPTION);
}
private Saml2X509Credential asVerificationCredential(Verification.Credential properties) {
X509Certificate certificate = readCertificate(properties.getCertificateLocation());
return new Saml2X509Credential(certificate, Saml2X509Credential.Saml2X509CredentialType.ENCRYPTION,
Saml2X509Credential.Saml2X509CredentialType.VERIFICATION);
}
private RSAPrivateKey readPrivateKey(@Nullable Resource location) {
Assert.state(location != null, "No private key location specified");
Assert.state(location.exists(), () -> "Private key location '" + location + "' does not exist");
try (InputStream inputStream = location.getInputStream()) {
PemContent pemContent = PemContent.load(inputStream);
PrivateKey privateKey = pemContent.getPrivateKey();
Assert.state(privateKey instanceof RSAPrivateKey,
() -> "PrivateKey in resource '" + location + "' must be an RSAPrivateKey");
return (RSAPrivateKey) privateKey; | }
catch (Exception ex) {
throw new IllegalArgumentException(ex);
}
}
private X509Certificate readCertificate(@Nullable Resource location) {
Assert.state(location != null, "No certificate location specified");
Assert.state(location.exists(), () -> "Certificate location '" + location + "' does not exist");
try (InputStream inputStream = location.getInputStream()) {
PemContent pemContent = PemContent.load(inputStream);
List<X509Certificate> certificates = pemContent.getCertificates();
return certificates.get(0);
}
catch (Exception ex) {
throw new IllegalArgumentException(ex);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-security-saml2\src\main\java\org\springframework\boot\security\saml2\autoconfigure\Saml2RelyingPartyRegistrationConfiguration.java | 2 |
请完成以下Java代码 | public void customizeSingle(ClassName className, Consumer<Builder> customizer) {
Builder builder = this.singleAnnotations.get(className);
if (builder != null) {
customizer.accept(builder);
}
}
/**
* Add a repeatable annotation.
* @param className the class name of an annotation
* @throws IllegalStateException if the annotation has already been added as a single
* annotation
*/
public void addRepeatable(ClassName className) {
addRepeatable(className, null);
}
/**
* Add a repeatable annotation.
* @param className the class name of an annotation
* @param annotation a {@link Consumer} to customize the annotation
* @throws IllegalStateException if the annotation has already been added as a single
* annotation
*/
public void addRepeatable(ClassName className, Consumer<Builder> annotation) {
if (hasSingle(className)) {
throw new IllegalStateException("%s has already been added as a single annotation".formatted(className));
}
Builder builder = new Builder(className);
if (annotation != null) {
annotation.accept(builder);
}
this.repeatableAnnotations.add(className, builder);
}
/**
* Remove the annotation with the specified classname from either the single
* annotation or the repeatable annotations. | * @param className the class name of the annotation
* @return {@code true} if such an annotation exists, {@code false} otherwise
*/
public boolean remove(ClassName className) {
return this.singleAnnotations.remove(className) != null || this.repeatableAnnotations.remove(className) != null;
}
/**
* Remove a single with the specified classname.
* @param className the class name of an annotation
* @return whether the annotation has been removed
*/
public boolean removeSingle(ClassName className) {
return this.singleAnnotations.remove(className) != null;
}
/**
* Remove all repeatable annotations with the specified classname.
* @param className the class name of an annotation
* @return whether any annotation has been removed
*/
public boolean removeAllRepeatable(ClassName className) {
return this.repeatableAnnotations.remove(className) != null;
}
public AnnotationContainer deepCopy() {
Map<ClassName, Builder> singleAnnotations = new LinkedHashMap<>();
this.singleAnnotations.forEach((className, builder) -> singleAnnotations.put(className, new Builder(builder)));
MultiValueMap<ClassName, Builder> repeatableAnnotations = new LinkedMultiValueMap<>();
this.repeatableAnnotations.forEach((className, builders) -> builders
.forEach((builder) -> repeatableAnnotations.add(className, new Builder(builder))));
return new AnnotationContainer(singleAnnotations, repeatableAnnotations);
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\AnnotationContainer.java | 1 |
请完成以下Java代码 | public IdentityLinkEntity create() {
return new IdentityLinkEntityImpl();
}
@Override
@SuppressWarnings("unchecked")
public List<IdentityLinkEntity> findIdentityLinksByTaskId(String taskId) {
return getDbSqlSession().selectList("selectIdentityLinksByTask", taskId);
}
@Override
@SuppressWarnings("unchecked")
public List<IdentityLinkEntity> findIdentityLinksByProcessInstanceId(String processInstanceId) {
return getList(
"selectIdentityLinksByProcessInstance",
processInstanceId,
identityLinkByProcessInstanceMatcher,
true
);
}
@Override
@SuppressWarnings("unchecked")
public List<IdentityLinkEntity> findIdentityLinksByProcessDefinitionId(String processDefinitionId) {
return getDbSqlSession().selectList("selectIdentityLinksByProcessDefinition", processDefinitionId);
}
@Override
@SuppressWarnings("unchecked")
public List<IdentityLinkEntity> findIdentityLinkByTaskUserGroupAndType(
String taskId,
String userId,
String groupId,
String type
) {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("taskId", taskId);
parameters.put("userId", userId);
parameters.put("groupId", groupId);
parameters.put("type", type);
return getDbSqlSession().selectList("selectIdentityLinkByTaskUserGroupAndType", parameters);
}
@Override
@SuppressWarnings("unchecked")
public List<IdentityLinkEntity> findIdentityLinkByProcessInstanceUserGroupAndType(
String processInstanceId,
String userId,
String groupId,
String type
) { | Map<String, String> parameters = new HashMap<String, String>();
parameters.put("processInstanceId", processInstanceId);
parameters.put("userId", userId);
parameters.put("groupId", groupId);
parameters.put("type", type);
return getDbSqlSession().selectList("selectIdentityLinkByProcessInstanceUserGroupAndType", parameters);
}
@Override
@SuppressWarnings("unchecked")
public List<IdentityLinkEntity> findIdentityLinkByProcessDefinitionUserAndGroup(
String processDefinitionId,
String userId,
String groupId
) {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("processDefinitionId", processDefinitionId);
parameters.put("userId", userId);
parameters.put("groupId", groupId);
return getDbSqlSession().selectList("selectIdentityLinkByProcessDefinitionUserAndGroup", parameters);
}
@Override
public void deleteIdentityLinksByProcDef(String processDefId) {
getDbSqlSession().delete("deleteIdentityLinkByProcDef", processDefId, IdentityLinkEntityImpl.class);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisIdentityLinkDataManager.java | 1 |
请完成以下Java代码 | int getPlayerNo() {
return playerNo;
}
void setPlayerNo(int playerNo) {
this.playerNo = playerNo;
}
int getOpponent() {
return 3 - playerNo;
}
public int getVisitCount() {
return visitCount;
}
public void setVisitCount(int visitCount) {
this.visitCount = visitCount;
}
double getWinScore() {
return winScore;
}
void setWinScore(double winScore) {
this.winScore = winScore;
}
public List<State> getAllPossibleStates() {
List<State> possibleStates = new ArrayList<>();
List<Position> availablePositions = this.board.getEmptyPositions();
availablePositions.forEach(p -> {
State newState = new State(this.board); | newState.setPlayerNo(3 - this.playerNo);
newState.getBoard().performMove(newState.getPlayerNo(), p);
possibleStates.add(newState);
});
return possibleStates;
}
void incrementVisit() {
this.visitCount++;
}
void addScore(double score) {
if (this.winScore != Integer.MIN_VALUE)
this.winScore += score;
}
void randomPlay() {
List<Position> availablePositions = this.board.getEmptyPositions();
int totalPossibilities = availablePositions.size();
int selectRandom = (int) (Math.random() * totalPossibilities);
this.board.performMove(this.playerNo, availablePositions.get(selectRandom));
}
void togglePlayer() {
this.playerNo = 3 - this.playerNo;
}
} | repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\mcts\montecarlo\State.java | 1 |
请完成以下Java代码 | public Amount subtract(@NonNull final Amount amtToSubtract)
{
assertSameCurrency(this, amtToSubtract);
if (amtToSubtract.isZero())
{
return this;
}
else
{
return new Amount(value.subtract(amtToSubtract.value), currencyCode);
}
}
public Amount multiply(@NonNull final Percent percent, @NonNull final CurrencyPrecision precision)
{
final BigDecimal newValue = percent.computePercentageOf(value, precision.toInt(), precision.getRoundingMode()); | return !newValue.equals(value)
? new Amount(newValue, currencyCode)
: this;
}
public Amount abs()
{
return value.signum() < 0
? new Amount(value.abs(), currencyCode)
: this;
}
public Money toMoney(@NonNull final Function<CurrencyCode, CurrencyId> currencyIdMapper)
{
return Money.of(value, currencyIdMapper.apply(currencyCode));
}
public static boolean equals(@Nullable final Amount a1, @Nullable final Amount a2) {return Objects.equals(a1, a2);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\Amount.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void configure(AbstractEngineConfiguration engineConfiguration) {
if (eventEngineConfiguration == null) {
eventEngineConfiguration = new StandaloneEventRegistryEngineConfiguration();
}
initialiseEventRegistryEngineConfiguration(eventEngineConfiguration);
initialiseCommonProperties(engineConfiguration, eventEngineConfiguration);
initEngine();
initServiceConfigurations(engineConfiguration, eventEngineConfiguration);
}
protected void initialiseEventRegistryEngineConfiguration(EventRegistryEngineConfiguration eventRegistryEngineConfiguration) {
// meant to be overridden
}
@Override
protected List<Class<? extends Entity>> getEntityInsertionOrder() {
return EntityDependencyOrder.INSERT_ORDER;
}
@Override
protected List<Class<? extends Entity>> getEntityDeletionOrder() {
return EntityDependencyOrder.DELETE_ORDER;
} | @Override
protected EventRegistryEngine buildEngine() {
if (eventEngineConfiguration == null) {
throw new FlowableException("EventRegistryEngineConfiguration is required");
}
return eventEngineConfiguration.buildEventRegistryEngine();
}
public EventRegistryEngineConfiguration getEventEngineConfiguration() {
return eventEngineConfiguration;
}
public EventRegistryEngineConfigurator setEventEngineConfiguration(EventRegistryEngineConfiguration eventEngineConfiguration) {
this.eventEngineConfiguration = eventEngineConfiguration;
return this;
}
public EventRegistryEngine getEventRegistryEngine() {
return buildEngine;
}
public void setEventRegistryEngine(EventRegistryEngine eventRegistryEngine) {
this.buildEngine = eventRegistryEngine;
}
} | repos\flowable-engine-main\modules\flowable-event-registry-configurator\src\main\java\org\flowable\eventregistry\impl\configurator\EventRegistryEngineConfigurator.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public EventSubscriptionBuilder scopeId(String scopeId) {
this.scopeId = scopeId;
return this;
}
@Override
public EventSubscriptionBuilder scopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
return this;
}
@Override
public EventSubscriptionBuilder scopeDefinitionKey(String scopeDefinitionKey) {
this.scopeDefinitionKey = scopeDefinitionKey;
return this;
}
@Override
public EventSubscriptionBuilder scopeType(String scopeType) {
this.scopeType = scopeType;
return this;
}
@Override
public EventSubscriptionBuilder tenantId(String tenantId) {
this.tenantId = tenantId;
return this;
}
@Override
public EventSubscriptionBuilder configuration(String configuration) {
this.configuration = configuration;
return this;
}
@Override
public EventSubscription create() {
return eventSubscriptionService.createEventSubscription(this);
}
@Override
public String getEventType() {
return eventType;
}
@Override
public String getEventName() {
return eventName;
}
@Override
public Signal getSignal() {
return signal;
}
@Override
public String getExecutionId() {
return executionId;
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
@Override
public String getProcessDefinitionId() {
return processDefinitionId;
}
@Override
public String getActivityId() {
return activityId;
} | @Override
public String getSubScopeId() {
return subScopeId;
}
@Override
public String getScopeId() {
return scopeId;
}
@Override
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
@Override
public String getScopeDefinitionKey() {
return scopeDefinitionKey;
}
@Override
public String getScopeType() {
return scopeType;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public String getConfiguration() {
return configuration;
}
} | repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\EventSubscriptionBuilderImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class JWTRelayGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {
private static final String BEARER = "Bearer ";
private ReactiveJwtDecoder jwtDecoder;
public JWTRelayGatewayFilterFactory(ReactiveJwtDecoder jwtDecoder) {
this.jwtDecoder = jwtDecoder;
}
@Override
public GatewayFilter apply(Object config) {
return (exchange, chain) -> {
String bearerToken = exchange.getRequest().getHeaders().getFirst(AUTHORIZATION);
if (bearerToken == null) {
// Allow anonymous requests.
return chain.filter(exchange); | }
String token = this.extractToken(bearerToken);
return jwtDecoder.decode(token).thenReturn(withBearerAuth(exchange, token)).flatMap(chain::filter);
};
}
private String extractToken(String bearerToken) {
if (StringUtils.hasText(bearerToken) && bearerToken.length() > 7 && bearerToken.startsWith(BEARER)) {
return bearerToken.substring(7);
}
throw new IllegalArgumentException("Invalid token in Authorization header");
}
private ServerWebExchange withBearerAuth(ServerWebExchange exchange, String authorizeToken) {
return exchange.mutate().request(r -> r.headers(headers -> headers.setBearerAuth(authorizeToken))).build();
}
} | repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\security\jwt\JWTRelayGatewayFilterFactory.java | 2 |
请完成以下Java代码 | public final class mysqlJavaTypeUtil {
public static final HashMap<String, String> mysqlJavaTypeMap = new HashMap<String, String>();
public static final HashMap<String, String> mysqlSwaggerTypeMap =new HashMap<String, String>();
static{
mysqlJavaTypeMap.put("bigint","Long");
mysqlJavaTypeMap.put("int","Integer");
mysqlJavaTypeMap.put("tinyint","Integer");
mysqlJavaTypeMap.put("smallint","Integer");
mysqlJavaTypeMap.put("mediumint","Integer");
mysqlJavaTypeMap.put("integer","Integer");
//小数
mysqlJavaTypeMap.put("float","Float");
mysqlJavaTypeMap.put("double","Double");
mysqlJavaTypeMap.put("decimal","Double");
//bool
mysqlJavaTypeMap.put("bit","Boolean");
//字符串
mysqlJavaTypeMap.put("char","String");
mysqlJavaTypeMap.put("varchar","String");
mysqlJavaTypeMap.put("varchar2","String"); // Oracle类型
mysqlJavaTypeMap.put("tinytext","String");
mysqlJavaTypeMap.put("text","String");
mysqlJavaTypeMap.put("mediumtext","String");
mysqlJavaTypeMap.put("longtext","String");
//日期
mysqlJavaTypeMap.put("date","Date");
mysqlJavaTypeMap.put("datetime","Date");
mysqlJavaTypeMap.put("timestamp","Date");
// 数字类型 - Oracle增强
mysqlJavaTypeMap.put("number","BigDecimal"); // Oracle的NUMBER类型默认映射为BigDecimal,支持精度
mysqlSwaggerTypeMap.put("bigint","integer");
mysqlSwaggerTypeMap.put("int","integer");
mysqlSwaggerTypeMap.put("tinyint","integer");
mysqlSwaggerTypeMap.put("smallint","integer"); | mysqlSwaggerTypeMap.put("mediumint","integer");
mysqlSwaggerTypeMap.put("integer","integer");
mysqlSwaggerTypeMap.put("boolean","boolean");
mysqlSwaggerTypeMap.put("float","number");
mysqlSwaggerTypeMap.put("double","number");
mysqlSwaggerTypeMap.put("decimal","number");
// Oracle类型
mysqlSwaggerTypeMap.put("varchar2","string");
mysqlSwaggerTypeMap.put("number","number");
}
public static HashMap<String, String> getMysqlJavaTypeMap() {
return mysqlJavaTypeMap;
}
public static HashMap<String, String> getMysqlSwaggerTypeMap() {
return mysqlSwaggerTypeMap;
}
} | repos\SpringBootCodeGenerator-master\src\main\java\com\softdev\system\generator\util\mysqlJavaTypeUtil.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public ReviewStatus getStatus() {
return status;
}
public void setStatus(ReviewStatus status) {
this.status = status;
}
@Override
public boolean equals(Object obj) { | if (obj == null) {
return false;
}
if (this == obj) {
return true;
}
if (!(obj instanceof BookReview)) {
return false;
}
return id != null && id.equals(((BookReview) obj).id);
}
@Override
public int hashCode() {
return 2021;
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootDomainEvents\src\main\java\com\bookstore\entity\BookReview.java | 1 |
请完成以下Java代码 | public void setColor (Color color)
{
int rgba = color.getRGB();
super.setCode(String.valueOf(rgba));
} // setColor
/**
* Get Color as RRGGBB hex string for HTML font tag
* @return rgb hex value
*/
public String getRRGGBB()
{
Color color = getColor();
StringBuffer sb = new StringBuffer();
sb.append(StringUtils.toHex((byte)color.getRed()))
.append(StringUtils.toHex((byte)color.getGreen()))
.append(StringUtils.toHex((byte)color.getBlue()));
return sb.toString();
} // getRRGGBB
/**
* String Representation
* @return info
*/
@Override
public String toString()
{
StringBuffer sb = new StringBuffer("MPrintColor[");
sb.append("ID=").append(get_ID())
.append(",Name=").append(getName())
.append(",RGB=").append(getCode())
.append(",").append(getColor())
.append("]");
return sb.toString();
} // toString
/**************************************************************************
* Create Standard Colors
* @param args args
*/
public static void main(String[] args)
{
org.compiere.Adempiere.startupEnvironment(true);
Color[] colors = new Color[]
{Color.black, Color.red, Color.green, Color.blue,
Color.darkGray, Color.gray, Color.lightGray, Color.white,
Color.cyan, Color.magenta, Color.orange, Color.pink, Color.yellow,
SystemColor.textHighlight};
String[] names = new String[]
{"Black", "Red", "Green", "Blue",
"Gray dark", "Gray", "Gray light", "White", | "Cyan", "Magenta", "Orange", "Pink", "Yellow",
"Blue dark"};
for (int i = 0; i < colors.length; i++)
System.out.println(names[i] + " = " + colors[i] + " RGB=" + colors[i].getRGB()
+ " -> " + new Color(colors[i].getRGB(), false)
+ " -> " + new Color(colors[i].getRGB(), true));
/**
// Create Colors
for (int i = 0; i < colors.length; i++)
create(colors[i], names[i]);
create(whiteGray, "Gray white");
create(darkGreen, "Green dark");
create(blackGreen, "Green black");
create(blackBlue, "Blue black");
create(brown, "Brown");
create(darkBrown, "Brown dark");
**/
// Read All Colors
int[] IDs = PO.getAllIDs ("AD_PrintColor", null, null);
for (int i = 0; i < IDs.length; i++)
{
MPrintColor pc = new MPrintColor(Env.getCtx(), IDs[i], null);
System.out.println(IDs[i] + ": " + pc + " = " + pc.getColor() + ", RGB=" + pc.getColor().getRGB());
}
} // main
} // MPrintColor | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\MPrintColor.java | 1 |
请完成以下Java代码 | public boolean containsAttribute(@NonNull final AttributeSetId attributeSetId, @NonNull final AttributeId attributeId)
{
return getAttributeSetDescriptorById(attributeSetId).contains(attributeId);
}
@Override
@Nullable
public I_M_Attribute retrieveAttribute(final AttributeSetId attributeSetId, final AttributeId attributeId)
{
if (!containsAttribute(attributeSetId, attributeId))
{
return null;
}
return getAttributeRecordById(attributeId);
}
private static final class AttributeListValueMap
{
public static AttributeListValueMap ofList(final List<AttributeListValue> list)
{
if (list.isEmpty())
{
return EMPTY;
}
return new AttributeListValueMap(list);
}
private static final AttributeListValueMap EMPTY = new AttributeListValueMap();
private final ImmutableMap<String, AttributeListValue> map;
private AttributeListValueMap()
{
map = ImmutableMap.of();
}
private AttributeListValueMap(@NonNull final List<AttributeListValue> list)
{ | map = Maps.uniqueIndex(list, AttributeListValue::getValue);
}
public List<AttributeListValue> toList()
{
return ImmutableList.copyOf(map.values());
}
@Nullable
public AttributeListValue getByIdOrNull(@NonNull final AttributeValueId id)
{
return map.values()
.stream()
.filter(av -> AttributeValueId.equals(av.getId(), id))
.findFirst()
.orElse(null);
}
public AttributeListValue getByValueOrNull(final String value)
{
return map.get(value);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\AttributeDAO.java | 1 |
请完成以下Java代码 | public void execute(DelegateExecution execution) {
SubProcess subProcess = getSubProcessFromExecution(execution);
FlowElement startElement = null;
if (CollectionUtil.isNotEmpty(subProcess.getFlowElements())) {
for (FlowElement subElement : subProcess.getFlowElements()) {
if (subElement instanceof StartEvent) {
StartEvent startEvent = (StartEvent) subElement;
// start none event
if (CollectionUtil.isEmpty(startEvent.getEventDefinitions())) {
startElement = startEvent;
break;
}
}
}
}
if (startElement == null) {
throw new ActivitiException("No initial activity found for subprocess " + subProcess.getId());
}
ExecutionEntity executionEntity = (ExecutionEntity) execution;
executionEntity.setScope(true);
// initialize the template-defined data objects as variables
Map<String, Object> dataObjectVars = processDataObjects(subProcess.getDataObjects());
if (dataObjectVars != null) {
executionEntity.setVariablesLocal(dataObjectVars);
}
ExecutionEntity startSubProcessExecution = Context.getCommandContext()
.getExecutionEntityManager()
.createChildExecution(executionEntity);
startSubProcessExecution.setCurrentFlowElement(startElement);
Context.getAgenda().planContinueProcessOperation(startSubProcessExecution);
}
protected SubProcess getSubProcessFromExecution(DelegateExecution execution) { | FlowElement flowElement = execution.getCurrentFlowElement();
SubProcess subProcess = null;
if (flowElement instanceof SubProcess) {
subProcess = (SubProcess) flowElement;
} else {
throw new ActivitiException(
"Programmatic error: sub process behaviour can only be applied" +
" to a SubProcess instance, but got an instance of " +
flowElement
);
}
return subProcess;
}
protected Map<String, Object> processDataObjects(Collection<ValuedDataObject> dataObjects) {
Map<String, Object> variablesMap = new HashMap<String, Object>();
// convert data objects to process variables
if (dataObjects != null) {
for (ValuedDataObject dataObject : dataObjects) {
variablesMap.put(dataObject.getName(), dataObject.getValue());
}
}
return variablesMap;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\SubProcessActivityBehavior.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CommentDTO other = (CommentDTO) obj;
if (comment == null) {
if (other.comment != null)
return false;
} else if (!comment.equals(other.comment))
return false;
if (posted == null) {
if (other.posted != null)
return false;
} else if (!posted.equals(other.posted))
return false;
if (taskId == null) {
if (other.taskId != null)
return false;
} else if (!taskId.equals(other.taskId))
return false;
return true;
}
/*
* (non-Javadoc) | *
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "CommentDTO [taskId=" + taskId + ", comment=" + comment + ", posted=" + posted + "]";
}
}
/**
* Custom date serializer that converts the date to long before sending it out
*
* @author anilallewar
*
*/
class CustomDateToLongSerializer extends JsonSerializer<Date> {
@Override
public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeNumber(value.getTime());
}
} | repos\spring-boot-microservices-master\comments-webservice\src\main\java\com\rohitghatol\microservices\comments\dtos\CommentDTO.java | 2 |
请完成以下Java代码 | public class MyBatisPlusGenerator extends BaseGenerator {
public static final String OUT_DIR = "D:\\github\\spring-boot-quick\\quick-archetype\\src\\main\\java";
// 处理 all 情况
protected static List<String> getTables(String tables) {
return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
}
public static void main(String[] args) throws IOException {
FastAutoGenerator.create(dataSourceGenerate())
// 全局配置
.globalConfig((scanner, builder) -> {
builder.author(scanner.apply("请输入作者")).fileOverride();
builder.outputDir(OUT_DIR);
})
// 包配置
.packageConfig((scanner, builder) -> {
builder
// .pathInfo(Collections.singletonMap(OutputFile.mapperXml, System.getProperty("user.dir") + "/src/main/resources/mapper"))
.parent(scanner.apply("请输入包名?"));
})
// 策略配置
.strategyConfig((scanner, builder) -> {
builder.addInclude(MyBatisPlusGenerator.getTables(scanner.apply("请输入表名,多个英文逗号分隔?所有输入 all")))
.controllerBuilder()
.enableRestStyle()
.enableHyphenStyle()
.build();
builder.serviceBuilder()
.formatServiceFileName("%sService")
.formatServiceImplFileName("%sServiceImp")
.build();
//entity的策略配置
builder.entityBuilder()
.enableLombok() | .enableTableFieldAnnotation()
.versionColumnName("version")
.logicDeleteColumnName("is_delete")
.columnNaming(NamingStrategy.underline_to_camel)
// .idType(IdType.AUTO)
.formatFileName("%sEntity")
.build();
// mapper xml配置
builder.mapperBuilder()
.formatMapperFileName("%sMapper")
.enableBaseColumnList()
.enableBaseResultMap()
.build();
})
.execute();
}
} | repos\spring-boot-quick-master\quick-sample-server\sample-server\src\main\java\com\quick\utils\MyBatisPlusGenerator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EmployeeRepositoryImpl implements EmployeeRepository {
final @NonNull EntityManager entityManager;
/*
* (non-Javadoc)
* @see example.springdata.jpa.compositions.EmployeeRepository#findCoworkers(example.springdata.jpa.compositions.Employee)
*/
@Override
@SuppressWarnings("unchecked")
public List<Employee> findCoworkers(Employee employee) {
return entityManager.createQuery("SELECT u from User u where u.manager = :manager") //
.setParameter("manager", employee.getManager()) //
.getResultList(); | }
/*
* (non-Javadoc)
* @see example.springdata.jpa.compositions.EmployeeRepository#findSubordinates(example.springdata.jpa.compositions.Employee)
*/
@Override
@SuppressWarnings("unchecked")
public List<Employee> findSubordinates(Employee manager) {
return entityManager.createQuery("SELECT u from User u where u.manager = :manager") //
.setParameter("manager", manager) //
.getResultList();
}
} | repos\spring-data-examples-main\jpa\example\src\main\java\example\springdata\jpa\compositions\EmployeeRepositoryImpl.java | 2 |
请完成以下Java代码 | public class RestartProcessInstanceDto {
protected List<String> processInstanceIds;
protected List<ProcessInstanceModificationInstructionDto> instructions;
protected HistoricProcessInstanceQueryDto historicProcessInstanceQuery;
protected boolean initialVariables;
protected boolean skipCustomListeners;
protected boolean skipIoMappings;
protected boolean withoutBusinessKey;
public List<String> getProcessInstanceIds() {
return processInstanceIds;
}
public void setProcessInstanceIds(List<String> processInstanceIds) {
this.processInstanceIds = processInstanceIds;
}
public List<ProcessInstanceModificationInstructionDto> getInstructions() {
return instructions;
}
public void setInstructions(List<ProcessInstanceModificationInstructionDto> instructions) {
this.instructions = instructions;
}
public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() {
return historicProcessInstanceQuery;
}
public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) {
this.historicProcessInstanceQuery = historicProcessInstanceQuery;
}
public boolean isInitialVariables() {
return initialVariables;
}
public void setInitialVariables(boolean initialVariables) {
this.initialVariables = initialVariables;
}
public boolean isSkipCustomListeners() {
return skipCustomListeners;
}
public void setSkipCustomListeners(boolean skipCustomListeners) {
this.skipCustomListeners = skipCustomListeners;
} | public boolean isSkipIoMappings() {
return skipIoMappings;
}
public void setSkipIoMappings(boolean skipIoMappings) {
this.skipIoMappings = skipIoMappings;
}
public boolean isWithoutBusinessKey() {
return withoutBusinessKey;
}
public void setWithoutBusinessKey(boolean withoutBusinessKey) {
this.withoutBusinessKey = withoutBusinessKey;
}
public void applyTo(RestartProcessInstanceBuilder builder, ProcessEngine processEngine, ObjectMapper objectMapper) {
for (ProcessInstanceModificationInstructionDto instruction : instructions) {
instruction.applyTo(builder, processEngine, objectMapper);
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\RestartProcessInstanceDto.java | 1 |
请完成以下Java代码 | public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/**
* NotificationType AD_Reference_ID=344
* Reference name: AD_User NotificationType
*/
public static final int NOTIFICATIONTYPE_AD_Reference_ID=344;
/** EMail = E */
public static final String NOTIFICATIONTYPE_EMail = "E";
/** Notice = N */
public static final String NOTIFICATIONTYPE_Notice = "N";
/** None = X */
public static final String NOTIFICATIONTYPE_None = "X";
/** EMailPlusNotice = B */
public static final String NOTIFICATIONTYPE_EMailPlusNotice = "B";
/** NotifyUserInCharge = O */ | public static final String NOTIFICATIONTYPE_NotifyUserInCharge = "O";
/** Set Benachrichtigungs-Art.
@param NotificationType
Art der Benachrichtigung
*/
@Override
public void setNotificationType (java.lang.String NotificationType)
{
set_Value (COLUMNNAME_NotificationType, NotificationType);
}
/** Get Benachrichtigungs-Art.
@return Art der Benachrichtigung
*/
@Override
public java.lang.String getNotificationType ()
{
return (java.lang.String)get_Value(COLUMNNAME_NotificationType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role_NotificationGroup.java | 1 |
请完成以下Java代码 | private void startWindow(final int AD_Workbench_ID, @Nullable final AdWindowId adWindowId)
{
// metas-ts: task 05796: moved the code to WindowBL.openWindow() to allow it beeing called on other occasions too
Services.get(IWindowBL.class).openWindow(
m_menu.getWindowManager(),
AD_Workbench_ID,
adWindowId);
} // startWindow
/**
* Start Process. Start/show Process Dialog which calls ProcessCtl
*
* @param AD_Process_ID process
* @param IsSOTrx is SO trx
*/
private void startProcess(final int AD_Process_ID, final boolean IsSOTrx)
{
ProcessDialog.builder()
.setAD_Process_ID(AD_Process_ID)
.setIsSOTrx(IsSOTrx)
.show();
}
private void startWorkflow(final WorkflowId workflowId)
{
if (m_menu == null)
{
new AdempiereException("Cannot start workflow because no menu")
.throwOrLogWarning(false, logger);
return;
}
m_menu.startWorkFlow(workflowId);
}
/**
* Start OS Task
* | * @param AD_Task_ID task
*/
private void startTask(final int AD_Task_ID)
{
// Get Command
MTask task = null;
if (AD_Task_ID > 0)
{
task = new MTask(Env.getCtx(), AD_Task_ID, ITrx.TRXNAME_None);
}
if (task.getAD_Task_ID() != AD_Task_ID)
{
task = null;
}
if (task == null)
{
return;
}
m_menu.getWindowManager().add(new ATask(m_name, task));
// ATask.start(m_name, task);
} // startTask
/**
* Start Form
*
* @param AD_Form_ID form
*/
private void startForm(final int AD_Form_ID)
{
m_menu.startForm(AD_Form_ID);
} // startForm
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\AMenuStartItem.java | 1 |
请完成以下Java代码 | public class InvalidKeyExamples {
public static byte[] decryptUsingCBCWithNoIV(SecretKey key, byte[] cipherTextBytes)
throws InvalidKeyException, GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(cipherTextBytes);
}
public static byte[] decryptUsingCBCWithIV(SecretKey key, byte[] cipherTextBytes)
throws InvalidKeyException, GeneralSecurityException {
byte[] ivBytes = new byte[] { 'B', 'a', 'e', 'l', 'd', 'u', 'n', 'g', 'I', 's', 'G', 'r', 'e', 'a', 't', '!' };
IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
return cipher.doFinal(cipherTextBytes);
}
public static byte[] encryptWithKeyTooShort() throws InvalidKeyException, GeneralSecurityException {
SecretKey encryptionKey = CryptoUtils.getKeyForText("ThisIsTooShort");
String plainText = "https://www.baeldung.com/";
byte[] bytes = plainText.getBytes();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); | cipher.init(Cipher.ENCRYPT_MODE, encryptionKey);
return cipher.doFinal(bytes);
}
public static byte[] encryptWithKeyTooLong() throws InvalidKeyException, GeneralSecurityException {
SecretKey encryptionKey = CryptoUtils.getKeyForText("ThisTextIsTooLong");
String plainText = "https://www.baeldung.com/";
byte[] bytes = plainText.getBytes();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, encryptionKey);
return cipher.doFinal(bytes);
}
} | repos\tutorials-master\core-java-modules\core-java-security-3\src\main\java\com\baeldung\crypto\exception\InvalidKeyExamples.java | 1 |
请完成以下Java代码 | public de.metas.invoicecandidate.model.I_M_ProductGroup getM_ProductGroup()
{
return get_ValueAsPO(COLUMNNAME_M_ProductGroup_ID, de.metas.invoicecandidate.model.I_M_ProductGroup.class);
}
@Override
public void setM_ProductGroup(final de.metas.invoicecandidate.model.I_M_ProductGroup M_ProductGroup)
{
set_ValueFromPO(COLUMNNAME_M_ProductGroup_ID, de.metas.invoicecandidate.model.I_M_ProductGroup.class, M_ProductGroup);
}
@Override
public void setM_ProductGroup_ID (final int M_ProductGroup_ID)
{
if (M_ProductGroup_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ProductGroup_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ProductGroup_ID, M_ProductGroup_ID);
} | @Override
public int getM_ProductGroup_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ProductGroup_ID);
}
@Override
public void setM_ProductGroup_Product_ID (final int M_ProductGroup_Product_ID)
{
if (M_ProductGroup_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ProductGroup_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ProductGroup_Product_ID, M_ProductGroup_Product_ID);
}
@Override
public int getM_ProductGroup_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ProductGroup_Product_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\invoicecandidate\model\X_M_ProductGroup_Product.java | 1 |
请完成以下Java代码 | protected String doIt() throws Exception
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final ITrxItemProcessorExecutorService trxItemProcessorExecutorService = Services.get(ITrxItemProcessorExecutorService.class);
// gh #1955: prevent an OutOfMemoryError
final IQueryFilter<I_DLM_Partition> processFilter = getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false));
final Iterator<I_DLM_Partition> partitionsToMigrate = queryBL.createQueryBuilder(I_DLM_Partition.class, this)
.addOnlyActiveRecordsFilter()
.addNotEqualsFilter(I_DLM_Partition.COLUMN_Target_DLM_Level, null)
.addNotEqualsFilter(I_DLM_Partition.COLUMN_Target_DLM_Level, IMigratorService.DLM_Level_NOT_SET)
.addNotEqualsFilter(I_DLM_Partition.COLUMN_Target_DLM_Level, ModelColumnNameValue.forColumn(I_DLM_Partition.COLUMN_Current_DLM_Level))
.filter(processFilter)
.orderBy().addColumn(I_DLM_Partition.COLUMNNAME_DLM_Partition_ID).endOrderBy()
.create()
.setOption(IQuery.OPTION_GuaranteedIteratorRequired, true)
.setOption(IQuery.OPTION_IteratorBufferSize, 500)
.iterate(I_DLM_Partition.class);
trxItemProcessorExecutorService.<I_DLM_Partition, Void> createExecutor()
.setContext(getCtx(), getTrxName())
.setProcessor(new TrxItemProcessorAdapter<I_DLM_Partition, Void>()
{
@Override
public void process(final I_DLM_Partition partitionDB) throws Exception
{
process0(partitionDB);
}
}) | .setExceptionHandler(LoggableTrxItemExceptionHandler.instance)
.process(partitionsToMigrate);
return MSG_OK;
}
private void process0(final I_DLM_Partition partitionDB)
{
final Partition partition = dlmService.loadPartition(partitionDB);
if (testMigrate)
{
migratorService.testMigratePartition(partition);
return;
}
final Partition migratedPartition = migratorService.migratePartition(partition);
addLog("Migrated partition={} with result={}", partition, migratedPartition);
dlmService.storePartition(migratedPartition, false);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\migrator\process\DLM_Partition_Migrate.java | 1 |
请完成以下Java代码 | private String createNewToken() {
return UUID.randomUUID().toString();
}
private Cookie mapToCookie(ResponseCookie responseCookie) {
Cookie cookie = new Cookie(responseCookie.getName(), responseCookie.getValue());
cookie.setSecure(responseCookie.isSecure());
cookie.setPath(responseCookie.getPath());
cookie.setMaxAge((int) responseCookie.getMaxAge().getSeconds());
cookie.setHttpOnly(responseCookie.isHttpOnly());
if (StringUtils.hasLength(responseCookie.getDomain())) {
cookie.setDomain(responseCookie.getDomain());
}
if (StringUtils.hasText(responseCookie.getSameSite())) {
cookie.setAttribute("SameSite", responseCookie.getSameSite());
}
return cookie;
}
/**
* Set the path that the Cookie will be created with. This will override the default | * functionality which uses the request context as the path.
* @param path the path to use
*/
public void setCookiePath(String path) {
this.cookiePath = path;
}
/**
* Get the path that the CSRF cookie will be set to.
* @return the path to be used.
*/
public @Nullable String getCookiePath() {
return this.cookiePath;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\csrf\CookieCsrfTokenRepository.java | 1 |
请完成以下Java代码 | public static void main(String[] args) {
int[] numbers = new int[] { 1, 2, 3, 4, 5 };
getArrayElementAtIndex(numbers, 5);
getListElementAtIndex(5);
addArrayElementsUsingLoop(numbers);
}
public static void addArrayElementsUsingLoop(int[] numbers) {
int sum = 0;
for (int i = 0; i <= numbers.length; i++) {
sum += numbers[i];
}
}
public static int addArrayElementsUsingLoopInsideTryCatchBlock(int[] numbers) {
int sum = 0;
try {
for (int i = 0; i <= numbers.length; i++) {
sum += numbers[i];
} | } catch (ArrayIndexOutOfBoundsException e) {
LOG.info("Attempted to access an index outside array bounds: {}", e.getMessage());
return -1;
}
return sum;
}
public static int getListElementAtIndex(int index) {
List<Integer> numbersList = Arrays.asList(1, 2, 3, 4, 5);
return numbersList.get(index);
}
public static int getArrayElementAtIndex(int[] numbers, int index) {
return numbers[index];
}
} | repos\tutorials-master\core-java-modules\core-java-exceptions-4\src\main\java\com\baeldung\exception\arrayindexoutofbounds\ArrayIndexOutOfBoundsExceptionDemo.java | 1 |
请完成以下Java代码 | public void run(final String localTrxName)
{
createTerm(partner, flatrateTermsCollector);
Loggables.addLog("@Processed@ @C_BPartner_ID@:" + partner.getValue() + "_" + partner.getName());
logger.debug("Created contract(s) for {}", partner);
}
// note for future developer: this swallows the user exception so it's no longer shown in webui, but as a "bell notification".
// Please consult with mark or torby if we want to swallow or throw.
// Please remember that this can be run for 10000 Partners when proposing this idea.
@Override
public boolean doCatch(final Throwable ex)
{
Loggables.addLog("@Error@ @C_BPartner_ID@:" + partner.getValue() + "_" + partner.getName() + ": " + ex.getLocalizedMessage());
logger.debug("Failed creating contract for {}", partner, ex);
return true; // rollback
}
});
}
}
return flatrateTermsCollector.build();
}
private void createTerm(@NonNull final I_C_BPartner partner, @NonNull final ImmutableList.Builder<I_C_Flatrate_Term> flatrateTermCollector)
{
final IFlatrateBL flatrateBL = Services.get(IFlatrateBL.class);
final IContextAware context = PlainContextAware.newWithThreadInheritedTrx(ctx);
for (final I_M_Product product : products)
{
final CreateFlatrateTermRequest createFlatrateTermRequest = CreateFlatrateTermRequest.builder()
.orgId(OrgId.ofRepoId(conditions.getAD_Org_ID())) | .context(context)
.bPartner(partner)
.conditions(conditions)
.startDate(startDate)
.endDate(endDate)
.userInCharge(userInCharge)
.productAndCategoryId(createProductAndCategoryId(product))
.isSimulation(isSimulation)
.completeIt(isCompleteDocument)
.build();
flatrateTermCollector.add(flatrateBL.createTerm(createFlatrateTermRequest));
}
}
@Nullable
public ProductAndCategoryId createProductAndCategoryId(@Nullable final I_M_Product productRecord)
{
if (productRecord == null)
{
return null;
}
return ProductAndCategoryId.of(productRecord.getM_Product_ID(), productRecord.getM_Product_Category_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\process\FlatrateTermCreator.java | 1 |
请完成以下Java代码 | public static String read(final Path path) throws MojoExecutionException {
try {
return new String(Files.readAllBytes(path));
} catch (IOException e) {
throw new MojoExecutionException("Unable to read file " + path, e);
}
}
/**
* Write to a file.
*
* @param path the file path
* @param contents the contents to write
* @throws org.apache.maven.plugin.MojoExecutionException if any.
*/
public static void write(final Path path, final String contents) throws MojoExecutionException {
try {
Files.write(path, contents.getBytes());
} catch (IOException e) {
throw new MojoExecutionException("Unable to write file " + path, e);
} | }
/**
* Load a file into properties.
*
* @param path the path
* @param properties the properties to mutate
* @throws org.apache.maven.plugin.MojoExecutionException if any.
*/
public static void load(final Path path, final Properties properties)
throws MojoExecutionException {
try {
properties.load(Files.newInputStream(path));
} catch (IOException e) {
throw new MojoExecutionException("Unable to load file " + path, e);
}
}
} | repos\jasypt-spring-boot-master\jasypt-maven-plugin\src\main\java\com\ulisesbocchio\jasyptmavenplugin\mojo\FileService.java | 1 |
请完成以下Java代码 | public java.lang.String getSKU ()
{
return (java.lang.String)get_Value(COLUMNNAME_SKU);
}
/** Set UPC/EAN.
@param UPC
Bar Code (Universal Product Code or its superset European Article Number)
*/
@Override
public void setUPC (java.lang.String UPC)
{
set_Value (COLUMNNAME_UPC, UPC);
}
/** Get UPC/EAN.
@return Bar Code (Universal Product Code or its superset European Article Number)
*/
@Override
public java.lang.String getUPC ()
{
return (java.lang.String)get_Value(COLUMNNAME_UPC);
}
@Override
public org.compiere.model.I_C_ElementValue getUser1() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser1(org.compiere.model.I_C_ElementValue User1)
{
set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1);
}
/** Set Nutzer 1.
@param User1_ID
User defined list element #1
*/
@Override
public void setUser1_ID (int User1_ID)
{
if (User1_ID < 1)
set_Value (COLUMNNAME_User1_ID, null);
else
set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID));
}
/** Get Nutzer 1.
@return User defined list element #1
*/
@Override
public int getUser1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID);
if (ii == null) | return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ElementValue getUser2() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser2(org.compiere.model.I_C_ElementValue User2)
{
set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2);
}
/** Set Nutzer 2.
@param User2_ID
User defined list element #2
*/
@Override
public void setUser2_ID (int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID));
}
/** Get Nutzer 2.
@return User defined list element #2
*/
@Override
public int getUser2_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User2_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_I_GLJournal.java | 1 |
请完成以下Java代码 | public IdGenerator getIdGenerator() {
return idGenerator;
}
public void setIdGenerator(IdGenerator idGenerator) {
this.idGenerator = idGenerator;
}
public ParsedDeploymentBuilderFactory getExParsedDeploymentBuilderFactory() {
return parsedDeploymentBuilderFactory;
}
public void setParsedDeploymentBuilderFactory(ParsedDeploymentBuilderFactory parsedDeploymentBuilderFactory) {
this.parsedDeploymentBuilderFactory = parsedDeploymentBuilderFactory;
}
public BpmnDeploymentHelper getBpmnDeploymentHelper() {
return bpmnDeploymentHelper;
}
public void setBpmnDeploymentHelper(BpmnDeploymentHelper bpmnDeploymentHelper) {
this.bpmnDeploymentHelper = bpmnDeploymentHelper;
}
public CachingAndArtifactsManager getCachingAndArtifcatsManager() { | return cachingAndArtifactsManager;
}
public void setCachingAndArtifactsManager(CachingAndArtifactsManager manager) {
this.cachingAndArtifactsManager = manager;
}
public void setDisableExistingStartEventSubscriptions(boolean disableExistingStartEventSubscriptions) {
this.disableExistingStartEventSubscriptions = disableExistingStartEventSubscriptions;
}
public boolean shouldDisableExistingStartEventSubscriptions() {
return disableExistingStartEventSubscriptions;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\deployer\BpmnDeployer.java | 1 |
请完成以下Java代码 | public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Set Print Text.
@param PrintName
The label text to be printed on a document or correspondence.
*/
public void setPrintName (String PrintName)
{
set_Value (COLUMNNAME_PrintName, PrintName);
}
/** Get Print Text.
@return The label text to be printed on a document or correspondence.
*/
public String getPrintName ()
{
return (String)get_Value(COLUMNNAME_PrintName);
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getSeqNo()));
}
/** Set X Position.
@param XPosition
Absolute X (horizontal) position in 1/72 of an inch
*/
public void setXPosition (int XPosition)
{
set_Value (COLUMNNAME_XPosition, Integer.valueOf(XPosition));
}
/** Get X Position.
@return Absolute X (horizontal) position in 1/72 of an inch
*/ | public int getXPosition ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_XPosition);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Y Position.
@param YPosition
Absolute Y (vertical) position in 1/72 of an inch
*/
public void setYPosition (int YPosition)
{
set_Value (COLUMNNAME_YPosition, Integer.valueOf(YPosition));
}
/** Get Y Position.
@return Absolute Y (vertical) position in 1/72 of an inch
*/
public int getYPosition ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_YPosition);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintLabelLine.java | 1 |
请完成以下Java代码 | public void handleEvent(@NonNull final AbstractPurchaseOfferEvent event)
{
final UpdateMainDataRequest dataUpdateRequest = createDataUpdateRequestForEvent(event, false);
dataUpdateRequestHandler.handleDataUpdateRequest(dataUpdateRequest);
final UpdateMainDataRequest dataUpdateRequestForNextDayQty = createDataUpdateRequestForEvent(event, true);
dataUpdateRequestHandler.handleDataUpdateRequest(dataUpdateRequestForNextDayQty);
}
private UpdateMainDataRequest createDataUpdateRequestForEvent(
@NonNull final AbstractPurchaseOfferEvent purchaseOfferedEvent,
final boolean forNextDayQty)
{
final OrgId orgId = purchaseOfferedEvent.getOrgId();
final ZoneId timeZone = orgDAO.getTimeZone(orgId);
final Instant date = TimeUtil.getDay(purchaseOfferedEvent.getDate(), timeZone);
final Instant dateToUse = forNextDayQty ? date.minus(1, ChronoUnit.DAYS) : date;
final MainDataRecordIdentifier identifier = MainDataRecordIdentifier.builder() | .productDescriptor(purchaseOfferedEvent.getProductDescriptor())
.date(dateToUse)
.build();
final UpdateMainDataRequest.UpdateMainDataRequestBuilder request = UpdateMainDataRequest.builder()
.identifier(identifier);
if (forNextDayQty)
{
request.offeredQtyNextDay(purchaseOfferedEvent.getQtyDelta());
}
else
{
request.offeredQty(purchaseOfferedEvent.getQtyDelta());
}
return request.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\view\eventhandler\AbstractPurchaseOfferEventHandler.java | 1 |
请完成以下Java代码 | public class Person {
private String name;
private Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
// comment this constructor to see the error.
public Person() {
}
public String getName() {
return name;
} | public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
} | repos\tutorials-master\core-java-modules\core-java-lang-oop-constructors-2\src\main\java\com\baeldung\implicitsuperconstructorundefined\Person.java | 1 |
请完成以下Java代码 | public static class MyState {
final Stream<Integer> getIntegers() {
return IntStream.range(1, 1000000)
.boxed();
}
final Predicate<Integer> PREDICATE = i -> i == 751879;
}
@Benchmark
public void evaluateFindUniqueElementMatchingPredicate_WithReduction(Blackhole blackhole, MyState state) {
blackhole.consume(FilterUtils.findUniqueElementMatchingPredicate_WithReduction(state.getIntegers(), state.PREDICATE));
}
@Benchmark
public void evaluateFindUniqueElementMatchingPredicate_WithCollectingAndThen(Blackhole blackhole, MyState state) {
blackhole.consume(FilterUtils.findUniqueElementMatchingPredicate_WithCollectingAndThen(state.getIntegers(), state.PREDICATE));
}
@Benchmark
public void evaluateGetUniqueElementMatchingPredicate_WithReduction(Blackhole blackhole, MyState state) { | try {
FilterUtils.getUniqueElementMatchingPredicate_WithReduction(state.getIntegers(), state.PREDICATE);
} catch (IllegalStateException exception) {
blackhole.consume(exception);
}
}
@Benchmark
public void evaluateGetUniqueElementMatchingPredicate_WithCollectingAndThen(Blackhole blackhole, MyState state) {
try {
FilterUtils.getUniqueElementMatchingPredicate_WithCollectingAndThen(state.getIntegers(), state.PREDICATE);
} catch (IllegalStateException exception) {
blackhole.consume(exception);
}
}
} | repos\tutorials-master\core-java-modules\core-java-streams-4\src\main\java\com\baeldung\streams\filteronlyoneelement\BenchmarkRunner.java | 1 |
请完成以下Java代码 | public Object getValue(ELContext context, Object base, Object property) {
if (resolve(context, base, property)) {
if (!isProperty((String) property)) {
throw new PropertyNotFoundException("Cannot find property " + property);
}
return getProperty((String) property);
}
return null;
}
@Override
public boolean isReadOnly(ELContext context, Object base, Object property) {
return resolve(context, base, property) ? readOnly : false;
}
@Override
public void setValue(ELContext context, Object base, Object property, Object value)
throws PropertyNotWritableException {
if (resolve(context, base, property)) {
if (readOnly) {
throw new PropertyNotWritableException("Resolver is read only!");
}
setProperty((String) property, value);
}
}
@Override
public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) {
if (resolve(context, base, method)) {
throw new NullPointerException("Cannot invoke method " + method + " on null");
}
return null;
}
/**
* Get property value
*
* @param property | * property name
* @return value associated with the given property
*/
public Object getProperty(String property) {
return map.get(property);
}
/**
* Set property value
*
* @param property
* property name
* @param value
* property value
*/
public void setProperty(String property, Object value) {
map.put(property, value);
}
/**
* Test property
*
* @param property
* property name
* @return <code>true</code> if the given property is associated with a value
*/
public boolean isProperty(String property) {
return map.containsKey(property);
}
/**
* Get properties
*
* @return all property names (in no particular order)
*/
public Iterable<String> properties() {
return map.keySet();
}
} | repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\util\RootPropertyResolver.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.