instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public class BottomCategory implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "middle_category_id")
private MiddleCategory middleCategory;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public MiddleCategory getMiddleCategory() {
return middleCategory;
}
public void setMiddleCategory(MiddleCategory middleCategory) {
this.middleCategory = middleCategory;
|
}
@Override
public int hashCode() {
return 2018;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof BottomCategory)) {
return false;
}
return id != null && id.equals(((BottomCategory) obj).id);
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoSqlResultSetMapping\src\main\java\com\app\entity\BottomCategory.java
| 2
|
请完成以下Java代码
|
public int compareTo(final HUTopLevel other)
{
if (this == other)
{
return 0;
}
if (other == null)
{
return +1; // nulls last
}
return hashKey.compareTo(other.hashKey);
}
/**
* @return top level HU; never return <code>null</code>
*/
public I_M_HU getM_HU_TopLevel()
|
{
return topLevelHU;
}
public I_M_HU getM_LU_HU()
{
return luHU;
}
public I_M_HU getM_TU_HU()
{
return tuHU;
}
public I_M_HU getVHU()
{
return vhu;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\util\HUTopLevel.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ReferenceType getOrdrspReference() {
return ordrspReference;
}
/**
* Sets the value of the ordrspReference property.
*
* @param value
* allowed object is
* {@link ReferenceType }
*
*/
public void setOrdrspReference(ReferenceType value) {
this.ordrspReference = value;
}
/**
* DEPRICATED: please use DocumentExtension/MessageFunction instead.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMessageFunction() {
return messageFunction;
}
/**
* Sets the value of the messageFunction property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMessageFunction(String value) {
this.messageFunction = value;
}
/**
* Gets the value of the billOfLadingReference property.
*
* @return
* possible object is
* {@link ReferenceType }
*
*/
public ReferenceType getBillOfLadingReference() {
return billOfLadingReference;
}
/**
* Sets the value of the billOfLadingReference property.
*
* @param value
* allowed object is
* {@link ReferenceType }
*
*/
public void setBillOfLadingReference(ReferenceType value) {
this.billOfLadingReference = value;
}
|
/**
* Gets the value of the supplierOrderReference property.
*
* @return
* possible object is
* {@link ReferenceType }
*
*/
public ReferenceType getSupplierOrderReference() {
return supplierOrderReference;
}
/**
* Sets the value of the supplierOrderReference property.
*
* @param value
* allowed object is
* {@link ReferenceType }
*
*/
public void setSupplierOrderReference(ReferenceType value) {
this.supplierOrderReference = value;
}
/**
* Reference to the consignment.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConsignmentReference() {
return consignmentReference;
}
/**
* Sets the value of the consignmentReference property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConsignmentReference(String value) {
this.consignmentReference = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\DESADVExtensionType.java
| 2
|
请完成以下Java代码
|
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + ((id == null) ? 0 : id.hashCode());
result = (prime * result) + ((name == null) ? 0 : name.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;
}
final Foo other = (Foo) obj;
if (id == null) {
if (other.id != null) {
|
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\custom\persistence\model\Foo.java
| 1
|
请完成以下Java代码
|
public void setAD_Language (final java.lang.String AD_Language)
{
set_ValueNoCheck (COLUMNNAME_AD_Language, AD_Language);
}
@Override
public java.lang.String getAD_Language()
{
return get_ValueAsString(COLUMNNAME_AD_Language);
}
@Override
public org.compiere.model.I_AD_Process getAD_Process()
{
return get_ValueAsPO(COLUMNNAME_AD_Process_ID, org.compiere.model.I_AD_Process.class);
}
@Override
public void setAD_Process(final org.compiere.model.I_AD_Process AD_Process)
{
set_ValueFromPO(COLUMNNAME_AD_Process_ID, org.compiere.model.I_AD_Process.class, AD_Process);
}
@Override
public void setAD_Process_ID (final int AD_Process_ID)
{
if (AD_Process_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Process_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Process_ID, AD_Process_ID);
}
@Override
public int getAD_Process_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Process_ID);
}
@Override
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 setHelp (final java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
@Override
public java.lang.String getHelp()
{
return get_ValueAsString(COLUMNNAME_Help);
}
@Override
public void setIsTranslated (final boolean IsTranslated)
{
set_Value (COLUMNNAME_IsTranslated, IsTranslated);
}
@Override
public boolean isTranslated()
{
return get_ValueAsBoolean(COLUMNNAME_IsTranslated);
}
@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);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Process_Trl.java
| 1
|
请完成以下Java代码
|
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Tag tag = (Tag) o;
return Objects.equals(this.id, tag.id) &&
Objects.equals(this.name, tag.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@Override
public String toString() {
|
StringBuilder sb = new StringBuilder();
sb.append("class Tag {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\tutorials-master\spring-swagger-codegen-modules\spring-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\model\Tag.java
| 1
|
请完成以下Java代码
|
public static Class<?> forType(String type) {
return forType(type, ObjectValue.class);
}
public static Class<?> forType(String type, Class<?> defaultType) {
return typeRegistry.getOrDefault(type, defaultType);
}
public static String forClass(Class<?> clazz) {
return classRegistry.getOrDefault(clazz, OBJECT_TYPE_KEY);
}
public static boolean isScalarType(Class<?> clazz) {
return scalarTypes.contains(clazz);
}
|
public static Optional<Class<?>> getContainerType(Class<?> clazz, Object value) {
return Stream.of(containerTypes)
.filter(type -> type.isInstance(value))
.findFirst();
}
public static boolean canConvert(Object value) {
Class<?> clazz = value.getClass();
return scalarTypes.contains(clazz) || getContainerType(clazz, value).isPresent();
}
public static boolean containsType(String type) {
return typeRegistry.containsKey(type);
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\ProcessVariablesMapTypeRegistry.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PmsOperatorLog extends PermissionBaseEntity {
private static final long serialVersionUID = 742891253537618199L;
private Long operatorId; // 操作员ID
private String operatorName; // 操作员登录名
private String operateType; // 操作类型(参与枚举:OperatorLogTypeEnum,1:增加,2:修改,3:删除,4:查询,5:登录)
private String ip; // IP地址
private String content; // 操作内容
public Long getOperatorId() {
return operatorId;
}
public void setOperatorId(Long operatorId) {
this.operatorId = operatorId;
}
public String getOperatorName() {
return operatorName;
}
public void setOperatorName(String operatorName) {
this.operatorName = operatorName;
}
public String getOperateType() {
return operateType;
}
public void setOperateType(String operateType) {
this.operateType = operateType;
}
public String getIp() {
|
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\entity\PmsOperatorLog.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class ExponentialBackoffRetryService {
private final RestTemplate restTemplate;
private int maxRetries = 5;
private long initialDelay = 1000;
public ExponentialBackoffRetryService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public String makeRequestWithExponentialBackoff(String url) {
int attempt = 0;
while (attempt < maxRetries) {
try {
return restTemplate.getForObject(url, String.class);
} catch (ResourceAccessException e) {
attempt++;
if (attempt >= maxRetries) {
throw new RuntimeException(
"Failed after " + maxRetries + " attempts", e);
}
long delay = initialDelay * (long) Math.pow(2, attempt - 1);
|
try {
Thread.sleep(delay);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new RuntimeException("Retry interrupted", ie);
}
}
}
throw new RuntimeException("Unexpected error in retry logic");
}
public void setMaxRetries(int maxRetries) {
this.maxRetries = maxRetries;
}
public void setInitialDelay(long initialDelay) {
this.initialDelay = initialDelay;
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-retries\src\main\java\com\baeldung\retries\service\ExponentialBackoffRetryService.java
| 2
|
请完成以下Java代码
|
public ServletOutputStream getOutputStream() throws IOException {
return new ServletOutputStream() {
@Override
public void write(int b) throws IOException {
builder.append(Character.valueOf((char) b));
}
@Override
public void setWriteListener(WriteListener listener) {
}
@Override
public boolean isReady() {
return true;
}
};
}
public ServletInputStream getInputStream() {
ByteArrayInputStream body = new ByteArrayInputStream(builder.toString().getBytes());
return new ServletInputStream() {
|
@Override
public int read() throws IOException {
return body.read();
}
@Override
public void setReadListener(ReadListener listener) {
}
@Override
public boolean isReady() {
return true;
}
@Override
public boolean isFinished() {
return body.available() <= 0;
}
};
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-proxyexchange-webmvc\src\main\java\org\springframework\cloud\gateway\mvc\ProxyExchange.java
| 1
|
请完成以下Java代码
|
public class BpmnMailActivityDelegate extends BaseMailActivityDelegate<DelegateExecution>
implements JavaDelegate {
@Override
public void execute(DelegateExecution execution) {
prepareAndExecuteRequest(execution);
}
@Override
protected FlowableMailClient getMailClient(DelegateExecution execution) {
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration();
String tenantId = execution.getTenantId();
FlowableMailClient mailClient = null;
if (StringUtils.isNotBlank(tenantId)) {
mailClient = processEngineConfiguration.getMailClient(tenantId);
}
if (mailClient == null) {
mailClient = processEngineConfiguration.getDefaultMailClient();
|
}
return mailClient;
}
@Override
protected Expression createExpression(String expressionText) {
return CommandContextUtil.getProcessEngineConfiguration().getExpressionManager().createExpression(expressionText);
}
@Override
protected ContentService getContentService() {
return CommandContextUtil.getContentService();
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\mail\BpmnMailActivityDelegate.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
application:
name: user-service # Spring 应用名
cloud:
nacos:
# Nacos 作为注册中心的配置项
discovery:
server-addr: 127.0.0.1:8848 # Nacos 服务器地址 "'lb://'+serviceId"
server:
|
port: ${random.int[10000,19999]} # 服务器端口。默认为 8080
# port: 18080 # 服务器端口。默认为 8080
|
repos\SpringBoot-Labs-master\labx-08-spring-cloud-gateway\labx-08-sc-user-service\src\main\resources\application.yaml
| 2
|
请完成以下Java代码
|
public class SetRemovalTimeToHistoricBatchesDto extends AbstractSetRemovalTimeDto {
protected String[] historicBatchIds;
protected HistoricBatchQueryDto historicBatchQuery;
protected boolean hierarchical;
public String[] getHistoricBatchIds() {
return historicBatchIds;
}
public void setHistoricBatchIds(String[] historicBatchIds) {
this.historicBatchIds = historicBatchIds;
}
public HistoricBatchQueryDto getHistoricBatchQuery() {
|
return historicBatchQuery;
}
public void setHistoricBatchQuery(HistoricBatchQueryDto historicBatchQuery) {
this.historicBatchQuery = historicBatchQuery;
}
public boolean isHierarchical() {
return hierarchical;
}
public void setHierarchical(boolean hierarchical) {
this.hierarchical = hierarchical;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\batch\removaltime\SetRemovalTimeToHistoricBatchesDto.java
| 1
|
请完成以下Java代码
|
public class DelegateExpressionCaseExecutionListener implements CaseExecutionListener {
protected Expression expression;
private final List<FieldDeclaration> fieldDeclarations;
public DelegateExpressionCaseExecutionListener(Expression expression, List<FieldDeclaration> fieldDeclarations) {
this.expression = expression;
this.fieldDeclarations = fieldDeclarations;
}
public void notify(DelegateCaseExecution caseExecution) throws Exception {
// Note: we can't cache the result of the expression, because the
// caseExecution can change: eg. delegateExpression='${mySpringBeanFactory.randomSpringBean()}'
Object delegate = expression.getValue(caseExecution);
applyFieldDeclaration(fieldDeclarations, delegate);
if (delegate instanceof CaseExecutionListener) {
CaseExecutionListener listenerInstance = (CaseExecutionListener) delegate;
Context
.getProcessEngineConfiguration()
.getDelegateInterceptor()
.handleInvocation(new CaseExecutionListenerInvocation(listenerInstance, caseExecution));
} else {
throw new ProcessEngineException("Delegate expression " + expression
+ " did not resolve to an implementation of " + CaseExecutionListener.class);
|
}
}
/**
* returns the expression text for this execution listener. Comes in handy if you want to
* check which listeners you already have.
*/
public String getExpressionText() {
return expression.getExpressionText();
}
public List<FieldDeclaration> getFieldDeclarations() {
return fieldDeclarations;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\listener\DelegateExpressionCaseExecutionListener.java
| 1
|
请完成以下Java代码
|
public void handle(AddProductCommand command) {
if (orderConfirmed) {
throw new OrderAlreadyConfirmedException(orderId);
}
String productId = command.getProductId();
if (orderLines.containsKey(productId)) {
throw new DuplicateOrderLineException(productId);
}
apply(new ProductAddedEvent(orderId, productId));
}
@CommandHandler
public void handle(ConfirmOrderCommand command) {
if (orderConfirmed) {
return;
}
apply(new OrderConfirmedEvent(orderId));
}
@CommandHandler
public void handle(ShipOrderCommand command) {
if (!orderConfirmed) {
throw new UnconfirmedOrderException();
}
apply(new OrderShippedEvent(orderId));
}
@EventSourcingHandler
public void on(OrderCreatedEvent event) {
this.orderId = event.getOrderId();
this.orderConfirmed = false;
this.orderLines = new HashMap<>();
|
}
@EventSourcingHandler
public void on(OrderConfirmedEvent event) {
this.orderConfirmed = true;
}
@EventSourcingHandler
public void on(ProductAddedEvent event) {
String productId = event.getProductId();
this.orderLines.put(productId, new OrderLine(productId));
}
@EventSourcingHandler
public void on(ProductRemovedEvent event) {
this.orderLines.remove(event.getProductId());
}
protected OrderAggregate() {
// Required by Axon to build a default Aggregate prior to Event Sourcing
}
}
|
repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\commandmodel\order\OrderAggregate.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getProdName() {
return prodName;
}
public void setProdName(String prodName) {
this.prodName = prodName;
}
public String getMarketPrice() {
return marketPrice;
}
public void setMarketPrice(String marketPrice) {
this.marketPrice = marketPrice;
}
public String getShopPrice() {
return shopPrice;
}
public void setShopPrice(String shopPrice) {
this.shopPrice = shopPrice;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
public int getSales() {
return sales;
}
public void setSales(int sales) {
this.sales = sales;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getTopCateEntityID() {
return topCateEntityID;
}
public void setTopCateEntityID(String topCateEntityID) {
this.topCateEntityID = topCateEntityID;
}
public String getSubCategEntityID() {
return subCategEntityID;
|
}
public void setSubCategEntityID(String subCategEntityID) {
this.subCategEntityID = subCategEntityID;
}
public String getBrandEntityID() {
return brandEntityID;
}
public void setBrandEntityID(String brandEntityID) {
this.brandEntityID = brandEntityID;
}
public Integer getProdState() {
return prodState;
}
public void setProdState(Integer prodState) {
this.prodState = prodState;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getCompanyEntityID() {
return companyEntityID;
}
public void setCompanyEntityID(String companyEntityID) {
this.companyEntityID = companyEntityID;
}
@Override
public String toString() {
return "ProdInsertReq{" +
"id='" + id + '\'' +
", prodName='" + prodName + '\'' +
", marketPrice='" + marketPrice + '\'' +
", shopPrice='" + shopPrice + '\'' +
", stock=" + stock +
", sales=" + sales +
", weight='" + weight + '\'' +
", topCateEntityID='" + topCateEntityID + '\'' +
", subCategEntityID='" + subCategEntityID + '\'' +
", brandEntityID='" + brandEntityID + '\'' +
", prodState=" + prodState +
", content='" + content + '\'' +
", companyEntityID='" + companyEntityID + '\'' +
'}';
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\product\ProdInsertReq.java
| 2
|
请完成以下Java代码
|
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public String getExternalTaskId() {
return externalTaskId;
}
public void setExternalTaskId(String externalTaskId) {
this.externalTaskId = externalTaskId;
}
public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[taskId=" + taskId
+ ", deploymentId=" + deploymentId
+ ", processDefinitionKey=" + processDefinitionKey
+ ", jobId=" + jobId
|
+ ", jobDefinitionId=" + jobDefinitionId
+ ", batchId=" + batchId
+ ", operationId=" + operationId
+ ", operationType=" + operationType
+ ", userId=" + userId
+ ", timestamp=" + timestamp
+ ", property=" + property
+ ", orgValue=" + orgValue
+ ", newValue=" + newValue
+ ", id=" + id
+ ", eventType=" + eventType
+ ", executionId=" + executionId
+ ", processDefinitionId=" + processDefinitionId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", processInstanceId=" + processInstanceId
+ ", externalTaskId=" + externalTaskId
+ ", tenantId=" + tenantId
+ ", entityType=" + entityType
+ ", category=" + category
+ ", annotation=" + annotation
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\UserOperationLogEntryEventEntity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setDefaultRedisSerializer(RedisSerializer<Object> defaultRedisSerializer) {
this.defaultRedisSerializer = defaultRedisSerializer;
}
@Autowired(required = false)
public void setSessionRepositoryCustomizer(
ObjectProvider<ReactiveSessionRepositoryCustomizer<ReactiveRedisSessionRepository>> sessionRepositoryCustomizers) {
this.sessionRepositoryCustomizers = sessionRepositoryCustomizers.orderedStream().collect(Collectors.toList());
}
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
@Override
public void setEmbeddedValueResolver(StringValueResolver resolver) {
this.embeddedValueResolver = resolver;
}
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
Map<String, Object> attributeMap = importMetadata
.getAnnotationAttributes(EnableRedisWebSession.class.getName());
AnnotationAttributes attributes = AnnotationAttributes.fromMap(attributeMap);
if (attributes == null) {
return;
}
this.maxInactiveInterval = Duration.ofSeconds(attributes.<Integer>getNumber("maxInactiveIntervalInSeconds"));
|
String redisNamespaceValue = attributes.getString("redisNamespace");
if (StringUtils.hasText(redisNamespaceValue)) {
this.redisNamespace = this.embeddedValueResolver.resolveStringValue(redisNamespaceValue);
}
this.saveMode = attributes.getEnum("saveMode");
}
private ReactiveRedisTemplate<String, Object> createReactiveRedisTemplate() {
RedisSerializer<String> keySerializer = RedisSerializer.string();
RedisSerializer<Object> defaultSerializer = (this.defaultRedisSerializer != null) ? this.defaultRedisSerializer
: new JdkSerializationRedisSerializer(this.classLoader);
RedisSerializationContext<String, Object> serializationContext = RedisSerializationContext
.<String, Object>newSerializationContext(defaultSerializer)
.key(keySerializer)
.hashKey(keySerializer)
.build();
return new ReactiveRedisTemplate<>(this.redisConnectionFactory, serializationContext);
}
@Autowired(required = false)
public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) {
this.sessionIdGenerator = sessionIdGenerator;
}
}
|
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\config\annotation\web\server\RedisWebSessionConfiguration.java
| 2
|
请完成以下Java代码
|
public LookupValuesPage getFieldTypeahead(final String fieldName, final String query)
{
return lookups.getFieldTypeahead(fieldName, query);
}
public LookupValuesList getFieldDropdown(final String fieldName)
{
return lookups.getFieldDropdown(fieldName);
}
public BPartnerId getBpartnerId()
{
return BPartnerId.ofRepoId(bpartner.getIdAsInt());
}
|
public String getBpartnerDisplayName()
{
return bpartner.getDisplayName();
}
public boolean isVendor()
{
return !isCustomer();
}
public CurrencyId getCurrencyId()
{
return CurrencyId.ofRepoId(currency.getIdAsInt());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsRow.java
| 1
|
请完成以下Java代码
|
public class Evaluator
{
public static double[] evaluate(String testPath, String predictedPath, HashSet<String> puncTags) throws IOException
{
CoNLLReader goldReader = new CoNLLReader(testPath);
CoNLLReader predictedReader = new CoNLLReader(predictedPath);
ArrayList<CompactTree> goldConfiguration = goldReader.readStringData();
ArrayList<CompactTree> predConfiguration = predictedReader.readStringData();
float unlabMatch = 0f;
float labMatch = 0f;
int all = 0;
float fullULabMatch = 0f;
float fullLabMatch = 0f;
int numTree = 0;
for (int i = 0; i < predConfiguration.size(); i++)
{
HashMap<Integer, Pair<Integer, String>> goldDeps = goldConfiguration.get(i).goldDependencies;
HashMap<Integer, Pair<Integer, String>> predDeps = predConfiguration.get(i).goldDependencies;
ArrayList<String> goldTags = goldConfiguration.get(i).posTags;
numTree++;
boolean fullMatch = true;
boolean fullUnlabMatch = true;
for (int dep : goldDeps.keySet())
{
if (!puncTags.contains(goldTags.get(dep - 1).trim()))
{
all++;
int gh = goldDeps.get(dep).first;
int ph = predDeps.get(dep).first;
String gl = goldDeps.get(dep).second.trim();
String pl = predDeps.get(dep).second.trim();
|
if (ph == gh)
{
unlabMatch++;
if (pl.equals(gl))
labMatch++;
else
{
fullMatch = false;
}
}
else
{
fullMatch = false;
fullUnlabMatch = false;
}
}
}
if (fullMatch)
fullLabMatch++;
if (fullUnlabMatch)
fullULabMatch++;
}
// DecimalFormat format = new DecimalFormat("##.00");
double labeledAccuracy = 100.0 * labMatch / all;
double unlabaledAccuracy = 100.0 * unlabMatch / all;
// System.err.println("Labeled accuracy: " + format.format(labeledAccuracy));
// System.err.println("Unlabeled accuracy: " + format.format(unlabaledAccuracy));
double labExact = 100.0 * fullLabMatch / numTree;
double ulabExact = 100.0 * fullULabMatch / numTree;
// System.err.println("Labeled exact match: " + format.format(labExact));
// System.err.println("Unlabeled exact match: " + format.format(ulabExact) + " \n");
return new double[]{unlabaledAccuracy, labeledAccuracy};
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\perceptron\accessories\Evaluator.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private ApiAuditConfigsMap retrieveMap()
{
return ApiAuditConfigsMap.ofList(
queryBL.createQueryBuilder(I_API_Audit_Config.class)
.create()
.stream()
.map(ApiAuditConfigRepository::fromRecord)
.collect(ImmutableList.toImmutableList()));
}
@NonNull
private static ApiAuditConfig fromRecord(@NonNull final I_API_Audit_Config record)
{
return ApiAuditConfig.builder()
.apiAuditConfigId(ApiAuditConfigId.ofRepoId(record.getAPI_Audit_Config_ID()))
.active(record.isActive())
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.seqNo(record.getSeqNo())
.isBypassAudit(record.isBypassAudit())
|
.forceProcessedAsync(record.isForceProcessedAsync())
.keepRequestDays(record.getKeepRequestDays())
.keepRequestBodyDays(record.getKeepRequestBodyDays())
.keepResponseDays(record.getKeepResponseDays())
.keepResponseBodyDays(record.getKeepResponseBodyDays())
.keepErroredRequestDays(record.getKeepErroredRequestDays())
.method(HttpMethod.ofNullableCode(record.getMethod()))
.pathPrefix(record.getPathPrefix())
.notifyUserInCharge(NotificationTriggerType.ofNullableCode(record.getNotifyUserInCharge()))
.userGroupInChargeId(UserGroupId.ofRepoIdOrNull(record.getAD_UserGroup_InCharge_ID()))
.performAuditAsync(!record.isSynchronousAuditLoggingEnabled())
.wrapApiResponse(record.isWrapApiResponse())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\audit\apirequest\config\ApiAuditConfigRepository.java
| 2
|
请完成以下Java代码
|
public String getTaxId() {
return taxId;
}
/**
* Sets the value of the taxId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTaxId(String value) {
this.taxId = value;
}
/**
* Gets the value of the regnId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRegnId() {
return regnId;
}
/**
* Sets the value of the regnId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRegnId(String value) {
this.regnId = value;
}
/**
* Gets the value of the taxTp property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTaxTp() {
return taxTp;
}
/**
* Sets the value of the taxTp property.
*
* @param value
* allowed object is
|
* {@link String }
*
*/
public void setTaxTp(String value) {
this.taxTp = value;
}
/**
* Gets the value of the authstn property.
*
* @return
* possible object is
* {@link TaxAuthorisation1 }
*
*/
public TaxAuthorisation1 getAuthstn() {
return authstn;
}
/**
* Sets the value of the authstn property.
*
* @param value
* allowed object is
* {@link TaxAuthorisation1 }
*
*/
public void setAuthstn(TaxAuthorisation1 value) {
this.authstn = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TaxParty2.java
| 1
|
请完成以下Java代码
|
public boolean isSortControlSupported() {
return sortControlSupported;
}
public void setSortControlSupported(boolean sortControlSupported) {
this.sortControlSupported = sortControlSupported;
}
public String getGroupIdAttribute() {
return groupIdAttribute;
}
public void setGroupIdAttribute(String groupIdAttribute) {
this.groupIdAttribute = groupIdAttribute;
}
public String getGroupMemberAttribute() {
return groupMemberAttribute;
}
public void setGroupMemberAttribute(String groupMemberAttribute) {
this.groupMemberAttribute = groupMemberAttribute;
}
public boolean isUseSsl() {
return useSsl;
}
public void setUseSsl(boolean useSsl) {
this.useSsl = useSsl;
}
public boolean isUsePosixGroups() {
return usePosixGroups;
}
public void setUsePosixGroups(boolean usePosixGroups) {
this.usePosixGroups = usePosixGroups;
}
public SearchControls getSearchControls() {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchControls.setTimeLimit(30000);
return searchControls;
}
public String getGroupTypeAttribute() {
return groupTypeAttribute;
}
public void setGroupTypeAttribute(String groupTypeAttribute) {
this.groupTypeAttribute = groupTypeAttribute;
|
}
public boolean isAllowAnonymousLogin() {
return allowAnonymousLogin;
}
public void setAllowAnonymousLogin(boolean allowAnonymousLogin) {
this.allowAnonymousLogin = allowAnonymousLogin;
}
public boolean isAuthorizationCheckEnabled() {
return authorizationCheckEnabled;
}
public void setAuthorizationCheckEnabled(boolean authorizationCheckEnabled) {
this.authorizationCheckEnabled = authorizationCheckEnabled;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public boolean isPasswordCheckCatchAuthenticationException() {
return passwordCheckCatchAuthenticationException;
}
public void setPasswordCheckCatchAuthenticationException(boolean passwordCheckCatchAuthenticationException) {
this.passwordCheckCatchAuthenticationException = passwordCheckCatchAuthenticationException;
}
}
|
repos\camunda-bpm-platform-master\engine-plugins\identity-ldap\src\main\java\org\camunda\bpm\identity\impl\ldap\LdapConfiguration.java
| 1
|
请完成以下Java代码
|
public class JaxbDateUnmarshalling {
public static final String DEFAULT_DATE_UNMARSHALLING_FILE = "default-date-unmarshalling.xml";
public static final String CUSTOM_DATE_UNMARSHALLING_FILE = "custom-date-unmarshalling.xml";
public static Book unmarshalDates(InputStream inputFile) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
return (Book) jaxbUnmarshaller.unmarshal(inputFile);
}
public static BookDateAdapter unmarshalDatesUsingCustomXmlAdapter(InputStream inputFile) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(BookDateAdapter.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
return (BookDateAdapter) jaxbUnmarshaller.unmarshal(inputFile);
}
public static BookLocalDateTimeAdapter unmarshalDatesUsingJava8(InputStream inputFile) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(BookLocalDateTimeAdapter.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
return (BookLocalDateTimeAdapter) jaxbUnmarshaller.unmarshal(inputFile);
|
}
public static InputStream getInputStream(String file) {
ClassLoader classLoader = JaxbDateUnmarshalling.class.getClassLoader();
return classLoader.getResourceAsStream(file);
}
public static void main(String[] args) throws JAXBException {
Book book = unmarshalDates(getInputStream(DEFAULT_DATE_UNMARSHALLING_FILE));
BookDateAdapter bookDateAdapter = unmarshalDatesUsingCustomXmlAdapter(getInputStream(CUSTOM_DATE_UNMARSHALLING_FILE));
BookLocalDateTimeAdapter bookLocalDateTimeAdapter = unmarshalDatesUsingJava8(getInputStream(CUSTOM_DATE_UNMARSHALLING_FILE));
System.out.println(book);
System.out.println(bookDateAdapter);
System.out.println(bookLocalDateTimeAdapter);
}
}
|
repos\tutorials-master\xml-modules\jaxb\src\main\java\com\baeldung\jaxb\dateunmarshalling\JaxbDateUnmarshalling.java
| 1
|
请完成以下Java代码
|
public static byte[] encrypt(byte[] content, byte[] aesKey) {
return aes(Pkcs7Encoder.encode(content), aesKey, Cipher.ENCRYPT_MODE);
}
/**
* 加密
*
* @param encrypted 内容
* @param aesKey 密钥
* @return byte[]
*/
public static byte[] decrypt(byte[] encrypted, byte[] aesKey) {
return Pkcs7Encoder.decode(aes(encrypted, aesKey, Cipher.DECRYPT_MODE));
}
/**
* ase加密
*
* @param encrypted 内容
* @param aesKey 密钥
* @param mode 模式
* @return byte[]
*/
@SneakyThrows
private static byte[] aes(byte[] encrypted, byte[] aesKey, int mode) {
Assert.isTrue(aesKey.length == 32, "IllegalAesKey, aesKey's length must be 32");
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));
cipher.init(mode, keySpec, iv);
return cipher.doFinal(encrypted);
}
/**
* 提供基于PKCS7算法的加解密接口.
*/
private static class Pkcs7Encoder {
private static final int BLOCK_SIZE = 32;
private static byte[] encode(byte[] src) {
int count = src.length;
// 计算需要填充的位数
int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE);
|
// 获得补位所用的字符
byte pad = (byte) (amountToPad & 0xFF);
byte[] pads = new byte[amountToPad];
for (int index = 0; index < amountToPad; index++) {
pads[index] = pad;
}
int length = count + amountToPad;
byte[] dest = new byte[length];
System.arraycopy(src, 0, dest, 0, count);
System.arraycopy(pads, 0, dest, count, amountToPad);
return dest;
}
private static byte[] decode(byte[] decrypted) {
int pad = decrypted[decrypted.length - 1];
if (pad < 1 || pad > BLOCK_SIZE) {
pad = 0;
}
if (pad > 0) {
return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
}
return decrypted;
}
}
}
|
repos\SpringBlade-master\blade-gateway\src\main\java\org\springblade\gateway\utils\JwtCrypto.java
| 1
|
请完成以下Java代码
|
public void setSumDeliveredInStockingUOM (final BigDecimal SumDeliveredInStockingUOM)
{
set_Value (COLUMNNAME_SumDeliveredInStockingUOM, SumDeliveredInStockingUOM);
}
@Override
public BigDecimal getSumDeliveredInStockingUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SumDeliveredInStockingUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSumOrderedInStockingUOM (final BigDecimal SumOrderedInStockingUOM)
{
set_Value (COLUMNNAME_SumOrderedInStockingUOM, SumOrderedInStockingUOM);
}
@Override
|
public BigDecimal getSumOrderedInStockingUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SumOrderedInStockingUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setUserFlag (final @Nullable java.lang.String UserFlag)
{
set_Value (COLUMNNAME_UserFlag, UserFlag);
}
@Override
public java.lang.String getUserFlag()
{
return get_ValueAsString(COLUMNNAME_UserFlag);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_Desadv.java
| 1
|
请完成以下Java代码
|
public void setDecisionLogic(DmnDecisionLogic decisionLogic) {
this.decisionLogic = decisionLogic;
}
public DmnDecisionLogic getDecisionLogic() {
return decisionLogic;
}
public void setRequiredDecision(List<DmnDecision> requiredDecision) {
this.requiredDecision = requiredDecision;
}
@Override
public Collection<DmnDecision> getRequiredDecisions() {
return requiredDecision;
}
|
@Override
public boolean isDecisionTable() {
return decisionLogic != null && decisionLogic instanceof DmnDecisionTableImpl;
}
@Override
public String toString() {
return "DmnDecisionTableImpl{" +
" key= "+ key +
", name= "+ name +
", requiredDecision=" + requiredDecision +
", decisionLogic=" + decisionLogic +
'}';
}
}
|
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnDecisionImpl.java
| 1
|
请完成以下Java代码
|
private int getItemsPerBatch()
{
return sysConfigBL.getIntValue(SYSCONFIG_ItemsPerBatch, DEFAULT_ItemsPerBatch);
}
/**
* IC update result.
*
* @author metas-dev <dev@metasfresh.com>
*/
private static final class ICUpdateResult
{
private int countOk = 0;
private int countErrors = 0;
public void addInvoiceCandidate()
{
countOk++;
}
public void incrementErrorsCount()
{
countErrors++;
}
@Override
public String toString()
{
return getSummary();
}
public String getSummary()
{
return "Updated " + countOk + " invoice candidates, " + countErrors + " errors";
}
}
|
/**
* IC update exception handler
*/
private final class ICTrxItemExceptionHandler extends FailTrxItemExceptionHandler
{
private final ICUpdateResult result;
public ICTrxItemExceptionHandler(@NonNull final ICUpdateResult result)
{
this.result = result;
}
/**
* Resets the given IC to its old values, and sets an error flag in it.
*/
@Override
public void onItemError(final Throwable e, final Object item)
{
result.incrementErrorsCount();
final I_C_Invoice_Candidate ic = InterfaceWrapperHelper.create(item, I_C_Invoice_Candidate.class);
// gh #428: don't discard changes that were already made, because they might include a change of QtyInvoice.
// in that case, a formerly Processed IC might need to be flagged as unprocessed.
// if we discard all changes in this case, then we will have IsError='Y' and also an error message in the IC,
// but the user will probably ignore it, because the IC is still flagged as processed.
invoiceCandBL.setError(ic, e);
// invoiceCandBL.discardChangesAndSetError(ic, e);
invoiceCandDAO.save(ic);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandInvalidUpdater.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DruidConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource getDataSource(){
return new DruidDataSource();
}
// 配置Druid监控
// 配置一个管理后台的Servlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String,String> initParams=new HashMap<>();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","admin");
initParams.put("allow",""); // 默认就是允许所有访问
// initParams.put("deny","127.0.0.1"); // 拒绝哪个网址访问,优先级大于allow
|
bean.setInitParameters(initParams);
return bean;
}
//2、配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams = new HashMap<>();
// 配置不拦截哪些请求
initParams.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
// 配置拦截所有请求
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
|
repos\springboot-demo-master\druid\src\main\java\com\et\druid\config\DruidConfig.java
| 2
|
请完成以下Java代码
|
public org.eevolution.model.I_PP_Cost_Collector getPP_Cost_Collector() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_PP_Cost_Collector_ID, org.eevolution.model.I_PP_Cost_Collector.class);
}
@Override
public void setPP_Cost_Collector(org.eevolution.model.I_PP_Cost_Collector PP_Cost_Collector)
{
set_ValueFromPO(COLUMNNAME_PP_Cost_Collector_ID, org.eevolution.model.I_PP_Cost_Collector.class, PP_Cost_Collector);
}
/** Set Manufacturing Cost Collector.
@param PP_Cost_Collector_ID Manufacturing Cost Collector */
@Override
public void setPP_Cost_Collector_ID (int PP_Cost_Collector_ID)
{
if (PP_Cost_Collector_ID < 1)
set_Value (COLUMNNAME_PP_Cost_Collector_ID, null);
|
else
set_Value (COLUMNNAME_PP_Cost_Collector_ID, Integer.valueOf(PP_Cost_Collector_ID));
}
/** Get Manufacturing Cost Collector.
@return Manufacturing Cost Collector */
@Override
public int getPP_Cost_Collector_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PP_Cost_Collector_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_M_Transaction.java
| 1
|
请完成以下Java代码
|
public boolean isReady() {
return true;
}
@Override
public void setWriteListener(WriteListener writeListener) {
}
@Override
public void write(int b) {
outputStream.write(b);
}
};
}
@Override
|
public PrintWriter getWriter() {
return writer;
}
@Override
public void flushBuffer() throws IOException {
super.flushBuffer();
writer.flush();
}
public String getBodyAsString() {
writer.flush();
return outputStream.toString();
}
}
|
repos\tutorials-master\logging-modules\log-all-requests\src\main\java\com\baeldung\logallrequests\ResponseWrapper.java
| 1
|
请完成以下Java代码
|
public void setCopyright(String value) {
this.copyright = value;
}
/**
* Gets the value of the description property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDescription(String value) {
this.description = value;
}
/**
* Gets the value of the version property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getVersion() {
return version;
}
/**
* Sets the value of the version property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setVersion(Long value) {
this.version = value;
}
/**
* Gets the value of the id property.
*
* @return
|
* possible object is
* {@link Long }
*
*/
public long getId() {
if (id == null) {
return 0L;
} else {
return id;
}
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setId(Long value) {
this.id = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\DependsOnType.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void assertValidApiKey(final String apiKey)
{
if (!Objects.equals(this.apiKey, apiKey))
{
throw new NotLoggedInException(i18n.get("LoginService.error.notLoggedIn"));
}
}
@GetMapping("/pullFromAppServer")
public void pullFromAppServer(
@RequestHeader("apiKey") final String apiKey)
{
assertValidApiKey(apiKey);
senderToMetasfreshService.requestFromMetasfreshAllMasterdataAsync();
}
/**
* @param dateFromStr inclusive (>=). Value e.g. {@link 2025-02-11}.
* @param dateToStr also inclusive (<=). Value e.g. {@link 2025-02-11}.
*/
@GetMapping("/pushReports")
public void pushReports(
@RequestHeader("apiKey") final String apiKey,
@RequestParam(name = "bpartnerId", required = false, defaultValue = "0") final long bpartnerId,
@RequestParam(name = "productId", required = false, defaultValue = "0") final long productId,
@RequestParam("dateFrom") final String dateFromStr,
@RequestParam("dateTo") final String dateToStr)
{
assertValidApiKey(apiKey);
final LocalDate dateFrom = LocalDate.parse(dateFromStr);
final LocalDate dateTo = LocalDate.parse(dateToStr);
pushDailyReports(bpartnerId, productId, dateFrom, dateTo);
pushWeeklyReports(bpartnerId, productId, dateFrom, dateTo);
}
private void pushDailyReports(
final long bpartnerId,
final long productId,
final LocalDate dateFrom,
final LocalDate dateTo)
{
final List<ProductSupply> productSupplies = productSuppliesService.getProductSupplies(
bpartnerId,
productId,
dateFrom,
dateTo);
senderToMetasfreshService.pushDailyReportsAsync(productSupplies);
}
|
private void pushWeeklyReports(
final long bpartnerId,
final long productId,
final LocalDate dateFrom,
final LocalDate dateTo)
{
final List<WeekSupply> records = productSuppliesService.getWeeklySupplies(
bpartnerId,
productId,
dateFrom,
dateTo);
senderToMetasfreshService.pushWeeklyReportsAsync(records);
}
@GetMapping("/pushActiveRfQs")
public void pushActiveRfQs(
@RequestHeader("apiKey") final String apiKey,
@RequestParam(name = "bpartnerId", required = false, defaultValue = "0") final long bpartnerId)
{
assertValidApiKey(apiKey);
final BPartner bpartner = bpartnerId > 0 ? bpartnersRepository.getOne(bpartnerId) : null;
final List<Rfq> rfqs = rfqService.getActiveRfqs(bpartner);
senderToMetasfreshService.pushRfqsAsync(rfqs);
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\rest\MetasfreshSyncRestController.java
| 2
|
请完成以下Java代码
|
public class InvokeOtherAction extends InvokeExternalSystemProcess
{
@Override
protected IExternalSystemChildConfigId getExternalChildConfigId()
{
// dev-note: for "Other" external system there is no "real" ChildConfig, so when `childConfigId` process param is set
// (i.e. only from the AD_Scheduler) it is actually referring to an ExternalSystem_Config_ID, aka ParentConfigID
final int parentConfigRepoId = childConfigId > 0 ? childConfigId : getRecord_ID();
final ExternalSystemParentConfigId parentConfigId = ExternalSystemParentConfigId.ofRepoId(parentConfigRepoId);
return ExternalSystemOtherConfigId.ofExternalSystemParentConfigId(parentConfigId);
}
@Override
protected Map<String, String> extractExternalSystemParameters(final ExternalSystemParentConfig externalSystemParentConfig)
{
final ExternalSystemOtherConfig otherConfig = ExternalSystemOtherConfig.cast(externalSystemParentConfig.getChildConfig());
final Map<String, String> parameters = new HashMap<>();
otherConfig.getParameters().forEach(parameter -> parameters.put(parameter.getName(), parameter.getValue()));
return parameters;
}
@Override
protected String getTabName()
{
return ExternalSystemType.Other.getValue();
}
@Override
protected ExternalSystemType getExternalSystemType()
{
return ExternalSystemType.Other;
}
@Override
protected long getSelectedRecordCount(final IProcessPreconditionsContext context)
{
throw new UnsupportedOperationException("getSelectedRecordCount unsupported for InvokeOtherAction!");
}
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.isMoreThanOneSelected())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
|
else if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
final ExternalSystemParentConfigId parentConfigId = ExternalSystemParentConfigId.ofRepoId(context.getSingleSelectedRecordId());
if (!ExternalSystemType.Other.getValue().equals(externalSystemConfigDAO.getParentTypeById(parentConfigId)))
{
return ProcessPreconditionsResolution.reject();
}
final ExternalSystemOtherConfigId externalSystemOtherConfigId = ExternalSystemOtherConfigId.ofExternalSystemParentConfigId(parentConfigId);
final ExternalSystemParentConfig externalSystemParentConfig = externalSystemConfigDAO.getById(externalSystemOtherConfigId);
final ExternalSystemOtherConfig otherConfig = ExternalSystemOtherConfig.cast(externalSystemParentConfig.getChildConfig());
if (otherConfig.getParameters().isEmpty())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\InvokeOtherAction.java
| 1
|
请完成以下Java代码
|
public void initialize(@NonNull final ModelValidationEngine engine, @Nullable final MClient client)
{
if (client != null)
{
m_AD_Client_ID = client.getAD_Client_ID();
}
final String tableName = getTableName();
if (isDocument())
{
engine.addDocValidate(tableName, this);
}
else
{
engine.addModelChange(tableName, this);
}
}
public void init()
{
if (m_AD_Client_ID > 0)
{
final I_AD_Client client = clientDAO.getById(m_AD_Client_ID);
modelValidationEngine.addModelValidator(this, client);
}
else
{
// register for all clients
modelValidationEngine.addModelValidator(this);
}
}
// NOTE: keep in sync with initialize method
public void destroy()
{
// Unregister from model validation engine
final String tableName = getTableName();
modelValidationEngine.removeModelChange(tableName, this);
modelValidationEngine.removeDocValidate(tableName, this);
}
@Override
public int getAD_Client_ID()
{
return m_AD_Client_ID;
}
@Override
public String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID)
{
return null; // nothing
}
@Nullable
@Override
public String modelChange(final PO po, final int type) throws Exception
{
return null; // nothing
}
@Nullable
@Override
public String docValidate(final PO po, final int timing) throws Exception
{
Check.assume(isDocument(), "PO '{}' is a document", po);
if (timing == ModelValidator.TIMING_AFTER_COMPLETE
&& !documentBL.isReversalDocument(po))
{
externalSystemScriptedExportConversionService
.retrieveBestMatchingConfig(AdTableAndClientId.of(AdTableId.ofRepoId(po.get_Table_ID()),
ClientId.ofRepoId(getAD_Client_ID())), po.get_ID())
.ifPresent(config -> executeInvokeScriptedExportConversionAction(config, po.get_ID()));
}
return null;
}
@NonNull
public AdTableId getTableId()
{
return adTableId;
|
}
private void executeInvokeScriptedExportConversionAction(
@NonNull final ExternalSystemScriptedExportConversionConfig config,
final int recordId)
{
final int configTableId = tableDAO.retrieveTableId(I_ExternalSystem_Config_ScriptedExportConversion.Table_Name);
try
{
trxManager.runAfterCommit(() -> {
ProcessInfo.builder()
.setCtx(getCtx())
.setRecord(configTableId, config.getId().getRepoId())
.setAD_ProcessByClassname(InvokeScriptedExportConversionAction.class.getName())
.addParameter(PARAM_EXTERNAL_REQUEST, COMMAND_CONVERT_MESSAGE_FROM_METASFRESH)
.addParameter(PARAM_CHILD_CONFIG_ID, config.getId().getRepoId())
.addParameter(PARAM_Record_ID, recordId)
.buildAndPrepareExecution()
.executeSync();
});
}
catch (final Exception e)
{
log.warn(InvokeScriptedExportConversionAction.class.getName() + " process failed for Config ID {}, Record ID: {}",
config.getId(), recordId, e);
}
}
private String getTableName()
{
return tableName;
}
private boolean isDocument()
{
return isDocument;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\scriptedexportconversion\interceptor\ExternalSystemScriptedExportConversionInterceptor.java
| 1
|
请完成以下Java代码
|
private static final class ProcessInfoParameterDocumentValuesSupplier implements DocumentValuesSupplier
{
private final DocumentId adPInstanceId;
private final Map<String, ProcessInfoParameter> processInfoParameters;
public ProcessInfoParameterDocumentValuesSupplier(final DocumentId adPInstanceId, final Map<String, ProcessInfoParameter> processInfoParameters)
{
this.adPInstanceId = adPInstanceId;
this.processInfoParameters = processInfoParameters;
}
@Override
public DocumentId getDocumentId()
{
return adPInstanceId;
|
}
@Override
public String getVersion()
{
return VERSION_DEFAULT;
}
@Override
public Object getValue(final DocumentFieldDescriptor parameterDescriptor)
{
return extractParameterValue(processInfoParameters, parameterDescriptor);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\adprocess\ADProcessParametersRepository.java
| 1
|
请完成以下Java代码
|
public IHUStorageDAO getHUStorageDAO()
{
return getHUStorageFactory().getHUStorageDAO();
}
@Override
public IHUStorageFactory getHUStorageFactory()
{
Check.assumeNotNull(huStorageFactory, "IHUStorageFactory member of AbstractAttributeStorageFactory {} is not null", this);
return huStorageFactory;
}
@Override
public void setHUStorageFactory(final IHUStorageFactory huStorageFactory)
{
this.huStorageFactory = huStorageFactory;
}
|
@Override
public String toString()
{
final ToStringHelper stringHelper = MoreObjects.toStringHelper(this);
toString(stringHelper);
return stringHelper.toString();
}
protected void toString(final ToStringHelper stringHelper)
{
// nothing on this level
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\AbstractAttributeStorageFactory.java
| 1
|
请完成以下Java代码
|
public Integer getYear() {
return year;
}
/**
* @param year the year to set
*/
public void setYear(Integer year) {
this.year = year;
}
/**
* @return the sku
*/
public String getSku() {
return sku;
}
/**
* @param sku the sku to set
*/
public void setSku(String sku) {
this.sku = sku;
}
/**
* @return the maker
*/
public CarMaker getMaker() {
return maker;
}
/**
* @param maker the maker to set
*/
public void setMaker(CarMaker maker) {
this.maker = maker;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((maker == null) ? 0 : maker.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((sku == null) ? 0 : sku.hashCode());
result = prime * result + ((year == null) ? 0 : year.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
|
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CarModel other = (CarModel) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (maker == null) {
if (other.maker != null)
return false;
} else if (!maker.equals(other.maker))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (sku == null) {
if (other.sku != null)
return false;
} else if (!sku.equals(other.sku))
return false;
if (year == null) {
if (other.year != null)
return false;
} else if (!year.equals(other.year))
return false;
return true;
}
}
|
repos\tutorials-master\apache-olingo\src\main\java\com\baeldung\examples\olingo2\domain\CarModel.java
| 1
|
请完成以下Java代码
|
public void train(String folderPath) throws IOException
{
train(folderPath, "UTF-8");
}
@Override
public Map<String, Double> predict(Document document)
{
AbstractModel model = getModel();
if (model == null)
{
throw new IllegalStateException("未训练模型!无法执行预测!");
}
if (document == null)
{
throw new IllegalArgumentException("参数 text == null");
}
double[] probs = categorize(document);
Map<String, Double> scoreMap = new TreeMap<String, Double>();
for (int i = 0; i < probs.length; i++)
{
scoreMap.put(model.catalog[i], probs[i]);
}
return scoreMap;
}
@Override
public int label(Document document) throws IllegalArgumentException, IllegalStateException
{
AbstractModel model = getModel();
if (model == null)
{
throw new IllegalStateException("未训练模型!无法执行预测!");
}
if (document == null)
|
{
throw new IllegalArgumentException("参数 text == null");
}
double[] probs = categorize(document);
double max = Double.NEGATIVE_INFINITY;
int best = -1;
for (int i = 0; i < probs.length; i++)
{
if (probs[i] > max)
{
max = probs[i];
best = i;
}
}
return best;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\classifiers\AbstractClassifier.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void refreshAccessToken() {
lock.lock();
try {
if (System.currentTimeMillis() > getTokenExpires()) {
AdminSettings settings = ctx.getAdminSettingsService().findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "mail");
JsonNode jsonValue = settings.getJsonValue();
String clientId = jsonValue.get("clientId").asText();
String clientSecret = jsonValue.get("clientSecret").asText();
String refreshToken = jsonValue.get("refreshToken").asText();
String tokenUri = jsonValue.get("tokenUri").asText();
String providerId = jsonValue.get("providerId").asText();
TokenResponse tokenResponse = new RefreshTokenRequest(new NetHttpTransport(), new GsonFactory(),
new GenericUrl(tokenUri), refreshToken)
.setClientAuthentication(new ClientParametersAuthentication(clientId, clientSecret))
.execute();
if (MailOauth2Provider.OFFICE_365.name().equals(providerId)) {
((ObjectNode) jsonValue).put("refreshToken", tokenResponse.getRefreshToken());
((ObjectNode) jsonValue).put("refreshTokenExpires", Instant.now().plus(Duration.ofDays(AZURE_DEFAULT_REFRESH_TOKEN_LIFETIME_IN_DAYS)).toEpochMilli());
ctx.getAdminSettingsService().saveAdminSettings(TenantId.SYS_TENANT_ID, settings);
}
accessToken = tokenResponse.getAccessToken();
tokenExpires = System.currentTimeMillis() + (tokenResponse.getExpiresInSeconds().intValue() * 1000);
|
}
} catch (Exception e) {
log.error("Unable to retrieve access token: {}", e.getMessage());
throw new RuntimeException("Error while retrieving access token: " + e.getMessage());
} finally {
lock.unlock();
}
}
private int parsePort(String strPort) {
try {
return Integer.parseInt(strPort);
} catch (NumberFormatException e) {
throw new IncorrectParameterException(String.format("Invalid smtp port value: %s", strPort));
}
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\mail\TbMailSender.java
| 2
|
请完成以下Java代码
|
public Amount convertToRealValue(@NonNull final Amount amount)
{
final int toRealValueMultiplier = getToRealValueMultiplier();
return toRealValueMultiplier > 0 ? amount : amount.negate();
}
public Money convertToRealValue(@NonNull final Money money)
{
final int toRealValueMultiplier = getToRealValueMultiplier();
return toRealValueMultiplier > 0 ? money : money.negate();
}
public Money convertToRelativeValue(@NonNull final Money realValue)
{
final int toRelativeValueMultiplier = getToRelativeValueMultiplier();
return toRelativeValueMultiplier > 0 ? realValue : realValue.negate();
}
public Amount convertToRelativeValue(@NonNull final Amount realValue)
{
final int toRelativeValueMultiplier = getToRelativeValueMultiplier();
return toRelativeValueMultiplier > 0 ? realValue : realValue.negate();
}
public boolean isNegateToConvertToRealValue()
{
return getToRealValueMultiplier() < 0;
}
private int getToRealValueMultiplier()
{
int toRealValueMultiplier = this.toRealValueMultiplier;
if (toRealValueMultiplier == 0)
{
toRealValueMultiplier = this.toRealValueMultiplier = computeToRealValueMultiplier();
}
return toRealValueMultiplier;
}
private int computeToRealValueMultiplier()
{
int multiplier = 1;
// Adjust by SOTrx if needed
if (!isAPAdjusted)
{
final int multiplierAP = soTrx.isPurchase() ? -1 : +1;
multiplier *= multiplierAP;
}
// Adjust by Credit Memo if needed
if (!isCreditMemoAdjusted)
{
final int multiplierCM = isCreditMemo ? -1 : +1;
multiplier *= multiplierCM;
}
return multiplier;
}
private int getToRelativeValueMultiplier()
{
// NOTE: the relative->real and real->relative value multipliers are the same
return getToRealValueMultiplier();
}
public Money fromNotAdjustedAmount(@NonNull final Money money)
{
final int multiplier = computeFromNotAdjustedAmountMultiplier();
|
return multiplier > 0 ? money : money.negate();
}
private int computeFromNotAdjustedAmountMultiplier()
{
int multiplier = 1;
// Do we have to SO adjust?
if (isAPAdjusted)
{
final int multiplierAP = soTrx.isPurchase() ? -1 : +1;
multiplier *= multiplierAP;
}
// Do we have to adjust by Credit Memo?
if (isCreditMemoAdjusted)
{
final int multiplierCM = isCreditMemo ? -1 : +1;
multiplier *= multiplierCM;
}
return multiplier;
}
/**
* @return {@code true} for purchase-invoice and sales-creditmemo. {@code false} otherwise.
*/
public boolean isOutgoingMoney()
{
return isCreditMemo ^ soTrx.isPurchase();
}
public InvoiceAmtMultiplier withAPAdjusted(final boolean isAPAdjustedNew)
{
return isAPAdjusted == isAPAdjustedNew ? this : toBuilder().isAPAdjusted(isAPAdjustedNew).build().intern();
}
public InvoiceAmtMultiplier withCMAdjusted(final boolean isCreditMemoAdjustedNew)
{
return isCreditMemoAdjusted == isCreditMemoAdjustedNew ? this : toBuilder().isCreditMemoAdjusted(isCreditMemoAdjustedNew).build().intern();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\InvoiceAmtMultiplier.java
| 1
|
请完成以下Java代码
|
public void setIsManual (final boolean IsManual)
{
set_Value (COLUMNNAME_IsManual, IsManual);
}
@Override
public boolean isManual()
{
return get_ValueAsBoolean(COLUMNNAME_IsManual);
}
@Override
public void setIsSOTrx (final boolean IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, IsSOTrx);
}
@Override
public boolean isSOTrx()
{
return get_ValueAsBoolean(COLUMNNAME_IsSOTrx);
}
@Override
public void setLine (final int Line)
{
set_Value (COLUMNNAME_Line, Line);
}
@Override
public int getLine()
{
return get_ValueAsInt(COLUMNNAME_Line);
}
@Override
public void setOpenAmt (final BigDecimal OpenAmt)
{
set_ValueNoCheck (COLUMNNAME_OpenAmt, OpenAmt);
}
@Override
public BigDecimal getOpenAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_OpenAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPayAmt (final BigDecimal PayAmt)
{
set_Value (COLUMNNAME_PayAmt, PayAmt);
}
@Override
public BigDecimal getPayAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PayAmt);
return bd != null ? bd : BigDecimal.ZERO;
|
}
/**
* PaymentRule AD_Reference_ID=195
* Reference name: _Payment Rule
*/
public static final int PAYMENTRULE_AD_Reference_ID=195;
/** Cash = B */
public static final String PAYMENTRULE_Cash = "B";
/** CreditCard = K */
public static final String PAYMENTRULE_CreditCard = "K";
/** DirectDeposit = T */
public static final String PAYMENTRULE_DirectDeposit = "T";
/** Check = S */
public static final String PAYMENTRULE_Check = "S";
/** OnCredit = P */
public static final String PAYMENTRULE_OnCredit = "P";
/** DirectDebit = D */
public static final String PAYMENTRULE_DirectDebit = "D";
/** Mixed = M */
public static final String PAYMENTRULE_Mixed = "M";
/** PayPal = L */
public static final String PAYMENTRULE_PayPal = "L";
/** PayPal Extern = V */
public static final String PAYMENTRULE_PayPalExtern = "V";
/** Kreditkarte Extern = U */
public static final String PAYMENTRULE_KreditkarteExtern = "U";
/** Sofortüberweisung = R */
public static final String PAYMENTRULE_Sofortueberweisung = "R";
/** Rückerstattung = E */
public static final String PAYMENTRULE_Rueckerstattung = "E";
/** Verrechnung = F */
public static final String PAYMENTRULE_Verrechnung = "F";
@Override
public void setPaymentRule (final java.lang.String PaymentRule)
{
set_Value (COLUMNNAME_PaymentRule, PaymentRule);
}
@Override
public java.lang.String getPaymentRule()
{
return get_ValueAsString(COLUMNNAME_PaymentRule);
}
@Override
public void setReference (final @Nullable java.lang.String Reference)
{
set_Value (COLUMNNAME_Reference, Reference);
}
@Override
public java.lang.String getReference()
{
return get_ValueAsString(COLUMNNAME_Reference);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaySelectionLine.java
| 1
|
请完成以下Java代码
|
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public List<String> getImageUrls() {
return imageUrls;
}
public void setImageUrls(List<String> imageUrls) {
this.imageUrls = imageUrls;
}
public List<String> getVideoUrls() {
return videoUrls;
}
public void setVideoUrls(List<String> videoUrls) {
this.videoUrls = videoUrls;
}
public Integer getStock() {
return stock;
}
|
public void setStock(Integer stock) {
this.stock = stock;
}
@Override
public String toString() {
return "ProductModel{" +
"name='" + name + '\'' +
", description='" + description + '\'' +
", status='" + status + '\'' +
", currency='" + currency + '\'' +
", price=" + price +
", imageUrls=" + imageUrls +
", videoUrls=" + videoUrls +
", stock=" + stock +
'}';
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-graphql-2\src\main\java\com\baeldung\graphqlvsrest\model\ProductModel.java
| 1
|
请完成以下Java代码
|
public List<CustomProperty> getCustomProperties() {
return customProperties;
}
public void setCustomProperties(List<CustomProperty> customProperties) {
this.customProperties = customProperties;
}
public String getSkipExpression() {
return skipExpression;
}
public void setSkipExpression(String skipExpression) {
this.skipExpression = skipExpression;
}
@Override
public String getValidateFormFields() {
return validateFormFields;
}
@Override
public void setValidateFormFields(String validateFormFields) {
this.validateFormFields = validateFormFields;
}
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 setA_RegistrationAttribute_ID (int A_RegistrationAttribute_ID)
{
if (A_RegistrationAttribute_ID < 1)
set_ValueNoCheck (COLUMNNAME_A_RegistrationAttribute_ID, null);
else
set_ValueNoCheck (COLUMNNAME_A_RegistrationAttribute_ID, Integer.valueOf(A_RegistrationAttribute_ID));
}
/** Get Registration Attribute.
@return Asset Registration Attribute
*/
public int getA_RegistrationAttribute_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_RegistrationAttribute_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
|
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
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 Product.
@return Product, Service, Item
*/
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_A_RegistrationProduct.java
| 1
|
请完成以下Java代码
|
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final SingleParameterStringExpression other = (SingleParameterStringExpression)obj;
return Objects.equals(parameter, other.parameter);
}
@Override
public String getExpressionString()
{
return expressionStr;
}
@Override
public String getFormatedExpressionString()
{
return parameter.toStringWithMarkers();
}
@Override
public Set<CtxName> getParameters()
{
return parametersAsCtxName;
}
@Override
public String evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException
{
try
|
{
return StringExpressionsHelper.evaluateParam(parameter, ctx, onVariableNotFound);
}
catch (final Exception e)
{
throw ExpressionEvaluationException.wrapIfNeeded(e)
.addExpression(this);
}
}
@Override
public IStringExpression resolvePartial(final Evaluatee ctx) throws ExpressionEvaluationException
{
try
{
final String value = StringExpressionsHelper.evaluateParam(parameter, ctx, OnVariableNotFound.ReturnNoResult);
if (value == null || value == EMPTY_RESULT)
{
return this;
}
return ConstantStringExpression.of(value);
}
catch (final Exception e)
{
throw ExpressionEvaluationException.wrapIfNeeded(e)
.addExpression(this);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\SingleParameterStringExpression.java
| 1
|
请完成以下Java代码
|
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public boolean isTree()
{
Object oo = get_Value(COLUMNNAME_IsTree);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public void setIsTree(boolean IsTree)
{
set_Value (COLUMNNAME_IsTree, Boolean.valueOf(IsTree));
}
@Override
public boolean isParameterNextLine()
{
Object oo = get_Value(COLUMNNAME_IsParameterNextLine);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public void setIsParameterNextLine(boolean IsParameterNextLine)
{
set_Value (COLUMNNAME_IsParameterNextLine, Boolean.valueOf(IsParameterNextLine));
}
public void setParameterSeqNo (int ParameterSeqNo)
{
set_Value (COLUMNNAME_ParameterSeqNo, Integer.valueOf(ParameterSeqNo));
}
public int getParameterSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ParameterSeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
public void setParameterDisplayLogic (String ParameterDisplayLogic)
{
set_Value (COLUMNNAME_ParameterDisplayLogic, ParameterDisplayLogic);
}
public String getParameterDisplayLogic ()
{
return (String)get_Value(COLUMNNAME_ParameterDisplayLogic);
}
public void setColumnName (String ColumnName)
{
set_Value (COLUMNNAME_ColumnName, ColumnName);
}
|
public String getColumnName ()
{
return (String)get_Value(COLUMNNAME_ColumnName);
}
/** Set Query Criteria Function.
@param QueryCriteriaFunction
column used for adding a sql function to query criteria
*/
public void setQueryCriteriaFunction (String QueryCriteriaFunction)
{
set_Value (COLUMNNAME_QueryCriteriaFunction, QueryCriteriaFunction);
}
/** Get Query Criteria Function.
@return column used for adding a sql function to query criteria
*/
public String getQueryCriteriaFunction ()
{
return (String)get_Value(COLUMNNAME_QueryCriteriaFunction);
}
@Override
public void setDefaultValue (String DefaultValue)
{
set_Value (COLUMNNAME_DefaultValue, DefaultValue);
}
@Override
public String getDefaultValue ()
{
return (String)get_Value(COLUMNNAME_DefaultValue);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_InfoColumn.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 setInternalName (final java.lang.String InternalName)
{
set_Value (COLUMNNAME_InternalName, InternalName);
}
@Override
public java.lang.String getInternalName()
{
return get_ValueAsString(COLUMNNAME_InternalName);
}
@Override
public void setMobile_Application_Action_ID (final int Mobile_Application_Action_ID)
{
|
if (Mobile_Application_Action_ID < 1)
set_ValueNoCheck (COLUMNNAME_Mobile_Application_Action_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Mobile_Application_Action_ID, Mobile_Application_Action_ID);
}
@Override
public int getMobile_Application_Action_ID()
{
return get_ValueAsInt(COLUMNNAME_Mobile_Application_Action_ID);
}
@Override
public void setMobile_Application_ID (final int Mobile_Application_ID)
{
if (Mobile_Application_ID < 1)
set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, Mobile_Application_ID);
}
@Override
public int getMobile_Application_ID()
{
return get_ValueAsInt(COLUMNNAME_Mobile_Application_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Mobile_Application_Action.java
| 1
|
请完成以下Java代码
|
public Object getVariable(String variableName) {
return getVariableLocal(variableName);
}
public Object getVariableLocal(String variableName) {
return wrappedScope.getVariableLocal(variableName);
}
public <T extends TypedValue> T getVariableTyped(String variableName) {
return getVariableLocalTyped(variableName);
}
public <T extends TypedValue> T getVariableTyped(String variableName, boolean deserializeValue) {
return getVariableLocalTyped(variableName, deserializeValue);
}
public <T extends TypedValue> T getVariableLocalTyped(String variableName) {
return wrappedScope.getVariableLocalTyped(variableName);
}
public <T extends TypedValue> T getVariableLocalTyped(String variableName, boolean deserializeValue) {
return wrappedScope.getVariableLocalTyped(variableName, deserializeValue);
}
public Set<String> getVariableNames() {
return getVariableNamesLocal();
}
public Set<String> getVariableNamesLocal() {
return wrappedScope.getVariableNamesLocal();
}
public void setVariable(String variableName, Object value) {
setVariableLocal(variableName, value);
}
public void setVariableLocal(String variableName, Object value) {
wrappedScope.setVariableLocal(variableName, value);
}
public void setVariables(Map<String, ? extends Object> variables) {
setVariablesLocal(variables);
}
public void setVariablesLocal(Map<String, ? extends Object> variables) {
wrappedScope.setVariablesLocal(variables);
|
}
public boolean hasVariables() {
return hasVariablesLocal();
}
public boolean hasVariablesLocal() {
return wrappedScope.hasVariablesLocal();
}
public boolean hasVariable(String variableName) {
return hasVariableLocal(variableName);
}
public boolean hasVariableLocal(String variableName) {
return wrappedScope.hasVariableLocal(variableName);
}
public void removeVariable(String variableName) {
removeVariableLocal(variableName);
}
public void removeVariableLocal(String variableName) {
wrappedScope.removeVariableLocal(variableName);
}
public void removeVariables(Collection<String> variableNames) {
removeVariablesLocal(variableNames);
}
public void removeVariablesLocal(Collection<String> variableNames) {
wrappedScope.removeVariablesLocal(variableNames);
}
public void removeVariables() {
removeVariablesLocal();
}
public void removeVariablesLocal() {
wrappedScope.removeVariablesLocal();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\variable\scope\VariableScopeLocalAdapter.java
| 1
|
请完成以下Java代码
|
public String getJobDefinitionConfiguration() {
return jobDefinitionConfiguration;
}
public void setJobDefinitionConfiguration(String jobDefinitionConfiguration) {
this.jobDefinitionConfiguration = jobDefinitionConfiguration;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public boolean isCreationLog() {
return state == JobState.CREATED.getStateCode();
}
public boolean isFailureLog() {
return state == JobState.FAILED.getStateCode();
}
|
public boolean isSuccessLog() {
return state == JobState.SUCCESSFUL.getStateCode();
}
public boolean isDeletionLog() {
return state == JobState.DELETED.getStateCode();
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public String getFailedActivityId() {
return failedActivityId;
}
public void setFailedActivityId(String failedActivityId) {
this.failedActivityId = failedActivityId;
}
public String getBatchId() {
return batchId;
}
public void setBatchId(String batchId) {
this.batchId = batchId;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricJobLogEvent.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static Book map(InputStream is) {
try(JsonReader jsonReader = Json.createReader(is)) {
JsonObject jsonObject = jsonReader.readObject();
Book book = new Book();
book.setId(getStringFromJson("id", jsonObject));
book.setIsbn(getStringFromJson("isbn", jsonObject));
book.setName(getStringFromJson("name", jsonObject));
book.setAuthor(getStringFromJson("author", jsonObject));
book.setPages(getIntFromJson("pages",jsonObject));
return book;
}
}
private static String getStringFromJson(String key, JsonObject json) {
String returnedString = null;
if (json.containsKey(key)) {
JsonString value = json.getJsonString(key);
if (value != null) {
returnedString = value.getString();
|
}
}
return returnedString;
}
private static Integer getIntFromJson(String key, JsonObject json) {
Integer returnedValue = null;
if (json.containsKey(key)) {
JsonNumber value = json.getJsonNumber(key);
if (value != null) {
returnedValue = value.intValue();
}
}
return returnedValue;
}
}
|
repos\tutorials-master\microservices-modules\helidon\helidon-mp\src\main\java\com\baeldung\microprofile\util\BookMapper.java
| 2
|
请完成以下Java代码
|
private final IAllocationResult allocateOnVirtualMaterialItem(
@NonNull final I_M_HU_Item vhuItem,
@NonNull final IAllocationRequest request)
{
//
// Create Actual Allocation Request depending on vhuItem's (remaining) capacity
final IAllocationRequest requestActual = createActualRequest(vhuItem, request);
if (requestActual.isZeroQty())
{
return AllocationUtils.nullResult();
}
final BigDecimal qtyToAllocate = request.getQty();
final BigDecimal qtyAllocated = requestActual.getQty();
//
// Create HU Transaction Candidate
final IHUTransactionCandidate trx = createHUTransaction(requestActual, vhuItem);
//
// Create Allocation Result
return AllocationUtils.createQtyAllocationResult(
qtyToAllocate,
qtyAllocated,
Arrays.asList(trx), // trxs
ImmutableList.of()); // attributeTrxs
}
/**
|
* Create transaction candidate which when it will be processed it will change the storage quantity.
*
* @param requestActual request (used to get Product, UOM, Date, Qty etc)
* @param vhuItem Virtual HU item on which we actually allocated/deallocated
*/
@NonNull
private final IHUTransactionCandidate createHUTransaction(
@NonNull final IAllocationRequest requestActual,
@Nullable final I_M_HU_Item vhuItem)
{
final I_M_HU_Item itemFirstNotPureVirtual = services.getFirstNotPureVirtualItem(vhuItem);
final Object referencedModel = AllocationUtils.getReferencedModel(requestActual);
final Quantity qtyTrx = AllocationUtils.getQuantity(requestActual, direction);
return new HUTransactionCandidate(
referencedModel,
itemFirstNotPureVirtual, // HU Item
vhuItem, // VHU Item
requestActual.getProductId(), // Product
qtyTrx, // Qty/UOM
requestActual.getDate()); // Date
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\strategy\AbstractAllocationStrategy.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public GrpcServiceDiscoverer defaultGrpcServiceDiscoverer() {
return new AnnotationGrpcServiceDiscoverer();
}
@ConditionalOnBean(CompressorRegistry.class)
@Bean
public GrpcServerConfigurer compressionServerConfigurer(final CompressorRegistry registry) {
return builder -> builder.compressorRegistry(registry);
}
@ConditionalOnBean(DecompressorRegistry.class)
@Bean
public GrpcServerConfigurer decompressionServerConfigurer(final DecompressorRegistry registry) {
return builder -> builder.decompressorRegistry(registry);
}
@ConditionalOnMissingBean(GrpcServerConfigurer.class)
|
@Bean
public List<GrpcServerConfigurer> defaultServerConfigurers() {
return Collections.emptyList();
}
@ConditionalOnMissingBean
@ConditionalOnBean(GrpcServerFactory.class)
@Bean
public GrpcServerLifecycle grpcServerLifecycle(
final GrpcServerFactory factory,
final GrpcServerProperties properties,
final ApplicationEventPublisher eventPublisher) {
return new GrpcServerLifecycle(factory, properties.getShutdownGracePeriod(), eventPublisher);
}
}
|
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\autoconfigure\GrpcServerAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public void run(String... args) throws Exception {
// Start the clock
long start = System.currentTimeMillis();
// Kick of multiple, asynchronous lookups
CompletableFuture<User> page1 = gitHubLookupService.findUser("vector4wang");
CompletableFuture<User> page2 = gitHubLookupService.findUser("Zhuinden");
CompletableFuture<User> page3 = gitHubLookupService.findUser("xialeistudio");
Future<User> futurePage1 = gitHubLookupService.findUser2("vector4wang");
Future<User> futurePage2 = gitHubLookupService.findUser2("Zhuinden");
Future<User> futurePage3 = gitHubLookupService.findUser2("xialeistudio");
logger.info("--> " + futurePage1.get());
logger.info("--> " + futurePage2.get());
logger.info("--> " + futurePage3.get());
|
// Wait until they are all done
CompletableFuture.allOf(page1,page2,page3).join();
// Print results, including elapsed time
logger.info("Elapsed time: " + (System.currentTimeMillis() - start));
logger.info("--> " + page1.get());
logger.info("--> " + page2.get());
logger.info("--> " + page3.get());
}
}
|
repos\spring-boot-quick-master\quick-async\src\main\java\com\async\init\AppRunner.java
| 1
|
请完成以下Java代码
|
public class SystemTime
{
private static final TimeSource defaultTimeSource = new SystemTimeSource();
@Nullable
private static TimeSource timeSource;
private static TimeSource getTimeSource()
{
return timeSource == null ? defaultTimeSource : timeSource;
}
/**
* After invocation of this method, the time returned will be the system time again.
*/
public static void resetTimeSource()
{
timeSource = null;
}
/**
* @param newTimeSource the given TimeSource will be used for the time returned by the
* methods of this class (unless it is null).
*/
public static void setTimeSource(@NonNull final TimeSource newTimeSource)
{
timeSource = newTimeSource;
}
public static void setFixedTimeSource(@NonNull final ZonedDateTime date)
{
setTimeSource(FixedTimeSource.ofZonedDateTime(date));
}
/**
* @param zonedDateTime ISO 8601 date time format (see {@link ZonedDateTime#parse(CharSequence)}).
* e.g. 2018-02-28T13:13:13+01:00[Europe/Berlin]
*/
public static void setFixedTimeSource(@NonNull final String zonedDateTime)
{
setTimeSource(FixedTimeSource.ofZonedDateTime(ZonedDateTime.parse(zonedDateTime)));
}
public static long millis()
{
return getTimeSource().millis();
}
public static ZoneId zoneId()
{
return getTimeSource().zoneId();
}
public static GregorianCalendar asGregorianCalendar()
{
final GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(millis());
return cal;
}
public static Date asDate()
{
return new Date(millis());
}
public static Timestamp asTimestamp()
{
return new Timestamp(millis());
}
/**
* Same as {@link #asTimestamp()} but the returned date will be truncated to DAY.
*/
public static Timestamp asDayTimestamp()
{
final GregorianCalendar cal = asGregorianCalendar();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return new Timestamp(cal.getTimeInMillis());
}
|
public static Instant asInstant()
{
return Instant.ofEpochMilli(millis());
}
public static LocalDateTime asLocalDateTime()
{
return asZonedDateTime().toLocalDateTime();
}
@NonNull
public static LocalDate asLocalDate()
{
return asLocalDate(zoneId());
}
@NonNull
public static LocalDate asLocalDate(@NonNull final ZoneId zoneId)
{
return asZonedDateTime(zoneId).toLocalDate();
}
public static ZonedDateTime asZonedDateTime()
{
return asZonedDateTime(zoneId());
}
public static ZonedDateTime asZonedDateTimeAtStartOfDay()
{
return asZonedDateTime(zoneId()).truncatedTo(ChronoUnit.DAYS);
}
public static ZonedDateTime asZonedDateTimeAtEndOfDay(@NonNull final ZoneId zoneId)
{
return asZonedDateTime(zoneId)
.toLocalDate()
.atTime(LocalTime.MAX)
.atZone(zoneId);
}
public static ZonedDateTime asZonedDateTime(@NonNull final ZoneId zoneId)
{
return asInstant().atZone(zoneId);
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\time\SystemTime.java
| 1
|
请完成以下Java代码
|
public class BouncyCastleAesCbcBytesEncryptor extends BouncyCastleAesBytesEncryptor {
public BouncyCastleAesCbcBytesEncryptor(String password, CharSequence salt) {
super(password, salt);
}
public BouncyCastleAesCbcBytesEncryptor(String password, CharSequence salt, BytesKeyGenerator ivGenerator) {
super(password, salt, ivGenerator);
}
@Override
public byte[] encrypt(byte[] bytes) {
byte[] iv = this.ivGenerator.generateKey();
CBCModeCipher cbcModeCipher = CBCBlockCipher.newInstance(AESEngine.newInstance());
PaddedBufferedBlockCipher blockCipher = new PaddedBufferedBlockCipher(cbcModeCipher, new PKCS7Padding());
blockCipher.init(true, new ParametersWithIV(this.secretKey, iv));
byte[] encrypted = process(blockCipher, bytes);
return (iv != null) ? EncodingUtils.concatenate(iv, encrypted) : encrypted;
}
@Override
public byte[] decrypt(byte[] encryptedBytes) {
CBCModeCipher cbcModeCipher = CBCBlockCipher.newInstance(AESEngine.newInstance());
byte[] iv = EncodingUtils.subArray(encryptedBytes, 0, this.ivGenerator.getKeyLength());
encryptedBytes = EncodingUtils.subArray(encryptedBytes, this.ivGenerator.getKeyLength(), encryptedBytes.length);
PaddedBufferedBlockCipher blockCipher = new PaddedBufferedBlockCipher(cbcModeCipher, new PKCS7Padding());
blockCipher.init(false, new ParametersWithIV(this.secretKey, iv));
return process(blockCipher, encryptedBytes);
}
private byte[] process(BufferedBlockCipher blockCipher, byte[] in) {
|
byte[] buf = new byte[blockCipher.getOutputSize(in.length)];
int bytesWritten = blockCipher.processBytes(in, 0, in.length, buf, 0);
try {
bytesWritten += blockCipher.doFinal(buf, bytesWritten);
}
catch (InvalidCipherTextException ex) {
throw new IllegalStateException("unable to encrypt/decrypt", ex);
}
if (bytesWritten == buf.length) {
return buf;
}
byte[] out = new byte[bytesWritten];
System.arraycopy(buf, 0, out, 0, bytesWritten);
return out;
}
}
|
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\encrypt\BouncyCastleAesCbcBytesEncryptor.java
| 1
|
请完成以下Java代码
|
public class SocketServer {
private static Logger logger = LoggerFactory.getLogger(SocketServer.class);
public static void main(String[] args) throws IOException {
//创建一个ServerSocket在端口4700监听客户请求
try (ServerSocket server = new ServerSocket(4700)) {
while (true) {
//使用accept()阻塞等待客户请求,有客户, 请求到来则产生一个Socket对象,并继续执行
Socket socket = server.accept();
ExecutorService executor = Executors.newFixedThreadPool(10);
executor.submit(() -> {
try (//由Socket对象得到输入流,并构造相应的BufferedReader对象
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//由Socket对象得到输出流,并构造PrintWriter对象
PrintWriter os = new PrintWriter(socket.getOutputStream());) {
String line = is.readLine();
while (!"bye".equals(line) && line != null) {
//在标准输出上打印从客户端读入的字符串
System.out.println(Thread.currentThread().getName() + " 收到客户端信息:" + line);
//向客户端输出该字符串
os.println("服务端收到了你的消息:" + line);
//刷新输出流,使Client马上收到该字符串
|
os.flush();
line = is.readLine();
}
// 关闭连接
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
});
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
}
|
repos\spring-boot-student-master\spring-boot-student-netty\src\main\java\com\xiaolyuh\bio\SocketServer.java
| 1
|
请完成以下Java代码
|
protected final boolean isNotReceivableService(final I_C_Invoice_Candidate ic)
{
final IProductDAO productDAO = Services.get(IProductDAO.class);
final IProductBL productBL = Services.get(IProductBL.class);
final I_M_Product product = productDAO.getById(ic.getM_Product_ID());
// If no product, consider it as a non receivable service (maybe it's a charge?!)
if (product == null)
{
return true;
}
final ProductType productType = productBL.getProductType(ProductId.ofRepoId(product.getM_Product_ID()));
if (productType.isFreightCost())
{
return false;
}
// If the product is not a service
// => return false
if (!productType.isService())
{
return false;
}
// NOTE: at this point i think we shall extend the business logic and check when a service will be received and when not
// but for now we are considering that it will never ever be received
return true;
}
/**
* Sets delivery data from first shipment/receipt that was created for this invoice candidate.
*
* @param ic invoice candidate
* @param firstInOut first shipment/receipt or <code>null</code>
*/
protected final void setDeliveredDataFromFirstInOut(@NonNull final I_C_Invoice_Candidate ic, @Nullable final I_M_InOut firstInOut)
{
ic.setM_InOut(firstInOut);
if (firstInOut == null)
{
ic.setDeliveryDate(null);
ic.setFirst_Ship_BPLocation_ID(-1);
ic.setC_Shipping_Location_ID(-1);
}
else
{
|
ic.setDeliveryDate(firstInOut.getMovementDate());
ic.setFirst_Ship_BPLocation_ID(firstInOut.getC_BPartner_Location_ID()); // C_BPartner_Location
ic.setC_Shipping_Location_ID(firstInOut.getC_BPartner_Location_Value_ID()); // C_Location
}
}
/**
* Assumes that the given {@code icRecord}'s {@code AD_Client_ID}, {@code AD_Org_ID} and {@code IsSOTrx} are already set at this point
*/
protected final void setDefaultInvoiceDocType(final @NonNull I_C_Invoice_Candidate icRecord)
{
final DocTypeQuery docTypeQuery = DocTypeQuery.builder()
.adClientId(icRecord.getAD_Client_ID())
.adOrgId(icRecord.getAD_Org_ID())
.isSOTrx(icRecord.isSOTrx())
.docBaseType(icRecord.isSOTrx()
? InvoiceDocBaseType.CustomerInvoice.getCode()
: InvoiceDocBaseType.VendorInvoice.getCode())
.build();
final DocTypeId docTypeIdOrNull = docTypeBL.getDocTypeIdOrNull(docTypeQuery);
if (docTypeIdOrNull != null)
{
icRecord.setC_DocTypeInvoice_ID(docTypeIdOrNull.getRepoId());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\AbstractInvoiceCandidateHandler.java
| 1
|
请完成以下Java代码
|
public String getCityList(final Model model) {
model.addAttribute("cityList", cityService.findAll());
return CITY_LIST_PATH_NAME;
}
@RequestMapping(value = "/create", method = RequestMethod.GET)
public String createCityForm(final Model model) {
model.addAttribute("city", new City());
model.addAttribute("action", "create");
return CITY_FORM_PATH_NAME;
}
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String postCity(@ModelAttribute City city) {
cityService.insertByCity(city);
return REDIRECT_TO_CITY_URL;
}
@RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
|
public String getCity(@PathVariable Long id, final Model model) {
final Mono<City> city = cityService.findById(id);
model.addAttribute("city", city);
model.addAttribute("action", "update");
return CITY_FORM_PATH_NAME;
}
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String putBook(@ModelAttribute City city) {
cityService.update(city);
return REDIRECT_TO_CITY_URL;
}
@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
public String deleteCity(@PathVariable Long id) {
cityService.delete(id);
return CITY_LIST_PATH_NAME;
}
}
|
repos\springboot-learning-example-master\springboot-webflux-10-book-manage-sys\src\main\java\demo\springboot\web\CityController.java
| 1
|
请完成以下Java代码
|
public void setC_Region(final org.compiere.model.I_C_Region C_Region)
{
set_ValueFromPO(COLUMNNAME_C_Region_ID, org.compiere.model.I_C_Region.class, C_Region);
}
@Override
public void setC_Region_ID (final int C_Region_ID)
{
if (C_Region_ID < 1)
set_Value (COLUMNNAME_C_Region_ID, null);
else
set_Value (COLUMNNAME_C_Region_ID, C_Region_ID);
}
@Override
public int getC_Region_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Region_ID);
}
@Override
public void 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 setFreight_Cost_Calc_Price (final BigDecimal Freight_Cost_Calc_Price)
{
set_Value (COLUMNNAME_Freight_Cost_Calc_Price, Freight_Cost_Calc_Price);
}
@Override
public BigDecimal getFreight_Cost_Calc_Price()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Freight_Cost_Calc_Price);
|
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setM_DiscountSchema_Calculated_Surcharge_Price_ID (final int M_DiscountSchema_Calculated_Surcharge_Price_ID)
{
if (M_DiscountSchema_Calculated_Surcharge_Price_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_Price_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_Price_ID, M_DiscountSchema_Calculated_Surcharge_Price_ID);
}
@Override
public int getM_DiscountSchema_Calculated_Surcharge_Price_ID()
{
return get_ValueAsInt(COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_Price_ID);
}
@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);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DiscountSchema_Calculated_Surcharge_Price.java
| 1
|
请完成以下Java代码
|
private SecretKey loadSecretKeyFromResource(Resource resource) {
byte[] secretKeyBytes = Base64.getDecoder().decode(getResourceBytes(resource));
return new SecretKeySpec(secretKeyBytes, "AES");
}
/**
* <p>generateSecretKey.</p>
*
* @return a {@link javax.crypto.SecretKey} object
*/
@SneakyThrows
public static SecretKey generateSecretKey() {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
SecureRandom random = SecureRandom.getInstanceStrong();
keyGenerator.init(AES_KEY_SIZE, random);
return keyGenerator.generateKey();
}
/**
* <p>generateBase64EncodedSecretKey.</p>
*
* @return a {@link java.lang.String} object
*/
@SneakyThrows
public static String generateBase64EncodedSecretKey() {
SecretKey key = generateSecretKey();
byte[] secretKeyBytes = key.getEncoded();
return Base64.getEncoder().encodeToString(secretKeyBytes);
}
/**
* <p>getAESKeyFromPassword.</p>
*
* @param password an array of {@link char} objects
* @param saltGenerator a {@link org.jasypt.salt.SaltGenerator} object
* @param iterations a int
* @param algorithm a {@link java.lang.String} object
* @return a {@link javax.crypto.SecretKey} object
*/
|
@SneakyThrows
public static SecretKey getAESKeyFromPassword(char[] password, SaltGenerator saltGenerator, int iterations, String algorithm){
SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
KeySpec spec = new PBEKeySpec(password, saltGenerator.generateSalt(AES_KEY_PASSWORD_SALT_LENGTH), iterations, AES_KEY_SIZE);
return new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
}
/**
* <p>Constructor for SimpleGCMByteEncryptor.</p>
*
* @param config a {@link com.ulisesbocchio.jasyptspringboot.encryptor.SimpleGCMConfig} object
*/
public SimpleGCMByteEncryptor(SimpleGCMConfig config) {
this.key = Singleton.from(this::loadSecretKey, config);
this.ivGenerator = Singleton.from(config::getActualIvGenerator);
this.algorithm = config.getAlgorithm();
}
}
|
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\encryptor\SimpleGCMByteEncryptor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public FilterRegistrationBean<Filter> processEngineAuthenticationFilter(JerseyApplicationPath applicationPath) {
FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
registration.setName("camunda-auth");
registration.setFilter(new ProcessEngineAuthenticationFilter());
registration.setOrder(AUTH_FILTER_PRECEDENCE);
String restApiPathPattern = applicationPath.getUrlMapping();
registration.addUrlPatterns(restApiPathPattern);
// if nothing is set, use Http Basic authentication
CamundaBpmRunAuthenticationProperties properties = camundaBpmRunProperties.getAuth();
if (properties.getAuthentication() == null || CamundaBpmRunAuthenticationProperties.DEFAULT_AUTH.equals(properties.getAuthentication())) {
registration.addInitParameter("authentication-provider", "org.camunda.bpm.engine.rest.security.auth.impl.HttpBasicAuthenticationProvider");
}
return registration;
}
@Bean
@ConditionalOnProperty(name = "enabled", havingValue = "true", prefix = CamundaBpmRunCorsProperty.PREFIX)
public FilterRegistrationBean<Filter> corsFilter(JerseyApplicationPath applicationPath) {
FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
registration.setName("camunda-cors");
CorsFilter corsFilter = new CorsFilter();
registration.setFilter(corsFilter);
registration.setOrder(CORS_FILTER_PRECEDENCE);
String restApiPathPattern = applicationPath.getUrlMapping();
registration.addUrlPatterns(restApiPathPattern);
registration.addInitParameter(CorsFilter.PARAM_CORS_ALLOWED_ORIGINS,
camundaBpmRunProperties.getCors().getAllowedOrigins());
registration.addInitParameter(CorsFilter.PARAM_CORS_ALLOWED_METHODS,
CamundaBpmRunCorsProperty.DEFAULT_HTTP_METHODS);
registration.addInitParameter(CorsFilter.PARAM_CORS_ALLOWED_HEADERS,
camundaBpmRunProperties.getCors().getAllowedHeaders());
registration.addInitParameter(CorsFilter.PARAM_CORS_EXPOSED_HEADERS,
camundaBpmRunProperties.getCors().getExposedHeaders());
|
registration.addInitParameter(CorsFilter.PARAM_CORS_SUPPORT_CREDENTIALS,
String.valueOf(camundaBpmRunProperties.getCors().getAllowCredentials()));
registration.addInitParameter(CorsFilter.PARAM_CORS_PREFLIGHT_MAXAGE,
camundaBpmRunProperties.getCors().getPreflightMaxAge());
return registration;
}
@Bean
public CamundaJerseyResourceConfig camundaRunJerseyResourceConfig() {
CamundaJerseyResourceConfig camundaJerseyResourceConfig = new CamundaJerseyResourceConfig();
camundaJerseyResourceConfig.setProperties(Collections.singletonMap("jersey.config.server.wadl.disableWadl", camundaBpmRunProperties.getRest().isDisableWadl()));
return camundaJerseyResourceConfig;
}
}
|
repos\camunda-bpm-platform-master\distro\run\core\src\main\java\org\camunda\bpm\run\CamundaBpmRunRestConfiguration.java
| 2
|
请完成以下Java代码
|
public int getAD_User_Login_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_Login_ID);
}
@Override
public void setHostKey (java.lang.String HostKey)
{
set_Value (COLUMNNAME_HostKey, HostKey);
}
@Override
public java.lang.String getHostKey()
{
return (java.lang.String)get_Value(COLUMNNAME_HostKey);
}
@Override
public void setPassword (java.lang.String Password)
{
set_Value (COLUMNNAME_Password, Password);
}
@Override
|
public java.lang.String getPassword()
{
return (java.lang.String)get_Value(COLUMNNAME_Password);
}
@Override
public void setUserName (java.lang.String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
@Override
public java.lang.String getUserName()
{
return (java.lang.String)get_Value(COLUMNNAME_UserName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_User_Login.java
| 1
|
请完成以下Java代码
|
public Optional<Manufacturer> findManufacturerByModel(String model) {
return stream().where(c -> c.getModel()
.equals(model))
.select(c -> c.getManufacturer())
.findFirst();
}
@Override
public List<Pair<Manufacturer, Car>> findCarsPerManufacturer() {
return streamOf(Manufacturer.class).join(m -> JinqStream.from(m.getCars()))
.toList();
}
@Override
public long countCarsByModel(String model) {
return stream().where(c -> c.getModel()
.equals(model))
.count();
|
}
@Override
public List<Car> findAll(int skip, int limit) {
return stream().skip(skip)
.limit(limit)
.toList();
}
@Override
protected Class<Car> entityType() {
return Car.class;
}
}
|
repos\tutorials-master\spring-jinq\src\main\java\com\baeldung\spring\jinq\repositories\CarRepositoryImpl.java
| 1
|
请完成以下Java代码
|
public void setC_BP_Group_ID (int C_BP_Group_ID)
{
if (C_BP_Group_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BP_Group_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BP_Group_ID, Integer.valueOf(C_BP_Group_ID));
}
/** Get Geschäftspartnergruppe.
@return Geschäftspartnergruppe
*/
@Override
public int getC_BP_Group_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BP_Group_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set CS Creditpass business partner group.
@param CS_Creditpass_BP_Group_ID CS Creditpass business partner group */
@Override
public void setCS_Creditpass_BP_Group_ID (int CS_Creditpass_BP_Group_ID)
{
if (CS_Creditpass_BP_Group_ID < 1)
set_ValueNoCheck (COLUMNNAME_CS_Creditpass_BP_Group_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CS_Creditpass_BP_Group_ID, Integer.valueOf(CS_Creditpass_BP_Group_ID));
}
/** Get CS Creditpass business partner group.
@return CS Creditpass business partner group */
@Override
public int getCS_Creditpass_BP_Group_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CS_Creditpass_BP_Group_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.vertical.creditscore.creditpass.model.I_CS_Creditpass_Config getCS_Creditpass_Config() throws RuntimeException
{
|
return get_ValueAsPO(COLUMNNAME_CS_Creditpass_Config_ID, de.metas.vertical.creditscore.creditpass.model.I_CS_Creditpass_Config.class);
}
@Override
public void setCS_Creditpass_Config(de.metas.vertical.creditscore.creditpass.model.I_CS_Creditpass_Config CS_Creditpass_Config)
{
set_ValueFromPO(COLUMNNAME_CS_Creditpass_Config_ID, de.metas.vertical.creditscore.creditpass.model.I_CS_Creditpass_Config.class, CS_Creditpass_Config);
}
/** Get Creditpass Einstellung.
@return Creditpass Einstellung */
@Override
public int getCS_Creditpass_Config_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CS_Creditpass_Config_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Creditpass Einstellung.
@param CS_Creditpass_Config_ID Creditpass Einstellung */
@Override
public void setCS_Creditpass_Config_ID (int CS_Creditpass_Config_ID)
{
if (CS_Creditpass_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_CS_Creditpass_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CS_Creditpass_Config_ID, Integer.valueOf(CS_Creditpass_Config_ID));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java-gen\de\metas\vertical\creditscore\creditpass\model\X_CS_Creditpass_BP_Group.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Batch create() {
if (commandExecutor != null) {
BatchBuilder selfBatchBuilder = this;
return commandExecutor.execute(new Command<>() {
@Override
public Batch execute(CommandContext commandContext) {
return batchServiceConfiguration.getBatchEntityManager().createBatch(selfBatchBuilder);
}
});
} else {
return ((BatchServiceImpl) batchServiceConfiguration.getBatchService()).createBatch(this);
}
}
@Override
public String getBatchType() {
return batchType;
}
@Override
public String getSearchKey() {
return searchKey;
}
|
@Override
public String getSearchKey2() {
return searchKey2;
}
@Override
public String getStatus() {
return status;
}
@Override
public String getBatchDocumentJson() {
return batchDocumentJson;
}
@Override
public String getTenantId() {
return tenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\BatchBuilderImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class SecondDataSourceConfig {
/**
* 扫描spring.datasource.second开头的配置信息
*
* @return 数据源配置信息
*/
@Bean(name = "secondDataSourceProperties")
@ConfigurationProperties(prefix = "spring.datasource.second")
public DataSourceProperties dataSourceProperties() {
return new DataSourceProperties();
}
/**
* 获取主库数据源对象
*
* @param dataSourceProperties 注入名为secondDataSourceProperties的bean
* @return 数据源对象
*/
@Bean(name = "secondDataSource")
|
public DataSource dataSource(@Qualifier("secondDataSourceProperties") DataSourceProperties dataSourceProperties) {
return dataSourceProperties.initializeDataSourceBuilder().build();
}
/**
* 该方法仅在需要使用JdbcTemplate对象时选用
*
* @param dataSource 注入名为secondDataSource的bean
* @return 数据源JdbcTemplate对象
*/
@Bean(name = "secondJdbcTemplate")
public JdbcTemplate jdbcTemplate(@Qualifier("secondDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
|
repos\spring-boot-demo-master\demo-multi-datasource-jpa\src\main\java\com\xkcoding\multi\datasource\jpa\config\SecondDataSourceConfig.java
| 2
|
请完成以下Java代码
|
private List<I_C_Period> getPeriodsOfCalendar(final I_C_Calendar calendar)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(calendar);
final String trxName = InterfaceWrapperHelper.getTrxName(calendar);
final List<I_C_Year> years = Services.get(ICalendarDAO.class).retrieveYearsOfCalendar(calendar);
final List<I_C_Period> periodsOfCalendar = new ArrayList<>();
for (final I_C_Year year : years)
{
final List<I_C_Period> periodsOfYear = Services.get(ICalendarDAO.class).retrievePeriods(ctx, year, trxName);
periodsOfCalendar.addAll(periodsOfYear);
}
Collections.sort(periodsOfCalendar, new AccessorComparator<I_C_Period, Timestamp>(
new ComparableComparator<Timestamp>(),
new TypedAccessor<Timestamp>()
{
@Override
public Timestamp getValue(final Object o)
{
return ((I_C_Period)o).getStartDate();
}
}));
return periodsOfCalendar;
}
@Override
public boolean isStandardPeriod(final I_C_Period period)
{
return X_C_Period.PERIODTYPE_StandardCalendarPeriod.equals(period.getPeriodType());
} // isStandardPeriod
@Override
public IBusinessDayMatcher createBusinessDayMatcherExcluding(final Set<DayOfWeek> excludeWeekendDays)
{
// TODO: consider I_C_NonBusinessDay and compose the matchers using CompositeBusinessDayMatcher
return ExcludeWeekendBusinessDayMatcher.builder()
|
.excludeWeekendDays(excludeWeekendDays)
.build();
}
@Override
@NonNull
public CalendarId getOrgCalendarOrDefault(final @NonNull OrgId orgId)
{
final OrgInfo orgInfo = orgDAO.getOrgInfoByIdInTrx(orgId);
if (orgInfo.getCalendarId() != null)
{
return orgInfo.getCalendarId();
}
final I_C_Calendar calendar = calendarDAO.getDefaultCalendar(orgId);
return CalendarId.ofRepoId(calendar.getC_Calendar_ID());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\calendar\impl\CalendarBL.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AccountReduceBalanceDTO {
/**
* 用户编号
*/
private Long userId;
/**
* 扣减金额
*/
private Integer price;
public Long getUserId() {
return userId;
}
|
public AccountReduceBalanceDTO setUserId(Long userId) {
this.userId = userId;
return this;
}
public Integer getPrice() {
return price;
}
public AccountReduceBalanceDTO setPrice(Integer price) {
this.price = price;
return this;
}
}
|
repos\SpringBoot-Labs-master\lab-52\lab-52-seata-at-httpclient-demo\lab-52-seata-at-httpclient-demo-account-service\src\main\java\cn\iocoder\springboot\lab52\accountservice\dto\AccountReduceBalanceDTO.java
| 2
|
请完成以下Java代码
|
public List<CaseInstance> findWithVariablesByCriteria(CaseInstanceQueryImpl query) {
setSafeInValueLists(query);
return getDbSqlSession().selectListNoCacheLoadAndStore("selectCaseInstanceWithVariablesByQueryCriteria", query, getManagedEntityClass());
}
@Override
public long countByCriteria(CaseInstanceQueryImpl query) {
setSafeInValueLists(query);
return (Long) getDbSqlSession().selectOne("selectCaseInstanceCountByQueryCriteria", query);
}
@Override
public void updateLockTime(String caseInstanceId, Date lockDate, String lockOwner, Date expirationTime) {
HashMap<String, Object> params = new HashMap<>();
params.put("id", caseInstanceId);
params.put("lockTime", lockDate);
params.put("expirationTime", expirationTime);
params.put("lockOwner", lockOwner);
int result = getDbSqlSession().directUpdate("updateCaseInstanceLockTime", params);
if (result == 0) {
throw new FlowableOptimisticLockingException("Could not lock case instance");
}
}
@Override
public void clearLockTime(String caseInstanceId) {
HashMap<String, Object> params = new HashMap<>();
params.put("id", caseInstanceId);
getDbSqlSession().directUpdate("clearCaseInstanceLockTime", params);
}
|
@Override
public void clearAllLockTimes(String lockOwner) {
HashMap<String, Object> params = new HashMap<>();
params.put("lockOwner", lockOwner);
getDbSqlSession().directUpdate("clearAllCaseInstanceLockTimes", params);
}
protected void setSafeInValueLists(CaseInstanceQueryImpl caseInstanceQuery) {
if (caseInstanceQuery.getCaseInstanceIds() != null) {
caseInstanceQuery.setSafeCaseInstanceIds(createSafeInValuesList(caseInstanceQuery.getCaseInstanceIds()));
}
if (caseInstanceQuery.getInvolvedGroups() != null) {
caseInstanceQuery.setSafeInvolvedGroups(createSafeInValuesList(caseInstanceQuery.getInvolvedGroups()));
}
if (caseInstanceQuery.getOrQueryObjects() != null && !caseInstanceQuery.getOrQueryObjects().isEmpty()) {
for (CaseInstanceQueryImpl orCaseInstanceQuery : caseInstanceQuery.getOrQueryObjects()) {
setSafeInValueLists(orCaseInstanceQuery);
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\data\impl\MybatisCaseInstanceDataManagerImpl.java
| 1
|
请完成以下Java代码
|
public void trigger(DelegateExecution execution, String triggerName, Object triggerData) {
ExecutionEntity executionEntity = deleteMessageEventSubScription(execution);
leaveIntermediateCatchEvent(executionEntity);
}
@Override
public void eventCancelledByEventGateway(DelegateExecution execution) {
deleteMessageEventSubScription(execution);
CommandContextUtil.getExecutionEntityManager().deleteExecutionAndRelatedData((ExecutionEntity) execution,
DeleteReason.EVENT_BASED_GATEWAY_CANCEL, false);
}
protected ExecutionEntity deleteMessageEventSubScription(DelegateExecution execution) {
CommandContext commandContext = Context.getCommandContext();
ExecutionEntity executionEntity = (ExecutionEntity) execution;
|
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
EventSubscriptionService eventSubscriptionService = processEngineConfiguration.getEventSubscriptionServiceConfiguration().getEventSubscriptionService();
List<EventSubscriptionEntity> eventSubscriptions = executionEntity.getEventSubscriptions();
String messageName = EventDefinitionExpressionUtil.determineMessageName(commandContext, messageEventDefinition, execution);
for (EventSubscriptionEntity eventSubscription : eventSubscriptions) {
if (eventSubscription instanceof MessageEventSubscriptionEntity && eventSubscription.getEventName().equals(messageName)) {
eventSubscriptionService.deleteEventSubscription(eventSubscription);
CountingEntityUtil.handleDeleteEventSubscriptionEntityCount(eventSubscription);
}
}
return executionEntity;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\behavior\IntermediateCatchMessageEventActivityBehavior.java
| 1
|
请完成以下Java代码
|
private ImmutableList<DunningAttachment> createDunningAttachments(@NonNull final DunningDocId dunningDocId)
{
final ImmutableList.Builder<DunningAttachment> dunningAttachments = ImmutableList.builder();
final List<I_C_Invoice> dunnedInvoiceRecords = dunningService.retrieveDunnedInvoices(dunningDocId);
for (final I_C_Invoice dunnedInvoiceRecord : dunnedInvoiceRecords)
{
final AttachmentEntryQuery query = AttachmentEntryQuery
.builder()
.referencedRecord(TableRecordReference.of(dunnedInvoiceRecord))
.tagSetToTrue(AttachmentTags.TAGNAME_IS_DOCUMENT)
.build();
final List<AttachmentEntry> attachments = attachmentEntryService.getByQuery(query);
for (final AttachmentEntry attachment : attachments)
{
final byte[] attachmentData = attachmentEntryService.retrieveData(attachment.getId());
final DunningAttachment invoiceAttachment = DunningAttachment.builder()
.fileName(attachment.getFilename())
.mimeType(attachment.getMimeType())
.data(attachmentData)
.tags(attachment.getTags().toMap())
.build();
dunningAttachments.add(invoiceAttachment);
|
}
}
return dunningAttachments.build();
}
private MetasfreshVersion createMetasfreshVersion()
{
final SoftwareVersion metasfreshBuildVersion = Adempiere.getBuildVersion();
final MetasfreshVersion metasfreshVersion = MetasfreshVersion.builder()
.major(metasfreshBuildVersion.getMajor())
.minor(metasfreshBuildVersion.getMinor())
.fullVersion(Adempiere.getBuildAndDateVersion())
.build();
return metasfreshVersion;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\export\DunningToExportFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public PageResult getCategoryPage(PageQueryUtil pageUtil) {
List<NewsCategory> categoryList = newsCategoryMapper.findCategoryList(pageUtil);
int total = newsCategoryMapper.getTotalCategories(pageUtil);
PageResult pageResult = new PageResult(categoryList, total, pageUtil.getLimit(), pageUtil.getPage());
return pageResult;
}
@Override
public Boolean saveCategory(String categoryName) {
/**
* 查询是否已存在
*/
NewsCategory temp = newsCategoryMapper.selectByCategoryName(categoryName);
if (temp == null) {
NewsCategory newsCategory = new NewsCategory();
newsCategory.setCategoryName(categoryName);
return newsCategoryMapper.insertSelective(newsCategory) > 0;
}
return false;
}
@Override
public Boolean updateCategory(Long categoryId, String categoryName) {
NewsCategory newsCategory = newsCategoryMapper.selectByPrimaryKey(categoryId);
|
if (newsCategory != null) {
newsCategory.setCategoryName(categoryName);
return newsCategoryMapper.updateByPrimaryKeySelective(newsCategory) > 0;
}
return false;
}
@Override
public Boolean deleteBatchByIds(Integer[] ids) {
if (ids.length < 1) {
return false;
}
//删除分类数据
return newsCategoryMapper.deleteBatch(ids) > 0;
}
}
|
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\service\impl\CategoryServiceImpl.java
| 2
|
请完成以下Java代码
|
public void setMsgText (final @Nullable java.lang.String MsgText)
{
set_Value (COLUMNNAME_MsgText, MsgText);
}
@Override
public java.lang.String getMsgText()
{
return get_ValueAsString(COLUMNNAME_MsgText);
}
@Override
public void setSource_Record_ID (final int Source_Record_ID)
{
if (Source_Record_ID < 1)
set_Value (COLUMNNAME_Source_Record_ID, null);
else
set_Value (COLUMNNAME_Source_Record_ID, Source_Record_ID);
}
@Override
public int getSource_Record_ID()
{
return get_ValueAsInt(COLUMNNAME_Source_Record_ID);
}
@Override
public void setSource_Table_ID (final int Source_Table_ID)
{
if (Source_Table_ID < 1)
set_Value (COLUMNNAME_Source_Table_ID, null);
else
set_Value (COLUMNNAME_Source_Table_ID, Source_Table_ID);
}
@Override
public int getSource_Table_ID()
{
|
return get_ValueAsInt(COLUMNNAME_Source_Table_ID);
}
@Override
public void setTarget_Record_ID (final int Target_Record_ID)
{
if (Target_Record_ID < 1)
set_Value (COLUMNNAME_Target_Record_ID, null);
else
set_Value (COLUMNNAME_Target_Record_ID, Target_Record_ID);
}
@Override
public int getTarget_Record_ID()
{
return get_ValueAsInt(COLUMNNAME_Target_Record_ID);
}
@Override
public void setTarget_Table_ID (final int Target_Table_ID)
{
if (Target_Table_ID < 1)
set_Value (COLUMNNAME_Target_Table_ID, null);
else
set_Value (COLUMNNAME_Target_Table_ID, Target_Table_ID);
}
@Override
public int getTarget_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_Target_Table_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_BusinessRule_Log.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CustomerServiceApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(CustomerServiceApplication.class)
.web(WebApplicationType.NONE)
.build()
.run(args);
}
@Bean
ApplicationRunner runner(CustomerRepository customerRepository) {
return args -> {
assertThat(customerRepository.count()).isEqualTo(0);
Customer jonDoe = Customer.newCustomer(1L, "Jon Doe");
System.err.printf("Saving Customer [%s]%n", jonDoe);
|
jonDoe = customerRepository.save(jonDoe);
assertThat(jonDoe).isNotNull();
assertThat(jonDoe.getId()).isEqualTo(1L);
assertThat(jonDoe.getName()).isEqualTo("Jon Doe");
assertThat(customerRepository.count()).isEqualTo(1);
System.err.println("Querying for Customer [SELECT * FROM /Customers WHERE name LIKE '%Doe']");
Customer queriedJonDoe = customerRepository.findByNameLike("%Doe");
assertThat(queriedJonDoe).isEqualTo(jonDoe);
System.err.printf("Customer was [%s]%n", queriedJonDoe);
};
}
}
// end::class[]
|
repos\spring-boot-data-geode-main\spring-geode-samples\boot\configuration\src\main\java\example\app\crm\CustomerServiceApplication.java
| 2
|
请完成以下Java代码
|
public CaseInstanceEntity getCaseInstance() {
return caseInstance;
}
public void setCaseInstance(CaseInstanceEntity caseInstance) {
this.caseInstance = caseInstance;
}
public Map<String, Object> getVariables() {
return variables;
}
public void setVariables(Map<String, Object> variables) {
this.variables = variables;
}
public Case getCaseModel() {
return caseModel;
}
|
public void setCaseModel(Case caseModel) {
this.caseModel = caseModel;
}
public CaseDefinition getCaseDefinition() {
return caseDefinition;
}
public void setCaseDefinition(CaseDefinition caseDefinition) {
this.caseDefinition = caseDefinition;
}
public CmmnModel getCmmnModel() {
return cmmnModel;
}
public void setCmmnModel(CmmnModel cmmnModel) {
this.cmmnModel = cmmnModel;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\interceptor\AbstractStartCaseInstanceAfterContext.java
| 1
|
请完成以下Java代码
|
public static HuPackingInstructionsVersionId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static int toRepoId(final HuPackingInstructionsVersionId HuPackingInstructionsVersionId)
{
return HuPackingInstructionsVersionId != null ? HuPackingInstructionsVersionId.getRepoId() : -1;
}
public static final HuPackingInstructionsVersionId TEMPLATE = new HuPackingInstructionsVersionId(100);
public static final HuPackingInstructionsVersionId VIRTUAL = new HuPackingInstructionsVersionId(101);
int repoId;
private HuPackingInstructionsVersionId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "M_HU_PI_Version_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(final HuPackingInstructionsVersionId o1, final HuPackingInstructionsVersionId o2)
{
return Objects.equals(o1, o2);
}
public boolean isTemplate()
{
return isTemplateRepoId(repoId);
}
public static boolean isTemplateRepoId(final int repoId)
{
return repoId == TEMPLATE.repoId;
}
public boolean isVirtual()
{
return isVirtualRepoId(repoId);
}
public static boolean isVirtualRepoId(final int repoId)
{
return repoId == VIRTUAL.repoId;
}
|
public boolean isRealPackingInstructions()
{
return isRealPackingInstructionsRepoId(repoId);
}
public static boolean isRealPackingInstructionsRepoId(final int repoId)
{
return repoId > 0
&& !isTemplateRepoId(repoId)
&& !isVirtualRepoId(repoId);
}
public HuPackingInstructionsId getKnownPackingInstructionsIdOrNull()
{
if (isVirtual())
{
return HuPackingInstructionsId.VIRTUAL;
}
if (isTemplate())
{
return HuPackingInstructionsId.TEMPLATE;
}
else
{
return null;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\HuPackingInstructionsVersionId.java
| 1
|
请完成以下Java代码
|
public void setAD_Role_OrgAccess_ID (int AD_Role_OrgAccess_ID)
{
if (AD_Role_OrgAccess_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Role_OrgAccess_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Role_OrgAccess_ID, Integer.valueOf(AD_Role_OrgAccess_ID));
}
/** Get AD_Role_OrgAccess.
@return AD_Role_OrgAccess */
@Override
public int getAD_Role_OrgAccess_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_OrgAccess_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Schreibgeschützt.
@param IsReadOnly
Field is read only
*/
@Override
public void setIsReadOnly (boolean IsReadOnly)
{
set_Value (COLUMNNAME_IsReadOnly, Boolean.valueOf(IsReadOnly));
}
|
/** Get Schreibgeschützt.
@return Field is read only
*/
@Override
public boolean isReadOnly ()
{
Object oo = get_Value(COLUMNNAME_IsReadOnly);
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_AD_Role_OrgAccess.java
| 1
|
请完成以下Java代码
|
public void setAD_Role_ID (final int AD_Role_ID)
{
if (AD_Role_ID < 0)
set_Value (COLUMNNAME_AD_Role_ID, null);
else
set_Value (COLUMNNAME_AD_Role_ID, AD_Role_ID);
}
@Override
public int getAD_Role_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Role_ID);
}
@Override
public void setAD_Role_TableOrg_Access_ID (final int AD_Role_TableOrg_Access_ID)
{
if (AD_Role_TableOrg_Access_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Role_TableOrg_Access_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Role_TableOrg_Access_ID, AD_Role_TableOrg_Access_ID);
}
@Override
public int getAD_Role_TableOrg_Access_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Role_TableOrg_Access_ID);
|
}
@Override
public void setAD_Table_ID (final int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID);
}
@Override
public int getAD_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Table_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role_TableOrg_Access.java
| 1
|
请完成以下Java代码
|
protected void done()
{
logger.debug("Done processing: {}", this);
try
{
final ResultType result = get(); // => throw exceptions if any
runnable.finallyUpdateUI(this, result);
}
catch (final InterruptedException ex)
{
handleExceptionInUI(ex);
}
catch (final ExecutionException ex)
{
final Throwable cause = CoalesceUtil.coalesce(ex.getCause(), ex);
handleExceptionInUI(cause);
}
finally
{
doFinallyInUI();
}
}
private void handleExceptionInUI(final Throwable ex)
{
runnable.handleExceptionInUI(this, ex);
}
@Override
public void publishPartialResults(final List<PartialResultType> partialResults)
{
logger.debug("Publishing partial results to UI thread: {} ({})", partialResults, this);
if (partialResults == null || partialResults.isEmpty())
{
return;
}
for (final PartialResultType partialResult : partialResults)
{
publish(partialResult);
}
}
@Override
public void publishPartialResult(final PartialResultType partialResult)
{
logger.debug("Publishing partial result to UI thread: {} ({})", partialResult, this);
publish(partialResult);
}
private RootPaneContainer findRootPaneContainer(@Nullable final Component comp)
{
final RootPaneContainer rootPaneContainer = AEnv.getParentComponent(comp, RootPaneContainer.class);
if (rootPaneContainer == null)
{
final String errmsg = "No " + RootPaneContainer.class + " found."
+ "Ignore, but please check because this could be a development error."
+ "\n Component: " + comp
+ "\n Executor: " + this;
new AdempiereException(errmsg).throwIfDeveloperModeOrLogWarningElse(logger);
}
return rootPaneContainer;
}
private Window findWindow(@Nullable final RootPaneContainer rootPaneContainer)
{
final Component comp;
|
if (rootPaneContainer == null)
{
comp = null;
}
else if (rootPaneContainer instanceof Window)
{
return (Window)rootPaneContainer;
}
else if (rootPaneContainer instanceof Component)
{
comp = (Component)rootPaneContainer;
}
else
{
comp = rootPaneContainer.getRootPane();
}
final Window window = AEnv.getParentComponent(comp, Window.class);
if (window == null)
{
final String errmsg = "No " + Window.class + " found."
+ "Ignore, but please check because this could be a development error."
+ "\n RootPaneContainer: " + rootPaneContainer
+ "\n Component: " + comp
+ "\n Executor: " + this;
new AdempiereException(errmsg).throwIfDeveloperModeOrLogWarningElse(logger);
}
return window;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\adempiere\form\swing\SwingClientUIAsyncInvoker.java
| 1
|
请完成以下Java代码
|
public String getDatum() {
return datum;
}
/**
* Sets the value of the datum property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDatum(String value) {
this.datum = value;
}
/**
* Gets the value of the uhrzeitVon property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUhrzeitVon() {
return uhrzeitVon;
}
/**
* Sets the value of the uhrzeitVon property.
*
* @param value
* allowed object is
* {@link String }
*
*/
|
public void setUhrzeitVon(String value) {
this.uhrzeitVon = value;
}
/**
* Gets the value of the uhrzeitBis property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUhrzeitBis() {
return uhrzeitBis;
}
/**
* Sets the value of the uhrzeitBis property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUhrzeitBis(String value) {
this.uhrzeitBis = value;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java-xjc\de\metas\shipper\gateway\go\schema\Sendung.java
| 1
|
请完成以下Java代码
|
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
User user = (User) o;
return Objects.equals(firstName, user.firstName) && Objects.equals(uId, user.uId) && Objects.equals(lastName, user.lastName) && Objects.equals(alias, user.alias);
}
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 String getId() {
return idAttribute.getValue(this);
}
public void setId(String id) {
idAttribute.setValue(this, id);
}
public Collection<Documentation> getDocumentations() {
return documentationCollection.get(this);
}
public ExtensionElements getExtensionElements() {
return extensionElementsChild.getChild(this);
}
public void setExtensionElements(ExtensionElements extensionElements) {
extensionElementsChild.setChild(this, extensionElements);
}
@SuppressWarnings("rawtypes")
public DiagramElement getDiagramElement() {
Collection<Reference> incomingReferences = getIncomingReferencesByType(DiagramElement.class);
for (Reference<?> reference : incomingReferences) {
for (ModelElementInstance sourceElement : reference.findReferenceSourceElements(this)) {
String referenceIdentifier = reference.getReferenceIdentifier(sourceElement);
if (referenceIdentifier != null && referenceIdentifier.equals(getId())) {
return (DiagramElement) sourceElement;
}
}
}
return null;
}
@SuppressWarnings("rawtypes")
|
public Collection<Reference> getIncomingReferencesByType(Class<? extends ModelElementInstance> referenceSourceTypeClass) {
Collection<Reference> references = new ArrayList<Reference>();
// we traverse all incoming references in reverse direction
for (Reference<?> reference : idAttribute.getIncomingReferences()) {
ModelElementType sourceElementType = reference.getReferenceSourceElementType();
Class<? extends ModelElementInstance> sourceInstanceType = sourceElementType.getInstanceType();
// if the referencing element (source element) is a BPMNDI element, dig deeper
if (referenceSourceTypeClass.isAssignableFrom(sourceInstanceType)) {
references.add(reference);
}
}
return references;
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\BaseElementImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
class MetadataCollectors {
private final ProcessingEnvironment processingEnvironment;
private final TypeUtils typeUtils;
private final MetadataStore metadataStore;
private final MetadataCollector metadataCollector;
private final Set<String> processedSourceTypes = new HashSet<>();
private final Map<TypeElement, MetadataCollector> metadataTypeCollectors = new HashMap<>();
MetadataCollectors(ProcessingEnvironment processingEnvironment, TypeUtils typeUtils) {
this.processingEnvironment = processingEnvironment;
this.typeUtils = typeUtils;
this.metadataStore = new MetadataStore(this.processingEnvironment, this.typeUtils);
this.metadataCollector = new MetadataCollector(this::shouldBeMerged, this.metadataStore.readMetadata());
}
void processing(RoundEnvironment roundEnv) {
for (Element element : roundEnv.getRootElements()) {
if (element instanceof TypeElement) {
this.processedSourceTypes.add(this.typeUtils.getQualifiedName(element));
}
}
}
MetadataCollector getModuleMetadataCollector() {
return this.metadataCollector;
}
|
MetadataCollector getMetadataCollector(TypeElement element) {
return this.metadataTypeCollectors.computeIfAbsent(element,
(ignored) -> new MetadataCollector(this::shouldBeMerged, this.metadataStore.readMetadata(element)));
}
Set<TypeElement> getSourceTypes() {
return this.metadataTypeCollectors.keySet();
}
private boolean shouldBeMerged(ItemMetadata itemMetadata) {
String sourceType = itemMetadata.getSourceType();
return (sourceType != null && !deletedInCurrentBuild(sourceType) && !processedInCurrentBuild(sourceType));
}
private boolean deletedInCurrentBuild(String sourceType) {
return this.processingEnvironment.getElementUtils().getTypeElement(sourceType.replace('$', '.')) == null;
}
private boolean processedInCurrentBuild(String sourceType) {
return this.processedSourceTypes.contains(sourceType);
}
}
|
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\MetadataCollectors.java
| 2
|
请完成以下Java代码
|
private static @Nullable String getCustomStackTracePrinter(StructuredLoggingJsonProperties properties) {
StackTrace stackTrace = properties.stackTrace();
return (stackTrace != null && stackTrace.hasCustomPrinter()) ? stackTrace.printer() : null;
}
private static final class AotContribution implements BeanFactoryInitializationAotContribution {
private final @Nullable ClassLoader classLoader;
private final Set<Class<? extends StructuredLoggingJsonMembersCustomizer<?>>> customizers;
private final @Nullable String stackTracePrinter;
private AotContribution(@Nullable ClassLoader classLoader,
Set<Class<? extends StructuredLoggingJsonMembersCustomizer<?>>> customizers,
@Nullable String stackTracePrinter) {
this.classLoader = classLoader;
this.customizers = customizers;
this.stackTracePrinter = stackTracePrinter;
|
}
@Override
public void applyTo(GenerationContext generationContext,
BeanFactoryInitializationCode beanFactoryInitializationCode) {
ReflectionHints reflection = generationContext.getRuntimeHints().reflection();
this.customizers.forEach((customizer) -> reflection.registerType(customizer,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS));
if (this.stackTracePrinter != null) {
reflection.registerTypeIfPresent(this.classLoader, this.stackTracePrinter,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS);
}
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\structured\StructuredLoggingJsonPropertiesBeanFactoryInitializationAotProcessor.java
| 1
|
请完成以下Java代码
|
public final class OrderCheckupBarcode
{
public static OrderCheckupBarcode ofC_OrderLine_ID(final int orderLineId)
{
return new OrderCheckupBarcode(VERSION_1, C_OrderLine_Table_ID, orderLineId);
}
public static OrderCheckupBarcode fromBarcodeString(final String barcode)
{
final List<String> barcodeParts = Splitter.on(SEPARATOR).splitToList(barcode);
if (barcodeParts.isEmpty())
{
throw new IllegalArgumentException("Invalid barcode: " + barcode);
}
final String version = barcodeParts.get(0);
if (VERSION_1.equals(version))
{
return fromBarcodeString_v1(barcodeParts);
}
else
{
throw new IllegalArgumentException("Unknown barcode version: " + barcode);
}
}
private static OrderCheckupBarcode fromBarcodeString_v1(final List<String> barcodeParts)
{
if (barcodeParts.size() < 3)
{
throw new IllegalArgumentException("Invalid barcode v1 format: " + barcodeParts);
}
final int adTableId = Integer.parseInt(barcodeParts.get(1));
if (adTableId != C_OrderLine_Table_ID)
{
throw new IllegalArgumentException("Invalid barcode's adTableId: " + barcodeParts);
}
final int recordId = Integer.parseInt(barcodeParts.get(2));
return new OrderCheckupBarcode(VERSION_1, adTableId, recordId);
}
private static final String SEPARATOR = "-";
private static final transient String VERSION_1 = "1";
|
/** @see I_C_OrderLine#Table_ID */
private static final transient int C_OrderLine_Table_ID = 260;
private final String version;
private final int adTableId;
private final int recordId;
private OrderCheckupBarcode(final String version, final int adTableId, final int recordId)
{
Preconditions.checkArgument(version != null && !version.isEmpty(), "Invalid version: %s", version);
Preconditions.checkArgument(adTableId > 0, "Invalid adTableId: %s", adTableId);
Preconditions.checkArgument(recordId > 0, "Invalid recordId: %s", recordId);
this.version = version;
this.adTableId = adTableId;
this.recordId = recordId;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("version", version)
.add("adTableId", adTableId)
.add("recordId", recordId)
.toString();
}
public String toBarcodeString()
{
// NOTE: don't use "_" because it might cause problems (see https://github.com/metasfresh/metasfresh/issues/1239#issuecomment-305407684 ).
return version + SEPARATOR + adTableId + SEPARATOR + recordId;
}
public OrderLineId getOrderLineId()
{
if (adTableId == C_OrderLine_Table_ID)
{
return OrderLineId.ofRepoId(recordId);
}
else
{
throw new IllegalStateException("Cannot get C_OrderLine_ID from " + this);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\ordercheckup\OrderCheckupBarcode.java
| 1
|
请完成以下Java代码
|
private static Money extractPayAmt(@NonNull final I_C_Payment payment)
{
final CurrencyId currencyId = CurrencyId.ofRepoId(payment.getC_Currency_ID());
return Money.of(payment.getPayAmt(), currencyId);
}
@Override
public BankStatementLineMultiPaymentLinkResult linkMultiPayments(@NonNull final BankStatementLineMultiPaymentLinkRequest request)
{
return BankStatementLineMultiPaymentLinkCommand.builder()
.bankStatementBL(bankStatementBL)
.bankStatementDAO(bankStatementDAO)
.paymentBL(paymentBL)
.bankStatementListenersService(bankStatementListenersService)
.moneyService(moneyService)
//
.request(request)
//
.build()
.execute();
}
@NonNull
private Optional<InvoiceToAllocate> getInvoiceToAllocate(
@NonNull final CurrencyId paymentCurrencyId,
@NonNull final InvoiceId invoiceId,
|
@NonNull final ZonedDateTime evaluationDate)
{
final InvoiceToAllocateQuery query = InvoiceToAllocateQuery.builder()
.currencyId(paymentCurrencyId)
.evaluationDate(evaluationDate)
.onlyInvoiceId(invoiceId)
.build();
return paymentAllocationService.retrieveInvoicesToAllocate(query)
.stream()
.filter(invoiceToAllocate -> {
// just to be sure
final InvoiceId invId = invoiceToAllocate.getInvoiceId();
if (invId == null)
{
return false;
}
return invId.equals(invoiceId);
})
.findFirst();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\impl\BankStatementPaymentBL.java
| 1
|
请完成以下Java代码
|
public void setQtyProcessed (final BigDecimal QtyProcessed)
{
set_Value (COLUMNNAME_QtyProcessed, QtyProcessed);
}
@Override
public BigDecimal getQtyProcessed()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyProcessed);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyToProcess (final BigDecimal QtyToProcess)
{
set_Value (COLUMNNAME_QtyToProcess, QtyToProcess);
}
@Override
public BigDecimal getQtyToProcess()
{
|
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToProcess);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSupplyDate (final java.sql.Timestamp SupplyDate)
{
set_Value (COLUMNNAME_SupplyDate, SupplyDate);
}
@Override
public java.sql.Timestamp getSupplyDate()
{
return get_ValueAsTimestamp(COLUMNNAME_SupplyDate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_DD_Order_Candidate.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String training(@RequestParam(defaultValue = "/home/djl-test/images-test")
String datasetRoot,
@RequestParam(defaultValue = "/home/djl-test/models") String modePath) throws TranslateException, IOException {
return imageClassificationService.training(datasetRoot, modePath);
}
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile(@RequestParam(defaultValue = "/home/djl-test/images-test") String directoryPath) {
List<String> imgPathList = new ArrayList<>();
try (Stream<Path> paths = Files.walk(Paths.get(directoryPath))) {
// Filter only regular files (excluding directories)
paths.filter(Files::isRegularFile)
.forEach(c-> imgPathList.add(c.toString()));
} catch (IOException e) {
return ResponseEntity.status(500).build();
}
Random random = new Random();
String filePath = imgPathList.get(random.nextInt(imgPathList.size()));
Path file = Paths.get(filePath);
Resource resource = new FileSystemResource(file.toFile());
if (!resource.exists()) {
|
return ResponseEntity.notFound().build();
}
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getFileName().toString());
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_JPEG_VALUE);
try {
return ResponseEntity.ok()
.headers(headers)
.contentLength(resource.contentLength())
.body(resource);
} catch (IOException e) {
return ResponseEntity.status(500).build();
}
}
}
|
repos\springboot-demo-master\djl\src\main\java\com\et\controller\ImageClassificationController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class GlobalQRCode
{
@NonNull GlobalQRCodeType type;
@Builder.Default
@NonNull GlobalQRCodeVersion version = GlobalQRCodeVersion.ofInt(1);
@NonNull String payloadAsJson;
private static final String SEPARATOR = "#";
public static GlobalQRCode of(
@NonNull final GlobalQRCodeType type,
@NonNull final GlobalQRCodeVersion version,
@NonNull final Object payload)
{
final String payloadAsJson;
try
{
payloadAsJson = JsonObjectMapperHolder.sharedJsonObjectMapper().writeValueAsString(payload);
}
catch (JsonProcessingException ex)
{
throw Check.mkEx("Failed converting payload to json: " + payload, ex);
}
return builder()
.type(type)
.version(version)
.payloadAsJson(payloadAsJson)
.build();
}
@Nullable
@JsonCreator
public static GlobalQRCode ofNullableString(@Nullable final String string)
{
return StringUtils.trimBlankToNullAndMap(string, GlobalQRCode::ofString);
}
public static GlobalQRCode ofString(@NonNull final String string)
{
return parse(string).orThrow();
}
public static GlobalQRCode ofBase64Encoded(@NonNull final String string)
{
final byte[] bytes = BaseEncoding.base64().decode(string);
return ofString(new String(bytes, StandardCharsets.UTF_8));
}
public static GlobalQRCodeParseResult parse(@NonNull final String string)
{
String remainingString = string;
//
// Extract type
final GlobalQRCodeType type;
{
int idx = remainingString.indexOf(SEPARATOR);
if (idx <= 0)
{
return GlobalQRCodeParseResult.error("Invalid global QR code(1): " + string);
|
}
type = GlobalQRCodeType.ofString(remainingString.substring(0, idx));
remainingString = remainingString.substring(idx + 1);
}
//
// Extract version
final GlobalQRCodeVersion version;
{
int idx = remainingString.indexOf(SEPARATOR);
if (idx <= 0)
{
return GlobalQRCodeParseResult.error("Invalid global QR code(2): " + string);
}
version = GlobalQRCodeVersion.ofString(remainingString.substring(0, idx));
remainingString = remainingString.substring(idx + 1);
}
//
// Payload
final String payloadAsJson = remainingString;
//
return GlobalQRCodeParseResult.ok(builder()
.type(type)
.version(version)
.payloadAsJson(payloadAsJson)
.build());
}
public <T> T getPayloadAs(@NonNull final Class<T> type)
{
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(payloadAsJson, type);
}
catch (JsonProcessingException e)
{
throw Check.mkEx("Failed converting payload to `" + type + "`: " + payloadAsJson, e);
}
}
@Override
@Deprecated
public String toString()
{
return getAsString();
}
@JsonValue
public String getAsString()
{
return type.toJson() + SEPARATOR + version + SEPARATOR + payloadAsJson;
}
public static boolean equals(@Nullable GlobalQRCode o1, @Nullable GlobalQRCode o2)
{
return Objects.equals(o1, o2);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.global_qrcode.api\src\main\java\de\metas\global_qrcodes\GlobalQRCode.java
| 2
|
请完成以下Java代码
|
public Boolean getWaitFlag() {
return waitFlag;
}
public void setWaitFlag(Boolean waitFlag) {
this.waitFlag = waitFlag;
}
public Boolean getCleanEnvBoolan() {
return cleanEnvBoolan;
}
public Boolean getRedirectErrorFlag() {
return redirectErrorFlag;
}
public String getDirectoryStr() {
return directoryStr;
}
public String getResultVariableStr() {
|
return resultVariableStr;
}
public String getErrorCodeVariableStr() {
return errorCodeVariableStr;
}
public List<String> getArgList() {
return argList;
}
public void setArgList(List<String> argList) {
this.argList = argList;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\ShellExecutorContext.java
| 1
|
请完成以下Java代码
|
public static boolean hasTrueCondition(SequenceFlow sequenceFlow, DelegateExecution execution) {
String conditionExpression = null;
if (CommandContextUtil.getProcessEngineConfiguration().isEnableProcessDefinitionInfoCache()) {
ObjectNode elementProperties = BpmnOverrideContext.getBpmnOverrideElementProperties(sequenceFlow.getId(), execution.getProcessDefinitionId());
conditionExpression = getActiveValue(sequenceFlow.getConditionExpression(), DynamicBpmnConstants.SEQUENCE_FLOW_CONDITION, elementProperties);
} else {
conditionExpression = sequenceFlow.getConditionExpression();
}
if (StringUtils.isNotEmpty(conditionExpression)) {
String conditionLanguage = sequenceFlow.getConditionLanguage();
return hasTrueCondition(sequenceFlow.getId(), conditionExpression, conditionLanguage, execution);
} else {
return true;
}
}
public static boolean hasTrueCondition(String elementId, String conditionExpression, String conditionLanguage, DelegateExecution execution) {
Condition condition;
if (conditionLanguage == null) {
Expression expression = CommandContextUtil.getProcessEngineConfiguration().getExpressionManager().createExpression(conditionExpression);
condition = new UelExpressionCondition(expression);
|
} else {
condition = new ScriptCondition(conditionExpression, conditionLanguage);
}
return condition.evaluate(elementId, execution);
}
protected static String getActiveValue(String originalValue, String propertyName, ObjectNode elementProperties) {
String activeValue = originalValue;
if (elementProperties != null) {
JsonNode overrideValueNode = elementProperties.get(propertyName);
if (overrideValueNode != null) {
if (overrideValueNode.isNull()) {
activeValue = null;
} else {
activeValue = overrideValueNode.asString();
}
}
}
return activeValue;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\util\condition\ConditionUtil.java
| 1
|
请完成以下Java代码
|
public byte[] encrypt(byte[] bytes) {
synchronized (this.encryptor) {
byte[] iv = this.ivGenerator.generateKey();
CipherUtils.initCipher(this.encryptor, Cipher.ENCRYPT_MODE, this.secretKey, this.alg.getParameterSpec(iv));
byte[] encrypted = CipherUtils.doFinal(this.encryptor, bytes);
return (this.ivGenerator != NULL_IV_GENERATOR) ? EncodingUtils.concatenate(iv, encrypted) : encrypted;
}
}
@Override
public byte[] decrypt(byte[] encryptedBytes) {
synchronized (this.decryptor) {
byte[] iv = iv(encryptedBytes);
CipherUtils.initCipher(this.decryptor, Cipher.DECRYPT_MODE, this.secretKey, this.alg.getParameterSpec(iv));
return CipherUtils.doFinal(this.decryptor,
(this.ivGenerator != NULL_IV_GENERATOR) ? encrypted(encryptedBytes, iv.length) : encryptedBytes);
}
}
private byte[] iv(byte[] encrypted) {
return (this.ivGenerator != NULL_IV_GENERATOR)
? EncodingUtils.subArray(encrypted, 0, this.ivGenerator.getKeyLength())
: NULL_IV_GENERATOR.generateKey();
}
private byte[] encrypted(byte[] encryptedBytes, int ivLength) {
return EncodingUtils.subArray(encryptedBytes, ivLength, encryptedBytes.length);
}
private static final BytesKeyGenerator NULL_IV_GENERATOR = new BytesKeyGenerator() {
private final byte[] VALUE = new byte[16];
@Override
public int getKeyLength() {
return this.VALUE.length;
}
@Override
public byte[] generateKey() {
return this.VALUE;
}
};
public enum CipherAlgorithm {
|
CBC(AES_CBC_ALGORITHM, NULL_IV_GENERATOR),
GCM(AES_GCM_ALGORITHM, KeyGenerators.secureRandom(16));
private BytesKeyGenerator ivGenerator;
private String name;
CipherAlgorithm(String name, BytesKeyGenerator ivGenerator) {
this.name = name;
this.ivGenerator = ivGenerator;
}
@Override
public String toString() {
return this.name;
}
public AlgorithmParameterSpec getParameterSpec(byte[] iv) {
return (this != CBC) ? new GCMParameterSpec(128, iv) : new IvParameterSpec(iv);
}
public Cipher createCipher() {
return CipherUtils.newCipher(this.toString());
}
public BytesKeyGenerator defaultIvGenerator() {
return this.ivGenerator;
}
}
}
|
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\encrypt\AesBytesEncryptor.java
| 1
|
请完成以下Java代码
|
public class BatchRequest {
@NotNull
private HttpMethod method;
@NotNull
private String relativeUrl;
@NotNull
private JsonNode data;
public JsonNode getData() {
return data;
}
public @NotNull String getRelativeUrl() {
return relativeUrl;
}
public void setRelativeUrl(@NotNull String relativeUrl) {
|
this.relativeUrl = relativeUrl;
}
public void setData(@NotNull JsonNode data) {
this.data = data;
}
public @NotNull HttpMethod getMethod() {
return method;
}
public void setMethod(@NotNull HttpMethod method) {
this.method = method;
}
}
|
repos\tutorials-master\spring-web-modules\spring-rest-http-3\src\main\java\com\baeldung\bulkandbatchapi\request\BatchRequest.java
| 1
|
请完成以下Java代码
|
private static final class IndexedCountries
{
/**
* contains also inactive countries
*/
private final ImmutableList<I_C_Country> countries;
/**
* contains also inactive countries
*/
private final ImmutableMap<CountryId, I_C_Country> countriesById;
/**
* contains only active countries
*/
private final ImmutableMap<String, I_C_Country> countriesByCountryCode;
private IndexedCountries(final List<I_C_Country> countries)
{
this.countries = ImmutableList.copyOf(countries);
this.countriesById = Maps.uniqueIndex(countries, c -> CountryId.ofRepoId(c.getC_Country_ID()));
this.countriesByCountryCode = countries.stream()
.filter(I_C_Country::isActive)
.filter(country -> Check.isNotBlank(country.getCountryCode())) // NOTE: in DB the CountryCode is mandatory but not in some unit tests
.collect(GuavaCollectors.toImmutableMapByKey(I_C_Country::getCountryCode));
}
public List<I_C_Country> getAll()
{
return countries;
}
/**
* @return the country with the given ID, even if the `C_Country` record is not active.
*/
public I_C_Country getByIdOrNull(final CountryId countryId)
{
return countriesById.get(countryId);
}
/**
* @return the country with the given ID, even if the `C_Country` record is not active.
*/
public I_C_Country getById(final CountryId countryId)
{
final I_C_Country country = getByIdOrNull(countryId);
if (country == null)
{
throw new AdempiereException("No country found for countryId=" + countryId);
}
return country;
}
/**
* @return the country with the given code, unless the `C_Country` record is inactive.
*/
public I_C_Country getByCountryCodeOrNull(@Nullable final String countryCode)
{
return countriesByCountryCode.get(countryCode);
}
/**
* @return the country with the given code, unless the `C_Country` record is inactive.
*/
|
public I_C_Country getByCountryCode(final String countryCode)
{
final I_C_Country country = getByCountryCodeOrNull(countryCode);
if (country == null)
{
throw new AdempiereException("No active country found for countryCode=" + countryCode);
}
return country;
}
/**
* @return the country with the given code, unless the `C_Country` record is inactive.
*/
@NonNull
public CountryId getIdByCountryCode(@NonNull final String countryCode)
{
final I_C_Country country = getByCountryCode(countryCode);
return CountryId.ofRepoId(country.getC_Country_ID());
}
@NonNull
public CountryId getIdByCountryCode(@NonNull final CountryCode countryCode)
{
return getIdByCountryCode(countryCode.getAlpha2());
}
@Nullable
public CountryId getIdByCountryCodeOrNull(@Nullable final String countryCode)
{
final I_C_Country country = getByCountryCodeOrNull(countryCode);
return country != null ? CountryId.ofRepoId(country.getC_Country_ID()) : null;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\impl\CountryDAO.java
| 1
|
请完成以下Java代码
|
public void setAuthentication(String userId, List<String> groups) {
setAuthentication(new Authentication(userId, groups));
}
public void setAuthentication(String userId, List<String> groups, List<String> tenantIds) {
setAuthentication(new Authentication(userId, groups, tenantIds));
}
public void clearAuthentication() {
currentAuthentication.remove();
}
public Authentication getCurrentAuthentication() {
return currentAuthentication.get();
}
public String getUserInfo(String userId, String key) {
return commandExecutor.execute(new GetUserInfoCmd(userId, key));
}
public List<String> getUserInfoKeys(String userId) {
return commandExecutor.execute(new GetUserInfoKeysCmd(userId, IdentityInfoEntity.TYPE_USERINFO));
}
public List<String> getUserAccountNames(String userId) {
return commandExecutor.execute(new GetUserInfoKeysCmd(userId, IdentityInfoEntity.TYPE_USERACCOUNT));
}
public void setUserInfo(String userId, String key, String value) {
commandExecutor.execute(new SetUserInfoCmd(userId, key, value));
}
public void deleteUserInfo(String userId, String key) {
commandExecutor.execute(new DeleteUserInfoCmd(userId, key));
}
public void deleteUserAccount(String userId, String accountName) {
commandExecutor.execute(new DeleteUserInfoCmd(userId, accountName));
}
|
public Account getUserAccount(String userId, String userPassword, String accountName) {
return commandExecutor.execute(new GetUserAccountCmd(userId, userPassword, accountName));
}
public void setUserAccount(String userId, String userPassword, String accountName, String accountUsername, String accountPassword, Map<String, String> accountDetails) {
commandExecutor.execute(new SetUserInfoCmd(userId, userPassword, accountName, accountUsername, accountPassword, accountDetails));
}
public void createTenantUserMembership(String tenantId, String userId) {
commandExecutor.execute(new CreateTenantUserMembershipCmd(tenantId, userId));
}
public void createTenantGroupMembership(String tenantId, String groupId) {
commandExecutor.execute(new CreateTenantGroupMembershipCmd(tenantId, groupId));
}
public void deleteTenantUserMembership(String tenantId, String userId) {
commandExecutor.execute(new DeleteTenantUserMembershipCmd(tenantId, userId));
}
public void deleteTenantGroupMembership(String tenantId, String groupId) {
commandExecutor.execute(new DeleteTenantGroupMembershipCmd(tenantId, groupId));
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\IdentityServiceImpl.java
| 1
|
请完成以下Java代码
|
private void updateLogDocStatus(@NonNull final TableRecordReference tableRecordReference, @Nullable final DocStatus docStatus)
{
final ICompositeQueryUpdater<I_C_Doc_Outbound_Log> queryUpdater = queryBL.createCompositeQueryUpdater(I_C_Doc_Outbound_Log.class)
.addSetColumnValue(I_C_Doc_Outbound_Log.COLUMNNAME_DocStatus, DocStatus.toCodeOrNull(docStatus));
queryBL.createQueryBuilder(I_C_Doc_Outbound_Log.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Doc_Outbound_Log.COLUMNNAME_AD_Table_ID, tableRecordReference.getAdTableId())
.addEqualsFilter(I_C_Doc_Outbound_Log.COLUMN_Record_ID, tableRecordReference.getRecord_ID())
.create()
.update(queryUpdater);
}
private void updateLogLineDocStatus(@NonNull final TableRecordReference tableRecordReference, @Nullable final DocStatus docStatus)
{
final ICompositeQueryUpdater<I_C_Doc_Outbound_Log_Line> queryUpdaterLogLine = queryBL.createCompositeQueryUpdater(I_C_Doc_Outbound_Log_Line.class)
.addSetColumnValue(I_C_Doc_Outbound_Log_Line.COLUMNNAME_DocStatus, DocStatus.toCodeOrNull(docStatus));
queryBL.createQueryBuilder(I_C_Doc_Outbound_Log_Line.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Doc_Outbound_Log_Line.COLUMNNAME_AD_Table_ID, tableRecordReference.getAdTableId())
.addEqualsFilter(I_C_Doc_Outbound_Log_Line.COLUMN_Record_ID, tableRecordReference.getRecord_ID())
.create()
.update(queryUpdaterLogLine);
}
@Override
@NonNull
public ImmutableList<LogWithLines> retrieveLogsWithLines(@NonNull final ImmutableList<I_C_Doc_Outbound_Log> logs)
{
if (logs.isEmpty())
{
return ImmutableList.of();
}
final ImmutableSet<DocOutboundLogId> ids = logs.stream()
.map(log -> DocOutboundLogId.ofRepoId(log.getC_Doc_Outbound_Log_ID()))
|
.collect(ImmutableSet.toImmutableSet());
final Map<Integer, List<I_C_Doc_Outbound_Log_Line>> linesByLogId = queryBL.createQueryBuilder(I_C_Doc_Outbound_Log_Line.class)
.addInArrayFilter(I_C_Doc_Outbound_Log_Line.COLUMNNAME_C_Doc_Outbound_Log_ID, ids)
.create()
.list()
.stream()
.collect(Collectors.groupingBy(I_C_Doc_Outbound_Log_Line::getC_Doc_Outbound_Log_ID));
return logs.stream()
.map(log -> LogWithLines.builder()
.log(log)
.lines(linesByLogId.getOrDefault(log.getC_Doc_Outbound_Log_ID(), Collections.emptyList()))
.build())
.collect(ImmutableList.toImmutableList());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\api\impl\DocOutboundDAO.java
| 1
|
请完成以下Java代码
|
public class RabbitMessageReceiverContext extends ReceiverContext<Message> {
private final String listenerId;
private final Message message;
@SuppressWarnings("this-escape")
public RabbitMessageReceiverContext(Message message, String listenerId) {
super((carrier, key) -> carrier.getMessageProperties().getHeader(key));
setCarrier(message);
this.message = message;
this.listenerId = listenerId;
setRemoteServiceName("RabbitMQ");
}
@Override
|
public Message getCarrier() {
return this.message;
}
public String getListenerId() {
return this.listenerId;
}
/**
* Return the source (queue) for this message.
* @return the source.
*/
public @Nullable String getSource() {
return this.message.getMessageProperties().getConsumerQueue();
}
}
|
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\support\micrometer\RabbitMessageReceiverContext.java
| 1
|
请完成以下Java代码
|
public ExtensionElements getExtensionElements() {
return extensionElementsChild.getChild(this);
}
public void setExtensionElements(ExtensionElements extensionElements) {
extensionElementsChild.setChild(this, extensionElements);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DmnElement.class, DMN_ELEMENT)
.namespaceUri(LATEST_DMN_NS)
.abstractType();
idAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_ID)
.idAttribute()
.build();
|
labelAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_LABEL)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
descriptionChild = sequenceBuilder.element(Description.class)
.build();
extensionElementsChild = sequenceBuilder.element(ExtensionElements.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\DmnElementImpl.java
| 1
|
请完成以下Java代码
|
private HuId performPickCU()
{
final HuId huIdToSplit = retrieveHUIdToSplit();
final ProductId productId = getProductId();
// validating the attributes here because it doesn't make sense to split the HU if it can't be used
huAttributesBL.validateMandatoryPickingAttributes(huIdToSplit, productId);
final List<I_M_HU> splitHUs = HUSplitBuilderCoreEngine.builder()
.huToSplit(handlingUnitsDAO.getById(huIdToSplit))
.requestProvider(this::createSplitAllocationRequest)
.destination(HUProducerDestination.ofVirtualPI())
.build()
.withPropagateHUValues()
.withAllowPartialUnloads(true) // we allow partial loads and unloads so if a user enters a very large number, then that will just account to "all of it" and there will be no error
.performSplit();
final I_M_HU splitCU = CollectionUtils.singleElement(splitHUs);
final HuId splitCUId = HuId.ofRepoId(splitCU.getM_HU_ID());
addHUIdToCurrentPickingSlot(splitCUId);
return splitCUId;
}
private IAllocationRequest createSplitAllocationRequest(final IHUContext huContext)
{
final ProductId productId = getProductId();
final I_C_UOM uom = productBL.getStockUOM(productId);
return AllocationUtils.builder()
.setHUContext(huContext)
.setProduct(productId)
.setQuantity(getQtyCUsPerTU(), uom)
.setDate(SystemTime.asZonedDateTime())
.setFromReferencedModel(null) // N/A
.setForceQtyAllocation(false)
.create();
|
}
private void autoProcessPicking(final HuId splitCUId)
{
final ShipmentScheduleId shipmentScheduleId = null;
pickingCandidateService.processForHUIds(ImmutableSet.of(splitCUId), shipmentScheduleId);
}
private HuId retrieveHUIdToSplit()
{
return retrieveEligibleHUEditorRows()
.map(HUEditorRow::getHuId)
.collect(GuavaCollectors.singleElementOrThrow(() -> new AdempiereException("Only one HU shall be selected")));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\husToPick\process\WEBUI_HUsToPick_PickCU.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.