instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public void sendData() {
Flux.interval(Duration.ofMillis(50))
.take(data.size())
.map(this::createFloatPayload)
.flatMap(socket::fireAndForget)
.blockLast();
}
/**
* Create a binary payload containing a single float value
*
* @param index Index into the data list
* @return Payload ready to send to the server
*/
private Payload createFloatPayload(Long index) {
float velocity = data.get(index.intValue());
ByteBuffer buffer = ByteBuffer.allocate(4).putFloat(velocity);
buffer.rewind();
return DefaultPayload.create(buffer);
}
/**
* Generate sample data
*
* @return List of random floats
*/
private List<Float> generateData() {
List<Float> dataList = new ArrayList<>(DATA_LENGTH); | float velocity = 0;
for (int i = 0; i < DATA_LENGTH; i++) {
velocity += Math.random();
dataList.add(velocity);
}
return dataList;
}
/**
* Get the data used for this client.
*
* @return list of data values
*/
public List<Float> getData() {
return data;
}
public void dispose() {
this.socket.dispose();
}
} | repos\tutorials-master\spring-reactive-modules\rsocket\src\main\java\com\baeldung\rsocket\FireNForgetClient.java | 1 |
请完成以下Spring Boot application配置 | # Fauna Blog Service
fauna.region=EU
fauna.secret=
# Fauna Health App
fauna-connections.EU=https://db.eu.fauna.com/
fauna-secrets.EU=eu-secret
fauna- | connections.US=https://db.us.fauna.com/
fauna-secrets.US=us-secret | repos\tutorials-master\persistence-modules\fauna\src\main\resources\application.properties | 2 |
请完成以下Spring Boot application配置 | server:
port: 8088
xss:
enabled: true
# Exclude links (separate multiple links with commas)
excludes: /ui/*
# match links (separ | ate multiple links with commas)
urlPatterns: /api/*,/admin/* | repos\springboot-demo-master\xss\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String path = exchange.getRequest().getURI().getPath();
if (isSkip(path)) {
return chain.filter(exchange);
}
ServerHttpResponse resp = exchange.getResponse();
String headerToken = exchange.getRequest().getHeaders().getFirst(AuthProvider.AUTH_KEY);
String paramToken = exchange.getRequest().getQueryParams().getFirst(AuthProvider.AUTH_KEY);
if (StringUtils.isBlank(headerToken) && StringUtils.isBlank(paramToken)) {
return unAuth(resp, "缺失令牌,鉴权失败");
}
String auth = StringUtils.isBlank(headerToken) ? paramToken : headerToken;
String token = JwtUtil.getToken(auth);
//校验 加密Token 合法性
if (JwtUtil.isCrypto(auth)) {
token = JwtCrypto.decryptToString(token, bladeProperties.getEnvironment().getProperty(BLADE_CRYPTO_AES_KEY));
}
Claims claims = JwtUtil.parseJWT(token);
if (claims == null) {
return unAuth(resp, "请求未授权");
}
return chain.filter(exchange);
}
private boolean isSkip(String path) {
return AuthProvider.getDefaultSkipUrl().stream().anyMatch(pattern -> antPathMatcher.match(pattern, path))
|| authProperties.getSkipUrl().stream().anyMatch(pattern -> antPathMatcher.match(pattern, path)); | }
private Mono<Void> unAuth(ServerHttpResponse resp, String msg) {
resp.setStatusCode(HttpStatus.UNAUTHORIZED);
resp.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
String result = "";
try {
result = objectMapper.writeValueAsString(ResponseProvider.unAuth(msg));
} catch (JsonProcessingException e) {
log.error(e.getMessage(), e);
}
DataBuffer buffer = resp.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8));
return resp.writeWith(Flux.just(buffer));
}
@Override
public int getOrder() {
return -100;
}
} | repos\SpringBlade-master\blade-gateway\src\main\java\org\springblade\gateway\filter\AuthFilter.java | 1 |
请完成以下Java代码 | private void addTopics(Admin adminClient, List<NewTopic> topicsToAdd) {
CreateTopicsResult topicResults = adminClient.createTopics(topicsToAdd);
try {
topicResults.all().get(this.operationTimeout, TimeUnit.SECONDS);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOGGER.error(e, "Interrupted while waiting for topic creation results");
}
catch (TimeoutException e) {
throw new KafkaException("Timed out waiting for create topics results", e);
}
catch (ExecutionException e) {
if (e.getCause() instanceof TopicExistsException) { // Possible race with another app instance
LOGGER.debug(e.getCause(), "Failed to create topics");
}
else {
LOGGER.error(e.getCause() != null ? e.getCause() : e, "Failed to create topics");
throw new KafkaException("Failed to create topics", e.getCause()); // NOSONAR
}
}
}
private void createMissingPartitions(Admin adminClient, Map<String, NewPartitions> topicsToModify) {
CreatePartitionsResult partitionsResult = adminClient.createPartitions(topicsToModify);
try {
partitionsResult.all().get(this.operationTimeout, TimeUnit.SECONDS);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOGGER.error(e, "Interrupted while waiting for partition creation results");
}
catch (TimeoutException e) {
throw new KafkaException("Timed out waiting for create partitions results", e);
}
catch (ExecutionException e) {
if (e.getCause() instanceof InvalidPartitionsException) { // Possible race with another app instance
LOGGER.debug(e.getCause(), "Failed to create partitions");
}
else {
LOGGER.error(e.getCause() != null ? e.getCause() : e, "Failed to create partitions");
if (!(e.getCause() instanceof UnsupportedVersionException)) {
throw new KafkaException("Failed to create partitions", e.getCause()); // NOSONAR
}
}
}
}
/**
* Wrapper for a collection of {@link NewTopic} to facilitate declaring multiple
* topics as a single bean. | *
* @since 2.7
*
*/
public static class NewTopics {
private final Collection<NewTopic> newTopics = new ArrayList<>();
/**
* Construct an instance with the {@link NewTopic}s.
* @param newTopics the topics.
*/
public NewTopics(NewTopic... newTopics) {
this.newTopics.addAll(Arrays.asList(newTopics));
}
Collection<NewTopic> getNewTopics() {
return this.newTopics;
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\core\KafkaAdmin.java | 1 |
请完成以下Java代码 | protected void walkToLoad(ByteArray byteArray, _ValueArray<V> valueArray)
{
c = byteArray.nextChar();
status = ARRAY_STATUS[byteArray.nextInt()];
if (status == Status.WORD_END_3 || status == Status.WORD_MIDDLE_2)
{
value = valueArray.nextValue();
}
int childSize = byteArray.nextInt();
child = new BaseNode[childSize];
for (int i = 0; i < childSize; ++i)
{
child[i] = new Node<V>();
child[i].walkToLoad(byteArray, valueArray);
}
}
protected void walkToLoad(ObjectInput byteArray) throws IOException, ClassNotFoundException
{
c = byteArray.readChar();
status = ARRAY_STATUS[byteArray.readInt()];
if (status == Status.WORD_END_3 || status == Status.WORD_MIDDLE_2)
{
value = (V) byteArray.readObject();
}
int childSize = byteArray.readInt();
child = new BaseNode[childSize];
for (int i = 0; i < childSize; ++i)
{
child[i] = new Node<V>();
child[i].walkToLoad(byteArray);
}
}
public enum Status
{
/**
* 未指定,用于删除词条
*/
UNDEFINED_0,
/**
* 不是词语的结尾
*/
NOT_WORD_1,
/**
* 是个词语的结尾,并且还可以继续
*/
WORD_MIDDLE_2,
/**
* 是个词语的结尾,并且没有继续
*/
WORD_END_3,
}
public class TrieEntry extends AbstractMap.SimpleEntry<String, V> implements Comparable<TrieEntry>
{
public TrieEntry(String key, V value)
{
super(key, value);
} | @Override
public int compareTo(TrieEntry o)
{
return getKey().compareTo(o.getKey());
}
}
@Override
public String toString()
{
if (child == null)
{
return "BaseNode{" +
"status=" + status +
", c=" + c +
", value=" + value +
'}';
}
return "BaseNode{" +
"child=" + child.length +
", status=" + status +
", c=" + c +
", value=" + value +
'}';
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\bintrie\BaseNode.java | 1 |
请完成以下Java代码 | public class EndpointMediaTypes {
/**
* Default {@link EndpointMediaTypes} for this version of Spring Boot.
*/
public static final EndpointMediaTypes DEFAULT = new EndpointMediaTypes(
ApiVersion.V3.getProducedMimeType().toString(), ApiVersion.V2.getProducedMimeType().toString(),
"application/json");
private final List<String> produced;
private final List<String> consumed;
/**
* Creates a new {@link EndpointMediaTypes} with the given {@code produced} and
* {@code consumed} media types.
* @param producedAndConsumed the default media types that are produced and consumed
* by an endpoint. Must not be {@code null}.
* @since 2.2.0
*/
public EndpointMediaTypes(String... producedAndConsumed) {
this(toList(producedAndConsumed));
}
private static List<String> toList(String[] producedAndConsumed) {
Assert.notNull(producedAndConsumed, "'producedAndConsumed' must not be null");
return Arrays.asList(producedAndConsumed);
}
/**
* Creates a new {@link EndpointMediaTypes} with the given {@code produced} and
* {@code consumed} media types.
* @param producedAndConsumed the default media types that are produced and consumed
* by an endpoint. Must not be {@code null}.
* @since 2.2.0
*/
public EndpointMediaTypes(List<String> producedAndConsumed) {
this(producedAndConsumed, producedAndConsumed);
} | /**
* Creates a new {@link EndpointMediaTypes} with the given {@code produced} and
* {@code consumed} media types.
* @param produced the default media types that are produced by an endpoint. Must not
* be {@code null}.
* @param consumed the default media types that are consumed by an endpoint. Must not
*/
public EndpointMediaTypes(List<String> produced, List<String> consumed) {
Assert.notNull(produced, "'produced' must not be null");
Assert.notNull(consumed, "'consumed' must not be null");
this.produced = Collections.unmodifiableList(produced);
this.consumed = Collections.unmodifiableList(consumed);
}
/**
* Returns the media types produced by an endpoint.
* @return the produced media types
*/
public List<String> getProduced() {
return this.produced;
}
/**
* Returns the media types consumed by an endpoint.
* @return the consumed media types
*/
public List<String> getConsumed() {
return this.consumed;
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\web\EndpointMediaTypes.java | 1 |
请完成以下Java代码 | public DecisionEntity findDecisionByDeploymentAndKeyAndTenantId(String deploymentId, String decisionKey, String tenantId) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("deploymentId", deploymentId);
parameters.put("decisionKey", decisionKey);
parameters.put("tenantId", tenantId);
return (DecisionEntity) getDbSqlSession().selectOne("selectDecisionByDeploymentAndKeyAndTenantId", parameters);
}
@Override
public DecisionEntity findDecisionByKeyAndVersion(String decisionKey, Integer decisionVersion) {
Map<String, Object> params = new HashMap<>();
params.put("decisionKey", decisionKey);
params.put("decisionVersion", decisionVersion);
List<DecisionEntity> results = getDbSqlSession().selectList("selectDecisionsByKeyAndVersion", params);
if (results.size() == 1) {
return results.get(0);
} else if (results.size() > 1) {
throw new FlowableException("There are " + results.size() + " decision tables with key = '" + decisionKey + "' and version = '" + decisionVersion + "'.");
}
return null;
}
@Override
@SuppressWarnings("unchecked")
public DecisionEntity findDecisionByKeyAndVersionAndTenantId(String decisionKey, Integer decisionVersion, String tenantId) {
Map<String, Object> params = new HashMap<>();
params.put("decisionKey", decisionKey);
params.put("decisionVersion", decisionVersion);
params.put("tenantId", tenantId);
List<DecisionEntity> results = getDbSqlSession().selectList("selectDecisionsByKeyAndVersionAndTenantId", params);
if (results.size() == 1) {
return results.get(0);
} else if (results.size() > 1) {
throw new FlowableException("There are " + results.size() + " decisions with key = '" + decisionKey + "' and version = '" + decisionVersion + "'.");
}
return null; | }
@Override
@SuppressWarnings("unchecked")
public List<DmnDecision> findDecisionsByNativeQuery(Map<String, Object> parameterMap) {
return getDbSqlSession().selectListWithRawParameter("selectDecisionByNativeQuery", parameterMap);
}
@Override
public long findDecisionCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectDecisionCountByNativeQuery", parameterMap);
}
@Override
public void updateDecisionTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().directUpdate("updateDecisionTenantIdForDeploymentId", params);
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\data\impl\MybatisDecisionDataManager.java | 1 |
请完成以下Java代码 | public void setAssignerId(String assignerId) {
this.assignerId = assignerId;
}
@CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class)
public void setTenantIdIn(List<String> tenantIds) {
this.tenantIds = tenantIds;
}
@CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class)
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
@Override
protected void applyFilters(HistoricIdentityLinkLogQuery query) {
if (dateBefore != null) {
query.dateBefore(dateBefore);
}
if (dateAfter != null) {
query.dateAfter(dateAfter);
}
if (type != null) {
query.type(type);
}
if (userId != null) {
query.userId(userId);
}
if (groupId != null) {
query.groupId(groupId);
}
if (taskId != null) {
query.taskId(taskId);
}
if (processDefinitionId != null) {
query.processDefinitionId(processDefinitionId);
}
if (processDefinitionKey != null) {
query.processDefinitionKey(processDefinitionKey);
}
if (operationType != null) {
query.operationType(operationType);
}
if (assignerId != null) {
query.assignerId(assignerId);
}
if (tenantIds != null && !tenantIds.isEmpty()) {
query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()]));
}
if (TRUE.equals(withoutTenantId)) { | query.withoutTenantId();
}
}
@Override
protected void applySortBy(HistoricIdentityLinkLogQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_TIME)) {
query.orderByTime();
} else if (sortBy.equals(SORT_BY_TYPE)) {
query.orderByType();
} else if (sortBy.equals(SORT_BY_USER_ID)) {
query.orderByUserId();
} else if (sortBy.equals(SORT_BY_GROUP_ID)) {
query.orderByGroupId();
} else if (sortBy.equals(SORT_BY_TASK_ID)) {
query.orderByTaskId();
} else if (sortBy.equals(SORT_BY_OPERATION_TYPE)) {
query.orderByOperationType();
} else if (sortBy.equals(SORT_BY_ASSIGNER_ID)) {
query.orderByAssignerId();
} else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_ID)) {
query.orderByProcessDefinitionId();
} else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_KEY)) {
query.orderByProcessDefinitionKey();
} else if (sortBy.equals(SORT_BY_TENANT_ID)) {
query.orderByTenantId();
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricIdentityLinkLogQueryDto.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
@Override
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
@Override
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
@Override
public String getCategory() {
return category;
}
public void setCategory(String category) { | this.category = category;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
ProcessDefinitionImpl that = (ProcessDefinitionImpl) o;
return (
version == that.version &&
Objects.equals(id, that.id) &&
Objects.equals(name, that.name) &&
Objects.equals(description, that.description) &&
Objects.equals(key, that.key) &&
Objects.equals(formKey, that.formKey)
);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), id, name, description, version, key, formKey);
}
@Override
public String toString() {
return (
"ProcessDefinition{" +
"id='" +
id +
'\'' +
", name='" +
name +
'\'' +
", key='" +
key +
'\'' +
", description='" +
description +
'\'' +
", formKey='" +
formKey +
'\'' +
", version=" +
version +
'}'
);
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\ProcessDefinitionImpl.java | 1 |
请完成以下Java代码 | public static Expression getFieldExpression(DelegateExecution execution, String fieldName) {
if (isExecutingExecutionListener(execution)) {
return getListenerFieldExpression(execution, fieldName);
} else {
return getFlowElementFieldExpression(execution, fieldName);
}
}
/**
* Similar to {@link #getFieldExpression(DelegateExecution, String)}, but for use within a {@link TaskListener}.
*/
public static Expression getFieldExpression(DelegateTask task, String fieldName) {
if (task.getCurrentActivitiListener() != null) {
List<FieldExtension> fieldExtensions = task.getCurrentActivitiListener().getFieldExtensions();
if (fieldExtensions != null && fieldExtensions.size() > 0) {
for (FieldExtension fieldExtension : fieldExtensions) {
if (fieldName.equals(fieldExtension.getFieldName())) {
return createExpressionForField(fieldExtension);
}
}
}
}
return null;
}
public static Expression getFlowElementFieldExpression(DelegateExecution execution, String fieldName) { | FieldExtension fieldExtension = getFlowElementField(execution, fieldName);
if (fieldExtension != null) {
return createExpressionForField(fieldExtension);
}
return null;
}
public static Expression getListenerFieldExpression(DelegateExecution execution, String fieldName) {
FieldExtension fieldExtension = getListenerField(execution, fieldName);
if (fieldExtension != null) {
return createExpressionForField(fieldExtension);
}
return null;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\delegate\DelegateHelper.java | 1 |
请完成以下Java代码 | public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Percent.
@param Percent
Percentage
*/
public void setPercent (BigDecimal Percent)
{
set_Value (COLUMNNAME_Percent, Percent);
}
/** Get Percent.
@return Percentage
*/
public BigDecimal getPercent ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Percent);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Threshold max.
@param ThresholdMax
Maximum gross amount for withholding calculation (0=no limit)
*/
public void setThresholdMax (BigDecimal ThresholdMax)
{
set_Value (COLUMNNAME_ThresholdMax, ThresholdMax);
}
/** Get Threshold max.
@return Maximum gross amount for withholding calculation (0=no limit) | */
public BigDecimal getThresholdMax ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ThresholdMax);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Threshold min.
@param Thresholdmin
Minimum gross amount for withholding calculation
*/
public void setThresholdmin (BigDecimal Thresholdmin)
{
set_Value (COLUMNNAME_Thresholdmin, Thresholdmin);
}
/** Get Threshold min.
@return Minimum gross amount for withholding calculation
*/
public BigDecimal getThresholdmin ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Thresholdmin);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Withholding.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void validatePreConditions() throws ODataJPARuntimeException {
if (oDataJPAContext.getEntityManager() == null) {
throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.ENTITY_MANAGER_NOT_INITIALIZED, null);
}
}
public final ODataJPAContext getODataJPAContext()
throws ODataJPARuntimeException {
if (oDataJPAContext == null) {
oDataJPAContext = ODataJPAFactory.createFactory()
.getODataJPAAccessFactory().createODataJPAContext();
}
if (oDataContext != null)
oDataJPAContext.setODataContext(oDataContext);
return oDataJPAContext;
}
protected ODataJPAContext initializeODataJPAContext() throws ODataJPARuntimeException { | ODataJPAContext oDataJPAContext = this.getODataJPAContext();
ODataContext oDataContext = oDataJPAContext.getODataContext();
HttpServletRequest request = (HttpServletRequest) oDataContext.getParameter(
ODataContext.HTTP_SERVLET_REQUEST_OBJECT);
EntityManager entityManager = (EntityManager) request
.getAttribute(JerseyConfig.EntityManagerFilter.EM_REQUEST_ATTRIBUTE);
oDataJPAContext.setEntityManager(entityManager);
oDataJPAContext.setPersistenceUnitName("default");
oDataJPAContext.setContainerManaged(true);
return oDataJPAContext;
}
} | repos\springboot-demo-master\olingo\src\main\java\com\et\olingo\service\CustomODataServiceFactory.java | 2 |
请完成以下Java代码 | public String getTaskIdVariableName() {
return taskIdVariableName;
}
public void setTaskIdVariableName(String taskIdVariableName) {
this.taskIdVariableName = taskIdVariableName;
}
public String getTaskCompleterVariableName() {
return taskCompleterVariableName;
}
public void setTaskCompleterVariableName(String taskCompleterVariableName) {
this.taskCompleterVariableName = taskCompleterVariableName;
}
@Override
public UserTask clone() {
UserTask clone = new UserTask();
clone.setValues(this);
return clone;
}
public void setValues(UserTask otherElement) {
super.setValues(otherElement);
setAssignee(otherElement.getAssignee());
setOwner(otherElement.getOwner());
setFormKey(otherElement.getFormKey());
setSameDeployment(otherElement.isSameDeployment());
setDueDate(otherElement.getDueDate()); | setPriority(otherElement.getPriority());
setCategory(otherElement.getCategory());
setTaskIdVariableName(otherElement.getTaskIdVariableName());
setTaskCompleterVariableName(otherElement.getTaskCompleterVariableName());
setExtensionId(otherElement.getExtensionId());
setSkipExpression(otherElement.getSkipExpression());
setValidateFormFields(otherElement.getValidateFormFields());
setCandidateGroups(new ArrayList<>(otherElement.getCandidateGroups()));
setCandidateUsers(new ArrayList<>(otherElement.getCandidateUsers()));
setCustomGroupIdentityLinks(otherElement.customGroupIdentityLinks);
setCustomUserIdentityLinks(otherElement.customUserIdentityLinks);
formProperties = new ArrayList<>();
if (otherElement.getFormProperties() != null && !otherElement.getFormProperties().isEmpty()) {
for (FormProperty property : otherElement.getFormProperties()) {
formProperties.add(property.clone());
}
}
taskListeners = new ArrayList<>();
if (otherElement.getTaskListeners() != null && !otherElement.getTaskListeners().isEmpty()) {
for (FlowableListener listener : otherElement.getTaskListeners()) {
taskListeners.add(listener.clone());
}
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\UserTask.java | 1 |
请完成以下Java代码 | public void setFreightAmt (final BigDecimal FreightAmt)
{
set_Value (COLUMNNAME_FreightAmt, FreightAmt);
}
@Override
public BigDecimal getFreightAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_FreightAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setM_FreightCostDetail_ID (final int M_FreightCostDetail_ID)
{
if (M_FreightCostDetail_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_FreightCostDetail_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_FreightCostDetail_ID, M_FreightCostDetail_ID);
}
@Override
public int getM_FreightCostDetail_ID()
{
return get_ValueAsInt(COLUMNNAME_M_FreightCostDetail_ID);
}
@Override
public org.adempiere.model.I_M_FreightCostShipper getM_FreightCostShipper()
{
return get_ValueAsPO(COLUMNNAME_M_FreightCostShipper_ID, org.adempiere.model.I_M_FreightCostShipper.class);
}
@Override
public void setM_FreightCostShipper(final org.adempiere.model.I_M_FreightCostShipper M_FreightCostShipper)
{
set_ValueFromPO(COLUMNNAME_M_FreightCostShipper_ID, org.adempiere.model.I_M_FreightCostShipper.class, M_FreightCostShipper);
}
@Override
public void setM_FreightCostShipper_ID (final int M_FreightCostShipper_ID)
{
if (M_FreightCostShipper_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_FreightCostShipper_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_FreightCostShipper_ID, M_FreightCostShipper_ID);
}
@Override
public int getM_FreightCostShipper_ID()
{ | return get_ValueAsInt(COLUMNNAME_M_FreightCostShipper_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setShipmentValueAmt (final BigDecimal ShipmentValueAmt)
{
set_Value (COLUMNNAME_ShipmentValueAmt, ShipmentValueAmt);
}
@Override
public BigDecimal getShipmentValueAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ShipmentValueAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\model\X_M_FreightCostDetail.java | 1 |
请完成以下Java代码 | public void readVectorFile() throws IOException
{
Predefine.logger.info(String.format("reading %s file. please wait...\n", file));
InputStream is = null;
Reader r = null;
BufferedReader br = null;
try
{
is = IOUtil.newInputStream(file);
r = new InputStreamReader(is, ENCODING);
br = new BufferedReader(r);
String line = br.readLine();
words = Integer.parseInt(line.split("\\s+")[0].trim());
size = Integer.parseInt(line.split("\\s+")[1].trim());
vocab = new String[words];
matrix = new float[words][];
for (int i = 0; i < words; i++)
{
line = br.readLine().trim();
String[] params = line.split("\\s+");
if (params.length != size + 1)
{
Predefine.logger.info("词向量有一行格式不规范(可能是单词含有空格):" + line);
--words;
--i;
continue;
}
vocab[i] = params[0];
matrix[i] = new float[size];
double len = 0;
for (int j = 0; j < size; j++)
{
matrix[i][j] = Float.parseFloat(params[j + 1]);
len += matrix[i][j] * matrix[i][j];
}
len = Math.sqrt(len);
for (int j = 0; j < size; j++)
{
matrix[i][j] /= len;
}
} | if (words != vocab.length)
{
vocab = Utility.shrink(vocab, new String[words]);
matrix = Utility.shrink(matrix, new float[words][]);
}
}
finally
{
Utility.closeQuietly(br);
Utility.closeQuietly(r);
Utility.closeQuietly(is);
}
}
public int getSize()
{
return size;
}
public int getNumWords()
{
return words;
}
public String getWord(int idx)
{
return vocab[idx];
}
public float getMatrixElement(int row, int column)
{
return matrix[row][column];
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\VectorsReader.java | 1 |
请完成以下Java代码 | public List<LUPickingTarget> getLUAvailableTargets(
@NonNull final PickingJob pickingJob,
@Nullable final PickingJobLineId lineId)
{
return pickingJobService.getLUAvailableTargets(pickingJob, lineId);
}
public List<TUPickingTarget> getTUAvailableTargets(
@NonNull final PickingJob pickingJob,
@Nullable final PickingJobLineId lineId)
{
return pickingJobService.getTUAvailableTargets(pickingJob, lineId);
}
public PickingJob setLUPickingTarget(
@NonNull final PickingJob pickingJob,
@Nullable final PickingJobLineId lineId,
@Nullable final LUPickingTarget target)
{
return pickingJobService.setLUPickingTarget(pickingJob, lineId, target);
}
public PickingJob setTUPickingTarget(
@NonNull final PickingJob pickingJob,
@Nullable final PickingJobLineId lineId,
@Nullable final TUPickingTarget target)
{
return pickingJobService.setTUPickingTarget(pickingJob, lineId, target);
}
public PickingJob closeLUAndTUPickingTargets(
@NonNull final PickingJob pickingJob,
@Nullable final PickingJobLineId lineId)
{
return pickingJobService.closeLUAndTUPickingTargets(pickingJob, lineId);
}
public PickingJob closeTUPickingTarget(
@NonNull final PickingJob pickingJob,
@Nullable final PickingJobLineId lineId)
{
return pickingJobService.closeTUPickingTarget(pickingJob, lineId);
}
@NonNull
public PickingJobOptions getPickingJobOptions(@Nullable final BPartnerId customerId) {return configService.getPickingJobOptions(customerId);}
@NonNull
public List<HuId> getClosedLUs(
@NonNull final PickingJob pickingJob,
@Nullable final PickingJobLineId lineId)
{
final Set<HuId> pickedHuIds = pickingJob.getPickedHuIds(lineId);
if (pickedHuIds.isEmpty())
{
return ImmutableList.of();
}
final HuId currentlyOpenedLUId = pickingJob.getLuPickingTarget(lineId)
.map(LUPickingTarget::getLuId)
.orElse(null);
return handlingUnitsBL.getTopLevelHUs(IHandlingUnitsBL.TopLevelHusQuery.builder()
.hus(handlingUnitsBL.getByIds(pickedHuIds))
.build()) | .stream()
.filter(handlingUnitsBL::isLoadingUnit)
.map(I_M_HU::getM_HU_ID)
.map(HuId::ofRepoId)
.filter(huId -> !HuId.equals(huId, currentlyOpenedLUId))
.collect(ImmutableList.toImmutableList());
}
public PickingSlotSuggestions getPickingSlotsSuggestions(@NonNull final PickingJob pickingJob)
{
return pickingJobService.getPickingSlotsSuggestions(pickingJob);
}
public PickingJob pickAll(@NonNull final PickingJobId pickingJobId, final @NonNull UserId callerId)
{
return pickingJobService.pickAll(pickingJobId, callerId);
}
public PickingJobQtyAvailable getQtyAvailable(@NonNull final PickingJobId pickingJobId, final @NonNull UserId callerId)
{
return pickingJobService.getQtyAvailable(pickingJobId, callerId);
}
public GetNextEligibleLineToPackResponse getNextEligibleLineToPack(final @NonNull GetNextEligibleLineToPackRequest request)
{
return pickingJobService.getNextEligibleLineToPack(request);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\PickingJobRestService.java | 1 |
请完成以下Java代码 | public Collection<ConfigAttribute> getAttributes(Method method, @Nullable Class<?> targetClass) {
// The method may be on an interface, but we need attributes from the target
// class.
// If the target class is null, the method will be unchanged.
Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass);
// First try is the method in the target class.
Collection<ConfigAttribute> attr = findAttributes(specificMethod, targetClass);
if (attr != null) {
return attr;
}
// Second try is the config attribute on the target class.
attr = findAttributes(specificMethod.getDeclaringClass());
if (attr != null) {
return attr;
}
if (specificMethod != method || targetClass == null) {
// Fallback is to look at the original method.
attr = findAttributes(method, method.getDeclaringClass());
if (attr != null) {
return attr;
}
// Last fallback is the class of the original method.
return findAttributes(method.getDeclaringClass());
}
return Collections.emptyList();
}
/** | * Obtains the security metadata applicable to the specified method invocation.
*
* <p>
* Note that the {@link Method#getDeclaringClass()} may not equal the
* <code>targetClass</code>. Both parameters are provided to assist subclasses which
* may wish to provide advanced capabilities related to method metadata being
* "registered" against a method even if the target class does not declare the method
* (i.e. the subclass may only inherit the method).
* @param method the method for the current invocation (never <code>null</code>)
* @param targetClass the target class for the invocation (may be <code>null</code>)
* @return the security metadata (or null if no metadata applies)
*/
protected abstract Collection<ConfigAttribute> findAttributes(Method method, @Nullable Class<?> targetClass);
/**
* Obtains the security metadata registered against the specified class.
*
* <p>
* Subclasses should only return metadata expressed at a class level. Subclasses
* should NOT aggregate metadata for each method registered against a class, as the
* abstract superclass will separate invoke {@link #findAttributes(Method, Class)} for
* individual methods as appropriate.
* @param clazz the target class for the invocation (never <code>null</code>)
* @return the security metadata (or null if no metadata applies)
*/
protected abstract Collection<ConfigAttribute> findAttributes(Class<?> clazz);
} | repos\spring-security-main\access\src\main\java\org\springframework\security\access\method\AbstractFallbackMethodSecurityMetadataSource.java | 1 |
请完成以下Java代码 | private POSShipFrom extractShipFrom(final I_C_POS record)
{
final WarehouseId shipFromWarehouseId = WarehouseId.ofRepoId(record.getM_Warehouse_ID());
return POSShipFrom.builder()
.warehouseId(shipFromWarehouseId)
.clientAndOrgId(warehouseBL.getWarehouseClientAndOrgId(shipFromWarehouseId))
.countryId(warehouseBL.getCountryId(shipFromWarehouseId))
.build();
}
private @NonNull BPartnerLocationAndCaptureId extractWalkInCustomerShipTo(final I_C_POS record)
{
final BPartnerId walkInCustomerId = BPartnerId.ofRepoId(record.getC_BPartnerCashTrx_ID());
return BPartnerLocationAndCaptureId.ofRecord(
bpartnerDAO.retrieveBPartnerLocation(BPartnerLocationQuery.builder()
.type(BPartnerLocationQuery.Type.SHIP_TO)
.bpartnerId(walkInCustomerId)
.build())
);
} | public POSTerminal updateById(@NonNull final POSTerminalId posTerminalId, @NonNull final UnaryOperator<POSTerminal> updater)
{
return trxManager.callInThreadInheritedTrx(() -> {
final I_C_POS record = retrieveRecordById(posTerminalId);
final POSTerminal posTerminalBeforeChange = fromRecord(record);
final POSTerminal posTerminal = updater.apply(posTerminalBeforeChange);
if (Objects.equals(posTerminal, posTerminalBeforeChange))
{
return posTerminalBeforeChange;
}
updateRecord(record, posTerminal);
InterfaceWrapperHelper.save(record);
return posTerminal;
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSTerminalService.java | 1 |
请完成以下Java代码 | public ProcessInstanceBuilder tenantId(String tenantId) {
this.tenantId = tenantId;
return this;
}
@Override
public ProcessInstanceBuilder variables(Map<String, Object> variables) {
if (this.variables == null) {
this.variables = new HashMap<>();
}
if (variables != null) {
for (String variableName : variables.keySet()) {
this.variables.put(variableName, variables.get(variableName));
}
}
return this;
}
@Override
public ProcessInstanceBuilder variable(String variableName, Object value) {
if (this.variables == null) {
this.variables = new HashMap<>();
}
this.variables.put(variableName, value);
return this;
}
@Override
public ProcessInstanceBuilder transientVariables(Map<String, Object> transientVariables) {
if (this.transientVariables == null) {
this.transientVariables = new HashMap<>();
}
if (transientVariables != null) {
for (String variableName : transientVariables.keySet()) {
this.transientVariables.put(variableName, transientVariables.get(variableName));
}
}
return this;
}
@Override
public ProcessInstanceBuilder transientVariable(String variableName, Object value) {
if (this.transientVariables == null) {
this.transientVariables = new HashMap<>(); | }
this.transientVariables.put(variableName, value);
return this;
}
@Override
public ProcessInstance start() {
return runtimeService.startProcessInstance(this);
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getMessageName() {
return messageName;
}
public String getProcessInstanceName() {
return processInstanceName;
}
public String getBusinessKey() {
return businessKey;
}
public String getTenantId() {
return tenantId;
}
public Map<String, Object> getVariables() {
return variables;
}
public Map<String, Object> getTransientVariables() {
return transientVariables;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\runtime\ProcessInstanceBuilderImpl.java | 1 |
请完成以下Java代码 | private @Nullable Class<?> doLoadClass(String name) {
if ((this.delegate || filter(name, true))) {
Class<?> result = loadFromParent(name);
return (result != null) ? result : findClassIgnoringNotFound(name);
}
Class<?> result = findClassIgnoringNotFound(name);
return (result != null) ? result : loadFromParent(name);
}
private Class<?> resolveIfNecessary(Class<?> resultClass, boolean resolve) {
if (resolve) {
resolveClass(resultClass);
}
return (resultClass);
}
@Override
protected void addURL(URL url) {
// Ignore URLs added by the Tomcat 8 implementation (see gh-919)
if (logger.isTraceEnabled()) {
logger.trace("Ignoring request to add " + url + " to the tomcat classloader");
}
}
private @Nullable Class<?> loadFromParent(String name) {
if (this.parent == null) {
return null;
}
try { | return Class.forName(name, false, this.parent);
}
catch (ClassNotFoundException ex) {
return null;
}
}
private @Nullable Class<?> findClassIgnoringNotFound(String name) {
try {
return findClass(name);
}
catch (ClassNotFoundException ex) {
return null;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\TomcatEmbeddedWebappClassLoader.java | 1 |
请完成以下Java代码 | public class ExclusiveGatewayActivityBehavior extends GatewayActivityBehavior {
protected static BpmnBehaviorLogger LOG = ProcessEngineLogger.BPMN_BEHAVIOR_LOGGER;
/**
* The default behaviour of BPMN, taking every outgoing sequence flow
* (where the condition evaluates to true), is not valid for an exclusive
* gateway.
*
* Hence, this behaviour is overriden and replaced by the correct behavior:
* selecting the first sequence flow which condition evaluates to true
* (or which hasn't got a condition) and leaving the activity through that
* sequence flow.
*
* If no sequence flow is selected (ie all conditions evaluate to false),
* then the default sequence flow is taken (if defined).
*/
@Override
public void doLeave(ActivityExecution execution) {
LOG.leavingActivity(execution.getActivity().getId());
PvmTransition outgoingSeqFlow = null;
String defaultSequenceFlow = (String) execution.getActivity().getProperty("default");
Iterator<PvmTransition> transitionIterator = execution.getActivity().getOutgoingTransitions().iterator();
while (outgoingSeqFlow == null && transitionIterator.hasNext()) {
PvmTransition seqFlow = transitionIterator.next();
Condition condition = (Condition) seqFlow.getProperty(BpmnParse.PROPERTYNAME_CONDITION);
if ( (condition == null && (defaultSequenceFlow == null || !defaultSequenceFlow.equals(seqFlow.getId())) )
|| (condition != null && condition.evaluate(execution)) ) {
LOG.outgoingSequenceFlowSelected(seqFlow.getId());
outgoingSeqFlow = seqFlow;
}
}
if (outgoingSeqFlow != null) {
execution.leaveActivityViaTransition(outgoingSeqFlow); | } else {
if (defaultSequenceFlow != null) {
PvmTransition defaultTransition = execution.getActivity().findOutgoingTransition(defaultSequenceFlow);
if (defaultTransition != null) {
execution.leaveActivityViaTransition(defaultTransition);
} else {
throw LOG.missingDefaultFlowException(execution.getActivity().getId(), defaultSequenceFlow);
}
} else {
//No sequence flow could be found, not even a default one
throw LOG.stuckExecutionException(execution.getActivity().getId());
}
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\ExclusiveGatewayActivityBehavior.java | 1 |
请完成以下Java代码 | public final IContextMenuActionContext getContext()
{
return context;
}
@Override
public String getTitle()
{
final String name = getName();
if (Check.isEmpty(name, true))
{
return null;
}
return Services.get(IMsgBL.class).translate(Env.getCtx(), name);
}
/** @return action's name (not translated) */
protected abstract String getName();
public final VEditor getEditor()
{
if (context == null)
{
return null;
}
return context.getEditor();
}
public final GridField getGridField()
{
final VEditor editor = getEditor();
if (editor == null)
{
return null;
}
final GridField gridField = editor.getField();
return gridField;
}
public final GridTab getGridTab()
{
final GridField gridField = getGridField();
if (gridField == null)
{
return null;
}
return gridField.getGridTab();
}
@Override
public List<IContextMenuAction> getChildren()
{
return Collections.emptyList();
}
@Override
public boolean isLongOperation()
{
return false;
}
@Override
public boolean isHideWhenNotRunnable()
{
return true; // hide when not runnable - backward compatibility
}
protected final String getColumnName()
{
final GridField gridField = getGridField();
if (gridField == null)
{
return null;
}
final String columnName = gridField.getColumnName();
return columnName;
}
protected final Object getFieldValue()
{
final IContextMenuActionContext context = getContext();
if (context == null)
{
return null;
}
//
// Get value when in Grid Mode
final VTable vtable = context.getVTable();
final int row = context.getViewRow();
final int column = context.getViewColumn();
if (vtable != null && row >= 0 && column >= 0)
{
final Object value = vtable.getValueAt(row, column);
return value;
}
// Get value when in single mode
else
{
final GridField gridField = getGridField();
if (gridField == null)
{
return null;
}
final Object value = gridField.getValue();
return value;
}
}
protected final GridController getGridController()
{
final IContextMenuActionContext context = getContext();
if (context == null) | {
return null;
}
final VTable vtable = context.getVTable();
final Component comp;
if (vtable != null)
{
comp = vtable;
}
else
{
final VEditor editor = getEditor();
if (editor instanceof Component)
{
comp = (Component)editor;
}
else
{
comp = null;
}
}
Component p = comp;
while (p != null)
{
if (p instanceof GridController)
{
return (GridController)p;
}
p = p.getParent();
}
return null;
}
protected final boolean isGridMode()
{
final GridController gc = getGridController();
if (gc == null)
{
return false;
}
final boolean gridMode = !gc.isSingleRow();
return gridMode;
}
@Override
public KeyStroke getKeyStroke()
{
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\AbstractContextMenuAction.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WebLogAspect {
private static final Logger loggger = LogManager.getLogger(WebLogAspect.class);
@Pointcut("execution(public * com.quick.log..controller.*.*(..))")//两个..代表所有子目录,最后括号里的两个..代表所有参数
public void logPointCut() {
}
@Before("logPointCut()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
loggger.info("请求地址 : " + request.getRequestURL().toString());
loggger.info("HTTP METHOD : " + request.getMethod());
loggger.info("IP : " + request.getRemoteAddr());
loggger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." | + joinPoint.getSignature().getName());
loggger.info("参数 : " + Arrays.toString(joinPoint.getArgs()));
// loggger.info("参数 : " + joinPoint.getArgs());
}
@AfterReturning(returning = "ret", pointcut = "logPointCut()")// returning的值和doAfterReturning的参数名一致
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
loggger.info("返回值 : " + ret);
}
@Around("logPointCut()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
long startTime = System.currentTimeMillis();
Object ob = pjp.proceed();// ob 为方法的返回值
loggger.info("耗时 : " + (System.currentTimeMillis() - startTime));
return ob;
}
} | repos\spring-boot-quick-master\quick-img2txt\src\main\java\com\quick\config\WebLogAspect.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public DeviceProfile find(DeviceProfileId deviceProfileId) {
return deviceProfileService.findDeviceProfileById(TenantId.SYS_TENANT_ID, deviceProfileId);
}
@Override
public DeviceProfile findOrCreateDeviceProfile(TenantId tenantId, String profileName) {
return deviceProfileService.findOrCreateDeviceProfile(tenantId, profileName);
}
@Override
public void removeListener(TenantId tenantId, EntityId listenerId) {
ConcurrentMap<EntityId, Consumer<DeviceProfile>> tenantListeners = profileListeners.get(tenantId);
if (tenantListeners != null) {
tenantListeners.remove(listenerId);
}
ConcurrentMap<EntityId, BiConsumer<DeviceId, DeviceProfile>> deviceListeners = deviceProfileListeners.get(tenantId);
if (deviceListeners != null) {
deviceListeners.remove(listenerId);
}
}
private void notifyProfileListeners(DeviceProfile profile) { | ConcurrentMap<EntityId, Consumer<DeviceProfile>> tenantListeners = profileListeners.get(profile.getTenantId());
if (tenantListeners != null) {
tenantListeners.forEach((id, listener) -> listener.accept(profile));
}
}
private void notifyDeviceListeners(TenantId tenantId, DeviceId deviceId, DeviceProfile profile) {
if (profile != null) {
ConcurrentMap<EntityId, BiConsumer<DeviceId, DeviceProfile>> tenantListeners = deviceProfileListeners.get(tenantId);
if (tenantListeners != null) {
tenantListeners.forEach((id, listener) -> listener.accept(deviceId, profile));
}
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\profile\DefaultTbDeviceProfileCache.java | 2 |
请完成以下Java代码 | public static @NonNull Consumer<Object> environmentAwareObjectInitializer(@Nullable Environment environment) {
return environment == null ? NO_OP : target -> {
if (target instanceof EnvironmentAware) {
((EnvironmentAware) target).setEnvironment(environment);
}
};
}
/**
* Returns a {@link Consumer} capable of initializing an {@link ResourceLoaderAware} {@link Object}
* with the given {@link ResourceLoader}.
*
* The {@link ResourceLoaderAware#setResourceLoader(ResourceLoader)} method is only called on
* the {@link ResourceLoaderAware} {@link Object} if the {@link ResourceLoader} is not {@literal null}.
*
* @param resourceLoader {@link ResourceLoader} set on the {@link ResourceLoaderAware} {@link Object}
* by the {@link Consumer}.
* @return a {@link Consumer} capable of initializing an {@link ResourceLoaderAware} {@link Object}
* with the given {@link ResourceLoader}; never {@literal null}. | * @see org.springframework.context.ResourceLoaderAware
* @see org.springframework.core.io.ResourceLoader
* @see java.util.function.Consumer
*/
public static @NonNull Consumer<Object> resourceLoaderAwareObjectInitializer(@Nullable ResourceLoader resourceLoader) {
return resourceLoader == null ? NO_OP : target -> {
if (target instanceof ResourceLoaderAware) {
((ResourceLoaderAware) target).setResourceLoader(resourceLoader);
}
};
}
private static boolean hasNoText(@Nullable String value) {
return !StringUtils.hasText(value);
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\util\ObjectAwareUtils.java | 1 |
请完成以下Java代码 | public void flush()
{
final List<BankStatementImportFileRequestLog> logEntries = buffer;
this.buffer = null;
if (logEntries == null || logEntries.isEmpty())
{
return;
}
try
{
bankStatementImportFileLogRepository.insertLogs(logEntries);
}
catch (final Exception ex)
{
// make sure flush never fails
logger.warn("Failed saving {} log entries but IGNORED: {}", logEntries.size(), logEntries, ex);
}
}
@NonNull
private BankStatementImportFileRequestLog createLogEntry(@NonNull final String msg, final Object... msgParameters)
{
final LoggableWithThrowableUtil.FormattedMsgWithAdIssueId msgAndAdIssueId = LoggableWithThrowableUtil.extractMsgAndAdIssue(msg, msgParameters); | return BankStatementImportFileRequestLog.builder()
.message(msgAndAdIssueId.getFormattedMessage())
.adIssueId(msgAndAdIssueId.getAdIsueId().orElse(null))
.timestamp(SystemTime.asInstant())
.bankStatementImportFileId(bankStatementImportFileId)
.clientId(clientId)
.userId(userId)
.build();
}
private void addToBuffer(@NonNull final BankStatementImportFileRequestLog logEntry)
{
List<BankStatementImportFileRequestLog> buffer = this.buffer;
if (buffer == null)
{
buffer = this.buffer = new ArrayList<>(bufferSize);
}
buffer.add(logEntry);
if (buffer.size() >= bufferSize)
{
flush();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\importfile\log\BankStatementImportFileLoggable.java | 1 |
请完成以下Java代码 | private CarrierGoodsType createGoodsType(final @NonNull ShipperId shipperId, @NonNull final String externalId, @NonNull final String name)
{
final I_Carrier_Goods_Type po = InterfaceWrapperHelper.newInstance(I_Carrier_Goods_Type.class);
po.setM_Shipper_ID(shipperId.getRepoId());
po.setExternalId(externalId);
po.setName(name);
InterfaceWrapperHelper.saveRecord(po);
return fromRecord(po);
}
@Nullable
private CarrierGoodsType getCachedGoodsTypeByShipperExternalId(@NonNull final ShipperId shipperId, @Nullable final String externalId)
{
if (externalId == null)
{
return null;
}
return carrierGoodsTypesByExternalId.getOrLoad(shipperId + externalId, () ->
queryBL.createQueryBuilder(I_Carrier_Goods_Type.class)
.addEqualsFilter(I_Carrier_Goods_Type.COLUMNNAME_M_Shipper_ID, shipperId)
.addEqualsFilter(I_Carrier_Goods_Type.COLUMNNAME_ExternalId, externalId)
.firstOptional()
.map(CarrierGoodsTypeRepository::fromRecord)
.orElse(null));
}
@Nullable
public CarrierGoodsType getCachedGoodsTypeById(@Nullable final CarrierGoodsTypeId goodsTypeId)
{
if (goodsTypeId == null)
{
return null;
}
return carrierGoodsTypesById.getOrLoad(goodsTypeId.toString(), () -> | queryBL.createQueryBuilder(I_Carrier_Goods_Type.class)
.addEqualsFilter(I_Carrier_Goods_Type.COLUMNNAME_Carrier_Goods_Type_ID, goodsTypeId)
.firstOptional()
.map(CarrierGoodsTypeRepository::fromRecord)
.orElse(null));
}
private static CarrierGoodsType fromRecord(@NotNull final I_Carrier_Goods_Type goodsType)
{
return CarrierGoodsType.builder()
.id(CarrierGoodsTypeId.ofRepoId(goodsType.getCarrier_Goods_Type_ID()))
.externalId(goodsType.getExternalId())
.name(goodsType.getName())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\model\CarrierGoodsTypeRepository.java | 1 |
请完成以下Java代码 | public int getLastSalesPrice_Currency_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_LastSalesPrice_Currency_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Letzte Lieferung.
@param LastShipDate Letzte Lieferung */
@Override
public void setLastShipDate (java.sql.Timestamp LastShipDate)
{
set_Value (COLUMNNAME_LastShipDate, LastShipDate);
}
/** Get Letzte Lieferung.
@return Letzte Lieferung */
@Override
public java.sql.Timestamp getLastShipDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_LastShipDate);
}
@Override
public org.compiere.model.I_M_Product getM_Product() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class);
}
@Override
public void setM_Product(org.compiere.model.I_M_Product M_Product)
{
set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product);
} | /** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
@Override
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_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();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Product_Stats.java | 1 |
请完成以下Java代码 | public class DeploymentStatisticsEntity extends DeploymentEntity implements DeploymentStatistics {
private static final long serialVersionUID = 1L;
protected int instances;
protected int failedJobs;
protected List<IncidentStatistics> incidentStatistics;
public int getInstances() {
return instances;
}
public void setInstances(int instances) {
this.instances = instances;
}
public int getFailedJobs() {
return failedJobs;
}
public void setFailedJobs(int failedJobs) {
this.failedJobs = failedJobs;
}
public List<IncidentStatistics> getIncidentStatistics() { | return incidentStatistics;
}
public void setIncidentStatistics(List<IncidentStatistics> incidentStatistics) {
this.incidentStatistics = incidentStatistics;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[instances=" + instances
+ ", failedJobs=" + failedJobs
+ ", id=" + id
+ ", name=" + name
+ ", resources=" + resources
+ ", deploymentTime=" + deploymentTime
+ ", validatingSchema=" + validatingSchema
+ ", isNew=" + isNew
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\DeploymentStatisticsEntity.java | 1 |
请完成以下Java代码 | public class CountLogStage implements GroupToScalarComputation<String, LogEvent, LogAggregate> {
private int duration;
@Override
public void init(Context context) {
duration = (int)context.getParameters().get("LogAggregationDuration", 1000);
}
@Override
public Observable<LogAggregate> call(Context context, Observable<MantisGroup<String, LogEvent>> mantisGroup) {
return mantisGroup
.window(duration, TimeUnit.MILLISECONDS)
.flatMap(o -> o.groupBy(MantisGroup::getKeyValue)
.flatMap(group -> group.reduce(0, (count, value) -> count = count + 1)
.map((count) -> new LogAggregate(count, group.getKey()))
));
}
public static GroupToScalar.Config<String, LogEvent, LogAggregate> config(){
return new GroupToScalar.Config<String, LogEvent, LogAggregate>()
.description("sum events for a log level")
.codec(JacksonCodecs.pojo(LogAggregate.class))
.withParameters(getParameters()); | }
public static List<ParameterDefinition<?>> getParameters() {
List<ParameterDefinition<?>> params = new ArrayList<>();
params.add(new IntParameter()
.name("LogAggregationDuration")
.description("window size for aggregation in milliseconds")
.validator(Validators.range(100, 10000))
.defaultValue(5000)
.build()) ;
return params;
}
} | repos\tutorials-master\netflix-modules\mantis\src\main\java\com\baeldung\netflix\mantis\stage\CountLogStage.java | 1 |
请完成以下Java代码 | public java.awt.Component getComponent()
{
return warehouseStockPanel;
}
/**
* Wrapper class for each of the detail tabs.
*
* @author ad
*
*/
private class InfoProductDetailTab
{
private final IInfoProductDetail detail;
private final Component component;
private final String titleTrl;
private Object refreshKeyLast;
public InfoProductDetailTab(String title, final IInfoProductDetail detail, final Component component)
{
super();
this.titleTrl = Services.get(IMsgBL.class).translate(Env.getCtx(), title);
this.detail = detail;
if(component instanceof JTable)
{
// Wrap the JTable in a scroll pane, else the table header won't be visible
// see http://stackoverflow.com/questions/2320812/jtable-wont-show-column-headers
this.component = new CScrollPane(component);
}
else
{
this.component = component;
}
}
public String getTitleTrl()
{
return titleTrl;
}
public Component getComponent()
{
return component;
}
/**
* Refresh (always)
*/
public void refresh()
{
final int M_Product_ID = getM_Product_ID();
final int M_Warehouse_ID = getM_Warehouse_ID();
final int M_PriceList_Version_ID = getM_PriceList_Version_ID();
final int M_AttributeSetInstance_ID = getM_AttributeSetInstance_ID(); | final boolean onlyIfStale = false;
refresh(onlyIfStale, M_Product_ID, M_Warehouse_ID, M_AttributeSetInstance_ID, M_PriceList_Version_ID);
}
/**
* Refresh only if stale
*/
private void refreshIfStale()
{
final int M_Product_ID = getM_Product_ID();
final int M_Warehouse_ID = getM_Warehouse_ID();
final int M_PriceList_Version_ID = getM_PriceList_Version_ID();
final int M_AttributeSetInstance_ID = getM_AttributeSetInstance_ID();
final boolean onlyIfStale = true;
refresh(onlyIfStale, M_Product_ID, M_Warehouse_ID, M_AttributeSetInstance_ID, M_PriceList_Version_ID);
}
private void refresh(boolean onlyIfStale, int M_Product_ID, int M_Warehouse_ID, int M_AttributeSetInstance_ID, int M_PriceList_Version_ID)
{
final ArrayKey refreshKey = Util.mkKey(M_Product_ID, M_Warehouse_ID, M_AttributeSetInstance_ID, M_PriceList_Version_ID);
if (!onlyIfStale || !isStale(refreshKey))
{
detail.refresh(M_Product_ID, M_Warehouse_ID, M_AttributeSetInstance_ID, M_PriceList_Version_ID);
}
this.refreshKeyLast = refreshKey;
}
private boolean isStale(final ArrayKey refreshKey)
{
return !Check.equals(refreshKey, refreshKeyLast);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\InfoProductDetails.java | 1 |
请完成以下Java代码 | private void readReference( int AD_Reference_ID)
{
m_values = new HashMap<String,String>();
String SQL;
// metas: added IsActive='Y' to where clauses
if (Env.isBaseLanguage(Env.getCtx(), "AD_Ref_List"))
SQL = "SELECT Value, Name FROM AD_Ref_List WHERE AD_Reference_ID=? AND IsActive='Y'";
else
SQL = "SELECT l.Value, t.Name FROM AD_Ref_List l, AD_Ref_List_Trl t "
+ "WHERE l.AD_Ref_List_ID=t.AD_Ref_List_ID"
+ " AND t.AD_Language='" + Env.getAD_Language(Env.getCtx()) + "'"
+ " AND l.AD_Reference_ID=? AND l.IsActive='Y'";
// metas end
try
{
PreparedStatement pstmt = DB.prepareStatement(SQL, null);
pstmt.setInt(1, AD_Reference_ID);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
String value = rs.getString(1);
String name = rs.getString(2);
// metas: tsa: if debugging display ColumnNames instead of regular name
if (Services.get(IDeveloperModeBL.class).isEnabled())
{
name = value + "_" + name;
}
// metas: end
m_values.put(value, name);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.error(SQL, e);
}
} // readReference
/**
* Return value/name
* @return HashMap with Value/Names
*/
public Map<String, String> getValues()
{
return m_values;
} // getValues
// Field for Value Preference
private GridField m_mField = null;
/**
* Set Field/WindowNo for ValuePreference
* @param mField field model
*/
@Override
public void setField (GridField mField)
{ | if (mField.getColumnName().endsWith("_ID") && ! IColumnBL.isRecordIdColumnName(mField.getColumnName()))
{
m_lookup = MLookupFactory.newInstance().get(Env.getCtx(), mField.getWindowNo(), 0,
mField.getAD_Column_ID(), DisplayType.Search);
}
else if (mField.getAD_Reference_Value_ID() != null)
{
// Assuming List
m_lookup = MLookupFactory.newInstance().get(Env.getCtx(), mField.getWindowNo(), 0,
mField.getAD_Column_ID(), DisplayType.List);
}
m_mField = mField;
} // setField
@Override
public GridField getField() {
return m_mField;
}
/**
* @return Returns the savedMnemonic.
*/
public char getSavedMnemonic ()
{
return m_savedMnemonic;
} // getSavedMnemonic
/**
* @param savedMnemonic The savedMnemonic to set.
*/
public void setSavedMnemonic (char savedMnemonic)
{
m_savedMnemonic = savedMnemonic;
} // getSavedMnemonic
@Override
public boolean isAutoCommit()
{
return true;
}
} // VButton | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VButton.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void removeVariableLocal(String variableName) {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
@Override
public void removeVariables() {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
@Override
public void removeVariablesLocal() {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
@Override
public void removeVariables(Collection<String> variableNames) {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
@Override
public void removeVariablesLocal(Collection<String> variableNames) {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
@Override
public void setTransientVariablesLocal(Map<String, Object> transientVariables) {
throw new UnsupportedOperationException("No execution active, no variables can be set");
}
@Override
public void setTransientVariableLocal(String variableName, Object variableValue) {
throw new UnsupportedOperationException("No execution active, no variables can be set");
}
@Override
public void setTransientVariables(Map<String, Object> transientVariables) {
throw new UnsupportedOperationException("No execution active, no variables can be set");
}
@Override
public void setTransientVariable(String variableName, Object variableValue) {
throw new UnsupportedOperationException("No execution active, no variables can be set");
}
@Override
public Object getTransientVariableLocal(String variableName) {
return null;
}
@Override
public Map<String, Object> getTransientVariablesLocal() {
return null;
}
@Override | public Object getTransientVariable(String variableName) {
return null;
}
@Override
public Map<String, Object> getTransientVariables() {
return null;
}
@Override
public void removeTransientVariableLocal(String variableName) {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
@Override
public void removeTransientVariablesLocal() {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
@Override
public void removeTransientVariable(String variableName) {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
@Override
public void removeTransientVariables() {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
@Override
public String getTenantId() {
return null;
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\el\NoExecutionVariableScope.java | 2 |
请完成以下Java代码 | public void setDescription (final java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setIsInitiallyClosed (final boolean IsInitiallyClosed)
{
set_Value (COLUMNNAME_IsInitiallyClosed, IsInitiallyClosed);
}
@Override
public boolean isInitiallyClosed()
{
return get_ValueAsBoolean(COLUMNNAME_IsInitiallyClosed);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setSectionName (final java.lang.String SectionName)
{
set_Value (COLUMNNAME_SectionName, SectionName);
} | @Override
public java.lang.String getSectionName()
{
return get_ValueAsString(COLUMNNAME_SectionName);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Section.java | 1 |
请完成以下Java代码 | protected void fail(final Throwable e, final Object item)
{
throw AdempiereException.wrapIfNeeded(e);
}
@Override
public void onNewChunkError(final Throwable e, final Object item)
{
fail(e, item);
}
@Override
public void onItemError(final Throwable e, final Object item)
{
fail(e, item);
}
@Override
public void onCompleteChunkError(final Throwable e)
{
final Object item = null;
fail(e, item);
}
@Override
public void afterCompleteChunkError(final Throwable e)
{ | // Nothing to do.
// This method will never be called because "onCompleteChunkError" method already threw exception.
}
@Override
public void onCommitChunkError(final Throwable e)
{
final Object item = null;
fail(e, item);
}
@Override
public void onCancelChunkError(final Throwable e)
{
final Object item = null;
fail(e, item);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\FailTrxItemExceptionHandler.java | 1 |
请完成以下Java代码 | public Object getPersistentState() {
Map<String, Object> persistentState = new HashMap<String, Object>();
persistentState.put("lockOwner", lockOwner);
persistentState.put("lockExpirationTime", lockExpirationTime);
persistentState.put("duedate", duedate);
return persistentState;
}
@Override
public int getRevisionNext() {
return revision + 1;
}
// getters and setters //////////////////////////////////////////////////////
@Override
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
@Override
public int getRevision() {
return revision;
}
@Override
public void setRevision(int revision) {
this.revision = revision;
}
public Date getDuedate() {
return duedate;
}
public void setDuedate(Date duedate) {
this.duedate = duedate;
}
public String getLockOwner() {
return lockOwner;
}
public void setLockOwner(String lockOwner) {
this.lockOwner = lockOwner;
}
public Date getLockExpirationTime() {
return lockExpirationTime;
}
public void setLockExpirationTime(Date lockExpirationTime) {
this.lockExpirationTime = lockExpirationTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public String getProcessInstanceId() {
return processInstanceId;
} | public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public boolean isExclusive() {
return isExclusive;
}
public void setExclusive(boolean isExclusive) {
this.isExclusive = isExclusive;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.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;
AcquirableJobEntity other = (AcquirableJobEntity) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", revision=" + revision
+ ", lockOwner=" + lockOwner
+ ", lockExpirationTime=" + lockExpirationTime
+ ", duedate=" + duedate
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", processInstanceId=" + processInstanceId
+ ", isExclusive=" + isExclusive
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AcquirableJobEntity.java | 1 |
请完成以下Java代码 | public static void main(String[] args) {
applicationContext = SpringApplication.run(SpringBootApplication.class, args);
}
@Bean
public ExecutorService executorService() {
return Executors.newFixedThreadPool(10);
}
@Bean
public HelloWorldServlet helloWorldServlet() {
return new HelloWorldServlet();
}
@Bean
public SpringHelloServletRegistrationBean servletRegistrationBean() {
SpringHelloServletRegistrationBean bean = new SpringHelloServletRegistrationBean(new SpringHelloWorldServlet(), "/springHelloWorld/*"); | bean.setLoadOnStartup(1);
bean.addInitParameter("message", "SpringHelloWorldServlet special message");
return bean;
}
@Bean
@Autowired
public ExecutorServiceExitCodeGenerator executorServiceExitCodeGenerator(ExecutorService executorService) {
return new ExecutorServiceExitCodeGenerator(executorService);
}
public void shutDown(ExecutorServiceExitCodeGenerator executorServiceExitCodeGenerator) {
SpringApplication.exit(applicationContext, executorServiceExitCodeGenerator);
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-mvc-4\src\main\java\com\baeldung\main\SpringBootApplication.java | 1 |
请完成以下Java代码 | 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_ValueNoCheck (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Service date.
@param ServiceDate
Date service was provided
*/
public void setServiceDate (Timestamp ServiceDate)
{
set_ValueNoCheck (COLUMNNAME_ServiceDate, ServiceDate);
}
/** Get Service date.
@return Date service was provided
*/ | public Timestamp getServiceDate ()
{
return (Timestamp)get_Value(COLUMNNAME_ServiceDate);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getServiceDate()));
}
/** Set Quantity Provided.
@param ServiceLevelProvided
Quantity of service or product provided
*/
public void setServiceLevelProvided (BigDecimal ServiceLevelProvided)
{
set_ValueNoCheck (COLUMNNAME_ServiceLevelProvided, ServiceLevelProvided);
}
/** Get Quantity Provided.
@return Quantity of service or product provided
*/
public BigDecimal getServiceLevelProvided ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ServiceLevelProvided);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ServiceLevelLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class InvoiceLinePriceAndDiscount
{
public static InvoiceLinePriceAndDiscount of(@NonNull final I_C_InvoiceLine invoiceLine, @NonNull final CurrencyPrecision precision)
{
return builder()
.precision(precision)
.priceEntered(invoiceLine.getPriceEntered())
.priceActual(invoiceLine.getPriceActual())
.discount(Percent.of(invoiceLine.getDiscount()))
.build();
}
private static final Logger logger = LogManager.getLogger(InvoiceLinePriceAndDiscount.class);
BigDecimal priceEntered;
BigDecimal priceActual;
Percent discount;
CurrencyPrecision precision;
@Builder(toBuilder = true)
private InvoiceLinePriceAndDiscount(
@Nullable final BigDecimal priceEntered,
@Nullable final BigDecimal priceActual,
@Nullable final Percent discount,
@Nullable final CurrencyPrecision precision)
{
this.precision = precision != null ? precision : CurrencyPrecision.ofInt(2);
this.priceEntered = this.precision.round(CoalesceUtil.coalesce(priceEntered, ZERO));
this.priceActual = this.precision.round(CoalesceUtil.coalesce(priceActual, ZERO));
this.discount = CoalesceUtil.coalesce(discount, Percent.ZERO);
}
public InvoiceLinePriceAndDiscount withUpdatedPriceActual()
{
if (priceEntered.signum() == 0)
{
return toBuilder().priceActual(ZERO).build(); | }
final BigDecimal priceActual = discount.subtractFromBase(priceEntered, precision.toInt(), precision.getRoundingMode());
return toBuilder().priceActual(priceActual).build();
}
public InvoiceLinePriceAndDiscount withUpdatedPriceEntered()
{
if (priceActual.signum() == 0)
{
return toBuilder().priceEntered(ZERO).build();
}
final BigDecimal priceEntered = discount.addToBase(priceActual, precision.toInt(), precision.getRoundingMode());
return toBuilder().priceEntered(priceEntered).build();
}
public InvoiceLinePriceAndDiscount withUpdatedDiscount()
{
if (priceEntered.signum() == 0)
{
return toBuilder().discount(Percent.ZERO).build();
}
final BigDecimal delta = priceEntered.subtract(priceActual);
final Percent discount = Percent.of(delta, priceEntered, precision.toInt());
return toBuilder().discount(discount).build();
}
public void applyTo(@NonNull final I_C_InvoiceLine invoiceLine)
{
logger.debug("Applying {} to {}", this, invoiceLine);
invoiceLine.setPriceEntered(priceEntered);
invoiceLine.setDiscount(discount.toBigDecimal());
invoiceLine.setPriceActual(priceActual);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\service\impl\InvoiceLinePriceAndDiscount.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getArea() {
return area;
}
}
public class AdvancedArticle {
private UUID id;
private String title;
private String content;
@AllowedTypes({ Timestamp.class, Date.class })
private Object createdAt;
private Area area;
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
public Object getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Object createdAt) {
this.createdAt = createdAt;
} | public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
} | repos\tutorials-master\json-modules\json-2\src\main\java\com\baeldung\jsonschemageneration\configuration\AdvancedArticle.java | 2 |
请完成以下Java代码 | public void pushUp()
{
// nothing
}
@Override
public void pushUpRollback()
{
// nothing
}
@Override
public void pushDown()
{
// nothing
}
@Override
public void saveChangesIfNeeded()
{
// nothing
// NOTE: not throwing UnsupportedOperationException because this storage contains no attributes so it will never have something to change
}
@Override
public void setSaveOnChange(final boolean saveOnChange)
{
// nothing
// NOTE: not throwing UnsupportedOperationException because this storage contains no attributes so it will never have something to change
}
@Override
public IAttributeStorageFactory getAttributeStorageFactory()
{
throw new UnsupportedOperationException();
}
@Nullable
@Override
public UOMType getQtyUOMTypeOrNull()
{
// no UOMType available
return null;
}
@Override
public String toString()
{
return "NullAttributeStorage []";
}
@Override
public BigDecimal getStorageQtyOrZERO() | {
// no storage quantity available; assume ZERO
return BigDecimal.ZERO;
}
/**
* @return <code>false</code>.
*/
@Override
public boolean isVirtual()
{
return false;
}
@Override
public boolean isNew(final I_M_Attribute attribute)
{
throw new AttributeNotFoundException(attribute, this);
}
/**
* @return true, i.e. never disposed
*/
@Override
public boolean assertNotDisposed()
{
return true; // not disposed
}
@Override
public boolean assertNotDisposedTree()
{
return true; // not disposed
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\NullAttributeStorage.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BatchResponse {
protected String id;
protected String url;
protected String batchType;
protected String searchKey;
protected String searchKey2;
@JsonSerialize(using = DateToStringSerializer.class, as = Date.class)
protected Date createTime;
@JsonSerialize(using = DateToStringSerializer.class, as = Date.class)
protected Date completeTime;
protected String status;
protected String tenantId;
@ApiModelProperty(example = "8")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@ApiModelProperty(example = "http://localhost:8182/management/batches/8")
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@ApiModelProperty(example = "processMigration")
public String getBatchType() {
return batchType;
}
public void setBatchType(String batchType) {
this.batchType = batchType;
}
@ApiModelProperty(example = "1:22:MP")
public String getSearchKey() {
return searchKey;
}
public void setSearchKey(String searchKey) {
this.searchKey = searchKey;
}
@ApiModelProperty(example = "1:24:MP")
public String getSearchKey2() {
return searchKey2;
}
public void setSearchKey2(String searchKey2) {
this.searchKey2 = searchKey2;
}
@ApiModelProperty(example = "2020-06-03T22:05:05.474+0000")
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime; | }
@ApiModelProperty(example = "2020-06-03T22:05:05.474+0000")
public Date getCompleteTime() {
return completeTime;
}
public void setCompleteTime(Date completeTime) {
this.completeTime = completeTime;
}
@ApiModelProperty(example = "completed")
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\management\BatchResponse.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class JsonResponsePaymentTerm
{
public static final String METASFRESH_ID = "metasfreshId";
public static final String NAME = "name";
public static final String VALUE = "value";
@ApiModelProperty( //
required = true, //
dataType = "java.lang.Integer", //
value = "This translates to `C_PaymentTerm.C_PaymentTerm_ID`.")
@JsonProperty(METASFRESH_ID)
@JsonInclude(JsonInclude.Include.NON_NULL)
JsonMetasfreshId metasfreshId;
@ApiModelProperty( value = "This translates to `C_PaymentTerm.Name`.")
@JsonProperty(NAME)
String name; | @ApiModelProperty( value = "This translates to `C_PaymentTerm.Value`.")
@JsonProperty(VALUE)
String value;
@JsonCreator
@Builder(toBuilder = true)
private JsonResponsePaymentTerm(
@JsonProperty(METASFRESH_ID) @NonNull final JsonMetasfreshId metasfreshId,
@JsonProperty(NAME) @NonNull final String name,
@JsonProperty(VALUE) @NonNull final String value)
{
this.metasfreshId = metasfreshId;
this.name = name;
this.value = value;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\response\JsonResponsePaymentTerm.java | 2 |
请完成以下Java代码 | public class Dimension2DImpl extends Dimension2D
{
/**
* Constructor 0/0
*/
public Dimension2DImpl()
{
} // Dimension2DImpl
/**
* Constructor 0/0
* @param dim dimension
*/
public Dimension2DImpl(Dimension dim)
{
setSize (dim);
} // Dimension2DImpl
/**
* Constructor 0/0
* @param Width width
* @param Height height
*/
public Dimension2DImpl(double Width, double Height)
{
setSize (Width, Height);
} // Dimension2DImpl
/** Width */
public double width = 0;
/** Height */
public double height = 0;
/**
* Set Size
* @param Width width
* @param Height height
*/
public void setSize (double Width, double Height)
{
this.width = Width;
this.height = Height;
} // setSize
/**
* Set Size
* @param dim dimension
*/
public void setSize (Dimension dim)
{
this.width = dim.getWidth();
this.height = dim.getHeight();
} // setSize
/**
* Add Size below existing
* @param dWidth width to increase if below
* @param dHeight height to add
*/
public void addBelow (double dWidth, double dHeight)
{
if (this.width < dWidth)
this.width = dWidth;
this.height += dHeight;
} // addBelow
/**
* Add Size below existing
* @param dim add dimension
*/
public void addBelow (Dimension dim)
{
addBelow (dim.width, dim.height);
} // addBelow
/**
* Round to next Int value
*/
public void roundUp()
{
width = Math.ceil(width);
height = Math.ceil(height);
} // roundUp
/**
* Get Width
* @return width
*/ | public double getWidth()
{
return width;
} // getWidth
/**
* Get Height
* @return height
*/
public double getHeight()
{
return height;
} // getHeight
/*************************************************************************/
/**
* Hash Code
* @return hash code
*/
public int hashCode()
{
long bits = Double.doubleToLongBits(width);
bits ^= Double.doubleToLongBits(height) * 31;
return (((int) bits) ^ ((int) (bits >> 32)));
} // hashCode
/**
* Equals
* @param obj object
* @return true if w/h is same
*/
public boolean equals (Object obj)
{
if (obj != null && obj instanceof Dimension2D)
{
Dimension2D d = (Dimension2D)obj;
if (d.getWidth() == width && d.getHeight() == height)
return true;
}
return false;
} // equals
/**
* String Representation
* @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append("Dimension2D[w=").append(width).append(",h=").append(height).append("]");
return sb.toString();
} // toString
} // Dimension2DImpl | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\Dimension2DImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private synchronized void commit()
{
final List<ItemState> itemsToCommit = new ArrayList<>(items.values());
for (final ItemState item : itemsToCommit)
{
item.commit();
}
items.clear();
}
private synchronized void rollback()
{
items.clear();
}
/**
* Gets the current state for given transactional item.
*
* @param item
* @return current stateș never returns null.
*/
public synchronized PackingItem getState(final TransactionalPackingItem item)
{
final long id = item.getId();
ItemState itemState = items.get(id);
if (itemState == null)
{
itemState = new ItemState(item);
items.put(id, itemState);
}
return itemState.getState();
}
/**
* Transactional item state holder.
*
* @author metas-dev <dev@metasfresh.com>
*
*/
private static final class ItemState | {
private final Reference<TransactionalPackingItem> transactionalItemRef;
private final PackingItem state;
public ItemState(final TransactionalPackingItem transactionalItem)
{
super();
// NOTE: we keep a weak reference to our transactional item
// because in case nobody is referencing it, there is no point to update on commit.
this.transactionalItemRef = new WeakReference<>(transactionalItem);
state = transactionalItem.createNewState();
}
public PackingItem getState()
{
return state;
}
public void commit()
{
final TransactionalPackingItem transactionalItem = transactionalItemRef.get();
if (transactionalItem == null)
{
// reference already expired
return;
}
transactionalItem.commit(state);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\TransactionalPackingItemSupport.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getUri() {
return this.uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public boolean isCompressed() {
return this.compressed;
}
public void setCompressed(boolean compressed) {
this.compressed = compressed;
}
public boolean isAutoCreateDb() {
return this.autoCreateDb;
}
public void setAutoCreateDb(boolean autoCreateDb) {
this.autoCreateDb = autoCreateDb;
}
public @Nullable InfluxApiVersion getApiVersion() {
return this.apiVersion;
}
public void setApiVersion(@Nullable InfluxApiVersion apiVersion) {
this.apiVersion = apiVersion;
}
public @Nullable String getOrg() {
return this.org;
}
public void setOrg(@Nullable String org) { | this.org = org;
}
public @Nullable String getBucket() {
return this.bucket;
}
public void setBucket(@Nullable String bucket) {
this.bucket = bucket;
}
public @Nullable String getToken() {
return this.token;
}
public void setToken(@Nullable String token) {
this.token = token;
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\influx\InfluxProperties.java | 2 |
请完成以下Java代码 | public I_CM_Chat getCM_Chat() throws RuntimeException
{
return (I_CM_Chat)MTable.get(getCtx(), I_CM_Chat.Table_Name)
.getPO(getCM_Chat_ID(), get_TrxName()); }
/** Set Chat.
@param CM_Chat_ID
Chat or discussion thread
*/
public void setCM_Chat_ID (int CM_Chat_ID)
{
if (CM_Chat_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_Chat_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CM_Chat_ID, Integer.valueOf(CM_Chat_ID));
}
/** Get Chat.
@return Chat or discussion thread
*/
public int getCM_Chat_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_Chat_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Self-Service. | @param IsSelfService
This is a Self-Service entry or this entry can be changed via Self-Service
*/
public void setIsSelfService (boolean IsSelfService)
{
set_Value (COLUMNNAME_IsSelfService, Boolean.valueOf(IsSelfService));
}
/** Get Self-Service.
@return This is a Self-Service entry or this entry can be changed via Self-Service
*/
public boolean isSelfService ()
{
Object oo = get_Value(COLUMNNAME_IsSelfService);
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_CM_ChatUpdate.java | 1 |
请完成以下Java代码 | public void afterCompletion(int status) {
if (TransactionSynchronization.STATUS_ROLLED_BACK == status) {
transactionListener.execute(commandContext);
}
}
}
);
}
}
protected abstract class TransactionSynchronizationAdapter implements TransactionSynchronization, Ordered {
public void suspend() {}
public void resume() {} | public void flush() {}
public void beforeCommit(boolean readOnly) {}
public void beforeCompletion() {}
public void afterCommit() {}
public void afterCompletion(int status) {}
@Override
public int getOrder() {
return transactionSynchronizationAdapterOrder;
}
}
} | repos\Activiti-develop\activiti-core\activiti-spring\src\main\java\org\activiti\spring\SpringTransactionContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AppManagement implements MachineDiscovery {
@Autowired
private ApplicationContext context;
private MachineDiscovery machineDiscovery;
@PostConstruct
public void init() {
machineDiscovery = context.getBean(SimpleMachineDiscovery.class);
}
@Override
public Set<AppInfo> getBriefApps() {
return machineDiscovery.getBriefApps();
}
@Override
public long addMachine(MachineInfo machineInfo) {
return machineDiscovery.addMachine(machineInfo);
}
@Override
public boolean removeMachine(String app, String ip, int port) {
return machineDiscovery.removeMachine(app, ip, port);
} | @Override
public List<String> getAppNames() {
return machineDiscovery.getAppNames();
}
@Override
public AppInfo getDetailApp(String app) {
return machineDiscovery.getDetailApp(app);
}
@Override
public void removeApp(String app) {
machineDiscovery.removeApp(app);
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\discovery\AppManagement.java | 2 |
请完成以下Java代码 | public void addEventDefinition(EventDefinition eventDefinition) {
eventDefinitions.add(eventDefinition);
}
@Override
public List<IOParameter> getInParameters() {
return inParameters;
}
@Override
public void addInParameter(IOParameter inParameter) {
inParameters.add(inParameter);
}
@Override
public void setInParameters(List<IOParameter> inParameters) {
this.inParameters = inParameters;
}
@Override
public List<IOParameter> getOutParameters() {
return outParameters;
}
@Override
public void addOutParameter(IOParameter outParameter) {
this.outParameters.add(outParameter);
}
@Override
public void setOutParameters(List<IOParameter> outParameters) {
this.outParameters = outParameters;
}
public void setValues(Event otherEvent) { | super.setValues(otherEvent);
eventDefinitions = new ArrayList<>();
if (otherEvent.getEventDefinitions() != null && !otherEvent.getEventDefinitions().isEmpty()) {
for (EventDefinition eventDef : otherEvent.getEventDefinitions()) {
eventDefinitions.add(eventDef.clone());
}
}
inParameters = new ArrayList<>();
if (otherEvent.getInParameters() != null && !otherEvent.getInParameters().isEmpty()) {
for (IOParameter parameter : otherEvent.getInParameters()) {
inParameters.add(parameter.clone());
}
}
outParameters = new ArrayList<>();
if (otherEvent.getOutParameters() != null && !otherEvent.getOutParameters().isEmpty()) {
for (IOParameter parameter : otherEvent.getOutParameters()) {
outParameters.add(parameter.clone());
}
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\Event.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DefaultHealthService implements HealthService {
@Autowired
private GeoLocationService geoLocationService;
@Autowired
private FaunaClients faunaClients;
@Override
public void process(HealthData healthData) throws MalformedURLException, InterruptedException, ExecutionException {
String region = geoLocationService.getRegion( //
healthData.latitude(), //
healthData.longitude());
FaunaClient faunaClient = faunaClients.getFaunaClient(region); | Value queryResponse = faunaClient.query(
Create(Collection("healthdata"),
Obj("data",
Obj(Map.of(
"userId", Value(healthData.userId()),
"temperature", Value(healthData.temperature()),
"pulseRate", Value(healthData.pulseRate()),
"bpSystolic", Value(healthData.bpSystolic()),
"bpDiastolic", Value(healthData.bpDiastolic()),
"latitude", Value(healthData.latitude()),
"longitude", Value(healthData.longitude()),
"timestamp", Now()))))
).get();
log.info("Query response received from Fauna: {}", queryResponse);
}
} | repos\tutorials-master\persistence-modules\fauna\src\main\java\com\baeldung\healthapp\service\DefaultHealthService.java | 2 |
请完成以下Java代码 | public int getC_DocType_ID()
{
return get_ValueAsInt(COLUMNNAME_C_DocType_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setFeePercentageOfGrandTotal (final BigDecimal FeePercentageOfGrandTotal)
{
set_Value (COLUMNNAME_FeePercentageOfGrandTotal, FeePercentageOfGrandTotal);
}
@Override
public BigDecimal getFeePercentageOfGrandTotal()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_FeePercentageOfGrandTotal);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setInvoiceProcessingServiceCompany_BPartnerAssignment_ID (final int InvoiceProcessingServiceCompany_BPartnerAssignment_ID)
{
if (InvoiceProcessingServiceCompany_BPartnerAssignment_ID < 1)
set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_BPartnerAssignment_ID, null);
else | set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_BPartnerAssignment_ID, InvoiceProcessingServiceCompany_BPartnerAssignment_ID);
}
@Override
public int getInvoiceProcessingServiceCompany_BPartnerAssignment_ID()
{
return get_ValueAsInt(COLUMNNAME_InvoiceProcessingServiceCompany_BPartnerAssignment_ID);
}
@Override
public org.compiere.model.I_InvoiceProcessingServiceCompany getInvoiceProcessingServiceCompany()
{
return get_ValueAsPO(COLUMNNAME_InvoiceProcessingServiceCompany_ID, org.compiere.model.I_InvoiceProcessingServiceCompany.class);
}
@Override
public void setInvoiceProcessingServiceCompany(final org.compiere.model.I_InvoiceProcessingServiceCompany InvoiceProcessingServiceCompany)
{
set_ValueFromPO(COLUMNNAME_InvoiceProcessingServiceCompany_ID, org.compiere.model.I_InvoiceProcessingServiceCompany.class, InvoiceProcessingServiceCompany);
}
@Override
public void setInvoiceProcessingServiceCompany_ID (final int InvoiceProcessingServiceCompany_ID)
{
if (InvoiceProcessingServiceCompany_ID < 1)
set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_ID, null);
else
set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_ID, InvoiceProcessingServiceCompany_ID);
}
@Override
public int getInvoiceProcessingServiceCompany_ID()
{
return get_ValueAsInt(COLUMNNAME_InvoiceProcessingServiceCompany_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_InvoiceProcessingServiceCompany_BPartnerAssignment.java | 1 |
请完成以下Java代码 | public List<HistoricDecisionInstance> getHistoricDecisionInstances(Date evaluatedAfter,
Date evaluatedAt,
int maxResults) {
checkIsAuthorizedToReadHistoryAndTenants();
Map<String, Object> params = new HashMap<>();
params.put("evaluatedAfter", evaluatedAfter);
params.put("evaluatedAt", evaluatedAt);
params.put("maxResults", maxResults);
List<HistoricDecisionInstance> decisionInstances =
getDbEntityManager().selectList("selectHistoricDecisionInstancePage", params);
HistoricDecisionInstanceQueryImpl query =
(HistoricDecisionInstanceQueryImpl) new HistoricDecisionInstanceQueryImpl()
.disableBinaryFetching()
.disableCustomObjectDeserialization()
.includeInputs()
.includeOutputs();
List<List<HistoricDecisionInstance>> partitions = CollectionUtil.partition(decisionInstances, DbSqlSessionFactory.MAXIMUM_NUMBER_PARAMS);
for (List<HistoricDecisionInstance> partition : partitions) { | getHistoricDecisionInstanceManager()
.enrichHistoricDecisionsWithInputsAndOutputs(query, partition);
}
return decisionInstances;
}
private void checkIsAuthorizedToReadHistoryAndTenants() {
CompositePermissionCheck necessaryPermissionsForOptimize = new PermissionCheckBuilder()
.conjunctive()
.atomicCheckForResourceId(PROCESS_DEFINITION, ANY, READ_HISTORY)
.atomicCheckForResourceId(DECISION_DEFINITION, ANY, READ_HISTORY)
.atomicCheckForResourceId(TENANT, ANY, READ)
.build();
getAuthorizationManager().checkAuthorization(necessaryPermissionsForOptimize);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\optimize\OptimizeManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class JsonbHttpMessageConvertersConfiguration {
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(Jsonb.class)
@Conditional(PreferJsonbOrMissingJacksonAndGsonCondition.class)
static class JsonbHttpMessageConverterConfiguration {
@Bean
@ConditionalOnMissingBean(JsonbHttpMessageConverter.class)
JsonbHttpMessageConvertersCustomizer jsonbHttpMessageConvertersCustomizer(Jsonb jsonb) {
return new JsonbHttpMessageConvertersCustomizer(jsonb);
}
}
static class JsonbHttpMessageConvertersCustomizer
implements ClientHttpMessageConvertersCustomizer, ServerHttpMessageConvertersCustomizer {
private final JsonbHttpMessageConverter converter;
JsonbHttpMessageConvertersCustomizer(Jsonb jsonb) {
this.converter = new JsonbHttpMessageConverter(jsonb);
}
@Override
public void customize(ClientBuilder builder) {
builder.withJsonConverter(this.converter);
}
@Override
public void customize(ServerBuilder builder) {
builder.withJsonConverter(this.converter);
}
} | private static class PreferJsonbOrMissingJacksonAndGsonCondition extends AnyNestedCondition {
PreferJsonbOrMissingJacksonAndGsonCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY,
havingValue = "jsonb")
static class JsonbPreferred {
}
@SuppressWarnings("removal")
@ConditionalOnMissingBean({ JacksonJsonHttpMessageConvertersCustomizer.class,
Jackson2HttpMessageConvertersConfiguration.Jackson2JsonMessageConvertersCustomizer.class,
GsonHttpConvertersCustomizer.class })
static class JacksonAndGsonMissing {
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-http-converter\src\main\java\org\springframework\boot\http\converter\autoconfigure\JsonbHttpMessageConvertersConfiguration.java | 2 |
请完成以下Java代码 | public boolean hasProcessDefinitionIdOrKey() {
return this.getProcessDefinitionId() != null || this.getProcessDefinitionKey() != null;
}
public ProcessInstance start() {
return runtimeService.startProcessInstance(this);
}
public ProcessInstance create() {
return runtimeService.createProcessInstance(this);
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getMessageName() {
return messageName;
}
public String getProcessInstanceName() {
return processInstanceName; | }
public String getBusinessKey() {
return businessKey;
}
public String getLinkedProcessInstanceId() {
return linkedProcessInstanceId;
}
public String getLinkedProcessInstanceType() {
return linkedProcessInstanceType;
}
public String getTenantId() {
return tenantId;
}
public Map<String, Object> getVariables() {
return variables;
}
public Map<String, Object> getTransientVariables() {
return transientVariables;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\runtime\ProcessInstanceBuilderImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DDOrderQuery
{
@NonNull ImmutableList<OrderBy> orderBys;
@Nullable DocStatus docStatus;
@NonNull @Builder.Default ValueRestriction<UserId> responsibleId = ValueRestriction.any();
@Nullable Set<WarehouseId> warehouseFromIds;
@Nullable InSetPredicate<WarehouseId> warehouseToIds;
@Nullable InSetPredicate<LocatorId> locatorToIds;
@Nullable Set<OrderId> salesOrderIds;
@Nullable Set<PPOrderId> manufacturingOrderIds;
@Nullable Set<LocalDate> datesPromised;
@Nullable Set<ProductId> productIds;
@Nullable Set<Quantity> qtysEntered;
@Nullable Set<ResourceId> plantIds;
@Nullable Set<DDOrderId> onlyDDOrderIds;
//
// | //
@Value(staticConstructor = "of")
public static class OrderBy
{
@NonNull OrderByField field;
@NonNull Direction direction;
}
public enum OrderByField
{
PriorityRule,
DatePromised,
SeqNo,
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddorder\DDOrderQuery.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal getOrderAmount() {
return orderAmount;
}
public void setOrderAmount(BigDecimal orderAmount) {
this.orderAmount = orderAmount;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getMerchantName() {
return merchantName;
}
public void setMerchantName(String merchantName) {
this.merchantName = merchantName;
}
public String getMerchantNo() {
return merchantNo;
}
public void setMerchantNo(String merchantNo) {
this.merchantNo = merchantNo;
}
public String getMerchantOrderNo() {
return merchantOrderNo;
}
public void setMerchantOrderNo(String merchantOrderNo) {
this.merchantOrderNo = merchantOrderNo;
}
public String getPayKey() {
return payKey;
}
public void setPayKey(String payKey) {
this.payKey = payKey;
} | public TradeStatusEnum getTradeStatus() {
return tradeStatus;
}
public void setTradeStatus(TradeStatusEnum tradeStatus) {
this.tradeStatus = tradeStatus;
}
public boolean isAuth() {
return isAuth;
}
public void setAuth(boolean auth) {
isAuth = auth;
}
public Map<String, PayTypeEnum> getPayTypeEnumMap() {
return payTypeEnumMap;
}
public void setPayTypeEnumMap(Map<String, PayTypeEnum> payTypeEnumMap) {
this.payTypeEnumMap = payTypeEnumMap;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\AuthInitResultVo.java | 2 |
请完成以下Java代码 | static private class TransactionContext
{
int locatorId;
@NonNull ProductId productId;
@NonNull String movementType;
@NonNull LocalDate movementDate;
}
private ImmutableSet<Integer> retrieveLocatorIds()
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final IQueryBuilder<I_M_Transaction> queryBuilder = queryBL.createQueryBuilder(I_M_Transaction.class)
.addOnlyActiveRecordsFilter();
if (minimumPrice.signum() < 0)
{
final Set<ProductId> productIds = Services.get(IPriceListDAO.class).retrieveHighPriceProducts(getMinimumPrice(), getMovementDate());
if (!productIds.isEmpty())
{
queryBuilder.addInArrayFilter(I_M_Transaction.COLUMNNAME_M_Product_ID, productIds);
}
}
final ImmutableSetMultimap<Integer, ProductId> productsByLocatorIds = queryBuilder
.create()
.listDistinct(I_M_Transaction.COLUMNNAME_M_Locator_ID, I_M_Transaction.COLUMNNAME_M_Product_ID,
I_M_Transaction.COLUMNNAME_MovementDate, I_M_Transaction.COLUMNNAME_MovementType)
.stream()
.map(record -> {
return TransactionContext.builder()
.locatorId((int)record.get(I_M_Locator.COLUMNNAME_M_Locator_ID))
.productId(ProductId.ofRepoId((int)record.get(I_M_Product.COLUMNNAME_M_Product_ID)))
.movementType((String)record.get(I_M_Transaction.COLUMNNAME_MovementType))
.movementDate(TimeUtil.asLocalDate(record.get(I_M_Transaction.COLUMNNAME_MovementDate))) | .build();
})
.sorted(TRANSACTIONS_COMPARATOR)
.map(transaction -> {
return GuavaCollectors.entry(transaction.getLocatorId(), transaction.getProductId());
}).collect(GuavaCollectors.toImmutableSetMultimap());
return productsByLocatorIds.keySet();
}
private WarehouseId mapToWarehouseId(final int locatorId)
{
final I_M_Locator locator = InterfaceWrapperHelper.load(locatorId, I_M_Locator.class);
return WarehouseId.ofRepoId(locator.getM_Warehouse_ID());
}
@Override
public int getMaxLocatorsAllowed()
{
return maxLocators;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\draftlinescreator\LeastRecentTransactionStrategy.java | 1 |
请完成以下Java代码 | private synchronized void updateFromRepository()
{
final ImmutableSet<AdTableId> tableIdsPrev = this.tableIds;
this.tableIds = configRepository.getDistinctConfigTableIds();
if (Objects.equals(this.tableIds, tableIdsPrev))
{
return;
}
updateRegisteredInterceptors();
}
private synchronized void updateRegisteredInterceptors()
{
final HashSet<AdTableId> registeredTableIdsNoLongerNeeded = new HashSet<>(this.registeredTableIds);
for (final AdTableId tableId : this.tableIds)
{
registeredTableIdsNoLongerNeeded.remove(tableId);
if (registeredTableIds.contains(tableId))
{
// already registered
continue;
}
registerOutboundProducer(tableId);
}
//
// Remove no longer necessary interceptors
for (final AdTableId tableId : registeredTableIdsNoLongerNeeded)
{
unregisterOutboundProducer(tableId); | }
}
private void registerOutboundProducer(@NonNull final AdTableId tableId)
{
final ModelValidationEngine engine = Check.assumeNotNull(this.engine, "engine not null");
producerService.registerProducer(new DocOutboundProducerValidator(engine, tableId));
registeredTableIds.add(tableId);
logger.info("Registered producer for {}", tableId);
}
private void unregisterOutboundProducer(@NonNull final AdTableId tableId)
{
producerService.unregisterProducerByTableId(tableId);
registeredTableIds.remove(tableId);
logger.info("Unregistered trigger for {}", tableId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\interceptor\C_Doc_Outbound_Config.java | 1 |
请完成以下Java代码 | public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setM_Allergen_Trace_ID (final int M_Allergen_Trace_ID)
{
if (M_Allergen_Trace_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Allergen_Trace_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Allergen_Trace_ID, M_Allergen_Trace_ID);
} | @Override
public int getM_Allergen_Trace_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Allergen_Trace_ID);
}
@Override
public void setName (final @Nullable java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Allergen_Trace.java | 1 |
请完成以下Java代码 | public void starting() {
System.out.println("HelloApplicationRunListener starting......");
}
@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
}
@Override
public void contextPrepared(ConfigurableApplicationContext context) {
}
@Override
public void contextLoaded(ConfigurableApplicationContext context) {
} | @Override
public void started(ConfigurableApplicationContext context) {
}
@Override
public void running(ConfigurableApplicationContext context) {
}
@Override
public void failed(ConfigurableApplicationContext context, Throwable exception) {
}
} | repos\SpringAll-master\45.Spring-Boot-SpringApplication\src\main\java\com\example\demo\listener\HelloApplicationRunListener.java | 1 |
请完成以下Java代码 | public String getuId() {
return uId;
}
public void setuId(String uId) {
this.uId = uId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAlias() { | return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public void generateMyUser() {
this.setAlias("007");
this.setFirstName("James");
this.setLastName("Bond");
this.setuId("JB");
}
@Override
public int hashCode() {
return Objects.hash(firstName, uId, lastName, alias);
}
} | repos\tutorials-master\libraries-data-3\src\main\java\com\baeldung\objecthydration\User.java | 1 |
请完成以下Java代码 | public boolean isPageBreak(final int row, final int col)
{
return false;
}
private interface RowsSupplier
{
IViewRow getRow(int rowIndex);
int getRowCount();
}
private static class AllRowsSupplier implements RowsSupplier
{
private final int pageSize;
private final IView view;
private final JSONOptions jsonOpts;
private final LoadingCache<PageIndex, ViewResult> cache = CacheBuilder.newBuilder()
.maximumSize(2) // cache max 2 pages
.build(new CacheLoader<PageIndex, ViewResult>()
{
@Override
public ViewResult load(@NotNull final PageIndex pageIndex)
{
final ViewRowsOrderBy orderBys = ViewRowsOrderBy.empty(jsonOpts); // default
return view.getPage(pageIndex.getFirstRow(), pageIndex.getPageLength(), orderBys);
}
});
private AllRowsSupplier(
@NonNull final IView view,
final int pageSize,
@NonNull final JSONOptions jsonOpts)
{
this.view = view;
this.pageSize = pageSize;
this.jsonOpts = jsonOpts;
}
private ViewResult getPage(final PageIndex pageIndex)
{
try
{
return cache.get(pageIndex);
}
catch (final ExecutionException e)
{
throw AdempiereException.wrapIfNeeded(e);
}
}
@Override
@Nullable
public IViewRow getRow(final int rowIndex)
{
final ViewResult page = getPage(PageIndex.getPageContainingRow(rowIndex, pageSize));
final int rowIndexInPage = rowIndex - page.getFirstRow();
if (rowIndexInPage < 0)
{
// shall not happen
return null;
}
final List<IViewRow> rows = page.getPage();
if (rowIndexInPage >= rows.size())
{
return null;
}
return rows.get(rowIndexInPage);
}
@Override
public int getRowCount()
{
return (int)view.size();
}
}
private static class ListRowsSupplier implements RowsSupplier
{
private final ImmutableList<IViewRow> rows;
private ListRowsSupplier(@NonNull final IView view, @NonNull final DocumentIdsSelection rowIds) | {
Check.assume(!rowIds.isAll(), "rowIds is not ALL");
this.rows = view.streamByIds(rowIds).collect(ImmutableList.toImmutableList());
}
@Override
public IViewRow getRow(final int rowIndex)
{
Check.assume(rowIndex >= 0, "rowIndex >= 0");
final int rowsCount = rows.size();
Check.assume(rowIndex < rowsCount, "rowIndex < {}", rowsCount);
return rows.get(rowIndex);
}
@Override
public int getRowCount()
{
return rows.size();
}
}
@Override
protected List<CellValue> getNextRow()
{
final ArrayList<CellValue> result = new ArrayList<>();
for (int i = 0; i < getColumnCount(); i++)
{
result.add(getValueAt(rowNumber, i));
}
rowNumber++;
return result;
}
@Override
protected boolean hasNextRow()
{
return rowNumber < getRowCount();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewExcelExporter.java | 1 |
请完成以下Java代码 | public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set VariantGroup. | @param VariantGroup VariantGroup */
@Override
public void setVariantGroup (java.lang.String VariantGroup)
{
set_Value (COLUMNNAME_VariantGroup, VariantGroup);
}
/** Get VariantGroup.
@return VariantGroup */
@Override
public java.lang.String getVariantGroup ()
{
return (java.lang.String)get_Value(COLUMNNAME_VariantGroup);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Report.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean isCashJournal(@NonNull final I_C_BankStatementLine bankStatementLine)
{
final BankStatementId bankStatementId = BankStatementId.ofRepoId(bankStatementLine.getC_BankStatement_ID());
final I_C_BankStatement bankStatement = getById(bankStatementId);
final BankAccountId bankAccountId = BankAccountId.ofRepoId(bankStatement.getC_BP_BankAccount_ID());
return bankAccountService.isCashBank(bankAccountId);
}
@Override
public PaymentCurrencyContext getPaymentCurrencyContext(@NonNull final I_C_BankStatementLine bankStatementLine)
{
final PaymentCurrencyContext.PaymentCurrencyContextBuilder result = PaymentCurrencyContext.builder()
.currencyConversionTypeId(null);
final BigDecimal fixedCurrencyRate = bankStatementLine.getCurrencyRate();
if (fixedCurrencyRate != null && fixedCurrencyRate.signum() != 0)
{
final CurrencyId paymentCurrencyId = CurrencyId.ofRepoId(bankStatementLine.getC_Currency_ID());
final ClientAndOrgId clientAndOrgId = ClientAndOrgId.ofClientAndOrg(bankStatementLine.getAD_Client_ID(), bankStatementLine.getAD_Org_ID());
final CurrencyId acctSchemaCurrencyId = moneyService.getBaseCurrencyId(clientAndOrgId);
result.paymentCurrencyId(paymentCurrencyId)
.sourceCurrencyId(acctSchemaCurrencyId)
.currencyRate(fixedCurrencyRate);
}
return result.build();
}
@Override
public void changeCurrencyRate(@NonNull final BankStatementLineId bankStatementLineId, @NonNull final BigDecimal currencyRate)
{
if (currencyRate.signum() == 0)
{
throw new AdempiereException("Invalid currency rate: " + currencyRate);
}
final I_C_BankStatementLine line = getLineById(bankStatementLineId);
final BankStatementId bankStatementId = BankStatementId.ofRepoId(line.getC_BankStatement_ID());
final I_C_BankStatement bankStatement = getById(bankStatementId); | assertBankStatementIsDraftOrInProcessOrCompleted(bankStatement);
final CurrencyId currencyId = CurrencyId.ofRepoId(line.getC_Currency_ID());
final CurrencyId baseCurrencyId = getBaseCurrencyId(line);
if (CurrencyId.equals(currencyId, baseCurrencyId))
{
throw new AdempiereException("line is not in foreign currency");
}
line.setCurrencyRate(currencyRate);
InterfaceWrapperHelper.save(line);
unpost(bankStatement);
}
@Override
public CurrencyId getBaseCurrencyId(final I_C_BankStatementLine line)
{
final ClientAndOrgId clientAndOrgId = ClientAndOrgId.ofClientAndOrg(line.getAD_Client_ID(), line.getAD_Org_ID());
return moneyService.getBaseCurrencyId(clientAndOrgId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\service\impl\BankStatementBL.java | 2 |
请完成以下Java代码 | private static List<User> readUsers(Resource resource) throws Exception {
Scanner scanner = new Scanner(resource.getInputStream());
String line = scanner.nextLine();
scanner.close();
DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
tokenizer.setNames(line.split(","));
tokenizer.setStrict(false);
DefaultLineMapper<User> lineMapper = new DefaultLineMapper<User>();
lineMapper.setFieldSetMapper(fields -> {
User user = new User();
user.setEmail(fields.readString("email"));
user.setFirstname(capitalize(fields.readString("first")));
user.setLastname(capitalize(fields.readString("last")));
user.setNationality(fields.readString("nationality"));
String city = Arrays.stream(fields.readString("city").split(" "))//
.map(StringUtils::capitalize)//
.collect(Collectors.joining(" "));
String street = Arrays.stream(fields.readString("street").split(" "))//
.map(StringUtils::capitalize)//
.collect(Collectors.joining(" "));
try {
user.setAddress(new Address(city, street, fields.readString("zip")));
} catch (IllegalArgumentException e) {
user.setAddress(new Address(city, street, fields.readString("postcode")));
}
user.setPicture(
new Picture(fields.readString("large"), fields.readString("medium"), fields.readString("thumbnail")));
user.setUsername(fields.readString("username"));
user.setPassword(fields.readString("password"));
return user;
});
lineMapper.setLineTokenizer(tokenizer);
FlatFileItemReader<User> reader = new FlatFileItemReader<User>(lineMapper);
reader.setResource(resource); | reader.setRecordSeparatorPolicy(new DefaultRecordSeparatorPolicy());
reader.setLinesToSkip(1);
reader.open(new ExecutionContext());
List<User> users = new ArrayList<>();
User user = null;
do {
user = reader.read();
if (user != null) {
users.add(user);
}
} while (user != null);
return users;
}
} | repos\spring-data-examples-main\web\querydsl\src\main\java\example\users\UserInitializer.java | 1 |
请完成以下Java代码 | public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Rating.
@param Rating
Classification or Importance
*/
public void setRating (int Rating)
{
set_Value (COLUMNNAME_Rating, Integer.valueOf(Rating));
}
/** Get Rating.
@return Classification or Importance
*/
public int getRating ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Rating);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
} | /** 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_K_Entry.java | 1 |
请完成以下Java代码 | public String getName() {
return name.get();
}
public StringProperty nameProperty() {
return name;
}
public void setName(String name) {
this.name.set(name);
}
public boolean getIsEmployed() {
return isEmployed.get();
}
public BooleanProperty isEmployedProperty() { | return isEmployed;
}
public void setIsEmployed(boolean isEmployed) {
this.isEmployed.set(isEmployed);
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", isEmployed=" + isEmployed +
'}';
}
} | repos\tutorials-master\javafx\src\main\java\com\baeldung\model\Person.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public JSONObject updateRole(JSONObject jsonObject) {
String roleId = jsonObject.getString("roleId");
List<Integer> newPerms = (List<Integer>) jsonObject.get("permissions");
JSONObject roleInfo = userDao.getRoleAllInfo(jsonObject);
Set<Integer> oldPerms = (Set<Integer>) roleInfo.get("permissionIds");
//修改角色名称
updateRoleName(jsonObject, roleInfo);
//添加新权限
saveNewPermission(roleId, newPerms, oldPerms);
//移除旧的不再拥有的权限
removeOldPermission(roleId, newPerms, oldPerms);
return CommonUtil.successJson();
}
/**
* 修改角色名称
*/
private void updateRoleName(JSONObject paramJson, JSONObject roleInfo) {
String roleName = paramJson.getString("roleName");
if (!roleName.equals(roleInfo.getString("roleName"))) {
userDao.updateRoleName(paramJson);
}
}
/**
* 为角色添加新权限
*/
private void saveNewPermission(String roleId, Collection<Integer> newPerms, Collection<Integer> oldPerms) {
List<Integer> waitInsert = new ArrayList<>();
for (Integer newPerm : newPerms) {
if (!oldPerms.contains(newPerm)) {
waitInsert.add(newPerm);
}
}
if (waitInsert.size() > 0) {
userDao.insertRolePermission(roleId, waitInsert);
}
}
/**
* 删除角色 旧的 不再拥有的权限
*/
private void removeOldPermission(String roleId, Collection<Integer> newPerms, Collection<Integer> oldPerms) {
List<Integer> waitRemove = new ArrayList<>();
for (Integer oldPerm : oldPerms) {
if (!newPerms.contains(oldPerm)) {
waitRemove.add(oldPerm); | }
}
if (waitRemove.size() > 0) {
userDao.removeOldPermission(roleId, waitRemove);
}
}
/**
* 删除角色
*/
@Transactional(rollbackFor = Exception.class)
public JSONObject deleteRole(JSONObject jsonObject) {
String roleId = jsonObject.getString("roleId");
int userCount = userDao.countRoleUser(roleId);
if (userCount > 0) {
return CommonUtil.errorJson(ErrorEnum.E_10008);
}
userDao.removeRole(roleId);
userDao.removeRoleAllPermission(roleId);
return CommonUtil.successJson();
}
} | repos\SpringBoot-Shiro-Vue-master\back\src\main\java\com\heeexy\example\service\UserService.java | 2 |
请完成以下Java代码 | public boolean hasAttribute(String attribute)
{
return(containsKey(attribute));
}
/**
Need a way to parse the stream so we can do string comparisons instead
of character comparisons.
*/
private String[] split(String to_split)
{
if ( to_split == null || to_split.length() == 0 )
{
String[] array = new String[0];
return array;
}
StringBuffer sb = new StringBuffer(to_split.length()+50);
StringCharacterIterator sci = new StringCharacterIterator(to_split);
int length = 0;
for (char c = sci.first(); c != CharacterIterator.DONE; c = sci.next())
{
if(String.valueOf(c).equals(" "))
length++;
else if(sci.getEndIndex()-1 == sci.getIndex())
length++;
} | String[] array = new String[length];
length = 0;
String tmp = new String();
for (char c = sci.first(); c!= CharacterIterator.DONE; c = sci.next())
{
if(String.valueOf(c).equals(" "))
{
array[length] = tmp;
tmp = new String();
length++;
}
else if(sci.getEndIndex()-1 == sci.getIndex())
{
tmp = tmp+String.valueOf(sci.last());
array[length] = tmp;
tmp = new String();
length++;
}
else
tmp += String.valueOf(c);
}
return(array);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\filter\StringFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int getOrder() {
return 0;
}
}
/**
* Condition that matches when {@code spring.couchbase.connection-string} has been
* configured or there is a {@link CouchbaseConnectionDetails} bean.
*/
static final class CouchbaseCondition extends AnyNestedCondition {
CouchbaseCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty("spring.couchbase.connection-string")
private static final class CouchbaseUrlCondition {
}
@ConditionalOnBean(CouchbaseConnectionDetails.class)
private static final class CouchbaseConnectionDetailsCondition {
}
}
/**
* Adapts {@link CouchbaseProperties} to {@link CouchbaseConnectionDetails}.
*/
static final class PropertiesCouchbaseConnectionDetails implements CouchbaseConnectionDetails {
private final CouchbaseProperties properties;
private final @Nullable SslBundles sslBundles;
PropertiesCouchbaseConnectionDetails(CouchbaseProperties properties, @Nullable SslBundles sslBundles) {
this.properties = properties;
this.sslBundles = sslBundles;
}
@Override | public String getConnectionString() {
String connectionString = this.properties.getConnectionString();
Assert.state(connectionString != null, "'connectionString' must not be null");
return connectionString;
}
@Override
public @Nullable String getUsername() {
return this.properties.getUsername();
}
@Override
public @Nullable String getPassword() {
return this.properties.getPassword();
}
@Override
public @Nullable SslBundle getSslBundle() {
Ssl ssl = this.properties.getEnv().getSsl();
if (!ssl.getEnabled()) {
return null;
}
if (StringUtils.hasLength(ssl.getBundle())) {
Assert.notNull(this.sslBundles, "SSL bundle name has been set but no SSL bundles found in context");
return this.sslBundles.getBundle(ssl.getBundle());
}
return SslBundle.systemDefault();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-couchbase\src\main\java\org\springframework\boot\couchbase\autoconfigure\CouchbaseAutoConfiguration.java | 2 |
请完成以下Java代码 | public class ScriptTask extends Task implements HasInParameters {
protected String scriptFormat;
protected String script;
protected String resultVariable;
protected String skipExpression;
protected boolean autoStoreVariables; // see https://activiti.atlassian.net/browse/ACT-1626
protected boolean doNotIncludeVariables = false;
protected List<IOParameter> inParameters;
public String getScriptFormat() {
return scriptFormat;
}
public void setScriptFormat(String scriptFormat) {
this.scriptFormat = scriptFormat;
}
public String getScript() {
return script;
}
public void setScript(String script) {
this.script = script;
}
public String getResultVariable() {
return resultVariable;
}
public void setResultVariable(String resultVariable) {
this.resultVariable = resultVariable;
}
public String getSkipExpression() {
return skipExpression;
}
public void setSkipExpression(String skipExpression) {
this.skipExpression = skipExpression;
}
public boolean isAutoStoreVariables() {
return autoStoreVariables;
}
public void setAutoStoreVariables(boolean autoStoreVariables) {
this.autoStoreVariables = autoStoreVariables;
} | public boolean isDoNotIncludeVariables() {
return doNotIncludeVariables;
}
public void setDoNotIncludeVariables(boolean doNotIncludeVariables) {
this.doNotIncludeVariables = doNotIncludeVariables;
}
@Override
public List<IOParameter> getInParameters() {
return inParameters;
}
@Override
public void addInParameter(IOParameter inParameter) {
if (inParameters == null) {
inParameters = new ArrayList<>();
}
inParameters.add(inParameter);
}
@Override
public void setInParameters(List<IOParameter> inParameters) {
this.inParameters = inParameters;
}
@Override
public ScriptTask clone() {
ScriptTask clone = new ScriptTask();
clone.setValues(this);
return clone;
}
public void setValues(ScriptTask otherElement) {
super.setValues(otherElement);
setScriptFormat(otherElement.getScriptFormat());
setScript(otherElement.getScript());
setResultVariable(otherElement.getResultVariable());
setSkipExpression(otherElement.getSkipExpression());
setAutoStoreVariables(otherElement.isAutoStoreVariables());
setDoNotIncludeVariables(otherElement.isDoNotIncludeVariables());
inParameters = null;
if (otherElement.getInParameters() != null && !otherElement.getInParameters().isEmpty()) {
inParameters = new ArrayList<>();
for (IOParameter parameter : otherElement.getInParameters()) {
inParameters.add(parameter.clone());
}
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ScriptTask.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OrderLineRepository
{
public OrderLine getById(@NonNull final OrderLineId orderLineId)
{
final I_C_OrderLine orderLineRecord = load(orderLineId.getRepoId(), I_C_OrderLine.class);
return ofRecord(orderLineRecord);
}
public static OrderLine ofRecord(@NonNull final I_C_OrderLine orderLineRecord)
{
final int warehouseRepoId = CoalesceUtil.firstGreaterThanZeroIntegerSupplier(
() -> orderLineRecord.getM_Warehouse_ID(),
() -> orderLineRecord.getC_Order().getM_Warehouse_ID());
final int bPartnerRepoId = CoalesceUtil.firstGreaterThanZeroIntegerSupplier(
() -> orderLineRecord.getC_BPartner_ID(),
() -> orderLineRecord.getC_Order().getC_BPartner_ID());
final PaymentTermId paymentTermId = Services.get(IOrderLineBL.class).getPaymentTermId(orderLineRecord);
final ZonedDateTime datePromised = CoalesceUtil.firstValidValue(
date -> date != null,
() -> TimeUtil.asZonedDateTime(orderLineRecord.getDatePromised()),
() -> TimeUtil.asZonedDateTime(orderLineRecord.getC_Order().getDatePromised()));
final de.metas.interfaces.I_C_OrderLine orderLineWithPackingMaterial = InterfaceWrapperHelper.create(orderLineRecord, de.metas.interfaces.I_C_OrderLine.class);
return OrderLine.builder()
.id(OrderLineId.ofRepoIdOrNull(orderLineRecord.getC_OrderLine_ID()))
.orderId(OrderId.ofRepoId(orderLineRecord.getC_Order_ID()))
.orgId(OrgId.ofRepoId(orderLineRecord.getAD_Org_ID()))
.line(orderLineRecord.getLine())
.bPartnerId(BPartnerId.ofRepoId(bPartnerRepoId))
.datePromised(datePromised)
.productId(ProductId.ofRepoId(orderLineRecord.getM_Product_ID()))
.priceActual(extractPriceActual(orderLineRecord))
.orderedQty(extractQtyEntered(orderLineRecord))
.asiId(AttributeSetInstanceId.ofRepoIdOrNone(orderLineRecord.getM_AttributeSetInstance_ID()))
.warehouseId(WarehouseId.ofRepoId(warehouseRepoId)) | .paymentTermId(paymentTermId)
.soTrx(SOTrx.ofBoolean(orderLineRecord.getC_Order().isSOTrx()))
.huPIItemProductId(HUPIItemProductId.ofRepoIdOrNull(orderLineWithPackingMaterial.getM_HU_PI_Item_Product_ID()))
.build();
}
private static ProductPrice extractPriceActual(@NonNull final I_C_OrderLine orderLineRecord)
{
// note that C_OrderLine C_Currency_ID and M_Product_ID are mandatory, so there won't be an NPE
final CurrencyId currencyId = CurrencyId.ofRepoId(orderLineRecord.getC_Currency_ID());
final ProductId productId = ProductId.ofRepoIdOrNull(orderLineRecord.getM_Product_ID());
final UomId effectivePriceUomId = UomId.ofRepoId(firstGreaterThanZero(orderLineRecord.getPrice_UOM_ID(), orderLineRecord.getC_UOM_ID()));
return ProductPrice
.builder()
.money(Money.of(orderLineRecord.getPriceActual(), currencyId))
.productId(productId)
.uomId(effectivePriceUomId)
.build();
}
private static Quantity extractQtyEntered(@NonNull final I_C_OrderLine orderLineRecord)
{
return Services.get(IOrderLineBL.class).getQtyEntered(orderLineRecord);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderLineRepository.java | 2 |
请完成以下Java代码 | public RefundInvoiceCandidate save(@NonNull final RefundInvoiceCandidate refundCandidate)
{
final I_C_Invoice_Candidate record;
if (refundCandidate.getId() == null)
{
record = newInstance(I_C_Invoice_Candidate.class);
}
else
{
record = load(refundCandidate.getId(), I_C_Invoice_Candidate.class);
}
InvoiceCandidateLocationAdapterFactory
.billLocationAdapter(record)
.setFrom(DocumentLocation.builder()
.bpartnerId(refundCandidate.getBpartnerId())
.bpartnerLocationId(refundCandidate.getBpartnerLocationId())
.contactId(BPartnerContactId.ofRepoIdOrNull(refundCandidate.getBpartnerId(), record.getBill_User_ID()))
.build());
record.setDateToInvoice(asTimestamp(refundCandidate.getInvoiceableFrom()));
record.setM_Product_ID(RefundConfigs.extractProductId(refundCandidate.getRefundConfigs()).getRepoId());
// note that Quantity = 1 is set elsewhere, in the invoice candidate handler
final Money money = refundCandidate.getMoney();
record.setPriceActual(money.toBigDecimal());
record.setPriceEntered(money.toBigDecimal());
record.setC_Currency_ID(money.getCurrencyId().getRepoId());
final RefundContract refundContract = refundCandidate.getRefundContract();
final RefundContract savedRefundContract = refundContractRepository.save(refundContract); | record.setAD_Table_ID(getTableId(I_C_Flatrate_Term.class));
record.setRecord_ID(savedRefundContract.getId().getRepoId());
saveRecord(record);
return refundCandidate
.toBuilder()
.id(InvoiceCandidateId.ofRepoId(record.getC_Invoice_Candidate_ID()))
.refundContract(savedRefundContract)
.build();
}
@Value
public static class RefundInvoiceCandidateQuery
{
RefundContract refundContract;
LocalDate invoicableFrom;
@Builder
private RefundInvoiceCandidateQuery(
@NonNull final RefundContract refundContract,
@NonNull final LocalDate invoicableFrom)
{
this.refundContract = refundContract;
this.invoicableFrom = CoalesceUtil.coalesce(invoicableFrom, refundContract.getStartDate());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\RefundInvoiceCandidateRepository.java | 1 |
请完成以下Java代码 | public String getCopyVariablesFromProperties() {
return copyVariablesFromProperties;
}
public void setCopyVariablesFromProperties(String copyVariablesFromProperties) {
this.copyVariablesFromProperties = copyVariablesFromProperties;
}
public String getCopyVariablesFromHeader() {
return copyVariablesFromHeader;
}
public void setCopyVariablesFromHeader(String copyVariablesFromHeader) {
this.copyVariablesFromHeader = copyVariablesFromHeader;
}
public boolean isCopyCamelBodyToBodyAsString() {
return copyCamelBodyToBodyAsString;
}
public void setCopyCamelBodyToBodyAsString(boolean copyCamelBodyToBodyAsString) {
this.copyCamelBodyToBodyAsString = copyCamelBodyToBodyAsString;
}
public boolean isSetProcessInitiator() {
return StringUtils.isNotEmpty(getProcessInitiatorHeaderName());
}
public Map<String, Object> getReturnVarMap() { | return returnVarMap;
}
public void setReturnVarMap(Map<String, Object> returnVarMap) {
this.returnVarMap = returnVarMap;
}
public String getProcessInitiatorHeaderName() {
return processInitiatorHeaderName;
}
public void setProcessInitiatorHeaderName(String processInitiatorHeaderName) {
this.processInitiatorHeaderName = processInitiatorHeaderName;
}
@Override
public boolean isLenientProperties() {
return true;
}
public long getTimeout() {
return timeout;
}
public int getTimeResolution() {
return timeResolution;
}
} | repos\flowable-engine-main\modules\flowable-camel\src\main\java\org\flowable\camel\FlowableEndpoint.java | 1 |
请完成以下Java代码 | public List<ModelType> getSelectedRows(final ListSelectionModel selectionModel, final Function<Integer, Integer> convertRowIndexToModel)
{
final int rowMinView = selectionModel.getMinSelectionIndex();
final int rowMaxView = selectionModel.getMaxSelectionIndex();
if (rowMinView < 0 || rowMaxView < 0)
{
return ImmutableList.of();
}
final ImmutableList.Builder<ModelType> selection = ImmutableList.builder();
for (int rowView = rowMinView; rowView <= rowMaxView; rowView++)
{
if (selectionModel.isSelectedIndex(rowView))
{
final int rowModel = convertRowIndexToModel.apply(rowView);
selection.add(getRow(rowModel));
} | }
return selection.build();
}
public ModelType getSelectedRow(final ListSelectionModel selectionModel, final Function<Integer, Integer> convertRowIndexToModel)
{
final int rowIndexView = selectionModel.getMinSelectionIndex();
if (rowIndexView < 0)
{
return null;
}
final int rowIndexModel = convertRowIndexToModel.apply(rowIndexView);
return getRow(rowIndexModel);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\swing\table\AnnotatedTableModel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data; | }
public void setData(T data) {
this.data = data;
}
@Override
public String toString() {
return "Result{" +
"isSuccess=" + isSuccess +
", errorCode=" + errorCode +
", message='" + message + '\'' +
", data=" + data +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\rsp\Result.java | 2 |
请完成以下Java代码 | public void clearSchedules(final I_DD_Order ddOrder)
{
final DDOrderId ddOrderId = DDOrderId.ofRepoId(ddOrder.getDD_Order_ID());
if (ddOrderMoveScheduleService.hasInProgressSchedules(ddOrderId))
{
throw new AdempiereException("Closing/Reversing is not allowed when there are schedules in progress");
}
ddOrderMoveScheduleService.removeNotStarted(ddOrderId);
}
@DocValidate(timings = { ModelValidator.TIMING_AFTER_COMPLETE })
public void createRequestsForQuarantineLines(final I_DD_Order ddOrder)
{
final List<DDOrderLineId> ddOrderLineToQuarantineIds = retrieveLineToQuarantineWarehouseIds(ddOrder);
C_Request_CreateFromDDOrder_Async.createWorkpackage(ddOrderLineToQuarantineIds);
}
@DocValidate(timings = {
ModelValidator.TIMING_AFTER_REACTIVATE,
ModelValidator.TIMING_AFTER_VOID,
ModelValidator.TIMING_AFTER_REVERSEACCRUAL,
ModelValidator.TIMING_AFTER_REVERSECORRECT })
public void voidMovements(final I_DD_Order ddOrder)
{
// void if creating them automating is activated
if (ddOrderService.isCreateMovementOnComplete())
{
final List<I_M_Movement> movements = movementDAO.retrieveMovementsForDDOrder(ddOrder.getDD_Order_ID());
for (final I_M_Movement movement : movements)
{
movementBL.voidMovement(movement);
}
}
}
@DocValidate(timings = { ModelValidator.TIMING_AFTER_COMPLETE })
public void createMovementsIfNeeded(final I_DD_Order ddOrder)
{
if (ddOrderService.isCreateMovementOnComplete())
{
ddOrderService.generateDirectMovements(ddOrder);
}
} | private List<DDOrderLineId> retrieveLineToQuarantineWarehouseIds(final I_DD_Order ddOrder)
{
return ddOrderService.retrieveLines(ddOrder)
.stream()
.filter(this::isQuarantineWarehouseLine)
.map(line -> DDOrderLineId.ofRepoId(line.getDD_OrderLine_ID()))
.collect(ImmutableList.toImmutableList());
}
private boolean isQuarantineWarehouseLine(final I_DD_OrderLine ddOrderLine)
{
final I_M_Warehouse warehouse = warehouseDAO.getWarehouseByLocatorRepoId(ddOrderLine.getM_LocatorTo_ID());
return warehouse != null && warehouse.isQuarantineWarehouse();
}
@DocValidate(timings = {
ModelValidator.TIMING_BEFORE_REVERSEACCRUAL,
ModelValidator.TIMING_BEFORE_REVERSECORRECT,
ModelValidator.TIMING_BEFORE_VOID })
public void removeDDOrderCandidateAllocations(@NonNull final I_DD_Order ddOrder)
{
final DDOrderId ddOrderId = DDOrderId.ofRepoId(ddOrder.getDD_Order_ID());
ddOrderCandidateService.deleteAndUpdateCandidatesByDDOrderId(ddOrderId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\interceptor\DD_Order.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DataExportAuditRepository
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
@NonNull
public DataExportAudit save(@NonNull final CreateDataExportAuditRequest createDataExportAuditRequest)
{
final I_Data_Export_Audit record = InterfaceWrapperHelper.loadOrNew(createDataExportAuditRequest.getDataExportAuditId(), I_Data_Export_Audit.class);
record.setAD_Table_ID(createDataExportAuditRequest.getTableRecordReference().getAD_Table_ID());
record.setRecord_ID(createDataExportAuditRequest.getTableRecordReference().getRecord_ID());
if (createDataExportAuditRequest.getParentId() != null)
{
record.setData_Export_Audit_Parent_ID(createDataExportAuditRequest.getParentId().getRepoId());
}
saveRecord(record);
return toDataExportAudit(record);
}
@NonNull
public Optional<DataExportAudit> getByTableRecordReference(@NonNull final TableRecordReference tableRecordReference)
{
return queryBL.createQueryBuilder(I_Data_Export_Audit.class) | .addOnlyActiveRecordsFilter()
.addEqualsFilter(I_Data_Export_Audit.COLUMNNAME_AD_Table_ID, tableRecordReference.getAD_Table_ID())
.addEqualsFilter(I_Data_Export_Audit.COLUMNNAME_Record_ID, tableRecordReference.getRecord_ID())
.create()
.firstOnlyOptional(I_Data_Export_Audit.class)
.map(DataExportAuditRepository::toDataExportAudit);
}
@NonNull
private static DataExportAudit toDataExportAudit(@NonNull final I_Data_Export_Audit record)
{
return DataExportAudit.builder()
.id(DataExportAuditId.ofRepoId(record.getData_Export_Audit_ID()))
.tableRecordReference(TableRecordReference.of(record.getAD_Table_ID(), record.getRecord_ID()))
.parentId(DataExportAuditId.ofRepoIdOrNull(record.getData_Export_Audit_Parent_ID()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\audit\data\repository\DataExportAuditRepository.java | 2 |
请完成以下Java代码 | public static JsonPOSOrderLine of(@NonNull final POSOrderLine line, @NonNull final String currencySymbol)
{
return builder()
.uuid(line.getExternalId())
.productId(line.getProductId())
.productName(line.getProductName())
.scannedBarcode(line.getScannedBarcode())
.taxCategoryId(line.getTaxCategoryId())
.currencySymbol(currencySymbol)
.price(line.getPrice().toBigDecimal())
.qty(line.getQty().toBigDecimal())
.uomId(line.getQty().getUomId())
.uomSymbol(line.getQty().getUOMSymbol())
.catchWeight(line.getCatchWeight() != null ? line.getCatchWeight().toBigDecimal() : null)
.catchWeightUomId(line.getCatchWeight() != null ? line.getCatchWeight().getUomId() : null)
.catchWeightUomSymbol(line.getCatchWeight() != null ? line.getCatchWeight().getUOMSymbol() : null)
.amount(line.getAmount().toBigDecimal())
.hashCode(line.hashCode())
.build();
}
RemotePOSOrderLine toRemotePOSOrderLine()
{ | return RemotePOSOrderLine.builder()
.uuid(uuid)
.productId(productId)
.productName(productName)
.scannedBarcode(scannedBarcode)
.taxCategoryId(taxCategoryId)
.price(price)
.qty(qty)
.uomId(uomId)
.catchWeight(catchWeight)
.catchWeightUomId(catchWeightUomId)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.rest-api\src\main\java\de\metas\pos\rest_api\json\JsonPOSOrderLine.java | 1 |
请完成以下Java代码 | private void collectSpecialField(final DocumentFieldDescriptor.Builder field)
{
if (_specialFieldsCollector == null)
{
return;
}
_specialFieldsCollector.collect(field);
}
private void collectSpecialFieldsDone()
{
if (_specialFieldsCollector == null)
{
return;
}
_specialFieldsCollector.collectFinish();
}
@Nullable
public DocumentFieldDescriptor.Builder getSpecialField_DocumentSummary()
{
return _specialFieldsCollector == null ? null : _specialFieldsCollector.getDocumentSummary();
}
@Nullable
public Map<Characteristic, DocumentFieldDescriptor.Builder> getSpecialField_DocSatusAndDocAction()
{
return _specialFieldsCollector == null ? null : _specialFieldsCollector.getDocStatusAndDocAction();
}
private WidgetTypeStandardNumberPrecision getStandardNumberPrecision()
{
WidgetTypeStandardNumberPrecision standardNumberPrecision = this._standardNumberPrecision; | if (standardNumberPrecision == null)
{
standardNumberPrecision = this._standardNumberPrecision = WidgetTypeStandardNumberPrecision.builder()
.quantityPrecision(getPrecisionFromSysConfigs(SYSCONFIG_QUANTITY_DEFAULT_PRECISION))
.build()
.fallbackTo(WidgetTypeStandardNumberPrecision.DEFAULT);
}
return standardNumberPrecision;
}
@SuppressWarnings("SameParameterValue")
private OptionalInt getPrecisionFromSysConfigs(@NonNull final String sysconfigName)
{
final int precision = sysConfigBL.getIntValue(sysconfigName, -1);
return precision > 0 ? OptionalInt.of(precision) : OptionalInt.empty();
}
private boolean isSkipField(@NonNull final String fieldName)
{
switch (fieldName)
{
case FIELDNAME_AD_Org_ID:
return !sysConfigBL.getBooleanValue(SYS_CONFIG_AD_ORG_ID_IS_DISPLAYED, true);
case FIELDNAME_AD_Client_ID:
return !sysConfigBL.getBooleanValue(SYS_CONFIG_AD_CLIENT_ID_IS_DISPLAYED, true);
default:
return false;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\standard\GridTabVOBasedDocumentEntityDescriptorFactory.java | 1 |
请完成以下Java代码 | public long count() {
this.resultType = ResultType.COUNT;
if (commandExecutor != null) {
return (Long) commandExecutor.execute(this);
}
return executeCount(Context.getCommandContext(), generateParameterMap());
}
@Override
public Object execute(CommandContext commandContext) {
if (resultType == ResultType.LIST) {
return executeList(commandContext, generateParameterMap());
} else if (resultType == ResultType.LIST_PAGE) {
return executeList(commandContext, generateParameterMap());
} else if (resultType == ResultType.SINGLE_RESULT) {
return executeSingleResult(commandContext);
} else {
return executeCount(commandContext, generateParameterMap());
}
}
public abstract long executeCount(CommandContext commandContext, Map<String, Object> parameterMap); | /**
* Executes the actual query to retrieve the list of results.
*
* @param commandContext
* @param parameterMap
*/
public abstract List<U> executeList(CommandContext commandContext, Map<String, Object> parameterMap);
public U executeSingleResult(CommandContext commandContext) {
List<U> results = executeList(commandContext, generateParameterMap());
if (results.size() == 1) {
return results.get(0);
} else if (results.size() > 1) {
throw new FlowableException("Query return " + results.size() + " results instead of max 1");
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\query\AbstractNativeQuery.java | 1 |
请完成以下Java代码 | protected boolean isNonInterruptingTimerTriggeredAlready(MigratingInstanceParseContext parseContext,
Map<String, TimerDeclarationImpl> sourceTimerDeclarationsInEventScope, TimerDeclarationImpl targetTimerDeclaration) {
if (targetTimerDeclaration.isInterruptingTimer() || targetTimerDeclaration.getJobHandlerType() != TimerExecuteNestedActivityJobHandler.TYPE || sourceTimerDeclarationsInEventScope.values().size() == 0) {
return false;
}
for (TimerDeclarationImpl sourceTimerDeclaration : sourceTimerDeclarationsInEventScope.values()) {
MigrationInstruction migrationInstruction = parseContext.findSingleMigrationInstruction(sourceTimerDeclaration.getActivityId());
ActivityImpl targetActivity = parseContext.getTargetActivity(migrationInstruction);
if (targetActivity != null && targetTimerDeclaration.getActivityId().equals(targetActivity.getActivityId())) {
return true;
}
}
return false;
}
protected boolean isNonInterruptingTimeoutListenerTriggeredAlready(MigratingInstanceParseContext parseContext,
Map<String, Map<String, TimerDeclarationImpl>> sourceTimeoutListenerDeclarationsInEventScope,
Entry<String, TimerDeclarationImpl> targetTimerDeclarationEntry) {
TimerDeclarationImpl targetTimerDeclaration = targetTimerDeclarationEntry.getValue();
if (targetTimerDeclaration.isInterruptingTimer() || targetTimerDeclaration.getJobHandlerType() != TimerTaskListenerJobHandler.TYPE || sourceTimeoutListenerDeclarationsInEventScope.values().size() == 0) { | return false;
}
for (Entry<String, Map<String, TimerDeclarationImpl>> sourceTimerDeclarationsEntry : sourceTimeoutListenerDeclarationsInEventScope.entrySet()) {
MigrationInstruction migrationInstruction = parseContext.findSingleMigrationInstruction(sourceTimerDeclarationsEntry.getKey());
ActivityImpl targetActivity = parseContext.getTargetActivity(migrationInstruction);
if (targetActivity != null && targetTimerDeclaration.getActivityId().equals(targetActivity.getActivityId())) {
for (Entry<String, TimerDeclarationImpl> sourceTimerDeclarationEntry : sourceTimerDeclarationsEntry.getValue().entrySet()) {
if (sourceTimerDeclarationEntry.getKey().equals(targetTimerDeclarationEntry.getKey())) {
return true;
}
}
}
}
return false;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\parser\ActivityInstanceJobHandler.java | 1 |
请完成以下Java代码 | private Object[] buildRelationPathParams(EntityRelationPathQuery query, int limit) {
final List<Object> params = new ArrayList<>();
// seed
params.add(query.rootEntityId().getId());
params.add(query.rootEntityId().getEntityType().name());
// levels
for (var lvl : query.levels()) {
params.add(lvl.relationType());
}
// limit
params.add(limit);
return params.toArray();
}
private static String buildRelationPathSql(EntityRelationPathQuery query) {
List<RelationPathLevel> levels = query.levels();
StringBuilder sb = new StringBuilder();
sb.append("WITH seed AS (\n")
.append(" SELECT ?::uuid AS id, ?::varchar AS type\n")
.append(")");
String prev = "seed";
for (int i = 0; i < levels.size() - 1; i++) {
RelationPathLevel lvl = levels.get(i);
boolean down = lvl.direction() == EntitySearchDirection.FROM;
String cur = "lvl" + (i + 1);
String joinCond = down
? "r.from_id = p.id AND r.from_type = p.type"
: "r.to_id = p.id AND r.to_type = p.type";
String selectNext = down | ? "r.to_id AS id, r.to_type AS type"
: "r.from_id AS id, r.from_type AS type";
sb.append(",\n").append(cur).append(" AS (\n")
.append(" SELECT ").append(selectNext).append("\n")
.append(" FROM ").append(RELATION_TABLE_NAME).append(" r\n")
.append(" JOIN ").append(prev).append(" p ON ").append(joinCond).append("\n")
.append(" WHERE r.relation_type_group = '").append(RelationTypeGroup.COMMON).append("'\n")
.append(" AND r.relation_type = ?\n")
.append(")");
prev = cur;
}
RelationPathLevel last = levels.get(levels.size() - 1);
boolean lastDown = last.direction() == EntitySearchDirection.FROM;
String prevForLast = (levels.size() == 1) ? "seed" : prev;
String lastJoin = lastDown
? "r.from_id = p.id AND r.from_type = p.type"
: "r.to_id = p.id AND r.to_type = p.type";
sb.append("\n")
.append("SELECT r.from_id, r.from_type, r.to_id, r.to_type,\n")
.append(" r.relation_type_group, r.relation_type, r.version\n")
.append("FROM ").append(RELATION_TABLE_NAME).append(" r\n")
.append("JOIN ").append(prevForLast).append(" p ON ").append(lastJoin).append("\n")
.append("WHERE r.relation_type_group = '").append(RelationTypeGroup.COMMON).append("'\n")
.append(" AND r.relation_type = ?\n")
.append("LIMIT ?");
return sb.toString();
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\relation\JpaRelationDao.java | 1 |
请完成以下Java代码 | private String getHttpSessionId(WebSocketSession wsSession) {
Map<String, Object> attributes = wsSession.getAttributes();
return SessionRepositoryMessageInterceptor.getSessionId(attributes);
}
private void afterConnectionClosed(String httpSessionId, String wsSessionId) {
if (httpSessionId == null) {
return;
}
Map<String, WebSocketSession> sessions = this.httpSessionIdToWsSessions.get(httpSessionId);
if (sessions != null) {
boolean result = sessions.remove(wsSessionId) != null;
if (logger.isDebugEnabled()) {
logger.debug("Removal of " + wsSessionId + " was " + result);
}
if (sessions.isEmpty()) {
this.httpSessionIdToWsSessions.remove(httpSessionId);
if (logger.isDebugEnabled()) {
logger.debug("Removed the corresponding HTTP Session for " + wsSessionId
+ " since it contained no WebSocket mappings");
}
}
}
}
private void registerWsSession(String httpSessionId, WebSocketSession wsSession) {
Map<String, WebSocketSession> sessions = this.httpSessionIdToWsSessions.get(httpSessionId);
if (sessions == null) {
sessions = new ConcurrentHashMap<>();
this.httpSessionIdToWsSessions.putIfAbsent(httpSessionId, sessions);
sessions = this.httpSessionIdToWsSessions.get(httpSessionId);
}
sessions.put(wsSession.getId(), wsSession);
}
private void closeWsSessions(String httpSessionId) {
Map<String, WebSocketSession> sessionsToClose = this.httpSessionIdToWsSessions.remove(httpSessionId); | if (sessionsToClose == null) {
return;
}
if (logger.isDebugEnabled()) {
logger.debug("Closing WebSocket connections associated to expired HTTP Session " + httpSessionId);
}
for (WebSocketSession toClose : sessionsToClose.values()) {
try {
toClose.close(SESSION_EXPIRED_STATUS);
}
catch (IOException ex) {
logger.debug("Failed to close WebSocketSession (this is nothing to worry about but for debugging only)",
ex);
}
}
}
} | repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\socket\handler\WebSocketRegistryListener.java | 1 |
请完成以下Java代码 | public class BatchStatisticsDto extends BatchDto {
protected int remainingJobs;
protected int completedJobs;
protected int failedJobs;
public int getRemainingJobs() {
return remainingJobs;
}
public int getCompletedJobs() {
return completedJobs;
}
public int getFailedJobs() {
return failedJobs;
}
public static BatchStatisticsDto fromBatchStatistics(BatchStatistics batchStatistics) {
BatchStatisticsDto dto = new BatchStatisticsDto();
dto.id = batchStatistics.getId(); | dto.type = batchStatistics.getType();
dto.totalJobs = batchStatistics.getTotalJobs();
dto.jobsCreated = batchStatistics.getJobsCreated();
dto.batchJobsPerSeed = batchStatistics.getBatchJobsPerSeed();
dto.invocationsPerBatchJob = batchStatistics.getInvocationsPerBatchJob();
dto.seedJobDefinitionId = batchStatistics.getSeedJobDefinitionId();
dto.monitorJobDefinitionId = batchStatistics.getMonitorJobDefinitionId();
dto.batchJobDefinitionId = batchStatistics.getBatchJobDefinitionId();
dto.tenantId = batchStatistics.getTenantId();
dto.createUserId = batchStatistics.getCreateUserId();
dto.suspended = batchStatistics.isSuspended();
dto.startTime = batchStatistics.getStartTime();
dto.executionStartTime = batchStatistics.getExecutionStartTime();
dto.remainingJobs = batchStatistics.getRemainingJobs();
dto.completedJobs = batchStatistics.getCompletedJobs();
dto.failedJobs = batchStatistics.getFailedJobs();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\batch\BatchStatisticsDto.java | 1 |
请完成以下Java代码 | private ITranslatableString extractProductValueAndName(final @NotNull DDOrderReference ddOrderReference)
{
final ProductId productId = ddOrderReference.getProductId();
return productId != null
? TranslatableStrings.anyLanguage(productService.getProductValueAndName(productId))
: TranslatableStrings.empty();
}
private @NotNull ITranslatableString extractGTIN(final @NotNull DDOrderReference ddOrderReference)
{
return Optional.ofNullable(ddOrderReference.getProductId())
.flatMap(productService::getGTIN)
.map(GTIN::getAsString)
.map(TranslatableStrings::anyLanguage)
.orElse(TranslatableStrings.empty());
}
@NonNull
private ITranslatableString extractSourceDoc(@NonNull final DDOrderReference ddOrderReference)
{
ImmutablePair<ITranslatableString, String> documentTypeAndNo;
if (ddOrderReference.getSalesOrderId() != null)
{
documentTypeAndNo = sourceDocService.getDocumentTypeAndName(ddOrderReference.getSalesOrderId()); | }
else if (ddOrderReference.getPpOrderId() != null)
{
documentTypeAndNo = sourceDocService.getDocumentTypeAndName(ddOrderReference.getPpOrderId());
}
else
{
return TranslatableStrings.empty();
}
return TranslatableStrings.builder()
.append(documentTypeAndNo.getLeft())
.append(" ")
.append(documentTypeAndNo.getRight())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\DistributionLauncherCaptionProvider.java | 1 |
请完成以下Java代码 | public void execute(DelegateExecution execution) {
JobManager jobManager = Context.getCommandContext().getJobManager();
// end date should be ignored for intermediate timer events.
TimerJobEntity timerJob = jobManager.createTimerJob(
timerEventDefinition,
false,
(ExecutionEntity) execution,
TriggerTimerEventJobHandler.TYPE,
TimerEventHandler.createConfiguration(
execution.getCurrentActivityId(),
null,
timerEventDefinition.getCalendarName()
)
);
if (timerJob != null) {
jobManager.scheduleTimerJob(timerJob);
}
} | @Override
public void eventCancelledByEventGateway(DelegateExecution execution) {
JobEntityManager jobEntityManager = Context.getCommandContext().getJobEntityManager();
List<JobEntity> jobEntities = jobEntityManager.findJobsByExecutionId(execution.getId());
for (JobEntity jobEntity : jobEntities) {
// Should be only one
jobEntityManager.delete(jobEntity);
}
Context.getCommandContext()
.getExecutionEntityManager()
.deleteExecutionAndRelatedData((ExecutionEntity) execution, DeleteReason.EVENT_BASED_GATEWAY_CANCEL);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\IntermediateCatchTimerEventActivityBehavior.java | 1 |
请完成以下Java代码 | public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getTips() { | return tips;
}
public void setTips(String tips) {
this.tips = tips;
}
public Date getPublishtime() {
return publishtime;
}
public void setPublishtime(Date publishtime) {
this.publishtime = publishtime;
}
} | repos\SpringBootBucket-master\springboot-swagger2\src\main\java\com\xncoding\jwt\api\model\VersionResult.java | 1 |
请完成以下Java代码 | public List<Class<? extends Throwable>> getExceptions() {
return exceptions;
}
public RetryConfig setExceptions(Class<? extends Throwable>... exceptions) {
this.exceptions = Arrays.asList(exceptions);
return this;
}
}
public static class BackoffConfig {
private Duration firstBackoff = Duration.ofMillis(5);
private @Nullable Duration maxBackoff;
private int factor = 2;
private boolean basedOnPreviousValue = true;
public BackoffConfig() {
}
public BackoffConfig(Duration firstBackoff, Duration maxBackoff, int factor, boolean basedOnPreviousValue) {
this.firstBackoff = firstBackoff;
this.maxBackoff = maxBackoff;
this.factor = factor;
this.basedOnPreviousValue = basedOnPreviousValue;
}
public void validate() {
Objects.requireNonNull(this.firstBackoff, "firstBackoff must be present");
}
public Duration getFirstBackoff() {
return firstBackoff;
}
public void setFirstBackoff(Duration firstBackoff) {
this.firstBackoff = firstBackoff;
}
public @Nullable Duration getMaxBackoff() {
return maxBackoff;
}
public void setMaxBackoff(Duration maxBackoff) {
this.maxBackoff = maxBackoff;
}
public int getFactor() {
return factor;
} | public void setFactor(int factor) {
this.factor = factor;
}
public boolean isBasedOnPreviousValue() {
return basedOnPreviousValue;
}
public void setBasedOnPreviousValue(boolean basedOnPreviousValue) {
this.basedOnPreviousValue = basedOnPreviousValue;
}
@Override
public String toString() {
return new ToStringCreator(this).append("firstBackoff", firstBackoff)
.append("maxBackoff", maxBackoff)
.append("factor", factor)
.append("basedOnPreviousValue", basedOnPreviousValue)
.toString();
}
}
public static class JitterConfig {
private double randomFactor = 0.5;
public void validate() {
Assert.isTrue(randomFactor >= 0 && randomFactor <= 1,
"random factor must be between 0 and 1 (default 0.5)");
}
public JitterConfig() {
}
public JitterConfig(double randomFactor) {
this.randomFactor = randomFactor;
}
public double getRandomFactor() {
return randomFactor;
}
public void setRandomFactor(double randomFactor) {
this.randomFactor = randomFactor;
}
@Override
public String toString() {
return new ToStringCreator(this).append("randomFactor", randomFactor).toString();
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RetryGatewayFilterFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DeviceImportService extends BaseEntityImportService<DeviceId, Device, DeviceExportData> {
private final DeviceService deviceService;
private final DeviceCredentialsService credentialsService;
@Override
protected void setOwner(TenantId tenantId, Device device, IdProvider idProvider) {
device.setTenantId(tenantId);
device.setCustomerId(idProvider.getInternalId(device.getCustomerId()));
}
@Override
protected Device prepare(EntitiesImportCtx ctx, Device device, Device old, DeviceExportData exportData, IdProvider idProvider) {
device.setDeviceProfileId(idProvider.getInternalId(device.getDeviceProfileId()));
device.setFirmwareId(idProvider.getInternalId(device.getFirmwareId()));
device.setSoftwareId(idProvider.getInternalId(device.getSoftwareId()));
return device;
}
@Override
protected Device deepCopy(Device d) {
return new Device(d);
}
@Override
protected void cleanupForComparison(Device e) {
super.cleanupForComparison(e);
if (e.getCustomerId() != null && e.getCustomerId().isNullUid()) {
e.setCustomerId(null);
}
}
@Override
protected Device saveOrUpdate(EntitiesImportCtx ctx, Device device, DeviceExportData exportData, IdProvider idProvider, CompareResult compareResult) {
Device savedDevice;
if (exportData.getCredentials() != null && ctx.isSaveCredentials()) {
exportData.getCredentials().setId(null);
exportData.getCredentials().setDeviceId(null); | savedDevice = deviceService.saveDeviceWithCredentials(device, exportData.getCredentials());
} else {
savedDevice = deviceService.saveDevice(device);
}
if (ctx.isFinalImportAttempt() || ctx.getCurrentImportResult().isUpdatedAllExternalIds()) {
importCalculatedFields(ctx, savedDevice, exportData, idProvider);
}
return savedDevice;
}
@Override
protected boolean updateRelatedEntitiesIfUnmodified(EntitiesImportCtx ctx, Device prepared, DeviceExportData exportData, IdProvider idProvider) {
boolean updated = super.updateRelatedEntitiesIfUnmodified(ctx, prepared, exportData, idProvider);
var credentials = exportData.getCredentials();
if (credentials != null && ctx.isSaveCredentials()) {
var existing = credentialsService.findDeviceCredentialsByDeviceId(ctx.getTenantId(), prepared.getId());
credentials.setId(existing.getId());
credentials.setDeviceId(prepared.getId());
if (!existing.equals(credentials)) {
credentialsService.updateDeviceCredentials(ctx.getTenantId(), credentials);
updated = true;
}
}
return updated;
}
@Override
public EntityType getEntityType() {
return EntityType.DEVICE;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\DeviceImportService.java | 2 |
请完成以下Java代码 | public void setShelfLifeMinDays (final int ShelfLifeMinDays)
{
set_Value (COLUMNNAME_ShelfLifeMinDays, ShelfLifeMinDays);
}
@Override
public int getShelfLifeMinDays()
{
return get_ValueAsInt(COLUMNNAME_ShelfLifeMinDays);
}
@Override
public void setShelfLifeMinPct (final int ShelfLifeMinPct)
{
set_Value (COLUMNNAME_ShelfLifeMinPct, ShelfLifeMinPct);
}
@Override
public int getShelfLifeMinPct()
{
return get_ValueAsInt(COLUMNNAME_ShelfLifeMinPct);
}
@Override
public void setUPC (final @Nullable java.lang.String UPC)
{
set_Value (COLUMNNAME_UPC, UPC);
}
@Override
public java.lang.String getUPC()
{
return get_ValueAsString(COLUMNNAME_UPC);
}
@Override
public void setUsedForCustomer (final boolean UsedForCustomer)
{
set_Value (COLUMNNAME_UsedForCustomer, UsedForCustomer);
}
@Override
public boolean isUsedForCustomer()
{
return get_ValueAsBoolean(COLUMNNAME_UsedForCustomer);
}
@Override
public void setUsedForVendor (final boolean UsedForVendor)
{
set_Value (COLUMNNAME_UsedForVendor, UsedForVendor);
} | @Override
public boolean isUsedForVendor()
{
return get_ValueAsBoolean(COLUMNNAME_UsedForVendor);
}
@Override
public void setVendorCategory (final @Nullable java.lang.String VendorCategory)
{
set_Value (COLUMNNAME_VendorCategory, VendorCategory);
}
@Override
public java.lang.String getVendorCategory()
{
return get_ValueAsString(COLUMNNAME_VendorCategory);
}
@Override
public void setVendorProductNo (final @Nullable java.lang.String VendorProductNo)
{
set_Value (COLUMNNAME_VendorProductNo, VendorProductNo);
}
@Override
public java.lang.String getVendorProductNo()
{
return get_ValueAsString(COLUMNNAME_VendorProductNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Product.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DataEntrySubTabId implements RepoIdAware
{
public static DataEntrySubTabId ofRepoId(final int repoId)
{
return new DataEntrySubTabId(repoId);
}
public static DataEntrySubTabId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
int repoId;
@JsonCreator
public DataEntrySubTabId(final int repoId) | {
this.repoId = assumeGreaterThanZero(repoId, "repoId");
}
@Override
@JsonValue // note: annotating just the repoId member worked "often" which was very annoying
public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable final DataEntrySubTabId id1, @Nullable final DataEntrySubTabId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\DataEntrySubTabId.java | 2 |
请完成以下Java代码 | public int getDocument_Acct_Log_ID()
{
return get_ValueAsInt(COLUMNNAME_Document_Acct_Log_ID);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
/**
* Type AD_Reference_ID=541967
* Reference name: Document_Acct_Log_Type
*/
public static final int TYPE_AD_Reference_ID=541967;
/** Enqueued = enqueued */
public static final String TYPE_Enqueued = "enqueued";
/** Posting Done = posting_ok */ | public static final String TYPE_PostingDone = "posting_ok";
/** Posting Error = posting_error */
public static final String TYPE_PostingError = "posting_error";
@Override
public void setType (final @Nullable java.lang.String Type)
{
set_ValueNoCheck (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Document_Acct_Log.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String technologyType() {
return obtain(v1(V1::getTechnologyType), DynatraceConfig.super::technologyType);
}
@Override
public String uri() {
return obtain(DynatraceProperties::getUri, DynatraceConfig.super::uri);
}
@Override
public @Nullable String group() {
return get(v1(V1::getGroup), DynatraceConfig.super::group);
}
@Override
public DynatraceApiVersion apiVersion() {
return obtain((properties) -> (properties.getV1().getDeviceId() != null) ? DynatraceApiVersion.V1
: DynatraceApiVersion.V2, DynatraceConfig.super::apiVersion);
}
@Override
public String metricKeyPrefix() {
return obtain(v2(V2::getMetricKeyPrefix), DynatraceConfig.super::metricKeyPrefix);
}
@Override
public Map<String, String> defaultDimensions() {
return obtain(v2(V2::getDefaultDimensions), DynatraceConfig.super::defaultDimensions); | }
@Override
public boolean enrichWithDynatraceMetadata() {
return obtain(v2(V2::isEnrichWithDynatraceMetadata), DynatraceConfig.super::enrichWithDynatraceMetadata);
}
@Override
public boolean useDynatraceSummaryInstruments() {
return obtain(v2(V2::isUseDynatraceSummaryInstruments), DynatraceConfig.super::useDynatraceSummaryInstruments);
}
@Override
public boolean exportMeterMetadata() {
return obtain(v2(V2::isExportMeterMetadata), DynatraceConfig.super::exportMeterMetadata);
}
private <V> Getter<DynatraceProperties, V> v1(Getter<V1, V> getter) {
return (properties) -> getter.get(properties.getV1());
}
private <V> Getter<DynatraceProperties, V> v2(Getter<V2, V> getter) {
return (properties) -> getter.get(properties.getV2());
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\dynatrace\DynatracePropertiesConfigAdapter.java | 2 |
请完成以下Java代码 | public class CompositeBatchInterceptor<K, V> implements BatchInterceptor<K, V> {
private final Collection<BatchInterceptor<K, V>> delegates = new ArrayList<>();
/**
* Construct an instance with the provided delegates.
* @param delegates the delegates.
*/
@SafeVarargs
@SuppressWarnings("varargs")
public CompositeBatchInterceptor(BatchInterceptor<K, V>... delegates) {
Assert.notNull(delegates, "'delegates' cannot be null");
Assert.noNullElements(delegates, "'delegates' cannot have null entries");
this.delegates.addAll(Arrays.asList(delegates));
}
@Override
public @Nullable ConsumerRecords<K, V> intercept(ConsumerRecords<K, V> records, Consumer<K, V> consumer) {
ConsumerRecords<K, V> recordsToIntercept = records;
for (BatchInterceptor<K, V> delegate : this.delegates) {
recordsToIntercept = delegate.intercept(recordsToIntercept, consumer);
if (recordsToIntercept == null) {
break;
}
}
return recordsToIntercept;
}
@Override
public void success(ConsumerRecords<K, V> records, Consumer<K, V> consumer) {
this.delegates.forEach(del -> del.success(records, consumer));
}
@Override
public void failure(ConsumerRecords<K, V> records, Exception exception, Consumer<K, V> consumer) { | this.delegates.forEach(del -> del.failure(records, exception, consumer));
}
@Override
public void setupThreadState(Consumer<?, ?> consumer) {
this.delegates.forEach(del -> del.setupThreadState(consumer));
}
@Override
public void clearThreadState(Consumer<?, ?> consumer) {
this.delegates.forEach(del -> del.clearThreadState(consumer));
}
/**
* Add an {@link BatchInterceptor} to delegates.
* @param batchInterceptor the interceptor.
* @since 4.0
*/
public void addBatchInterceptor(BatchInterceptor<K, V> batchInterceptor) {
this.delegates.add(batchInterceptor);
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\CompositeBatchInterceptor.java | 1 |
请完成以下Java代码 | public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Scrapped Quantity.
@param ScrappedQty
The Quantity scrapped due to QA issues
*/
public void setScrappedQty (BigDecimal ScrappedQty) | {
set_Value (COLUMNNAME_ScrappedQty, ScrappedQty);
}
/** Get Scrapped Quantity.
@return The Quantity scrapped due to QA issues
*/
public BigDecimal getScrappedQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_InOutLineConfirm.java | 1 |
请完成以下Java代码 | public void setPostStatistical (final boolean PostStatistical)
{
set_Value (COLUMNNAME_PostStatistical, PostStatistical);
}
@Override
public boolean isPostStatistical()
{
return get_ValueAsBoolean(COLUMNNAME_PostStatistical);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_ValueNoCheck (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{ | set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ElementValue.java | 1 |
请完成以下Java代码 | public int getR_Status_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_Status_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_AD_User getSalesRep() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getSalesRep_ID(), get_TrxName()); }
/** Set Sales Representative.
@param SalesRep_ID
Sales Representative or Company Agent
*/
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_ValueNoCheck (COLUMNNAME_SalesRep_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Sales Representative.
@return Sales Representative or Company Agent
*/
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Start Date.
@param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
/** Set Summary.
@param Summary
Textual summary of this request
*/
public void setSummary (String Summary)
{
set_ValueNoCheck (COLUMNNAME_Summary, Summary);
}
/** Get Summary.
@return Textual summary of this request
*/
public String getSummary ()
{
return (String)get_Value(COLUMNNAME_Summary);
}
/** TaskStatus AD_Reference_ID=366 */
public static final int TASKSTATUS_AD_Reference_ID=366;
/** 0% Not Started = 0 */
public static final String TASKSTATUS_0NotStarted = "0"; | /** 100% Complete = D */
public static final String TASKSTATUS_100Complete = "D";
/** 20% Started = 2 */
public static final String TASKSTATUS_20Started = "2";
/** 80% Nearly Done = 8 */
public static final String TASKSTATUS_80NearlyDone = "8";
/** 40% Busy = 4 */
public static final String TASKSTATUS_40Busy = "4";
/** 60% Good Progress = 6 */
public static final String TASKSTATUS_60GoodProgress = "6";
/** 90% Finishing = 9 */
public static final String TASKSTATUS_90Finishing = "9";
/** 95% Almost Done = A */
public static final String TASKSTATUS_95AlmostDone = "A";
/** 99% Cleaning up = C */
public static final String TASKSTATUS_99CleaningUp = "C";
/** Set Task Status.
@param TaskStatus
Status of the Task
*/
public void setTaskStatus (String TaskStatus)
{
set_Value (COLUMNNAME_TaskStatus, TaskStatus);
}
/** Get Task Status.
@return Status of the Task
*/
public String getTaskStatus ()
{
return (String)get_Value(COLUMNNAME_TaskStatus);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_RequestAction.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.