instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getProductCode()
{
return productCode;
}
public void setProductCode(String productCode)
{
this.productCode = productCode;
}
public int getQuantity() | {
return quantity;
}
public void setQuantity(int quantity)
{
this.quantity = quantity;
}
public Order getOrder()
{
return order;
}
public void setOrder(Order order)
{
this.order = order;
}
} | repos\Spring-Boot-Advanced-Projects-main\springboot-multiple-datasources\src\main\java\net\alanbinu\springboot\springbootmultipledatasources\orders\entities\OrderItem.java | 1 |
请完成以下Java代码 | public CamundaExecutionListener newInstance(ModelTypeInstanceContext instanceContext) {
return new CamundaExecutionListenerImpl(instanceContext);
}
});
camundaEventAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_EVENT)
.namespace(CAMUNDA_NS)
.build();
camundaClassAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CLASS)
.namespace(CAMUNDA_NS)
.build();
camundaExpressionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_EXPRESSION)
.namespace(CAMUNDA_NS)
.build();
camundaDelegateExpressionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DELEGATE_EXPRESSION)
.namespace(CAMUNDA_NS)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
camundaFieldCollection = sequenceBuilder.elementCollection(CamundaField.class)
.build();
camundaScriptChild = sequenceBuilder.element(CamundaScript.class)
.build();
typeBuilder.build();
}
public CamundaExecutionListenerImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getCamundaEvent() {
return camundaEventAttribute.getValue(this);
}
public void setCamundaEvent(String camundaEvent) {
camundaEventAttribute.setValue(this, camundaEvent);
}
public String getCamundaClass() { | return camundaClassAttribute.getValue(this);
}
public void setCamundaClass(String camundaClass) {
camundaClassAttribute.setValue(this, camundaClass);
}
public String getCamundaExpression() {
return camundaExpressionAttribute.getValue(this);
}
public void setCamundaExpression(String camundaExpression) {
camundaExpressionAttribute.setValue(this, camundaExpression);
}
public String getCamundaDelegateExpression() {
return camundaDelegateExpressionAttribute.getValue(this);
}
public void setCamundaDelegateExpression(String camundaDelegateExpression) {
camundaDelegateExpressionAttribute.setValue(this, camundaDelegateExpression);
}
public Collection<CamundaField> getCamundaFields() {
return camundaFieldCollection.get(this);
}
public CamundaScript getCamundaScript() {
return camundaScriptChild.getChild(this);
}
public void setCamundaScript(CamundaScript camundaScript) {
camundaScriptChild.setChild(this, camundaScript);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaExecutionListenerImpl.java | 1 |
请完成以下Java代码 | protected Properties getCtx()
{
return migrationExecutorContext.getCtx();
}
/**
* Log error messages as WARNING and normal ones as INFO.
*
* @param msg
* @param resolution
* @param isError
*/
protected final void log(final String msg, final String resolution, final boolean isError)
{
final StringBuilder sb = new StringBuilder();
sb.append("Step ").append(step.getSeqNo());
if (!Check.isEmpty(msg, true)) | {
sb.append(": ").append(msg.trim());
}
if (resolution != null)
{
sb.append(" [").append(resolution).append("]");
}
if(isError)
{
logger.error(sb.toString());
}
else
{
logger.info(sb.toString());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\AbstractMigrationStepExecutor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Integer getRetries() {
return retries;
}
public void setRetries(Integer retries) {
this.retries = retries;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = exceptionMessage;
}
public Date getDueDate() {
return dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantId() {
return tenantId;
} | public String getLockOwner() {
return lockOwner;
}
public void setLockOwner(String lockOwner) {
this.lockOwner = lockOwner;
}
public Date getLockExpirationTime() {
return lockExpirationTime;
}
public void setLockExpirationTime(Date lockExpirationTime) {
this.lockExpirationTime = lockExpirationTime;
}
} | repos\flowable-engine-main\modules\flowable-external-job-rest\src\main\java\org\flowable\external\job\rest\service\api\query\ExternalWorkerJobResponse.java | 2 |
请完成以下Java代码 | public <T> T decodeStream(final InputStream in, final Class<T> clazz)
{
if (in == null)
{
throw new IllegalArgumentException("'in' input stream is null");
}
String str = null;
try
{
str = Util.toString(in);
return mapper.readValue(str, clazz);
}
catch (final Exception e)
{
throw new RuntimeException("Cannot parse input stream:"
+ "\n---------------"
+ str
+ "\n---------------", e);
}
}
@Override
public <T> T decodeBytes(final byte[] data, final Class<T> clazz)
{
try
{
return mapper.readValue(data, clazz);
}
catch (final Exception e)
{
throw new RuntimeException("Cannot parse bytes: " + data, e);
}
}
@Override
public <T> byte[] encode(final T object) | {
try
{
return mapper.writeValueAsBytes(object);
}
catch (final Exception e)
{
throw new RuntimeException(e);
}
}
@Override
public String getContentType()
{
return "application/json";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\encoder\JsonBeanEncoder.java | 1 |
请完成以下Java代码 | public BigDecimal getQtyToAllocate()
{
return BigDecimal.ZERO;
}
@Override
public BigDecimal getQtyAllocated()
{
return BigDecimal.ZERO;
}
@Override
public boolean isZeroAllocated()
{
return true;
}
/**
* @return true always
*/
@Override
public boolean isCompleted() | {
return true;
}
@Override
public List<IHUTransactionCandidate> getTransactions()
{
return Collections.emptyList();
}
@Override
public List<IHUTransactionAttribute> getAttributeTransactions()
{
return Collections.emptyList();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\NullAllocationResult.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String get(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
private static String name_sex = "";
public static int getNum(int start,int end) {
return (int)(Math.random()*(end-start+1)+start);
}
private static String getChineseName() {
int index=getNum(0, firstName.length()-1);
String first=firstName.substring(index, index+1);
int sex=getNum(0,1);
String str=boy;
int length=boy.length();
if(sex==0){
str=girl;
length=girl.length();
name_sex = "女"; | }else {
name_sex="男";
}
index=getNum(0,length-1);
String second=str.substring(index, index+1);
int hasThird=getNum(0,1);
String third="";
if(hasThird==1){
index=getNum(0,length-1);
third=str.substring(index, index+1);
}
return first+second+third;
}
} | repos\spring-boot-quick-master\quick-redies\src\main\java\com\quick\redis\service\impl\CompanyServiceImpl.java | 2 |
请完成以下Java代码 | public static Builder builder() {
return new DefaultBuilder();
}
/**
* Builder for {@link HttpRequestHeaderInterceptor}.
*/
public interface Builder {
/**
* Add names of HTTP headers to copy to the GraphQL context, using keys
* identical to the header names. Only the first value is copied.
* @param headerName the name(s) of header(s) to copy
*/
Builder mapHeader(String... headerName);
/**
* Add a mapping between an HTTP header name and the key under which it
* should appear in the GraphQL context. Only the first value is copied.
* @param headerName the name of a header to copy
* @param contextKey the key to map to in the GraphQL context
*/
Builder mapHeaderToKey(String headerName, String contextKey);
/**
* Add names of HTTP headers to copy to the GraphQL context, using keys
* identical to the header names. All values are copied as a List.
* @param headerName the name(s) of header(s) to copy
*/
Builder mapMultiValueHeader(String... headerName);
/**
* Add a mapping between an HTTP header name and the key under which it
* should appear in the GraphQL context. All values are copied as a List.
* @param headerName the name of a header to copy
* @param contextKey the key to map to in the GraphQL context
*/
Builder mapMultiValueHeaderToKey(String headerName, String contextKey);
/**
* Create the interceptor instance.
*/
HttpRequestHeaderInterceptor build();
}
/**
* Default implementation of {@link Builder}.
*/
private static final class DefaultBuilder implements Builder {
private final List<BiConsumer<HttpHeaders, Map<String, Object>>> mappers = new ArrayList<>();
@Override
public DefaultBuilder mapHeader(String... headers) {
for (String header : headers) {
initMapper(header, null);
}
return this;
}
@Override
public DefaultBuilder mapHeaderToKey(String header, String contextKey) { | initMapper(header, contextKey);
return this;
}
private void initMapper(String header, @Nullable String key) {
this.mappers.add((headers, target) -> {
Object value = headers.getFirst(header);
if (value != null) {
target.put((key != null) ? key : header, value);
}
});
}
@Override
public DefaultBuilder mapMultiValueHeader(String... headers) {
for (String header : headers) {
initMultiValueMapper(header, null);
}
return this;
}
@Override
public DefaultBuilder mapMultiValueHeaderToKey(String header, String contextKey) {
initMultiValueMapper(header, contextKey);
return this;
}
private void initMultiValueMapper(String header, @Nullable String key) {
this.mappers.add((headers, target) -> {
List<?> list = headers.getValuesAsList(header);
if (!ObjectUtils.isEmpty(list)) {
target.put((key != null) ? key : header, list);
}
});
}
@Override
public HttpRequestHeaderInterceptor build() {
return new HttpRequestHeaderInterceptor(this.mappers);
}
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\server\support\HttpRequestHeaderInterceptor.java | 1 |
请完成以下Java代码 | public class PaymentView_Launcher_From_BPartnerView extends ViewBasedProcessTemplate implements IProcessPrecondition
{
private final IViewsRepository viewsFactory = SpringContextHolder.instance.getBean(IViewsRepository.class);
@Override
protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (!getSingleSelectedBPartnerId().isPresent())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("not a single selected BPartner");
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
final BPartnerId bPartnerId = getSingleSelectedBPartnerId().orElse(null);
final ViewId viewId = viewsFactory.createView(CreateViewRequest.builder(PaymentsViewFactory.WINDOW_ID) | .setParameter(PaymentsViewFactory.PARAMETER_TYPE_BPARTNER_ID, bPartnerId)
.build())
.getViewId();
getResult().setWebuiViewToOpen(WebuiViewToOpen.builder()
.viewId(viewId.getViewId())
.target(ViewOpenTarget.ModalOverlay)
.build());
return MSG_OK;
}
private Optional<BPartnerId> getSingleSelectedBPartnerId()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
return selectedRowIds.isSingleDocumentId()
? Optional.of(selectedRowIds.getSingleDocumentId().toId(BPartnerId::ofRepoId))
: Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\process\PaymentView_Launcher_From_BPartnerView.java | 1 |
请完成以下Java代码 | public Layout<? extends Serializable> getLayout() {
return layout;
}
public Builder setLayout(Layout<? extends Serializable> layout) {
this.layout = layout;
return this;
}
public Filter getFilter() {
return filter;
}
public String getName() {
return name;
}
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setFilter(Filter filter) {
this.filter = filter;
return this;
}
public String getIpAddress() {
return ipAddress;
}
public Builder setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
return this;
}
public int getPort() {
return port;
}
public Builder setPort(int port) {
this.port = port;
return this;
}
public String getTopic() { | return topic;
}
public Builder setTopic(String topic) {
this.topic = topic;
return this;
}
public String getPartition() {
return partition;
}
public Builder setPartition(String partition) {
this.partition = partition;
return this;
}
@Override
public KafkaAppender build() {
return new KafkaAppender(getName(), getFilter(), getLayout(), true, new KafkaBroker(ipAddress, port, topic, partition));
}
}
private KafkaBroker broker;
private KafkaAppender(String name, Filter filter, Layout<? extends Serializable> layout, boolean ignoreExceptions, KafkaBroker broker) {
super(name, filter, layout, ignoreExceptions);
this.broker = broker;
}
@Override
public void append(LogEvent event) {
connectAndSendToKafka(broker, event);
}
private void connectAndSendToKafka(KafkaBroker broker, LogEvent event) {
//send to Kafka
}
} | repos\tutorials-master\logging-modules\log4j2\src\main\java\com\baeldung\logging\log4j2\plugins\KafkaAppender.java | 1 |
请完成以下Java代码 | public class Attributes
{
private static final Attributes EMPTY = new Attributes(ImmutableList.of());
@NonNull private final ImmutableList<Attribute> list;
@NonNull private final ImmutableMap<AttributeCode, Attribute> byCode;
private Attributes(@NonNull final List<Attribute> list)
{
this.list = ImmutableList.copyOf(list);
this.byCode = Maps.uniqueIndex(list, Attribute::getAttributeCode);
}
public static Attributes of(final ImmutableAttributeSet attributeSet)
{
if (attributeSet.isEmpty()) {return EMPTY;}
return ofList(
attributeSet.getAttributeCodes()
.stream()
.map(attributeCode -> toAttribute(attributeSet, attributeCode))
.collect(ImmutableList.toImmutableList())
);
}
private static Attribute toAttribute(@NonNull ImmutableAttributeSet attributeSet, @NonNull AttributeCode attributeCode)
{
return Attribute.builder()
.attributeCode(attributeCode)
.displayName(TranslatableStrings.anyLanguage(attributeSet.getAttributeNameByCode(attributeCode)))
.valueType(attributeSet.getAttributeValueType(attributeCode))
.value(attributeSet.getValue(attributeCode))
.build();
}
public static Attributes ofList(final List<Attribute> list)
{
return list.isEmpty() ? EMPTY : new Attributes(list);
}
public boolean hasAttribute(final @NonNull AttributeCode attributeCode)
{
return byCode.containsKey(attributeCode);
}
@NonNull
public Attribute getAttribute(@NonNull final AttributeCode attributeCode)
{
final Attribute attribute = byCode.get(attributeCode);
if (attribute == null)
{ | throw new AdempiereException("No attribute `" + attributeCode + "` found in " + byCode.keySet());
}
return attribute;
}
public List<Attribute> getAttributes() {return list;}
public Attributes retainOnly(@NonNull final Set<AttributeCode> attributeCodes, @NonNull final Attributes fallback)
{
Check.assumeNotEmpty(attributeCodes, "attributeCodes is not empty");
final ArrayList<Attribute> newList = new ArrayList<>();
for (AttributeCode attributeCode : attributeCodes)
{
if (hasAttribute(attributeCode))
{
newList.add(getAttribute(attributeCode));
}
else if (fallback.hasAttribute(attributeCode))
{
newList.add(fallback.getAttribute(attributeCode));
}
}
return ofList(newList);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\deps\products\Attributes.java | 1 |
请完成以下Java代码 | public String getActiveActivityId() {
return activeActivityId;
}
public void setActiveActivityId(String activeActivityId) {
this.activeActivityId = activeActivityId;
}
public Set<String> getActiveActivityIds() {
return activeActivityIds;
}
public void setActiveActivityIds(Set<String> activeActivityIds) {
this.activeActivityIds = activeActivityIds;
}
public Date getStartedBefore() {
return startedBefore;
}
public void setStartedBefore(Date startedBefore) {
this.startedBefore = startedBefore;
}
public Date getStartedAfter() {
return startedAfter;
}
public void setStartedAfter(Date startedAfter) {
this.startedAfter = startedAfter;
}
public String getStartedBy() {
return startedBy;
}
public void setStartedBy(String startedBy) {
this.startedBy = startedBy;
}
public String getLocale() {
return locale;
}
public boolean isWithLocalizationFallback() {
return withLocalizationFallback;
} | public String getCallbackId() {
return callbackId;
}
public Set<String> getCallBackIds() {
return callbackIds;
}
public String getCallbackType() {
return callbackType;
}
public String getParentCaseInstanceId() {
return parentCaseInstanceId;
}
public List<ExecutionQueryImpl> getOrQueryObjects() {
return orQueryObjects;
}
public List<List<String>> getSafeProcessInstanceIds() {
return safeProcessInstanceIds;
}
public void setSafeProcessInstanceIds(List<List<String>> safeProcessInstanceIds) {
this.safeProcessInstanceIds = safeProcessInstanceIds;
}
public List<List<String>> getSafeInvolvedGroups() {
return safeInvolvedGroups;
}
public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) {
this.safeInvolvedGroups = safeInvolvedGroups;
}
public String getRootScopeId() {
return null;
}
public String getParentScopeId() {
return null;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ExecutionQueryImpl.java | 1 |
请完成以下Java代码 | public Duration getFirstBackoff() {
return firstBackoff;
}
public void setFirstBackoff(Duration firstBackoff) {
this.firstBackoff = firstBackoff;
}
public @Nullable Duration getMaxBackoff() {
return maxBackoff;
}
public void setMaxBackoff(Duration maxBackoff) {
this.maxBackoff = maxBackoff;
}
public int getFactor() {
return factor;
}
public void setFactor(int factor) {
this.factor = factor;
}
public boolean isBasedOnPreviousValue() {
return basedOnPreviousValue;
}
public void setBasedOnPreviousValue(boolean basedOnPreviousValue) {
this.basedOnPreviousValue = basedOnPreviousValue;
}
@Override
public String toString() {
return new ToStringCreator(this).append("firstBackoff", firstBackoff)
.append("maxBackoff", maxBackoff)
.append("factor", factor)
.append("basedOnPreviousValue", basedOnPreviousValue)
.toString();
}
}
public static class JitterConfig {
private double randomFactor = 0.5;
public void validate() {
Assert.isTrue(randomFactor >= 0 && randomFactor <= 1,
"random factor must be between 0 and 1 (default 0.5)"); | }
public JitterConfig() {
}
public JitterConfig(double randomFactor) {
this.randomFactor = randomFactor;
}
public double getRandomFactor() {
return randomFactor;
}
public void setRandomFactor(double randomFactor) {
this.randomFactor = randomFactor;
}
@Override
public String toString() {
return new ToStringCreator(this).append("randomFactor", randomFactor).toString();
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RetryGatewayFilterFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
SimpleModule module = new SimpleModule();
module.addDeserializer(String.class, new StringWithoutSpaceDeserializer(String.class));
mapper.registerModule(module);
converter.setObjectMapper(mapper);
return converter;
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/user/**")
.allowedMethods("GET", "POST")
.allowedOrigins("https://javastack.cn")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(true).maxAge(3600);
}
@Bean
public ServletRegistrationBean registerServlet() {
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new RegisterServlet(), "/registerServlet");
servletRegistrationBean.addInitParameter("name", "registerServlet");
servletRegistrationBean.addInitParameter("sex", "man");
servletRegistrationBean.setIgnoreRegistrationFailure(true);
return servletRegistrationBean;
}
@Bean
public ServletContextInitializer servletContextInitializer() {
return (servletContext) -> {
ServletRegistration initServlet = servletContext.addServlet("initServlet", InitServlet.class);
initServlet.addMapping("/initServlet");
initServlet.setInitParameter("name", "initServlet"); | initServlet.setInitParameter("sex", "man");
};
}
@Bean
public RestTemplate defaultRestTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder
.setConnectTimeout(Duration.ofSeconds(5))
.setReadTimeout(Duration.ofSeconds(5))
.basicAuthentication("test", "test")
.build();
}
@Bean
public RestClient defaultRestClient(RestClient.Builder restClientBuilder) {
ClientHttpRequestFactorySettings settings = ClientHttpRequestFactorySettings.DEFAULTS
.withConnectTimeout(Duration.ofSeconds(3))
.withReadTimeout(Duration.ofSeconds(3));
ClientHttpRequestFactory requestFactory = ClientHttpRequestFactories.get(settings);
return restClientBuilder
.baseUrl("http://localhost:8080")
.defaultHeader("Authorization", "Bearer test")
.requestFactory(requestFactory)
.build();
}
} | repos\spring-boot-best-practice-master\spring-boot-web\src\main\java\cn\javastack\springboot\web\config\WebConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private void fireSupplyRequiredEventIfNeeded(@NonNull final Candidate demandCandidate, @NonNull final Candidate stockCandidate)
{
if (demandCandidate.isSimulated())
{
fireSimulatedSupplyRequiredEvent(demandCandidate, stockCandidate);
}
else
{
fireSupplyRequiredEventIfQtyBelowZero(demandCandidate);
}
}
private void fireSimulatedSupplyRequiredEvent(@NonNull final Candidate simulatedCandidate, @NonNull final Candidate stockCandidate)
{
Check.assume(simulatedCandidate.isSimulated(), "fireSimulatedSupplyRequiredEvent should only be called for simulated candidates!");
if (stockCandidate.getQuantity().signum() < 0)
{
postSupplyRequiredEvent(simulatedCandidate, stockCandidate.getQuantity().negate());
}
}
private void postSupplyRequiredEvent(@NonNull final Candidate demandCandidateWithId, @NonNull final BigDecimal requiredQty)
{
// create supply record now! otherwise | final Candidate supplyCandidate = Candidate.builderForClientAndOrgId(demandCandidateWithId.getClientAndOrgId())
.type(CandidateType.SUPPLY)
.businessCase(null)
.businessCaseDetail(null)
.materialDescriptor(demandCandidateWithId.getMaterialDescriptor().withQuantity(requiredQty))
//.groupId() // don't assign the new supply candidate to the demand candidate's groupId! it needs to "found" its own group
.minMaxDescriptor(demandCandidateWithId.getMinMaxDescriptor())
.quantity(requiredQty)
.simulated(demandCandidateWithId.isSimulated())
.build();
final CandidateId supplyCandidateId = supplyCandidateHandler.onCandidateNewOrChange(supplyCandidate, OnNewOrChangeAdvise.DONT_UPDATE).getId();
final SupplyRequiredEvent supplyRequiredEvent = SupplyRequiredEventCreator
.createSupplyRequiredEvent(demandCandidateWithId, requiredQty, supplyCandidateId);
materialEventService.enqueueEventAfterNextCommit(supplyRequiredEvent);
Loggables.addLog("Fire supplyRequiredEvent after next commit; event={}", supplyRequiredEvent);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\candidatechange\handler\DemandCandiateHandler.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public List<Candidate> retrieveOrderedByDateAndSeqNo(@NonNull final CandidatesQuery query)
{
final IQueryBuilder<I_MD_Candidate> queryBuilderWithoutOrdering = RepositoryCommons.mkQueryBuilder(query);
return retrieveForQueryBuilder(queryBuilderWithoutOrdering);
}
/**
* Only use this method in testing
*/
@VisibleForTesting
public List<Candidate> retrieveAllNotStockOrderedByDateAndSeqNoFor(@NonNull final ProductId productId)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final IQueryBuilder<I_MD_Candidate> queryBuilderWithoutOrdering = queryBL.createQueryBuilder(I_MD_Candidate.class)
.addNotEqualsFilter(I_MD_Candidate.COLUMNNAME_MD_Candidate_Type, X_MD_Candidate.MD_CANDIDATE_TYPE_STOCK)
.addEqualsFilter(I_MD_Candidate.COLUMNNAME_M_Product_ID, productId);
return retrieveForQueryBuilder(queryBuilderWithoutOrdering);
}
@NonNull
private List<Candidate> retrieveForQueryBuilder(@NonNull final IQueryBuilder<I_MD_Candidate> queryBuilderWithoutOrdering)
{
final Stream<I_MD_Candidate> candidateRecords = addOrderingYoungestFirst(queryBuilderWithoutOrdering)
.create()
.stream();
return candidateRecords
.map(this::fromCandidateRecordOrNull)
.collect(Collectors.toList());
}
private IQueryBuilder<I_MD_Candidate> addOrderingYoungestFirst(final IQueryBuilder<I_MD_Candidate> queryBuilderWithoutOrdering)
{
return queryBuilderWithoutOrdering | .orderBy()
.addColumnAscending(I_MD_Candidate.COLUMNNAME_DateProjected)
.addColumnAscending(I_MD_Candidate.COLUMNNAME_SeqNo)
.addColumnAscending(I_MD_Candidate.COLUMNNAME_MD_Candidate_ID)
.endOrderBy();
}
public List<Candidate> retrieveCandidatesForPPOrderId(@NonNull final PPOrderId ppOrderId)
{
final CandidatesQuery query = CandidatesQuery.builder()
.productionDetailsQuery(ProductionDetailsQuery.builder()
.ppOrderId(ppOrderId)
.build())
.build();
return retrieveOrderedByDateAndSeqNo(query);
}
@NonNull
private static List<TransactionDetail> getTransactionDetails(@NonNull final I_MD_Candidate candidateRecord)
{
final CandidateId candidateId = CandidateId.ofRepoId(candidateRecord.getMD_Candidate_ID());
final List<I_MD_Candidate_Transaction_Detail> transactionDetailRecords = RepositoryCommons
.createCandidateDetailQueryBuilder(candidateId, I_MD_Candidate_Transaction_Detail.class)
.list();
return fromRecords(transactionDetailRecords, candidateRecord);
}
private static boolean isSimulated(@NonNull final I_MD_Candidate candidateRecord)
{
return X_MD_Candidate.MD_CANDIDATE_STATUS_Simulated.equals(candidateRecord.getMD_Candidate_Status());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\CandidateRepositoryRetrieval.java | 2 |
请完成以下Java代码 | public String toString()
{
StringBuffer sb = new StringBuffer ("X_CM_Ad_Cat[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Advertisement Category.
@param CM_Ad_Cat_ID
Advertisement Category like Banner Homepage
*/
public void setCM_Ad_Cat_ID (int CM_Ad_Cat_ID)
{
if (CM_Ad_Cat_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_Ad_Cat_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CM_Ad_Cat_ID, Integer.valueOf(CM_Ad_Cat_ID));
}
/** Get Advertisement Category.
@return Advertisement Category like Banner Homepage
*/
public int getCM_Ad_Cat_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_Ad_Cat_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_CM_WebProject getCM_WebProject() throws RuntimeException
{
return (I_CM_WebProject)MTable.get(getCtx(), I_CM_WebProject.Table_Name)
.getPO(getCM_WebProject_ID(), get_TrxName()); }
/** Set Web Project.
@param CM_WebProject_ID
A web project is the main data container for Containers, URLs, Ads, Media etc.
*/
public void setCM_WebProject_ID (int CM_WebProject_ID)
{
if (CM_WebProject_ID < 1)
set_Value (COLUMNNAME_CM_WebProject_ID, null);
else
set_Value (COLUMNNAME_CM_WebProject_ID, Integer.valueOf(CM_WebProject_ID));
}
/** Get Web Project.
@return A web project is the main data container for Containers, URLs, Ads, Media etc.
*/
public int getCM_WebProject_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_WebProject_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
} | /** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Ad_Cat.java | 1 |
请完成以下Java代码 | public Stream<DocumentId> stream()
{
assertNotAll();
return documentIds.stream();
}
public void forEach(final Consumer<DocumentId> action)
{
assertNotAll();
documentIds.forEach(action);
}
public int size()
{
assertNotAll();
return documentIds.size();
}
public boolean contains(final DocumentId documentId)
{
return all || documentIds.contains(documentId);
}
public Set<DocumentId> toSet()
{
assertNotAll();
return documentIds;
}
public <T> ImmutableSet<T> toSet(@NonNull final Function<DocumentId, T> mapper)
{
assertNotAll();
if (documentIds.isEmpty())
{
return ImmutableSet.of();
}
return documentIds.stream().map(mapper).collect(ImmutableSet.toImmutableSet());
}
@NonNull
public ImmutableList<DocumentId> toImmutableList()
{
assertNotAll();
if (documentIds.isEmpty())
{
return ImmutableList.of();
}
return ImmutableList.copyOf(documentIds);
}
@NonNull
public <T> ImmutableList<T> toImmutableList(@NonNull final Function<DocumentId, T> mapper)
{
assertNotAll();
if (documentIds.isEmpty())
{
return ImmutableList.of();
}
return documentIds.stream().map(mapper).collect(ImmutableList.toImmutableList());
}
public Set<Integer> toIntSet()
{
return toSet(DocumentId::toInt);
}
public <ID extends RepoIdAware> ImmutableSet<ID> toIds(@NonNull final Function<Integer, ID> idMapper)
{
return toSet(idMapper.compose(DocumentId::toInt));
}
public <ID extends RepoIdAware> ImmutableSet<ID> toIdsFromInt(@NonNull final IntFunction<ID> idMapper)
{
return toSet(documentId -> idMapper.apply(documentId.toInt()));
}
/**
* Similar to {@link #toIds(Function)} but this returns a list, so it preserves the order | */
public <ID extends RepoIdAware> ImmutableList<ID> toIdsList(@NonNull final Function<Integer, ID> idMapper)
{
return toImmutableList(idMapper.compose(DocumentId::toInt));
}
public Set<String> toJsonSet()
{
if (all)
{
return ALL_StringSet;
}
return toSet(DocumentId::toJson);
}
public SelectionSize toSelectionSize()
{
if (isAll())
{
return SelectionSize.ofAll();
}
return SelectionSize.ofSize(size());
}
public DocumentIdsSelection addAll(@NonNull final DocumentIdsSelection documentIdsSelection)
{
if (this.isEmpty())
{
return documentIdsSelection;
}
else if (documentIdsSelection.isEmpty())
{
return this;
}
if (this.all)
{
return this;
}
else if (documentIdsSelection.all)
{
return documentIdsSelection;
}
final ImmutableSet<DocumentId> combinedIds = Stream.concat(this.stream(), documentIdsSelection.stream()).collect(ImmutableSet.toImmutableSet());
final DocumentIdsSelection result = DocumentIdsSelection.of(combinedIds);
if (this.equals(result))
{
return this;
}
else if (documentIdsSelection.equals(result))
{
return documentIdsSelection;
}
else
{
return result;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DocumentIdsSelection.java | 1 |
请完成以下Java代码 | public static boolean checkUsingIsDigitMethod(String str) {
if (str == null || str.length() == 0) {
return false;
}
return Character.isDigit(str.charAt(0));
}
public static boolean checkUsingPatternClass(String str) {
if (str == null || str.length() == 0) {
return false;
}
return Pattern.compile("^[0-9].*")
.matcher(str)
.matches();
}
public static boolean checkUsingMatchesMethod(String str) {
if (str == null || str.length() == 0) {
return false;
}
return str.matches("^[0-9].*");
}
public static boolean checkUsingCharMatcherInRangeMethod(String str) {
if (str == null || str.length() == 0) {
return false; | }
return CharMatcher.inRange('0', '9')
.matches(str.charAt(0));
}
public static boolean checkUsingCharMatcherForPredicateMethod(String str) {
if (str == null || str.length() == 0) {
return false;
}
return CharMatcher.forPredicate(Character::isDigit)
.matches(str.charAt(0));
}
} | repos\tutorials-master\core-java-modules\core-java-string-operations-5\src\main\java\com\baeldung\firstchardigit\FirstCharDigit.java | 1 |
请完成以下Java代码 | public String getBPartnerAddress()
{
return address;
}
@Override
public void setBPartnerAddress(String address)
{
this.address = address;
}
@Override
public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentLocationAdapter.super.setRenderedAddressAndCapturedLocation(from);
}
@Override
public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentLocationAdapter.super.setRenderedAddress(from);
}
@Override
public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL) | {
return documentLocationBL.toPlainDocumentLocation(this);
}
@Override
public BPartnerLocationAdapter toOldValues()
{
InterfaceWrapperHelper.assertNotOldValues(delegate);
return new BPartnerLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_OLCand.class));
}
@Override
public I_C_OLCand getWrappedRecord()
{
return delegate;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\location\adapter\BPartnerLocationAdapter.java | 1 |
请完成以下Java代码 | public void setMessageSource(MessageSource messageSource) {
Assert.notNull(messageSource, "messageSource cannot be null");
this.messages = new MessageSourceAccessor(messageSource);
}
/**
* Sets if the principal name should be extracted from the emailAddress or CN
* attribute (default).
*
* By default, the format {@link X500Principal#RFC2253} is passed to
* {@link X500Principal#getName(String)} and the principal is extracted from the CN
* attribute as defined in
* <a href="https://datatracker.ietf.org/doc/html/rfc2253#section-2.3">Converting
* AttributeTypeAndValue of RFC2253</a>.
*
* If {@link #setExtractPrincipalNameFromEmail(boolean)} is {@code true}, then the
* format {@link X500Principal#RFC2253} is passed to
* {@link X500Principal#getName(String)} and the principal is extracted from the
* <a href="https://oid-base.com/get/1.2.840.113549.1.9.1">OID.1.2.840.113549.1.9.1
* (emailAddress)</a> attribute as defined in
* <a href="https://datatracker.ietf.org/doc/html/rfc1779#section-2.3">Section 2.3 of | * RFC1779</a>.
* @param extractPrincipalNameFromEmail whether to extract the principal from the
* emailAddress (default false)
* @see <a href="https://datatracker.ietf.org/doc/html/rfc2253">RFC2253</a>
* @see <a href="https://datatracker.ietf.org/doc/html/rfC1779">RFC1779</a>
*/
public void setExtractPrincipalNameFromEmail(boolean extractPrincipalNameFromEmail) {
if (extractPrincipalNameFromEmail) {
this.subjectDnPattern = EMAIL_SUBJECT_DN_PATTERN;
this.x500PrincipalFormat = X500Principal.RFC1779;
}
else {
this.subjectDnPattern = CN_SUBJECT_DN_PATTERN;
this.x500PrincipalFormat = X500Principal.RFC2253;
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\preauth\x509\SubjectX500PrincipalExtractor.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city; | }
public void setCity(String city) {
this.city = city;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
} | repos\Hibernate-SpringBoot-master\Java EE\AMPCandBMT\src\main\java\com\sample\model\Player.java | 1 |
请完成以下Java代码 | private boolean isEligible(final I_C_OrderLine orderLine)
{
// Skip if given line is currently changed by the repository (to avoid race conditions)
if (OrderGroupRepository.isRepositoryUpdate(orderLine))
{
return false;
}
// Skip if not a group line
if (!OrderGroupCompensationUtils.isInGroup(orderLine))
{
return false;
}
// Don't touch processed lines (e.g. completed orders)
return !orderLine.isProcessed();
}
public void onOrderLineDeleted(final I_C_OrderLine orderLine)
{
if (!isEligible(orderLine))
{
return;
}
final boolean groupCompensationLine = orderLine.isGroupCompensationLine();
if (groupCompensationLine)
{
onCompensationLineDeleted(orderLine);
}
}
private void onCompensationLineDeleted(final I_C_OrderLine compensationLine)
{
final GroupId groupId = OrderGroupRepository.extractGroupId(compensationLine);
final Group group = groupsRepo.retrieveGroupIfExists(groupId);
// If no group found => nothing to do
// Usually this case happens when we delete the order, so all the lines together.
if (group == null)
{
return;
}
if (!group.hasCompensationLines())
{
groupsRepo.destroyGroup(group);
} | else
{
group.updateAllCompensationLines();
groupsRepo.saveGroup(group);
}
}
public void updateCompensationLineNoSave(final I_C_OrderLine orderLine)
{
final Group group = groupsRepo.createPartialGroupFromCompensationLine(orderLine);
group.updateAllCompensationLines();
final OrderLinesStorage orderLinesStorage = groupsRepo.createNotSaveableSingleOrderLineStorage(orderLine);
groupsRepo.saveGroup(group, orderLinesStorage);
}
@Nullable
public GroupTemplateId getGroupTemplateId(@NonNull final GroupId groupId)
{
return groupsRepo.getGroupTemplateId(groupId);
}
public boolean isProductExcludedFromFlatrateConditions(@Nullable final GroupTemplateId groupTemplateId, @NonNull final ProductId productId)
{
if (groupTemplateId == null)
{
return false;
}
return flatrateConditionsExcludedProductsRepo.isProductExcludedFromFlatrateConditions(groupTemplateId, productId);
}
public IQueryBuilder<I_C_OrderLine> retrieveGroupOrderLinesQuery(final GroupId groupId)
{
return groupsRepo.retrieveGroupOrderLinesQuery(groupId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\compensationGroup\OrderGroupCompensationChangesHandler.java | 1 |
请完成以下Java代码 | public class AD_PrintPaper_Default extends JavaProcess
{
/** The Client */
private int p_AD_Client_ID = -1;
/** The Record */
private int p_Record_ID = 0;
/**
* Prepare - e.g., get Parameters.
*/
protected void prepare()
{
ProcessInfoParameter[] para = getParametersAsArray();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null)
;
else if (name.equals("AD_Client_ID"))
p_AD_Client_ID = para[i].getParameterAsInt();
else
log.error("Unknown Parameter: " + name);
}
p_Record_ID = getRecord_ID();
} // prepare
/**
* Process
* @return message
* @throws Exception
*/
protected String doIt() throws Exception
{
StringBuffer sql = new StringBuffer("");
int cnt = 0;
log.info("Set Print Format");
try | {
sql.append("UPDATE AD_PrintFormat pf "
+ "SET AD_PrintPaper_ID = " + p_Record_ID + " "
+ "WHERE EXISTS (SELECT * FROM AD_PrintPaper pp "
+ "WHERE pf.AD_PrintPaper_ID=pp.AD_PrintPaper_ID "
+ "AND IsLandscape = (SELECT IsLandscape FROM AD_PrintPaper "
+ "WHERE AD_PrintPaper_ID=" + p_Record_ID + "))");
if (p_AD_Client_ID != -1) {
sql.append(" AND AD_Client_ID = " + p_AD_Client_ID);
}
cnt = DB.executeUpdateAndSaveErrorOnFail(sql.toString(), get_TrxName());
log.info("Updated " + cnt + " columns");
log.debug("Committing ...");
DB.commit(true, null);
}
catch (Exception e)
{
log.error("set print format", e);
}
return "@Copied@=" + cnt;
} // doIt
} // AD_PrintPaper_Default | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\AD_PrintPaper_Default.java | 1 |
请完成以下Java代码 | public I_C_ValidCombination getCB_Differences_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getCB_Differences_Acct(), get_TrxName()); }
/** Set Cash Book Differences.
@param CB_Differences_Acct
Cash Book Differences Account
*/
public void setCB_Differences_Acct (int CB_Differences_Acct)
{
set_Value (COLUMNNAME_CB_Differences_Acct, Integer.valueOf(CB_Differences_Acct));
}
/** Get Cash Book Differences.
@return Cash Book Differences Account
*/
public int getCB_Differences_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CB_Differences_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getCB_Expense_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getCB_Expense_Acct(), get_TrxName()); }
/** Set Cash Book Expense.
@param CB_Expense_Acct
Cash Book Expense Account
*/
public void setCB_Expense_Acct (int CB_Expense_Acct)
{
set_Value (COLUMNNAME_CB_Expense_Acct, Integer.valueOf(CB_Expense_Acct));
}
/** Get Cash Book Expense.
@return Cash Book Expense Account
*/
public int getCB_Expense_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CB_Expense_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getCB_Receipt_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getCB_Receipt_Acct(), get_TrxName()); }
/** Set Cash Book Receipt.
@param CB_Receipt_Acct
Cash Book Receipts Account
*/
public void setCB_Receipt_Acct (int CB_Receipt_Acct)
{ | set_Value (COLUMNNAME_CB_Receipt_Acct, Integer.valueOf(CB_Receipt_Acct));
}
/** Get Cash Book Receipt.
@return Cash Book Receipts Account
*/
public int getCB_Receipt_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CB_Receipt_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_CashBook getC_CashBook() throws RuntimeException
{
return (I_C_CashBook)MTable.get(getCtx(), I_C_CashBook.Table_Name)
.getPO(getC_CashBook_ID(), get_TrxName()); }
/** Set Cash Book.
@param C_CashBook_ID
Cash Book for recording petty cash transactions
*/
public void setC_CashBook_ID (int C_CashBook_ID)
{
if (C_CashBook_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_CashBook_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_CashBook_ID, Integer.valueOf(C_CashBook_ID));
}
/** Get Cash Book.
@return Cash Book for recording petty cash transactions
*/
public int getC_CashBook_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_CashBook_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CashBook_Acct.java | 1 |
请完成以下Java代码 | public class DeliveryAccuracy extends SLACriteria
{
/**
* DeliveryAccuracy
*/
public DeliveryAccuracy ()
{
super ();
} // DeliveryAccuracy
/** Logger */
protected Logger log = LogManager.getLogger(getClass());
/**
* Create new Measures for the Goal
* @param goal the goal
* @return number created
*/
@Override
public int createMeasures (MSLAGoal goal)
{
String sql = "SELECT M_InOut_ID, io.MovementDate-o.DatePromised," // 1..2
+ " io.MovementDate, o.DatePromised, o.DocumentNo "
+ "FROM M_InOut io"
+ " INNER JOIN C_Order o ON (io.C_Order_ID=o.C_Order_ID) "
+ "WHERE io.C_BPartner_ID=?"
+ " AND NOT EXISTS "
+ "(SELECT * FROM PA_SLA_Measure m "
+ "WHERE m.PA_SLA_Goal_ID=?"
+ " AND m.AD_Table_ID=" + getTableId(I_M_InOut.class)
+ " AND m.Record_ID=io.M_InOut_ID)";
int counter = 0;
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement (sql, null);
pstmt.setInt (1, goal.getC_BPartner_ID());
pstmt.setInt (2, goal.getPA_SLA_Goal_ID());
rs = pstmt.executeQuery ();
while (rs.next ())
{
int M_InOut_ID = rs.getInt(1);
BigDecimal MeasureActual = rs.getBigDecimal(2);
Timestamp MovementDate = rs.getTimestamp(3);
String Description = rs.getString(5) + ": " + rs.getTimestamp(4);
if (goal.isDateValid(MovementDate))
{
MSLAMeasure measure = new MSLAMeasure(goal, MovementDate,
MeasureActual, Description);
measure.setLink(getTableId(I_M_InOut.class), M_InOut_ID);
if (measure.save())
counter++;
}
}
}
catch (Exception e)
{
log.error("createMeasures", e);
}
finally
{
DB.close(rs, pstmt);
rs = null; pstmt = null;
}
return counter; | } // createMeasures
/**************************************************************************
* Calculate Goal Actual from unprocessed Measures
* @return goal actual measure
*/
@Override
public BigDecimal calculateMeasure (MSLAGoal goal)
{
// Average
BigDecimal retValue = Env.ZERO;
BigDecimal total = Env.ZERO;
int count = 0;
//
MSLAMeasure[] measures = goal.getAllMeasures();
for (int i = 0; i < measures.length; i++)
{
MSLAMeasure measure = measures[i];
if (!measure.isActive()
|| (goal.getValidFrom() != null && measure.getDateTrx().before(goal.getValidFrom()))
|| (goal.getValidTo() != null && measure.getDateTrx().after(goal.getValidTo())))
continue;
//
total = total.add(measure.getMeasureActual());
count++;
//
if (!measure.isProcessed())
{
measure.setProcessed(true);
measure.save();
}
}
// Goal Expired
if (goal.getValidTo() != null
&& goal.getValidTo().after(new Timestamp(System.currentTimeMillis())))
goal.setProcessed(true);
// Calculate with 2 digits precision
if (count != 0)
retValue = total.divide(new BigDecimal(count), 2, BigDecimal.ROUND_HALF_UP);
return retValue;
} // calculateMeasure
} // DeliveryAccuracy | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\sla\DeliveryAccuracy.java | 1 |
请完成以下Java代码 | public Builder addColumn(final DocumentLayoutColumnDescriptor.Builder columnBuilder)
{
Check.assumeNotNull(columnBuilder, "Parameter columnBuilder is not null");
columnsBuilders.add(columnBuilder);
return this;
}
public Builder addColumn(final List<DocumentLayoutElementDescriptor.Builder> elementsBuilders)
{
if (elementsBuilders == null || elementsBuilders.isEmpty())
{
return this;
}
final DocumentLayoutElementGroupDescriptor.Builder elementsGroupBuilder = DocumentLayoutElementGroupDescriptor.builder();
elementsBuilders.stream()
.map(elementBuilder -> DocumentLayoutElementLineDescriptor.builder().addElement(elementBuilder))
.forEach(elementLineBuilder -> elementsGroupBuilder.addElementLine(elementLineBuilder));
final DocumentLayoutColumnDescriptor.Builder column = DocumentLayoutColumnDescriptor.builder().addElementGroup(elementsGroupBuilder);
addColumn(column);
return this;
}
public Builder setInvalid(final String invalidReason)
{
Check.assumeNotEmpty(invalidReason, "invalidReason is not empty");
this.invalidReason = invalidReason;
logger.trace("Layout section was marked as invalid: {}", this);
return this;
}
public Builder setClosableMode(@NonNull final ClosableMode closableMode)
{
this.closableMode = closableMode;
return this;
}
public Builder setCaptionMode(@NonNull final CaptionMode captionMode)
{
this.captionMode = captionMode;
return this;
}
public boolean isValid() | {
return invalidReason == null;
}
public boolean isInvalid()
{
return invalidReason != null;
}
public boolean isNotEmpty()
{
return streamElementBuilders().findAny().isPresent();
}
private Stream<DocumentLayoutElementDescriptor.Builder> streamElementBuilders()
{
return columnsBuilders.stream().flatMap(DocumentLayoutColumnDescriptor.Builder::streamElementBuilders);
}
public Builder setExcludeSpecialFields()
{
streamElementBuilders().forEach(elementBuilder -> elementBuilder.setExcludeSpecialFields());
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutSectionDescriptor.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setAD_Issue_ID (final int AD_Issue_ID)
{
if (AD_Issue_ID < 1)
set_Value (COLUMNNAME_AD_Issue_ID, null);
else
set_Value (COLUMNNAME_AD_Issue_ID, AD_Issue_ID);
}
@Override
public int getAD_Issue_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Issue_ID);
}
@Override
public I_C_BankStatement_Import_File getC_BankStatement_Import_File()
{
return get_ValueAsPO(COLUMNNAME_C_BankStatement_Import_File_ID, I_C_BankStatement_Import_File.class);
}
@Override
public void setC_BankStatement_Import_File(final I_C_BankStatement_Import_File C_BankStatement_Import_File)
{
set_ValueFromPO(COLUMNNAME_C_BankStatement_Import_File_ID, I_C_BankStatement_Import_File.class, C_BankStatement_Import_File);
}
@Override
public void setC_BankStatement_Import_File_ID (final int C_BankStatement_Import_File_ID)
{
if (C_BankStatement_Import_File_ID < 1)
set_Value (COLUMNNAME_C_BankStatement_Import_File_ID, null);
else
set_Value (COLUMNNAME_C_BankStatement_Import_File_ID, C_BankStatement_Import_File_ID);
}
@Override
public int getC_BankStatement_Import_File_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BankStatement_Import_File_ID);
}
@Override
public void setC_BankStatement_Import_File_Log_ID (final int C_BankStatement_Import_File_Log_ID)
{ | if (C_BankStatement_Import_File_Log_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BankStatement_Import_File_Log_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BankStatement_Import_File_Log_ID, C_BankStatement_Import_File_Log_ID);
}
@Override
public int getC_BankStatement_Import_File_Log_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BankStatement_Import_File_Log_ID);
}
@Override
public void setLogmessage (final @Nullable java.lang.String Logmessage)
{
set_Value (COLUMNNAME_Logmessage, Logmessage);
}
@Override
public java.lang.String getLogmessage()
{
return get_ValueAsString(COLUMNNAME_Logmessage);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\org\adempiere\banking\model\X_C_BankStatement_Import_File_Log.java | 1 |
请完成以下Java代码 | public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setSplitterStrategy_JavaClass_ID (final int SplitterStrategy_JavaClass_ID)
{
if (SplitterStrategy_JavaClass_ID < 1)
set_Value (COLUMNNAME_SplitterStrategy_JavaClass_ID, null);
else
set_Value (COLUMNNAME_SplitterStrategy_JavaClass_ID, SplitterStrategy_JavaClass_ID);
}
@Override
public int getSplitterStrategy_JavaClass_ID() | {
return get_ValueAsInt(COLUMNNAME_SplitterStrategy_JavaClass_ID);
}
@Override
public void setUseInASI (final boolean UseInASI)
{
set_Value (COLUMNNAME_UseInASI, UseInASI);
}
@Override
public boolean isUseInASI()
{
return get_ValueAsBoolean(COLUMNNAME_UseInASI);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PI_Attribute.java | 1 |
请完成以下Java代码 | public BigDecimal getOrderQtyReserved()
{
return getSalesOrderLine().getQtyReserved();
}
public BigDecimal getOrderPriceActual()
{
return getSalesOrderLine().getPriceActual();
}
public DocStatus getOrderDocStatus()
{
return DocStatus.ofCode(getSalesOrderLine().getC_Order().getDocStatus());
}
public I_M_ShipmentSchedule getSched()
{
return shipmentSchedule;
}
public ShipmentScheduleId getShipmentScheduleId()
{
return ShipmentScheduleId.ofRepoId(shipmentSchedule.getM_ShipmentSchedule_ID());
}
/**
* @return shipment schedule's QtyToDeliver_Override or <code>null</code>
*/
public BigDecimal getQtyOverride()
{
return InterfaceWrapperHelper.getValueOrNull(shipmentSchedule, I_M_ShipmentSchedule.COLUMNNAME_QtyToDeliver_Override);
}
public BigDecimal getInitialSchedQtyDelivered()
{
return initialSchedQtyDelivered;
}
public void setShipmentScheduleLineNetAmt(final BigDecimal lineNetAmt)
{
shipmentSchedule.setLineNetAmt(lineNetAmt);
}
@Nullable | public String getSalesOrderPORef()
{
return salesOrder.map(I_C_Order::getPOReference).orElse(null);
}
@Nullable
public InputDataSourceId getSalesOrderADInputDatasourceID()
{
if(!salesOrder.isPresent())
{
return null;
}
final I_C_Order orderRecord = salesOrder.get();
return InputDataSourceId.ofRepoIdOrNull(orderRecord.getAD_InputDataSource_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\OlAndSched.java | 1 |
请完成以下Java代码 | public HttpHeaders getResponseHeaders() {
return this.responseHeaders;
}
/**
* Transform the underlying {@link ExecutionResult} through a {@link Builder}
* and return a new instance with the modified values.
* @param consumer callback to transform the result
* @return the new response instance with the mutated {@code ExecutionResult}
*/
public WebGraphQlResponse transform(Consumer<Builder> consumer) {
Builder builder = new Builder(this);
consumer.accept(builder);
return builder.build();
}
/**
* Builder to transform a {@link WebGraphQlResponse}. | */
public static final class Builder extends DefaultExecutionGraphQlResponse.Builder<Builder, WebGraphQlResponse> {
private Builder(WebGraphQlResponse original) {
super(original);
}
@Override
protected WebGraphQlResponse build(WebGraphQlResponse original, ExecutionResult newResult) {
return new WebGraphQlResponse(original, newResult);
}
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\server\WebGraphQlResponse.java | 1 |
请完成以下Java代码 | public String getAsString()
{
return attributesKeyString;
}
public boolean isNone()
{
return NONE.equals(this);
}
public boolean isAll()
{
return ALL.equals(this);
}
public boolean isOther()
{
return OTHER.equals(this);
}
public void assertNotAllOrOther()
{
Check.errorIf(isOther() || isAll(),
"AttributesKeys.OTHER or .ALL of the given attributesKey is not supported; attributesKey={}", this);
}
private static ImmutableSet<AttributesKeyPart> extractAttributeKeyParts(final String attributesKeyString)
{
if (attributesKeyString.trim().isEmpty())
{
return ImmutableSet.of();
}
try
{
return ATTRIBUTEVALUEIDS_SPLITTER.splitToList(attributesKeyString.trim())
.stream()
.map(AttributesKeyPart::parseString)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(ImmutableSet.toImmutableSet());
}
catch (final Exception ex)
{
throw AdempiereException.wrapIfNeeded(ex)
.appendParametersToMessage()
.setParameter("attributesKeyString", attributesKeyString);
}
}
public boolean contains(@NonNull final AttributesKey attributesKey) | {
return parts.containsAll(attributesKey.parts);
}
public AttributesKey getIntersection(@NonNull final AttributesKey attributesKey)
{
final HashSet<AttributesKeyPart> ownMutableParts = new HashSet<>(parts);
ownMutableParts.retainAll(attributesKey.parts);
return AttributesKey.ofParts(ownMutableParts);
}
/**
* @return {@code true} if ad least one attributeValueId from the given {@code attributesKey} is included in this instance.
*/
public boolean intersects(@NonNull final AttributesKey attributesKey)
{
return parts.stream().anyMatch(attributesKey.parts::contains);
}
public String getValueByAttributeId(@NonNull final AttributeId attributeId)
{
for (final AttributesKeyPart part : parts)
{
if (part.getType() == AttributeKeyPartType.AttributeIdAndValue
&& AttributeId.equals(part.getAttributeId(), attributeId))
{
return part.getValue();
}
}
throw new AdempiereException("Attribute `" + attributeId + "` was not found in `" + this + "`");
}
public static boolean equals(@Nullable final AttributesKey k1, @Nullable final AttributesKey k2)
{
return Objects.equals(k1, k2);
}
@Override
public int compareTo(@Nullable final AttributesKey o)
{
if (o == null)
{
return 1; // we assume that null is less than not-null
}
return this.getAsString().compareTo(o.getAsString());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\commons\AttributesKey.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable List<String> getSupported() {
return this.supported;
}
public void setSupported(@Nullable List<String> supported) {
this.supported = supported;
}
public @Nullable Boolean getDetectSupported() {
return this.detectSupported;
}
public void setDetectSupported(@Nullable Boolean detectSupported) {
this.detectSupported = detectSupported;
}
public Use getUse() {
return this.use;
}
public static class Use {
/**
* Use the HTTP header with the given name to obtain the version.
*/
private @Nullable String header;
/**
* Use the query parameter with the given name to obtain the version.
*/
private @Nullable String queryParameter;
/**
* Use the path segment at the given index to obtain the version.
*/
private @Nullable Integer pathSegment;
/**
* Use the media type parameter with the given name to obtain the version.
*/ | private Map<MediaType, String> mediaTypeParameter = new LinkedHashMap<>();
public @Nullable String getHeader() {
return this.header;
}
public void setHeader(@Nullable String header) {
this.header = header;
}
public @Nullable String getQueryParameter() {
return this.queryParameter;
}
public void setQueryParameter(@Nullable String queryParameter) {
this.queryParameter = queryParameter;
}
public @Nullable Integer getPathSegment() {
return this.pathSegment;
}
public void setPathSegment(@Nullable Integer pathSegment) {
this.pathSegment = pathSegment;
}
public Map<MediaType, String> getMediaTypeParameter() {
return this.mediaTypeParameter;
}
public void setMediaTypeParameter(Map<MediaType, String> mediaTypeParameter) {
this.mediaTypeParameter = mediaTypeParameter;
}
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\autoconfigure\WebFluxProperties.java | 2 |
请完成以下Java代码 | public Balance toSingleSide()
{
final Money min = debit.min(credit);
if (min.isZero())
{
return this;
}
return new Balance(this.debit.subtract(min), this.credit.subtract(min));
}
public Balance computeDiffToBalance()
{
final Money diff = toMoney();
if (isReversal())
{
return diff.signum() < 0 ? ofCredit(diff) : ofDebit(diff.negate());
}
else
{
return diff.signum() < 0 ? ofDebit(diff.negate()) : ofCredit(diff);
}
}
public Balance invert()
{
return new Balance(this.credit, this.debit);
}
//
//
//
//
//
@ToString
private static class BalanceBuilder
{
private Money debit;
private Money credit; | public void add(@NonNull Balance balance)
{
add(balance.getDebit(), balance.getCredit());
}
public BalanceBuilder combine(@NonNull BalanceBuilder balanceBuilder)
{
add(balanceBuilder.debit, balanceBuilder.credit);
return this;
}
public void add(@Nullable Money debitToAdd, @Nullable Money creditToAdd)
{
if (debitToAdd != null)
{
this.debit = this.debit != null ? this.debit.add(debitToAdd) : debitToAdd;
}
if (creditToAdd != null)
{
this.credit = this.credit != null ? this.credit.add(creditToAdd) : creditToAdd;
}
}
public Optional<Balance> build()
{
return debit != null || credit != null
? Optional.of(new Balance(debit, credit))
: Optional.empty();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Balance.java | 1 |
请完成以下Java代码 | public List<MessageEventSubscriptionEntity> findMessageStartEventSubscriptions() {
return toMessageEventSubscriptionEntityList(getList("selectMessageStartEventSubscriptions", null, null, true));
}
@Override
public void updateEventSubscriptionTenantId(String oldTenantId, String newTenantId) {
Map<String, String> params = new HashMap<String, String>();
params.put("oldTenantId", oldTenantId);
params.put("newTenantId", newTenantId);
getDbSqlSession().update("updateTenantIdOfEventSubscriptions", params);
}
@Override
public void deleteEventSubscriptionsForProcessDefinition(String processDefinitionId) {
getDbSqlSession().delete(
"deleteEventSubscriptionsForProcessDefinition",
processDefinitionId,
EventSubscriptionEntityImpl.class
);
}
protected List<SignalEventSubscriptionEntity> toSignalEventSubscriptionEntityList(
List<EventSubscriptionEntity> result
) {
List<SignalEventSubscriptionEntity> signalEventSubscriptionEntities = new ArrayList<
SignalEventSubscriptionEntity
>(result.size());
for (EventSubscriptionEntity eventSubscriptionEntity : result) { | signalEventSubscriptionEntities.add((SignalEventSubscriptionEntity) eventSubscriptionEntity);
}
return signalEventSubscriptionEntities;
}
protected List<MessageEventSubscriptionEntity> toMessageEventSubscriptionEntityList(
List<EventSubscriptionEntity> result
) {
List<MessageEventSubscriptionEntity> messageEventSubscriptionEntities = new ArrayList<
MessageEventSubscriptionEntity
>(result.size());
for (EventSubscriptionEntity eventSubscriptionEntity : result) {
messageEventSubscriptionEntities.add((MessageEventSubscriptionEntity) eventSubscriptionEntity);
}
return messageEventSubscriptionEntities;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisEventSubscriptionDataManager.java | 1 |
请完成以下Java代码 | public Long getTimestamp() {
return this.timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
public Player getCreator() {
return this.creator;
}
public void setCreator(Player creator) {
this.creator = creator;
addPlayer(creator);
} | public void addPlayer(Player player) {
this.players.add(player);
}
public List<Player> getPlayers() {
return Collections.unmodifiableList(this.players);
}
public GameSettings getSettings() {
return this.settings;
}
public void setSettings(GameSettings settings) {
this.settings = settings;
}
} | repos\tutorials-master\libraries-data\src\main\java\com\baeldung\modelmapper\domain\Game.java | 1 |
请完成以下Java代码 | public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
if (beanFactory instanceof ConfigurableListableBeanFactory) {
this.embeddedValueResolver = new EmbeddedValueResolver((ConfigurableBeanFactory) beanFactory);
this.resolver = ((ConfigurableListableBeanFactory) beanFactory).getBeanExpressionResolver();
this.expressionContext = new BeanExpressionContext((ConfigurableListableBeanFactory) beanFactory, null);
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (event.getApplicationContext() == this.applicationContext) {
this.contextRefreshed = true;
}
}
public RabbitOperations getRabbitOperations() {
return rabbitOperations;
}
public void setRabbitOperations(RabbitOperations rabbitOperations) {
this.rabbitOperations = rabbitOperations;
}
public RabbitListenerEndpointRegistry getEndpointRegistry() {
return endpointRegistry;
}
public void setEndpointRegistry(RabbitListenerEndpointRegistry endpointRegistry) {
this.endpointRegistry = endpointRegistry;
} | public String getContainerFactoryBeanName() {
return containerFactoryBeanName;
}
public void setContainerFactoryBeanName(String containerFactoryBeanName) {
this.containerFactoryBeanName = containerFactoryBeanName;
}
public RabbitListenerContainerFactory<?> getContainerFactory() {
return containerFactory;
}
public void setContainerFactory(RabbitListenerContainerFactory<?> containerFactory) {
this.containerFactory = containerFactory;
}
} | repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\rabbit\RabbitChannelDefinitionProcessor.java | 1 |
请完成以下Java代码 | public final PPOrderUserNotificationsProducer notifyGenerated(@NonNull final I_PP_Order ppOrder)
{
notifyGenerated(ImmutableList.of(ppOrder));
return this;
}
private UserNotificationRequest createUserNotification(@NonNull final I_PP_Order ppOrder)
{
final UserId recipientUserId = getNotificationRecipientUserId(ppOrder);
final TableRecordReference ppOrderRef = TableRecordReference.of(ppOrder);
return newUserNotificationRequest()
.recipientUserId(recipientUserId)
.contentADMessage(MSG_Event_PPOrderGenerated)
.contentADMessageParam(ppOrderRef)
.targetAction(TargetRecordAction.of(ppOrderRef))
.build();
} | private UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest()
{
return UserNotificationRequest.builder()
.topic(USER_NOTIFICATIONS_TOPIC);
}
private UserId getNotificationRecipientUserId(final I_PP_Order ppOrder)
{
return UserId.ofRepoId(ppOrder.getCreatedBy());
}
private void postNotifications(final List<UserNotificationRequest> notifications)
{
notificationBL.sendAfterCommit(notifications);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\event\PPOrderUserNotificationsProducer.java | 1 |
请完成以下Java代码 | public int getM_HU_Item_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_Item_ID);
}
@Override
public de.metas.handlingunits.model.I_M_HU_PackingMaterial getM_HU_PackingMaterial()
{
return get_ValueAsPO(COLUMNNAME_M_HU_PackingMaterial_ID, de.metas.handlingunits.model.I_M_HU_PackingMaterial.class);
}
@Override
public void setM_HU_PackingMaterial(final de.metas.handlingunits.model.I_M_HU_PackingMaterial M_HU_PackingMaterial)
{
set_ValueFromPO(COLUMNNAME_M_HU_PackingMaterial_ID, de.metas.handlingunits.model.I_M_HU_PackingMaterial.class, M_HU_PackingMaterial);
}
@Override
public void setM_HU_PackingMaterial_ID (final int M_HU_PackingMaterial_ID)
{
if (M_HU_PackingMaterial_ID < 1)
set_Value (COLUMNNAME_M_HU_PackingMaterial_ID, null);
else
set_Value (COLUMNNAME_M_HU_PackingMaterial_ID, M_HU_PackingMaterial_ID);
}
@Override
public int getM_HU_PackingMaterial_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PackingMaterial_ID);
}
@Override
public de.metas.handlingunits.model.I_M_HU_PI_Item getM_HU_PI_Item()
{
return get_ValueAsPO(COLUMNNAME_M_HU_PI_Item_ID, de.metas.handlingunits.model.I_M_HU_PI_Item.class);
}
@Override
public void setM_HU_PI_Item(final de.metas.handlingunits.model.I_M_HU_PI_Item M_HU_PI_Item)
{
set_ValueFromPO(COLUMNNAME_M_HU_PI_Item_ID, de.metas.handlingunits.model.I_M_HU_PI_Item.class, M_HU_PI_Item);
}
@Override
public void setM_HU_PI_Item_ID (final int M_HU_PI_Item_ID)
{
if (M_HU_PI_Item_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_ID, null);
else | set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_ID, M_HU_PI_Item_ID);
}
@Override
public int getM_HU_PI_Item_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PI_Item_ID);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Item.java | 1 |
请完成以下Java代码 | public BigDecimal getQtyOrdered()
{
return deliverRequest.getQtyOrdered();
}
public boolean hasSalesOrderLine()
{
return salesOrderLine.isPresent();
}
private I_C_OrderLine getSalesOrderLine()
{
return salesOrderLine.get();
}
public ProductId getProductId()
{
return ProductId.ofRepoId(shipmentSchedule.getM_Product_ID());
}
public WarehouseId getWarehouseId()
{
return Services.get(IShipmentScheduleEffectiveBL.class).getWarehouseId(shipmentSchedule);
}
public I_C_UOM getOrderPriceUOM()
{
final int priceUomId = getSalesOrderLine().getPrice_UOM_ID();
return Services.get(IUOMDAO.class).getById(priceUomId);
}
public BigDecimal getOrderQtyReserved()
{
return getSalesOrderLine().getQtyReserved();
}
public BigDecimal getOrderPriceActual()
{
return getSalesOrderLine().getPriceActual();
}
public DocStatus getOrderDocStatus()
{
return DocStatus.ofCode(getSalesOrderLine().getC_Order().getDocStatus());
}
public I_M_ShipmentSchedule getSched()
{
return shipmentSchedule;
}
public ShipmentScheduleId getShipmentScheduleId() | {
return ShipmentScheduleId.ofRepoId(shipmentSchedule.getM_ShipmentSchedule_ID());
}
/**
* @return shipment schedule's QtyToDeliver_Override or <code>null</code>
*/
public BigDecimal getQtyOverride()
{
return InterfaceWrapperHelper.getValueOrNull(shipmentSchedule, I_M_ShipmentSchedule.COLUMNNAME_QtyToDeliver_Override);
}
public BigDecimal getInitialSchedQtyDelivered()
{
return initialSchedQtyDelivered;
}
public void setShipmentScheduleLineNetAmt(final BigDecimal lineNetAmt)
{
shipmentSchedule.setLineNetAmt(lineNetAmt);
}
@Nullable
public String getSalesOrderPORef()
{
return salesOrder.map(I_C_Order::getPOReference).orElse(null);
}
@Nullable
public InputDataSourceId getSalesOrderADInputDatasourceID()
{
if(!salesOrder.isPresent())
{
return null;
}
final I_C_Order orderRecord = salesOrder.get();
return InputDataSourceId.ofRepoIdOrNull(orderRecord.getAD_InputDataSource_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\OlAndSched.java | 1 |
请完成以下Java代码 | private static Frame getParentFrame(Component c)
{
Frame parent = null;
Container e = c.getParent();
while (e != null)
{
if (e instanceof Frame)
{
parent = (Frame)e;
break;
}
e = e.getParent();
}
return parent;
}
private static JTextComponent getTextComponent(Object c)
{
if (c == null)
{
return null;
}
if (c instanceof JTextComponent)
{
return (JTextComponent)c;
}
if (c instanceof Container)
{
final Container container = (Container)c;
for (Component cc : container.getComponents())
{
if (cc instanceof JTextComponent)
{
return (JTextComponent)cc;
}
else if (cc instanceof Container)
{ | return getTextComponent(cc);
}
}
}
return null;
}
public static boolean isAdvancedText(GridField gridField)
{
if (gridField == null)
{
log.warn("gridField is null");
return false;
}
final GridTab gridTab = gridField.getGridTab();
if (gridTab == null)
return false;
final MColumn column = MTable.get(Env.getCtx(), gridTab.getTableName()).getColumn(gridField.getColumnName());
if (column == null)
return false;
final I_AD_Column bean = InterfaceWrapperHelper.create(column, I_AD_Column.class);
return bean.isAdvancedText();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\BoilerPlateMenu.java | 1 |
请完成以下Java代码 | public Optional<PickingSlotRow> findRowMatching(@NonNull final Predicate<PickingSlotRow> predicate)
{
return streamThisRowAndIncludedRowsRecursivelly()
.filter(predicate)
.findFirst();
}
public boolean thereIsAnOpenPickingForOrderId(@NonNull final OrderId orderId)
{
final HuId huId = getHuId();
if (huId == null)
{
throw new AdempiereException("Not a PickedHURow!")
.appendParametersToMessage()
.setParameter("PickingSlotRow", this);
}
final boolean hasOpenPickingForOrderId = getPickingOrderIdsForHUId(huId).contains(orderId);
if (hasOpenPickingForOrderId)
{
return true;
}
if (isLU()) | {
return findRowMatching(row -> !row.isLU() && row.thereIsAnOpenPickingForOrderId(orderId))
.isPresent();
}
return false;
}
@NonNull
private ImmutableSet<OrderId> getPickingOrderIdsForHUId(@NonNull final HuId huId)
{
return Optional.ofNullable(huId2OpenPickingOrderIds.get(huId))
.orElse(ImmutableSet.of());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotRow.java | 1 |
请完成以下Java代码 | public String getName() {
return TYPE_NAME;
}
public TypedValue convertValue(TypedValue propertyValue) {
if(propertyValue instanceof BooleanValue) {
return propertyValue;
}
else {
Object value = propertyValue.getValue();
if(value == null) {
return Variables.booleanValue(null, propertyValue.isTransient());
}
else if((value instanceof Boolean) || (value instanceof String)) {
return Variables.booleanValue(Boolean.valueOf(value.toString()), propertyValue.isTransient());
}
else {
throw new ProcessEngineException("Value '"+value+"' is not of type Boolean.");
}
}
}
// deprecated /////////////////////////////////////////////////
public Object convertFormValueToModelValue(Object propertyValue) {
if (propertyValue==null || "".equals(propertyValue)) {
return null;
} | return Boolean.valueOf(propertyValue.toString());
}
public String convertModelValueToFormValue(Object modelValue) {
if (modelValue==null) {
return null;
}
if(Boolean.class.isAssignableFrom(modelValue.getClass())
|| boolean.class.isAssignableFrom(modelValue.getClass())) {
return modelValue.toString();
}
throw new ProcessEngineException("Model value is not of type boolean, but of type " + modelValue.getClass().getName());
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\type\BooleanFormType.java | 1 |
请完成以下Java代码 | static boolean hasAnotherScheme(URI uri) {
return schemePattern.matcher(uri.getSchemeSpecificPart()).matches() && uri.getHost() == null
&& uri.getRawPath() == null;
}
@Override
public int getOrder() {
return ROUTE_TO_URL_FILTER_ORDER;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
if (route == null) {
return chain.filter(exchange);
}
log.trace("RouteToRequestUrlFilter start");
URI uri = exchange.getRequest().getURI();
boolean encoded = containsEncodedParts(uri);
URI routeUri = route.getUri();
if (hasAnotherScheme(routeUri)) {
// this is a special url, save scheme to special attribute
// replace routeUri with schemeSpecificPart
exchange.getAttributes().put(GATEWAY_SCHEME_PREFIX_ATTR, routeUri.getScheme());
routeUri = URI.create(routeUri.getSchemeSpecificPart());
} | if ("lb".equalsIgnoreCase(routeUri.getScheme()) && routeUri.getHost() == null) {
// Load balanced URIs should always have a host. If the host is null it is
// most likely because the host name was invalid (for example included an
// underscore)
throw new IllegalStateException("Invalid host: " + routeUri.toString());
}
URI mergedUrl = UriComponentsBuilder.fromUri(uri)
// .uri(routeUri)
.scheme(routeUri.getScheme())
.host(routeUri.getHost())
.port(routeUri.getPort())
.build(encoded)
.toUri();
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, mergedUrl);
return chain.filter(exchange);
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\RouteToRequestUrlFilter.java | 1 |
请完成以下Java代码 | private int appendUnit()
{
_isIntersections.append();
_units.add(0);
_labels.add((byte) 0);
return _isIntersections.size() - 1;
}
private int appendNode()
{
int id;
if (_recycleBin.empty())
{
id = _nodes.size();
_nodes.add(new DawgNode());
}
else
{
id = _recycleBin.get(_recycleBin.size() - 1);
_nodes.get(id).reset();
_recycleBin.deleteLast();
}
return id;
}
private void freeNode(int id)
{
_recycleBin.add(id);
}
private static int hash(int key) | {
key = ~key + (key << 15); // key = (key << 15) - key - 1;
key = key ^ (key >>> 12);
key = key + (key << 2);
key = key ^ (key >>> 4);
key = key * 2057; // key = (key + (key << 3)) + (key << 11);
key = key ^ (key >>> 16);
return key;
}
private static final int INITIAL_TABLE_SIZE = 1 << 10;
private ArrayList<DawgNode> _nodes = new ArrayList<DawgNode>();
private AutoIntPool _units = new AutoIntPool();
private AutoBytePool _labels = new AutoBytePool();
private BitVector _isIntersections = new BitVector();
private AutoIntPool _table = new AutoIntPool();
private AutoIntPool _nodeStack = new AutoIntPool();
private AutoIntPool _recycleBin = new AutoIntPool();
private int _numStates;
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\DawgBuilder.java | 1 |
请完成以下Java代码 | public ESRPaymentInfo provideCustomPayload(@NonNull final InvoiceToExport invoiceWithoutEsrInfo)
{
final InvoiceId invoiceId = invoiceWithoutEsrInfo.getId();
final I_C_BPartner bpartnerRecord = loadOutOfTrx(invoiceWithoutEsrInfo.getBiller().getId(), I_C_BPartner.class);
final String companyName = CoalesceUtil.coalesce(bpartnerRecord.getCompanyName(), bpartnerRecord.getName());
final I_C_Payment_Request paymentRequestRecord = Services.get(IQueryBL.class)
.createQueryBuilder(I_C_Payment_Request.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Payment_Request.COLUMN_C_Invoice_ID, invoiceId)
.create()
.firstOnly(I_C_Payment_Request.class);
if (paymentRequestRecord == null)
{
logger.debug("C_Invoice_ID has no C_Payment_Request; -> returning null");
return null;
}
try (final MDCCloseable paymentRequestRecordMDC = TableRecordMDC.putTableRecordReference(paymentRequestRecord))
{
if (paymentRequestRecord.getC_BP_BankAccount_ID() <= 0)
{
logger.debug("C_Payment_Request for C_Invoice_ID has C_BP_BankAccount_ID={}; -> returning null", paymentRequestRecord.getC_BP_BankAccount_ID());
return null;
}
final I_C_BP_BankAccount esrBankAccount = create(paymentRequestRecord.getC_BP_BankAccount(), I_C_BP_BankAccount.class);
if (!esrBankAccount.isEsrAccount())
{
logger.debug("C_BP_BankAccount.isErsAccount=N; -> returning null", paymentRequestRecord.getC_BP_BankAccount_ID());
return null;
}
final BankId esrBankId = BankId.ofRepoIdOrNull(esrBankAccount.getC_Bank_ID());
final ESRPaymentInfo esrPaymentInfo = ESRPaymentInfo.builder()
.referenceNumber(ESRStringUtil.formatReferenceNumber(paymentRequestRecord.getReference()))
.codingLine(paymentRequestRecord.getFullPaymentString())
.companyName(companyName)
.addressInfo(createAddressInfo(esrBankId))
.participantNumber(esrBankAccount.getESR_RenderedAccountNo())
.build();
return esrPaymentInfo;
}
}
private AddressInfo createAddressInfo(@Nullable final BankId esrBankId)
{
if(esrBankId == null)
{
return null;
} | final Bank esrBank = bankRepo.getById(esrBankId);
if(esrBank.getLocationId() == null)
{
return null;
}
final I_C_Location bankLocation = locationDAO.getById(esrBank.getLocationId());
if(bankLocation == null)
{
return null;
}
return AddressInfo
.builder()
.street(bankLocation.getAddress1())
.pobox(bankLocation.getPOBox())
.city(bankLocation.getCity())
.zip(bankLocation.getPostal())
.state(bankLocation.getRegionName())
.isoCountryCode(bankLocation.getC_Country().getCountryCode()) // C_Location.C_Country_ID is mandatory
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\invoice_gateway\ESRInfoProviderImpl.java | 1 |
请完成以下Java代码 | public Object getRenderedTaskForm(String taskId, String engineName) {
return commandExecutor.execute(new GetRenderedTaskFormCmd(taskId, engineName));
}
@Override
public StartFormData getStartFormData(String processDefinitionId) {
return commandExecutor.execute(new GetStartFormCmd(processDefinitionId));
}
@Override
public TaskFormData getTaskFormData(String taskId) {
return commandExecutor.execute(new GetTaskFormCmd(taskId));
}
@Override
public ProcessInstance submitStartFormData(String processDefinitionId, Map<String, String> properties) {
return commandExecutor.execute(new SubmitStartFormCmd(processDefinitionId, null, properties));
}
@Override
public ProcessInstance submitStartFormData(String processDefinitionId, String businessKey, Map<String, String> properties) {
return commandExecutor.execute(new SubmitStartFormCmd(processDefinitionId, businessKey, properties));
}
@Override
public void submitTaskFormData(String taskId, Map<String, String> properties) { | commandExecutor.execute(new SubmitTaskFormCmd(taskId, properties, true));
}
@Override
public String getStartFormKey(String processDefinitionId) {
return commandExecutor.execute(new GetFormKeyCmd(processDefinitionId));
}
@Override
public String getTaskFormKey(String processDefinitionId, String taskDefinitionKey) {
return commandExecutor.execute(new GetFormKeyCmd(processDefinitionId, taskDefinitionKey));
}
@Override
public void saveFormData(String taskId, Map<String, String> properties) {
commandExecutor.execute(new SubmitTaskFormCmd(taskId, properties, false));
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\FormServiceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public OrderLineItems itemId(String itemId)
{
this.itemId = itemId;
return this;
}
/**
* The unique identifier of the eBay listing associated with the order.
*
* @return itemId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The unique identifier of the eBay listing associated with the order.")
public String getItemId()
{
return itemId;
}
public void setItemId(String itemId)
{
this.itemId = itemId;
}
public OrderLineItems lineItemId(String lineItemId)
{
this.lineItemId = lineItemId;
return this;
}
/**
* The unique identifier of the line item within the order. The lineItemId value is created once the buyer actually purchases the item, or if there is a commitment to buy (such as an auction that is won by the buyer, an accepted Best Offer, or other situation that does not require immediate payment from the buyer).
*
* @return lineItemId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The unique identifier of the line item within the order. The lineItemId value is created once the buyer actually purchases the item, or if there is a commitment to buy (such as an auction that is won by the buyer, an accepted Best Offer, or other situation that does not require immediate payment from the buyer).")
public String getLineItemId()
{
return lineItemId;
}
public void setLineItemId(String lineItemId)
{
this.lineItemId = lineItemId;
}
@Override
public boolean equals(Object o)
{ | if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
OrderLineItems orderLineItems = (OrderLineItems)o;
return Objects.equals(this.itemId, orderLineItems.itemId) &&
Objects.equals(this.lineItemId, orderLineItems.lineItemId);
}
@Override
public int hashCode()
{
return Objects.hash(itemId, lineItemId);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class OrderLineItems {\n");
sb.append(" itemId: ").append(toIndentedString(itemId)).append("\n");
sb.append(" lineItemId: ").append(toIndentedString(lineItemId)).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(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\OrderLineItems.java | 2 |
请完成以下Java代码 | public class InfoWindowGridRowBuilders implements IInfoWindowGridRowBuilders
{
private final Map<Integer, CompositeGridTabRowBuilder> builders = new HashMap<Integer, CompositeGridTabRowBuilder>();
public InfoWindowGridRowBuilders()
{
}
@Override
public void addGridTabRowBuilder(final int recordId, final IGridTabRowBuilder builder)
{
CompositeGridTabRowBuilder recordBuilders = builders.get(recordId);
if (recordBuilders == null)
{
recordBuilders = new CompositeGridTabRowBuilder();
builders.put(recordId, recordBuilders);
}
recordBuilders.addGridTabRowBuilder(builder);
}
@Override
public Set<Integer> getRecordIds()
{
final Set<Integer> recordIds = new HashSet<Integer>();
for (final Map.Entry<Integer, CompositeGridTabRowBuilder> e : builders.entrySet())
{
final CompositeGridTabRowBuilder builder = e.getValue();
if (!builder.isValid())
{
continue;
}
if (!builder.isCreateNewRecord())
{
continue;
}
final Integer recordId = e.getKey();
recordIds.add(recordId);
}
return recordIds;
}
@Override
public IGridTabRowBuilder getGridTabRowBuilder(final int recordId)
{
final CompositeGridTabRowBuilder recordBuilders = builders.get(recordId);
if (recordBuilders == null)
{
return NullGridTabRowBuilder.instance;
}
return recordBuilders;
}
private static final String createContextName(final int windowNo)
{
final String ctxName = windowNo + "|" + InfoWindowGridRowBuilders.class.getName();
return ctxName; | }
public void saveToContext(final Properties ctx, final int windowNo)
{
final String ctxName = createContextName(windowNo);
Env.put(ctx, ctxName, this);
}
/**
* Gets the builders from context and then it clears the context
*
* @param ctx
* @param windowNo
* @return builders or null
*/
public static IInfoWindowGridRowBuilders getFromContextOrNull(final Properties ctx, final int windowNo)
{
final String ctxName = createContextName(windowNo);
final IInfoWindowGridRowBuilders builders = Env.getAndRemove(ctx, ctxName);
return builders;
}
@Override
public String toString()
{
return String.format("InfoWindowGridRowBuilders [builders=%s]", builders);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\apps\search\impl\InfoWindowGridRowBuilders.java | 1 |
请完成以下Java代码 | public final class ResidentKeyRequirement {
/**
* The <a href=
* "https://www.w3.org/TR/webauthn-3/#dom-residentkeyrequirement-discouraged">discouraged</a>
* requirement indicates that the Relying Party prefers creating a server-side
* credential, but will accept a client-side discoverable credential.
*/
public static final ResidentKeyRequirement DISCOURAGED = new ResidentKeyRequirement("discouraged");
/**
* The <a href=
* "https://www.w3.org/TR/webauthn-3/#dom-residentkeyrequirement-preferred">preferred</a>
* requirement indicates that the Relying Party strongly prefers creating a
* client-side discoverable credential, but will accept a server-side credential.
*/
public static final ResidentKeyRequirement PREFERRED = new ResidentKeyRequirement("preferred");
/**
* The <a href=
* "https://www.w3.org/TR/webauthn-3/#dom-residentkeyrequirement-required">required</a>
* value indicates that the Relying Party requires a client-side discoverable
* credential.
*/
public static final ResidentKeyRequirement REQUIRED = new ResidentKeyRequirement("required");
private final String value; | private ResidentKeyRequirement(String value) {
this.value = value;
}
/**
* Gets the value.
* @return the value
*/
public String getValue() {
return this.value;
}
public static ResidentKeyRequirement valueOf(String value) {
if (DISCOURAGED.getValue().equals(value)) {
return DISCOURAGED;
}
if (PREFERRED.getValue().equals(value)) {
return PREFERRED;
}
if (REQUIRED.getValue().equals(value)) {
return REQUIRED;
}
return new ResidentKeyRequirement(value);
}
} | repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\ResidentKeyRequirement.java | 1 |
请完成以下Java代码 | public ProcessEngineConfiguration setDatabaseSchema(String databaseSchema) {
this.databaseSchema = databaseSchema;
return this;
}
public String getXmlEncoding() {
return xmlEncoding;
}
public ProcessEngineConfiguration setXmlEncoding(String xmlEncoding) {
this.xmlEncoding = xmlEncoding;
return this;
}
public Clock getClock() {
return clock;
}
public ProcessEngineConfiguration setClock(Clock clock) {
this.clock = clock;
return this;
}
public AsyncExecutor getAsyncExecutor() {
return asyncExecutor;
}
public ProcessEngineConfiguration setAsyncExecutor(AsyncExecutor asyncExecutor) {
this.asyncExecutor = asyncExecutor;
return this;
}
public int getLockTimeAsyncJobWaitTime() {
return lockTimeAsyncJobWaitTime;
}
public ProcessEngineConfiguration setLockTimeAsyncJobWaitTime(int lockTimeAsyncJobWaitTime) {
this.lockTimeAsyncJobWaitTime = lockTimeAsyncJobWaitTime;
return this;
}
public int getDefaultFailedJobWaitTime() { | return defaultFailedJobWaitTime;
}
public ProcessEngineConfiguration setDefaultFailedJobWaitTime(int defaultFailedJobWaitTime) {
this.defaultFailedJobWaitTime = defaultFailedJobWaitTime;
return this;
}
public int getAsyncFailedJobWaitTime() {
return asyncFailedJobWaitTime;
}
public ProcessEngineConfiguration setAsyncFailedJobWaitTime(int asyncFailedJobWaitTime) {
this.asyncFailedJobWaitTime = asyncFailedJobWaitTime;
return this;
}
public boolean isEnableProcessDefinitionInfoCache() {
return enableProcessDefinitionInfoCache;
}
public ProcessEngineConfiguration setEnableProcessDefinitionInfoCache(boolean enableProcessDefinitionInfoCache) {
this.enableProcessDefinitionInfoCache = enableProcessDefinitionInfoCache;
return this;
}
public ProcessEngineConfiguration setCopyVariablesToLocalForTasks(boolean copyVariablesToLocalForTasks) {
this.copyVariablesToLocalForTasks = copyVariablesToLocalForTasks;
return this;
}
public boolean isCopyVariablesToLocalForTasks() {
return copyVariablesToLocalForTasks;
}
public void setEngineAgendaFactory(ActivitiEngineAgendaFactory engineAgendaFactory) {
this.engineAgendaFactory = engineAgendaFactory;
}
public ActivitiEngineAgendaFactory getEngineAgendaFactory() {
return engineAgendaFactory;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\ProcessEngineConfiguration.java | 1 |
请完成以下Java代码 | static boolean hasZeroInFirstRow(int[][] matrix, int cols) {
for (int j = 0; j < cols; j++) {
if (matrix[0][j] == 0) {
return true;
}
}
return false;
}
static boolean hasZeroInFirstCol(int[][] matrix, int rows) {
for (int i = 0; i < rows; i++) {
if (matrix[i][0] == 0) {
return true;
}
}
return false;
}
static void markZeroesInMatrix(int[][] matrix, int rows, int cols) {
for (int i = 1; i < rows; i++) {
for (int j = 1; j < cols; j++) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
}
static void setZeroesInRows(int[][] matrix, int rows, int cols) {
for (int i = 1; i < rows; i++) {
if (matrix[i][0] == 0) {
for (int j = 1; j < cols; j++) {
matrix[i][j] = 0;
}
}
}
}
static void setZeroesInCols(int[][] matrix, int rows, int cols) {
for (int j = 1; j < cols; j++) {
if (matrix[0][j] == 0) {
for (int i = 1; i < rows; i++) {
matrix[i][j] = 0;
}
}
}
} | static void setZeroesInFirstRow(int[][] matrix, int cols) {
for (int j = 0; j < cols; j++) {
matrix[0][j] = 0;
}
}
static void setZeroesInFirstCol(int[][] matrix, int rows) {
for (int i = 0; i < rows; i++) {
matrix[i][0] = 0;
}
}
static void setZeroesByOptimalApproach(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
boolean firstRowZero = hasZeroInFirstRow(matrix, cols);
boolean firstColZero = hasZeroInFirstCol(matrix, rows);
markZeroesInMatrix(matrix, rows, cols);
setZeroesInRows(matrix, rows, cols);
setZeroesInCols(matrix, rows, cols);
if (firstRowZero) {
setZeroesInFirstRow(matrix, cols);
}
if (firstColZero) {
setZeroesInFirstCol(matrix, rows);
}
}
} | repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced-2\src\main\java\com\baeldung\matrixtozero\SetMatrixToZero.java | 1 |
请完成以下Java代码 | public final class BoardDescriptor
{
private final int boardId;
@NonNull
private final ITranslatableString caption;
@NonNull
private final WebsocketTopicName websocketEndpoint;
@Singular
private final ImmutableMap<Integer, BoardLaneDescriptor> lanes;
@Singular("cardFieldByFieldName")
final ImmutableMap<String, BoardCardFieldDescriptor> cardFieldsByFieldName;
// Source document info
@NonNull
private final WindowId documentWindowId;
@NonNull
private LookupDescriptorProvider documentLookupDescriptorProvider;
/** document sticky filters (those will be applied no matter what; can come from WEBUI_Dashboard.AD_Val_Rule_ID for example) */
@Default
private DocumentFilterList documentFilters = DocumentFilterList.EMPTY;
// Source record mapping
@NonNull
private final String tableName;
@NonNull
private final String tableAlias;
@NonNull
private final String keyColumnName;
@NonNull
private final String userIdColumnName; | public void assertLaneIdExists(final int laneId)
{
if (lanes.get(laneId) == null)
{
throw new AdempiereException("Lane ID=" + laneId + " found for board ID=" + getBoardId())
.setParameter("board", this)
.setParameter("laneId", laneId);
}
}
public Collection<BoardCardFieldDescriptor> getCardFields()
{
return cardFieldsByFieldName.values();
}
public BoardCardFieldDescriptor getCardFieldByName(final String fieldName)
{
final BoardCardFieldDescriptor cardField = cardFieldsByFieldName.get(fieldName);
if (cardField == null)
{
throw new AdempiereException("No card field found for " + fieldName)
.setParameter("board", this);
}
return cardField;
}
public LookupDescriptor getLookupDescriptor()
{
return getDocumentLookupDescriptorProvider()
.provide()
.get();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\board\BoardDescriptor.java | 1 |
请完成以下Java代码 | public void setArticleList(List<BaeldungArticle> articleList) {
this.articleList = articleList;
}
public List<BaeldungArticle> getArticleList() {
return this.articleList;
}
}
public static class BaeldungArticle {
private String title;
private String content;
public void setTitle(String title) {
this.title = title; | }
public String getTitle() {
return this.title;
}
public void setContent(String content) {
this.content = content;
}
public String getContent() {
return this.content;
}
}
} | repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\sax\SaxParserMain.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DictDetailServiceImpl implements DictDetailService {
private final DictRepository dictRepository;
private final DictDetailRepository dictDetailRepository;
private final DictDetailMapper dictDetailMapper;
private final RedisUtils redisUtils;
@Override
public PageResult<DictDetailDto> queryAll(DictDetailQueryCriteria criteria, Pageable pageable) {
Page<DictDetail> page = dictDetailRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
return PageUtil.toPage(page.map(dictDetailMapper::toDto));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void create(DictDetail resources) {
dictDetailRepository.save(resources);
// 清理缓存
delCaches(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(DictDetail resources) {
DictDetail dictDetail = dictDetailRepository.findById(resources.getId()).orElseGet(DictDetail::new);
ValidationUtil.isNull( dictDetail.getId(),"DictDetail","id",resources.getId());
resources.setId(dictDetail.getId());
dictDetailRepository.save(resources); | // 清理缓存
delCaches(resources);
}
@Override
public List<DictDetailDto> getDictByName(String name) {
String key = CacheKey.DICT_NAME + name;
List<DictDetail> dictDetails = redisUtils.getList(key, DictDetail.class);
if(CollUtil.isEmpty(dictDetails)){
dictDetails = dictDetailRepository.findByDictName(name);
redisUtils.set(key, dictDetails, 1 , TimeUnit.DAYS);
}
return dictDetailMapper.toDto(dictDetails);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Long id) {
DictDetail dictDetail = dictDetailRepository.findById(id).orElseGet(DictDetail::new);
// 清理缓存
delCaches(dictDetail);
dictDetailRepository.deleteById(id);
}
public void delCaches(DictDetail dictDetail){
Dict dict = dictRepository.findById(dictDetail.getDict().getId()).orElseGet(Dict::new);
redisUtils.del(CacheKey.DICT_NAME + dict.getName());
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\DictDetailServiceImpl.java | 2 |
请完成以下Java代码 | class StructuredLoggingJsonPropertiesBeanFactoryInitializationAotProcessor
implements BeanFactoryInitializationAotProcessor {
private static final String ENVIRONMENT_BEAN_NAME = "environment";
@Override
public @Nullable BeanFactoryInitializationAotContribution processAheadOfTime(
ConfigurableListableBeanFactory beanFactory) {
Environment environment = beanFactory.getBean(ENVIRONMENT_BEAN_NAME, Environment.class);
StructuredLoggingJsonProperties properties = StructuredLoggingJsonProperties.get(environment);
if (properties != null) {
Set<Class<? extends StructuredLoggingJsonMembersCustomizer<?>>> customizers = properties.customizer();
String stackTracePrinter = getCustomStackTracePrinter(properties);
if (stackTracePrinter != null || !customizers.isEmpty()) {
return new AotContribution(beanFactory.getBeanClassLoader(), customizers, stackTracePrinter);
}
}
return null;
}
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 class GraphQlContextAccessor implements ContextAccessor<GraphQLContext, GraphQLContext> {
@Override
public Class<? extends GraphQLContext> readableType() {
return GraphQLContext.class;
}
@Override
public void readValues(GraphQLContext context, Predicate<Object> keyPredicate, Map<Object, Object> readValues) {
context.stream().forEach((entry) -> {
if (keyPredicate.test(entry.getKey())) {
readValues.put(entry.getKey(), entry.getValue());
}
});
}
@Override | public <T> T readValue(GraphQLContext context, Object key) {
return context.get(key);
}
@Override
public Class<? extends GraphQLContext> writeableType() {
return GraphQLContext.class;
}
@Override
public GraphQLContext writeValues(Map<Object, Object> valuesToWrite, GraphQLContext targetContext) {
return targetContext.putAll(valuesToWrite);
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\execution\GraphQlContextAccessor.java | 1 |
请完成以下Java代码 | public int getBill_User_ID()
{
return delegate.getBill_User_ID();
}
@Override
public void setBill_User_ID(final int Bill_User_ID)
{
delegate.setBill_User_ID(Bill_User_ID);
}
@Override
public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentBillLocationAdapter.super.setRenderedAddressAndCapturedLocation(from);
}
@Override
public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentBillLocationAdapter.super.setRenderedAddress(from);
} | @Override
public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL)
{
return documentLocationBL.toPlainDocumentLocation(this);
}
@Override
public DocumentBillLocationAdapter toOldValues()
{
return new DocumentBillLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_OLCand.class));
}
@Override
public I_C_OLCand getWrappedRecord()
{
return delegate;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\location\adapter\DocumentBillLocationAdapter.java | 1 |
请完成以下Java代码 | public void setEventModelValidator (java.lang.String EventModelValidator)
{
set_Value (COLUMNNAME_EventModelValidator, EventModelValidator);
}
/** Get Event Model Validator.
@return Event Model Validator */
@Override
public java.lang.String getEventModelValidator ()
{
return (java.lang.String)get_Value(COLUMNNAME_EventModelValidator);
}
/** Set Reihenfolge.
@param SeqNo
Method of ordering records; lowest number comes first
*/ | @Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Method of ordering records; lowest number comes first
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Table_ScriptValidator.java | 1 |
请完成以下Java代码 | public int getXmlColumnNumber() {
return xmlColumnNumber;
}
public void setXmlColumnNumber(int xmlColumnNumber) {
this.xmlColumnNumber = xmlColumnNumber;
}
public double getRotation() {
return rotation;
}
public void setRotation(double rotation) {
this.rotation = rotation;
}
public boolean equals(GraphicInfo ginfo) {
if (this.getX() != ginfo.getX()) {
return false;
}
if (this.getY() != ginfo.getY()) {
return false;
}
if (this.getHeight() != ginfo.getHeight()) {
return false;
}
if (this.getWidth() != ginfo.getWidth()) {
return false;
}
if (this.getRotation() != ginfo.getRotation()) { | return false;
}
// check for zero value in case we are comparing model value to BPMN DI value
// model values do not have xml location information
if (0 != this.getXmlColumnNumber() && 0 != ginfo.getXmlColumnNumber() && this.getXmlColumnNumber() != ginfo.getXmlColumnNumber()) {
return false;
}
if (0 != this.getXmlRowNumber() && 0 != ginfo.getXmlRowNumber() && this.getXmlRowNumber() != ginfo.getXmlRowNumber()) {
return false;
}
// only check for elements that support this value
if (null != this.getExpanded() && null != ginfo.getExpanded() && !this.getExpanded().equals(ginfo.getExpanded())) {
return false;
}
return true;
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\GraphicInfo.java | 1 |
请完成以下Java代码 | public SqlSelect getMainSqlSelect()
{
return sqlSelects.get(mainSqlIndex);
}
/**
* Transform the key words WHERE, FROM and ON in lowercase.
* TODO: Delete this logic when we get rid of the workaround in org.compiere.model.AccessSqlParser.getTableInfo(String)
*
* @param whereClause
* @return
*/
public static String rewriteWhereClauseWithLowercaseKeyWords(final String whereClause)
{
return whereClause.replaceAll("\\s", " ")
.replaceAll(WHERE, WHERE_LOWERCASE)
.replaceAll(FROM, FROM_LOWERCASE)
.replaceAll(ON, ON_LOWERCASE);
}
@Value
public static class TableNameAndAlias
{
public static TableNameAndAlias ofTableNameAndAlias(final String tableName, final String alias)
{
return new TableNameAndAlias(tableName, alias);
}
public static TableNameAndAlias ofTableName(final String tableName)
{
final String synonym = "";
return new TableNameAndAlias(tableName, synonym);
}
private final String tableName;
private final String alias;
private TableNameAndAlias(@NonNull final String tableName, final String alias)
{
this.tableName = tableName;
this.alias = alias != null ? alias : "";
}
public String getAliasOrTableName()
{
return !alias.isEmpty() ? alias : tableName;
} | public boolean isTrlTable()
{
return tableName.toUpperCase().endsWith("_TRL");
}
}
@Value
public static final class SqlSelect
{
private final String sql;
private final ImmutableList<TableNameAndAlias> tableNameAndAliases;
@Builder
private SqlSelect(
@NonNull final String sql,
@NonNull @Singular final ImmutableList<TableNameAndAlias> tableNameAndAliases)
{
this.sql = sql;
this.tableNameAndAliases = tableNameAndAliases;
}
public boolean hasWhereClause()
{
return sql.indexOf(" WHERE ") >= 0;
}
public String getFirstTableAliasOrTableName()
{
if (tableNameAndAliases.isEmpty()) // TODO check if we still need this check!
{
return "";
}
return tableNameAndAliases.get(0).getAliasOrTableName();
}
public String getFirstTableNameOrEmpty()
{
if (tableNameAndAliases.isEmpty())
{
return "";
}
return tableNameAndAliases.get(0).getTableName();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\ParsedSql.java | 1 |
请完成以下Java代码 | public static int toIntByHashCode(String value) {
return value.hashCode();
}
public static int toIntByCR32(String value) {
CRC32 crc32 = new CRC32();
crc32.update(value.getBytes());
return (int) crc32.getValue();
}
public static int toIntByCharFormula(String value) {
return value.chars()
.reduce(17, (a, b) -> a * 13 + (b / a));
}
public static int toIntByMD5(String value) {
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] hash = digest.digest(value.getBytes()); | return ((hash[0] & 0xFF) << 24) | ((hash[1] & 0xFF) << 16) | ((hash[2] & 0xFF) << 8) | (hash[3] & 0xFF);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("MD5 not supported", e);
}
}
public static int toIntByLookup(String value) {
Integer found = lookupMap.get(value);
if (found != null) {
return found;
}
Integer intValue = counter.incrementAndGet();
lookupMap.put(value, intValue);
return intValue;
}
} | repos\tutorials-master\core-java-modules\core-java-string-algorithms-5\src\main\java\com\baeldung\uniqueint\StringToUniqueInt.java | 1 |
请完成以下Java代码 | public void attachState(MigratingScopeInstance owningInstance) {
ExecutionEntity representativeExecution = owningInstance.resolveRepresentativeExecution();
representativeExecution.addTask(userTask);
for (VariableInstanceEntity variable : userTask.getVariablesInternal()) {
variable.setExecution(representativeExecution);
}
userTask.setExecution(representativeExecution);
}
@Override
public void attachState(MigratingTransitionInstance targetTransitionInstance) {
throw MIGRATION_LOGGER.cannotAttachToTransitionInstance(this);
}
@Override
public void migrateState() {
userTask.setProcessDefinitionId(migratingActivityInstance.getTargetScope().getProcessDefinition().getId());
userTask.setTaskDefinitionKey(migratingActivityInstance.getTargetScope().getId()); | migrateHistory();
}
protected void migrateHistory() {
HistoryLevel historyLevel = Context.getProcessEngineConfiguration().getHistoryLevel();
if (historyLevel.isHistoryEventProduced(HistoryEventTypes.TASK_INSTANCE_MIGRATE, this)) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
return producer.createTaskInstanceMigrateEvt(userTask);
}
});
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingUserTaskInstance.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean hasCodecFor(Class<?> type) {
return this.delegate.hasCodecFor(type);
}
@Override
public Mono<MongoDatabase> getMongoDatabase() throws DataAccessException {
String gridFsDatabase = getGridFsDatabase();
if (StringUtils.hasText(gridFsDatabase)) {
return this.delegate.getMongoDatabase(gridFsDatabase);
}
return this.delegate.getMongoDatabase();
}
private @Nullable String getGridFsDatabase() {
return this.properties.getGridfs().getDatabase();
}
@Override
public Mono<MongoDatabase> getMongoDatabase(String dbName) throws DataAccessException {
return this.delegate.getMongoDatabase(dbName);
}
@Override
public <T> Optional<Codec<T>> getCodecFor(Class<T> type) {
return this.delegate.getCodecFor(type);
}
@Override
public PersistenceExceptionTranslator getExceptionTranslator() { | return this.delegate.getExceptionTranslator();
}
@Override
public CodecRegistry getCodecRegistry() {
return this.delegate.getCodecRegistry();
}
@Override
public Mono<ClientSession> getSession(ClientSessionOptions options) {
return this.delegate.getSession(options);
}
@Override
public ReactiveMongoDatabaseFactory withSession(ClientSession session) {
return this.delegate.withSession(session);
}
@Override
public boolean isTransactionActive() {
return this.delegate.isTransactionActive();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-data-mongodb\src\main\java\org\springframework\boot\data\mongodb\autoconfigure\DataMongoReactiveAutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class PutProductSuppliesRequest extends RequestToMetasfresh
{
public static PutProductSuppliesRequest of(@NonNull final SyncProductSupply syncProductSupply)
{
return PutProductSuppliesRequest.builder()
.productSupply(syncProductSupply)
.build();
}
public static PutProductSuppliesRequest of(final Collection<SyncProductSupply> syncProductSupplies)
{
final PutProductSuppliesRequestBuilder requestBuilder = PutProductSuppliesRequest.builder();
if (syncProductSupplies != null)
{
requestBuilder.productSupplies(syncProductSupplies);
}
return requestBuilder.build(); | }
String eventId;
List<SyncProductSupply> productSupplies;
@Builder
@JsonCreator
public PutProductSuppliesRequest(
@JsonProperty("eventId") final String eventId,
@JsonProperty("productSupplies") @Singular final List<SyncProductSupply> productSupplies)
{
this.eventId = eventId != null ? eventId : UUID.randomUUID().toString();
this.productSupplies = productSupplies;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-procurement\src\main\java\de\metas\common\procurement\sync\protocol\request_to_metasfresh\PutProductSuppliesRequest.java | 2 |
请完成以下Java代码 | public int getM_Inventory_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Inventory_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Verarbeiten.
@param Processing Verarbeiten */ | @Override
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Verarbeiten.
@return Verarbeiten */
@Override
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InOutConfirm.java | 1 |
请完成以下Java代码 | public int compareTo(ImmutablePair<L, R> o) {
if (o == null) {
throw new IllegalArgumentException("Pair to compare to must not be null");
}
try {
int leftComparison = compare((Comparable<L>) getLeft(), (Comparable<L>) o.getLeft());
return leftComparison == 0 ? compare((Comparable<R>) getRight(), (Comparable<R>) o.getRight()) : leftComparison;
} catch (ClassCastException cce) {
throw new IllegalArgumentException("Please provide comparable elements", cce);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
protected int compare(Comparable original, Comparable other) {
if (original == other) {
return 0;
}
if (original == null) {
return -1;
}
if (other == null) {
return 1;
}
return original.compareTo(other);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (!(obj instanceof Entry)) {
return false;
} else {
Entry<?, ?> other = (Entry<?, ?>) obj; | return Objects.equals(this.getKey(), other.getKey()) &&
Objects.equals(this.getValue(), other.getValue());
}
}
@Override
public int hashCode() {
return (this.getKey() == null ? 0 : this.getKey().hashCode()) ^
(this.getValue() == null ? 0 : this.getValue().hashCode());
}
@Override
public String toString() {
return "(" + this.getLeft() + ',' + this.getRight() + ')';
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\ImmutablePair.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ActualImportRecordsResult
{
/**
* target table name, where the records were imported (e.g. C_BPartner)
*/
@NonNull String targetTableName;
/**
* import table name, FROM where the records are imported (e.g. I_BPartner)
*/
@NonNull String importTableName;
@NonNull OptionalInt countImportRecordsConsidered;
@NonNull OptionalInt countInsertsIntoTargetTable;
@NonNull OptionalInt countUpdatesIntoTargetTable;
@NonNull @Singular ImmutableList<Error> errors;
public String getSummary()
{
final StringBuilder sb = new StringBuilder();
if (countImportRecordsConsidered.isPresent() && countImportRecordsConsidered.getAsInt() > 0)
{
if (sb.length() > 0) {sb.append("; ");}
sb.append(countImportRecordsConsidered.getAsInt()).append(" record(s) processed");
}
if (!errors.isEmpty())
{
if (sb.length() > 0) {sb.append("; ");}
sb.append(errors.size()).append(" import errors encountered");
}
return sb.toString();
}
public String getCountInsertsIntoTargetTableString()
{
return counterToString(getCountInsertsIntoTargetTable());
}
public String getCountUpdatesIntoTargetTableString()
{
return counterToString(getCountUpdatesIntoTargetTable());
} | private static String counterToString(final OptionalInt counter)
{
return counter.isPresent() ? String.valueOf(counter.getAsInt()) : "N/A";
}
public boolean hasErrors()
{
return !getErrors().isEmpty();
}
public int getCountErrors()
{
return getErrors().size();
}
@Value
@Builder
public static class Error
{
@NonNull String message;
@NonNull AdIssueId adIssueId;
@Nullable transient Throwable exception;
int affectedImportRecordsCount;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\ActualImportRecordsResult.java | 2 |
请完成以下Java代码 | public void updateProcessDefinitionInfo(ProcessDefinitionInfoEntity updatedProcessDefinitionInfo) {
update(updatedProcessDefinitionInfo, true);
}
@Override
public void deleteProcessDefinitionInfo(String processDefinitionId) {
ProcessDefinitionInfoEntity processDefinitionInfo = findProcessDefinitionInfoByProcessDefinitionId(processDefinitionId);
if (processDefinitionInfo != null) {
delete(processDefinitionInfo);
deleteInfoJson(processDefinitionInfo);
}
}
@Override
public void updateInfoJson(String id, byte[] json) {
ProcessDefinitionInfoEntity processDefinitionInfo = findById(id);
if (processDefinitionInfo != null) {
ByteArrayRef ref = new ByteArrayRef(processDefinitionInfo.getInfoJsonId(), null);
ref.setValue("json", json, engineConfiguration.getEngineCfgKey());
if (processDefinitionInfo.getInfoJsonId() == null) {
processDefinitionInfo.setInfoJsonId(ref.getId());
}
updateProcessDefinitionInfo(processDefinitionInfo);
}
}
@Override
public void deleteInfoJson(ProcessDefinitionInfoEntity processDefinitionInfo) {
if (processDefinitionInfo.getInfoJsonId() != null) { | ByteArrayRef ref = new ByteArrayRef(processDefinitionInfo.getInfoJsonId(), null);
ref.delete(engineConfiguration.getEngineCfgKey());
}
}
@Override
public ProcessDefinitionInfoEntity findProcessDefinitionInfoByProcessDefinitionId(String processDefinitionId) {
return dataManager.findProcessDefinitionInfoByProcessDefinitionId(processDefinitionId);
}
@Override
public byte[] findInfoJsonById(String infoJsonId) {
ByteArrayRef ref = new ByteArrayRef(infoJsonId, null);
return ref.getBytes(engineConfiguration.getEngineCfgKey());
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\ProcessDefinitionInfoEntityManagerImpl.java | 1 |
请完成以下Java代码 | private static DistributionFacetId ofLocalDate(@NonNull DistributionFacetGroupType groupType, @NonNull LocalDate localDate)
{
final WorkflowLaunchersFacetId workflowLaunchersFacetId = WorkflowLaunchersFacetId.ofLocalDate(groupType.toWorkflowLaunchersFacetGroupId(), localDate);
return ofWorkflowLaunchersFacetId(workflowLaunchersFacetId);
}
public static DistributionFacetId ofQuantity(@NonNull Quantity qty)
{
return ofWorkflowLaunchersFacetId(
WorkflowLaunchersFacetId.ofQuantity(
DistributionFacetGroupType.QUANTITY.toWorkflowLaunchersFacetGroupId(),
qty.toBigDecimal(),
qty.getUomId()
)
); | }
public static DistributionFacetId ofPlantId(@NonNull final ResourceId plantId)
{
return ofRepoId(DistributionFacetGroupType.PLANT_RESOURCE_ID, plantId);
}
private static Quantity getAsQuantity(final @NonNull WorkflowLaunchersFacetId workflowLaunchersFacetId)
{
final ImmutablePair<BigDecimal, Integer> parts = workflowLaunchersFacetId.getAsQuantity();
return Quantitys.of(parts.getLeft(), UomId.ofRepoId(parts.getRight()));
}
public WorkflowLaunchersFacetId toWorkflowLaunchersFacetId() {return workflowLaunchersFacetId;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\facets\DistributionFacetId.java | 1 |
请完成以下Java代码 | 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代码 | public int hashCode() {
return Objects.hash(slug, title, description, body, tagList, favorited, favoritesCount, author);
}
Boolean favorited;
Integer favoritesCount;
ProfileView author;
public static ArticleView toArticleView(Article article, ProfileView author, boolean favorited) {
return new ArticleView()
.setSlug(article.getSlug())
.setTitle(article.getTitle())
.setDescription(article.getDescription())
.setBody(article.getBody())
.setTagList(article.getTags())
.setCreatedAt(article.getCreatedAt())
.setUpdatedAt(article.getUpdatedAt())
.setFavorited(favorited)
.setFavoritesCount(article.getFavoritesCount()) | .setAuthor(author);
}
public static ArticleView ofOwnArticle(Article article, User articleOwner) {
return toArticleViewForViewer(article, ProfileView.toOwnProfile(articleOwner), articleOwner);
}
public static ArticleView toArticleViewForViewer(Article article, ProfileView author, User user) {
return toArticleView(article, author, user.isFavoriteArticle(article));
}
public static ArticleView toUnfavoredArticleView(Article article, ProfileView author) {
return toArticleView(article, author, false);
}
} | repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\article\dto\ArticleView.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public R save(@Valid @RequestBody AuthClient authClient) {
return R.status(clientService.save(authClient));
}
/**
* 修改
*/
@PostMapping("/update")
@ApiOperationSupport(order = 4)
@Operation(summary = "修改", description = "传入client")
public R update(@Valid @RequestBody AuthClient authClient) {
return R.status(clientService.updateById(authClient));
}
/**
* 新增或修改
*/
@PostMapping("/submit")
@ApiOperationSupport(order = 5)
@Operation(summary = "新增或修改", description = "传入client")
public R submit(@Valid @RequestBody AuthClient authClient) { | return R.status(clientService.saveOrUpdate(authClient));
}
/**
* 删除
*/
@PostMapping("/remove")
@ApiOperationSupport(order = 6)
@Operation(summary = "逻辑删除", description = "传入ids")
public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
return R.status(clientService.deleteLogic(Func.toLongList(ids)));
}
} | repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\AuthClientController.java | 2 |
请完成以下Java代码 | public class Tag {
@JsonProperty("id")
private Long id = null;
@JsonProperty("name")
private String name = null;
public Tag id(Long id) {
this.id = id;
return this;
}
/**
* Get id
* @return id
**/
@ApiModelProperty(value = "")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Tag name(String name) {
this.name = name;
return this;
}
/**
* Get name
* @return name
**/
@ApiModelProperty(value = "")
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-swagger-codegen-api-client\src\main\java\com\baeldung\petstore\client\model\Tag.java | 1 |
请完成以下Java代码 | protected BusinessProcessEvent createEvent(DelegateTask task) {
ProcessEngineConfigurationImpl engineConfiguration = org.flowable.engine.impl.context.Context.getProcessEngineConfiguration();
ProcessDefinition processDefinition = engineConfiguration.getProcessDefinitionCache().get(task.getProcessDefinitionId()).getProcessDefinition();
Date now = engineConfiguration.getClock().getCurrentTime();
return new CdiBusinessProcessEvent(activityId, transitionName, processDefinition, task, type, task.getProcessInstanceId(), task.getExecutionId(), now);
}
protected BeanManager getBeanManager() {
BeanManager bm = BeanManagerLookup.getBeanManager();
if (bm == null) {
throw new FlowableException("No cdi bean manager available, cannot publish event.");
}
return bm;
}
protected Annotation[] getQualifiers(BusinessProcessEvent event) {
Annotation businessProcessQualifier = new BusinessProcessLiteral(event.getProcessDefinition().getKey()); | if (type == BusinessProcessEventType.CREATE_TASK) {
return new Annotation[] { businessProcessQualifier, new CreateTaskLiteral(activityId) };
}
if (type == BusinessProcessEventType.ASSIGN_TASK) {
return new Annotation[] { businessProcessQualifier, new AssignTaskLiteral(activityId) };
}
if (type == BusinessProcessEventType.COMPLETE_TASK) {
return new Annotation[] { businessProcessQualifier, new CompleteTaskLiteral(activityId) };
}
if (type == BusinessProcessEventType.DELETE_TASK) {
return new Annotation[] { businessProcessQualifier, new DeleteTaskLiteral(activityId) };
}
return new Annotation[] {};
}
} | repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\impl\event\CdiTaskListener.java | 1 |
请完成以下Java代码 | public List<ForeignKey<ArticleRecord, ?>> getReferences() {
return Arrays.<ForeignKey<ArticleRecord, ?>>asList(Keys.ARTICLE__XXX);
}
public Author author() {
return new Author(this, Keys.ARTICLE__XXX);
}
@Override
public Article as(String alias) {
return new Article(DSL.name(alias), this);
}
@Override
public Article as(Name alias) {
return new Article(alias, this);
}
/**
* Rename this table
*/
@Override
public Article rename(String name) {
return new Article(DSL.name(name), null);
} | /**
* Rename this table
*/
@Override
public Article rename(Name name) {
return new Article(name, null);
}
// -------------------------------------------------------------------------
// Row4 type methods
// -------------------------------------------------------------------------
@Override
public Row4<Integer, String, String, Integer> fieldsRow() {
return (Row4) super.fieldsRow();
}
} | repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\model\tables\Article.java | 1 |
请完成以下Java代码 | private SocketAddress getOwnAddress() {
final String address = this.properties.getAddress();
final int port = this.properties.getPort();
final SocketAddress target;
if (GrpcServerProperties.ANY_IP_ADDRESS.equals(address)) {
target = new InetSocketAddress(port);
} else {
target = new InetSocketAddress(InetAddresses.forString(address), port);
}
return target;
}
private String getOwnAddressString(final String fallback) {
try {
return getOwnAddress().toString().substring(1);
} catch (final IllegalArgumentException e) {
return fallback;
}
}
@Override
public String toString() {
return "SelfNameResolver [" + getOwnAddressString("<unavailable>") + "]";
}
/**
* The logic for assigning the own address.
*/
private final class Resolve implements Runnable {
private final Listener2 savedListener;
/**
* Creates a new Resolve that stores a snapshot of the relevant states of the resolver.
*
* @param listener The listener to send the results to.
*/ | Resolve(final Listener2 listener) {
this.savedListener = requireNonNull(listener, "listener");
}
@Override
public void run() {
try {
this.savedListener.onResult(ResolutionResult.newBuilder()
.setAddresses(ImmutableList.of(
new EquivalentAddressGroup(getOwnAddress())))
.build());
} catch (final Exception e) {
this.savedListener.onError(Status.UNAVAILABLE
.withDescription("Failed to resolve own address").withCause(e));
} finally {
SelfNameResolver.this.syncContext.execute(() -> SelfNameResolver.this.resolving = false);
}
}
}
} | repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\nameresolver\SelfNameResolver.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class TaskExecutorConfiguration {
@Bean("receiveTextChannelThreadPool")
public TaskExecutor receiveTextChannelThreadPool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(1);
executor.setMaxPoolSize(5);
executor.setThreadNamePrefix("receive-text-channel-thread-pool");
executor.initialize();
return executor;
}
@Bean("splitWordsChannelThreadPool")
public TaskExecutor splitWordsChannelThreadPool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(1);
executor.setMaxPoolSize(5);
executor.setThreadNamePrefix("split-words-channel-thread-pool");
executor.initialize();
return executor;
}
@Bean("toLowerCaseChannelThreadPool")
public TaskExecutor toLowerCaseChannelThreadPool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(1);
executor.setMaxPoolSize(5);
executor.setThreadNamePrefix("tto-lower-case-channel-thread-pool"); | executor.initialize();
return executor;
}
@Bean("countWordsChannelThreadPool")
public TaskExecutor countWordsChannelThreadPool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(1);
executor.setMaxPoolSize(5);
executor.setThreadNamePrefix("count-words-channel-thread-pool");
executor.initialize();
return executor;
}
@Bean("returnResponseChannelThreadPool")
public TaskExecutor returnResponseChannelThreadPool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(1);
executor.setMaxPoolSize(5);
executor.setThreadNamePrefix("return-response-channel-thread-pool");
executor.initialize();
return executor;
}
} | repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\seda\springintegration\TaskExecutorConfiguration.java | 2 |
请完成以下Java代码 | public Boolean getWaitFlag() {
return waitFlag;
}
public void setWaitFlag(Boolean waitFlag) {
this.waitFlag = waitFlag;
}
public Boolean getCleanEnvBoolean() {
return cleanEnvBoolean;
}
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;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\ShellCommandExecutor.java | 1 |
请完成以下Java代码 | public abstract class ReflectUtil {
public static InputStream getResourceAsStream(String name) {
// Try the current Thread context class loader
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream resourceStream = classLoader.getResourceAsStream(name);
if (resourceStream == null) {
// Finally, try the class loader for this class
classLoader = ReflectUtil.class.getClassLoader();
resourceStream = classLoader.getResourceAsStream(name);
}
return resourceStream;
}
public static URL getResource(String name) {
return getResource(name, null);
}
public static URL getResource(String name, ClassLoader classLoader) {
if(classLoader == null) {
// Try the current Thread context class loader
classLoader = Thread.currentThread().getContextClassLoader();
}
URL url = classLoader.getResource(name);
if (url == null) {
// Finally, try the class loader for this class
classLoader = ReflectUtil.class.getClassLoader();
url = classLoader.getResource(name);
}
return url;
}
public static File getResourceAsFile(String path) {
URL resource = getResource(path);
try {
return new File(resource.toURI());
} catch (URISyntaxException e) {
throw new ModelException("Exception while loading resource file " + path, e);
}
}
/**
* Create a new instance of the provided type
*
* @param type the class to create a new instance of | * @param parameters the parameters to pass to the constructor
* @return the created instance
*/
public static <T> T createInstance(Class<T> type, Object... parameters) {
// get types for parameters
Class<?>[] parameterTypes = new Class<?>[parameters.length];
for (int i = 0; i < parameters.length; i++) {
Object parameter = parameters[i];
parameterTypes[i] = parameter.getClass();
}
try {
// create instance
Constructor<T> constructor = type.getConstructor(parameterTypes);
return constructor.newInstance(parameters);
} catch (Exception e) {
throw new ModelException("Exception while creating an instance of type "+type, e);
}
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\util\ReflectUtil.java | 1 |
请完成以下Java代码 | public String getSysDate() {
return DateUtils.formatDate();
}
public String getSysTime() {
return DateUtils.now();
}
public String getSysUserCode() {
return sysUserCode;
}
public void setSysUserCode(String sysUserCode) {
this.sysUserCode = sysUserCode;
}
public String getSysUserName() {
return sysUserName;
}
public void setSysUserName(String sysUserName) {
this.sysUserName = sysUserName;
}
public String getSysOrgCode() {
return sysOrgCode;
}
public void setSysOrgCode(String sysOrgCode) {
this.sysOrgCode = sysOrgCode;
}
public List<String> getSysMultiOrgCode() {
return sysMultiOrgCode;
}
public void setSysMultiOrgCode(List<String> sysMultiOrgCode) {
this.sysMultiOrgCode = sysMultiOrgCode;
}
public String getSysUserId() {
return sysUserId;
} | public void setSysUserId(String sysUserId) {
this.sysUserId = sysUserId;
}
public String getSysOrgId() {
return sysOrgId;
}
public void setSysOrgId(String sysOrgId) {
this.sysOrgId = sysOrgId;
}
public String getSysRoleCode() {
return sysRoleCode;
}
public void setSysRoleCode(String sysRoleCode) {
this.sysRoleCode = sysRoleCode;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\vo\SysUserCacheInfo.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_C_ValidCombination getPr() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_Price, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setPr(org.compiere.model.I_C_ValidCombination Pr)
{
set_ValueFromPO(COLUMNNAME_Price, org.compiere.model.I_C_ValidCombination.class, Pr);
}
/** Set Preis.
@param Price
Price
*/
@Override
public void setPrice (int Price)
{
set_ValueNoCheck (COLUMNNAME_Price, Integer.valueOf(Price));
}
/** Get Preis.
@return Price
*/
@Override
public int getPrice ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Price);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Menge.
@param Qty
Quantity
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_ValueNoCheck (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Quantity
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null) | return BigDecimal.ZERO;
return bd;
}
/** Set Symbol.
@param UOMSymbol
Symbol for a Unit of Measure
*/
@Override
public void setUOMSymbol (java.lang.String UOMSymbol)
{
set_ValueNoCheck (COLUMNNAME_UOMSymbol, UOMSymbol);
}
/** Get Symbol.
@return Symbol for a Unit of Measure
*/
@Override
public java.lang.String getUOMSymbol ()
{
return (java.lang.String)get_Value(COLUMNNAME_UOMSymbol);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponseLineQty_v.java | 1 |
请完成以下Java代码 | private static HUReservationDocRef extractDocumentRef(@NonNull final I_M_HU_Reservation record)
{
return HUReservationDocRef.builder()
.salesOrderLineId(OrderLineId.ofRepoIdOrNull(record.getC_OrderLineSO_ID()))
.projectId(ProjectId.ofRepoIdOrNull(record.getC_Project_ID()))
.pickingJobStepId(PickingJobStepId.ofRepoIdOrNull(record.getM_Picking_Job_Step_ID()))
.ddOrderLineId(DDOrderLineId.ofRepoIdOrNull(record.getDD_OrderLine_ID()))
.build();
}
public void transferReservation(
@NonNull final Collection<HUReservationDocRef> from,
@NonNull final HUReservationDocRef to,
@NonNull final Set<HuId> onlyVHUIds)
{
if (from.size() == 1 && Objects.equals(from.iterator().next(), to))
{ | return;
}
final List<I_M_HU_Reservation> records = retrieveRecordsByDocumentRef(from, onlyVHUIds);
if (records.isEmpty())
{
return;
}
for (final I_M_HU_Reservation record : records)
{
updateRecordFromDocumentRef(record, to);
saveRecord(record);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\reservation\HUReservationRepository.java | 1 |
请完成以下Spring Boot application配置 | spring:
# datasource 数据源配置内容
datasource:
url: jdbc:mysql://47.112.193.81:3306/testb5f4?useSSL=false&useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.jdbc.Driver
username: testb5f4
password: F4df4db0ed86@11
# mybatis 配置内容
mybatis:
config-location: classpath:mybatis-config.xml # 配置 MyBatis 配置文件路径
| # mapper-locations: classpath:mapper/*.xml # 配置 Mapper XML 地址
type-aliases-package: cn.iocoder.springboot.lab12.mybatis.dataobject # 配置数据库实体包路径 | repos\SpringBoot-Labs-master\lab-12-mybatis\lab-12-mybatis-annotation\src\main\resources\application.yaml | 2 |
请在Spring Boot框架中完成以下Java代码 | public class UserDao extends BaseDao<User, Long> {
@Autowired
public UserDao(JdbcTemplate jdbcTemplate) {
super(jdbcTemplate);
}
/**
* 保存用户
*
* @param user 用户对象
* @return 操作影响行数
*/
public Integer insert(User user) {
return super.insert(user, true);
}
/**
* 根据主键删除用户
*
* @param id 主键id
* @return 操作影响行数
*/
public Integer delete(Long id) {
return super.deleteById(id);
}
/**
* 更新用户
*
* @param user 用户对象
* @param id 主键id
* @return 操作影响行数
*/
public Integer update(User user, Long id) { | return super.updateById(user, id, true);
}
/**
* 根据主键获取用户
*
* @param id 主键id
* @return id对应的用户
*/
public User selectById(Long id) {
return super.findOneById(id);
}
/**
* 根据查询条件获取用户列表
*
* @param user 用户查询条件
* @return 用户列表
*/
public List<User> selectUserList(User user) {
return super.findByExample(user);
}
} | repos\spring-boot-demo-master\demo-orm-jdbctemplate\src\main\java\com\xkcoding\orm\jdbctemplate\dao\UserDao.java | 2 |
请完成以下Java代码 | public TransactionDescriptor ofRecord(@NonNull final I_M_Transaction record)
{
final WarehouseId warehouseId = warehousesRepo.getWarehouseIdByLocatorRepoId(record.getM_Locator_ID());
return TransactionDescriptor.builder()
.eventDescriptor(EventDescriptor.ofClientAndOrg(record.getAD_Client_ID(), record.getAD_Org_ID()))
.transactionId(record.getM_Transaction_ID())
.productId(ProductId.ofRepoId(record.getM_Product_ID()))
.warehouseId(warehouseId)
.locatorId(LocatorId.ofRepoIdOrNull(warehouseId, record.getM_Locator_ID()))
.transactionDate(extractTransactionDate(record))
.movementQty(record.getMovementQty())
.costCollectorId(PPCostCollectorId.ofRepoIdOrNull(record.getPP_Cost_Collector_ID()))
.inoutLineId(InOutLineId.ofRepoIdOrNull(record.getM_InOutLine_ID()))
.movementLineId(MovementLineId.ofRepoIdOrNull(record.getM_MovementLine_ID()))
.inventoryLineId(InventoryLineId.ofRepoIdOrNull(record.getM_InventoryLine_ID()))
.movementType(record.getMovementType())
.build();
}
private static Instant extractTransactionDate(@NonNull final I_M_Transaction record)
{
final Timestamp movementDate = record.getMovementDate();
final Timestamp movementDateDay = getDay(movementDate); | final boolean movementDateContainsTime = !movementDate.equals(movementDateDay);
if (movementDateContainsTime)
{
return asInstant(movementDate);
}
// try to fall back to the M_Transaction's created or update date, to get the actual movement date *and time*.
final Timestamp created = record.getCreated();
if (movementDateDay.equals(getDay(created)))
{
return asInstant(created);
}
final Timestamp updated = record.getUpdated();
if (movementDateDay.equals(getDay(updated)))
{
return asInstant(updated);
}
return asInstant(movementDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\material\interceptor\transactionevent\TransactionDescriptorFactory.java | 1 |
请完成以下Java代码 | public void setAD_PrinterHW_ID (final int AD_PrinterHW_ID)
{
if (AD_PrinterHW_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_PrinterHW_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_PrinterHW_ID, AD_PrinterHW_ID);
}
@Override
public int getAD_PrinterHW_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_PrinterHW_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 setExternalSystem_Config_ID (final int ExternalSystem_Config_ID)
{
if (ExternalSystem_Config_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_Config_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID);
}
@Override
public int getExternalSystem_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID);
}
@Override
public void setHostKey (final @Nullable java.lang.String HostKey)
{
set_ValueNoCheck (COLUMNNAME_HostKey, HostKey);
}
@Override
public java.lang.String getHostKey()
{
return get_ValueAsString(COLUMNNAME_HostKey);
}
@Override
public void setIPP_URL (final @Nullable java.lang.String IPP_URL)
{
set_Value (COLUMNNAME_IPP_URL, IPP_URL);
}
@Override
public java.lang.String getIPP_URL()
{
return get_ValueAsString(COLUMNNAME_IPP_URL);
} | @Override
public void setName (final java.lang.String Name)
{
set_ValueNoCheck (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
/**
* OutputType AD_Reference_ID=540632
* Reference name: OutputType
*/
public static final int OUTPUTTYPE_AD_Reference_ID=540632;
/** Attach = Attach */
public static final String OUTPUTTYPE_Attach = "Attach";
/** Store = Store */
public static final String OUTPUTTYPE_Store = "Store";
/** Queue = Queue */
public static final String OUTPUTTYPE_Queue = "Queue";
/** Frontend = Frontend */
public static final String OUTPUTTYPE_Frontend = "Frontend";
@Override
public void setOutputType (final java.lang.String OutputType)
{
set_Value (COLUMNNAME_OutputType, OutputType);
}
@Override
public java.lang.String getOutputType()
{
return get_ValueAsString(COLUMNNAME_OutputType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_PrinterHW.java | 1 |
请完成以下Java代码 | public byte[] getAvatar() {
return avatar;
}
public void setAvatar(byte[] avatar) {
this.avatar = avatar;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGenre() {
return genre;
} | public void setGenre(String genre) {
this.genre = genre;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Author{" + "name=" + name + "}";
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootAttributeLazyLoadingBasic\src\main\java\com\bookstore\entity\Author.java | 1 |
请完成以下Java代码 | public boolean isActive()
{
return active;
}
public void setActive(boolean active)
{
this.active = active;
}
@Override
public boolean isApplyClientSecurity()
{
return applyClientSecurity;
}
public void setApplyClientSecurity(boolean applyClientSecurity)
{
this.applyClientSecurity = applyClientSecurity;
}
@Override
public Boolean getProcessed()
{
return processed;
}
public void setProcessed(Boolean processed)
{
this.processed = processed;
}
@Override
public Boolean getWriteOff()
{ | return writeOff;
}
public void setWriteOff(Boolean writeOff)
{
this.writeOff = writeOff;
}
@Override
public String getAdditionalWhere()
{
return additionalWhere;
}
public void setAdditionalWhere(String additionalWhere)
{
this.additionalWhere = additionalWhere;
}
@Override
public ApplyAccessFilter getApplyAccessFilter()
{
return applyAccessFilter;
}
public void setApplyAccessFilter(ApplyAccessFilter applyAccessFilter)
{
this.applyAccessFilter = applyAccessFilter;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunningCandidateQuery.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonHUQtyChangeRequest
{
@Nullable ScannedCode huQRCode;
@Nullable HuId huId;
@NonNull JsonQuantity qty;
@Nullable String description;
boolean splitOneIfAggregated;
@Nullable String locatorQRCode;
boolean setBestBeforeDate;
@Nullable @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") LocalDate bestBeforeDate;
boolean setLotNo;
@Nullable String lotNo;
public JsonHUQtyChangeRequest withHuIdAndValidate(@NonNull final HuId huId)
{
if (this.huId != null) | {
if (!HuId.equals(this.huId, huId))
{
throw new AdempiereException("Overriding request huId with `" + huId + "` is not allowed for request " + this);
}
else
{
return this;
}
}
else
{
return toBuilder().huId(huId).build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.mobileui\src\main\java\de\metas\handlingunits\rest_api\JsonHUQtyChangeRequest.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getTAXAMOUNT() {
return taxamount;
}
/**
* Sets the value of the taxamount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTAXAMOUNT(String value) {
this.taxamount = value;
}
/**
* Gets the value of the taxableamount property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTAXABLEAMOUNT() {
return taxableamount;
}
/**
* Sets the value of the taxableamount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTAXABLEAMOUNT(String value) {
this.taxableamount = value;
}
/**
* Gets the value of the linesamount property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLINESAMOUNT() {
return linesamount;
} | /**
* Sets the value of the linesamount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLINESAMOUNT(String value) {
this.linesamount = value;
}
/**
* Gets the value of the chargesamount property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCHARGESAMOUNT() {
return chargesamount;
}
/**
* Sets the value of the chargesamount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCHARGESAMOUNT(String value) {
this.chargesamount = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\TTAXI1.java | 2 |
请完成以下Java代码 | public Long getBlockQps() {
return blockQps;
}
public void setBlockQps(Long blockQps) {
this.blockQps = blockQps;
}
public Long getExceptionQps() {
return exceptionQps;
}
public void setExceptionQps(Long exceptionQps) {
this.exceptionQps = exceptionQps;
}
public double getRt() {
return rt;
}
public void setRt(double rt) {
this.rt = rt;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getResourceCode() {
return resourceCode;
}
public Long getSuccessQps() {
return successQps;
}
public void setSuccessQps(Long successQps) {
this.successQps = successQps;
} | @Override
public String toString() {
return "MetricEntity{" +
"id=" + id +
", gmtCreate=" + gmtCreate +
", gmtModified=" + gmtModified +
", app='" + app + '\'' +
", timestamp=" + timestamp +
", resource='" + resource + '\'' +
", passQps=" + passQps +
", blockQps=" + blockQps +
", successQps=" + successQps +
", exceptionQps=" + exceptionQps +
", rt=" + rt +
", count=" + count +
", resourceCode=" + resourceCode +
'}';
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\MetricEntity.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String[] getRoles() {
return roles;
}
public void setRoles(String[] roles) {
this.roles = roles;
}
public Integer[] getLocations() {
return locations; | }
public void setLocations(Integer[] locations) {
this.locations = locations;
}
public String[] getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(String[] phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
} | repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\hibernate\arraymapping\User.java | 1 |
请完成以下Java代码 | public com.baeldung.protobuf.AddressBookProtos.AddressBook getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_protobuf_Person_descriptor;
private static final
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_protobuf_Person_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_protobuf_AddressBook_descriptor;
private static final
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_protobuf_AddressBook_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n$src/main/resources/addressbook.proto\022\010" +
"protobuf\"B\n\006Person\022\014\n\004name\030\001 \002(\t\022\n\n\002id\030\002" +
" \002(\005\022\r\n\005email\030\003 \001(\t\022\017\n\007numbers\030\004 \003(\t\"/\n\013" +
"AddressBook\022 \n\006people\030\001 \003(\0132\020.protobuf.P" +
"ersonB*\n\025com.baeldung.protobufB\021AddressB" +
"ookProtos"
};
descriptor = com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
}); | internal_static_protobuf_Person_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_protobuf_Person_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_protobuf_Person_descriptor,
new java.lang.String[] { "Name", "Id", "Email", "Numbers", });
internal_static_protobuf_AddressBook_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_protobuf_AddressBook_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_protobuf_AddressBook_descriptor,
new java.lang.String[] { "People", });
descriptor.resolveAllFeaturesImmutable();
}
// @@protoc_insertion_point(outer_class_scope)
} | repos\tutorials-master\google-protocol-buffer\src\main\java\com\baeldung\protobuf\AddressBookProtos.java | 1 |
请完成以下Java代码 | public IReturnsInOutProducer setC_BPartner_Location(final I_C_BPartner_Location bpLocation)
{
assertConfigurable();
Check.assumeNotNull(bpLocation, "bpLocation not null");
_bpartnerLocationId = bpLocation.getC_BPartner_Location_ID();
return this;
}
@Override
public IReturnsInOutProducer setMovementType(final String movementType)
{
assertConfigurable();
_movementType = movementType;
return this;
}
@Override
public IReturnsInOutProducer setM_Warehouse(final I_M_Warehouse warehouse)
{
assertConfigurable();
_warehouse = warehouse;
return this;
}
private static I_C_DocType getEmptiesDocType(final String docBaseType, final int adClientId, final int adOrgId, final boolean isSOTrx)
{
//
// Search for specific empties shipment/receipt document sub-type (task 07694)
// 07694: using the empties-subtype for receipts.
final String docSubType = isSOTrx ? X_C_DocType.DOCSUBTYPE_Leergutanlieferung : X_C_DocType.DOCSUBTYPE_Leergutausgabe;
final IDocTypeDAO docTypeDAO = Services.get(IDocTypeDAO.class);
final List<I_C_DocType> docTypes = docTypeDAO.retrieveDocTypesByBaseType(DocTypeQuery.builder()
.docBaseType(docBaseType)
.docSubType(DocTypeQuery.DOCSUBTYPE_Any)
.adClientId(adClientId)
.adOrgId(adOrgId)
.build());
if (docTypes == null)
{
logger.warn("No document types found for docBaseType={}, adClientId={}, adOrgId={}", docBaseType, adClientId, adOrgId);
return null;
}
for (final I_C_DocType docType : docTypes)
{
final String subType = docType.getDocSubType();
if (docSubType.equals(subType))
{
return docType;
}
}
//
// If the empties doc type was not found (should not happen) fallback to the default one
{
final I_C_DocType defaultDocType = docTypes.get(0);
logger.warn("No empties document type found for docBaseType={}, docSubType={}, adClientId={}, adOrgId={}. Using fallback docType={}", docBaseType, docSubType, adClientId, adOrgId, defaultDocType);
return defaultDocType;
}
}
@Override
protected void createLines()
{ | inoutLinesBuilder.addSources(sources);
inoutLinesBuilder.create();
}
@Override
protected int getReturnsDocTypeId(final String docBaseType, final boolean isSOTrx, final int adClientId, final int adOrgId)
{
final I_C_DocType docType = getEmptiesDocType(docBaseType, adClientId, adOrgId, isSOTrx);
DocTypeId docTypeId = docType == null ? null : DocTypeId.ofRepoId(docType.getC_DocType_ID());
// If the empties doc type was not found (should not happen) fallback to the default one
if (docTypeId == null)
{
final IDocTypeDAO docTypeDAO = Services.get(IDocTypeDAO.class);
docTypeId = docTypeDAO.getDocTypeId(
DocTypeQuery.builder()
.docBaseType(docBaseType)
.adClientId(adClientId)
.adOrgId(adOrgId)
.build()
//Env.getCtx(), docBaseType, adClientId, adOrgId, ITrx.TRXNAME_None
);
}
return DocTypeId.toRepoId(docTypeId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\empties\impl\EmptiesInOutProducer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String audit(HttpServletRequest request, Model model, DwzAjax dwz) {
String settId = request.getParameter("settId");
String settStatus = request.getParameter("settStatus");
String remark = request.getParameter("remark");
rpSettHandleService.audit(settId, settStatus, remark);
dwz.setStatusCode(DWZ.SUCCESS);
dwz.setMessage(DWZ.SUCCESS_MSG);
model.addAttribute("dwz", dwz);
return DWZ.AJAX_DONE;
}
/**
* 函数功能说明 :跳转打款
*
* @参数: @return
* @return String
* @throws
*/
@RequiresPermissions("sett:record:edit")
@RequestMapping(value = "/remitUI", method = RequestMethod.GET)
public String remitUI(Model model, @RequestParam("id") String id) {
RpSettRecord settRecord = rpSettQueryService.getDataById(id);
model.addAttribute("settRecord", settRecord);
return "sett/remit";
}
/**
* 函数功能说明 : 发起打款
*
* @参数: @return
* @return String
* @throws
*/
@RequiresPermissions("sett:record:edit")
@RequestMapping(value = "/remit", method = RequestMethod.POST)
public String remit(HttpServletRequest request, Model model, DwzAjax dwz) {
String settId = request.getParameter("settId");
String settStatus = request.getParameter("settStatus");
String remark = request.getParameter("remark");
rpSettHandleService.remit(settId, settStatus, remark);
dwz.setStatusCode(DWZ.SUCCESS);
dwz.setMessage(DWZ.SUCCESS_MSG); | model.addAttribute("dwz", dwz);
return DWZ.AJAX_DONE;
}
/**
* 函数功能说明 :查看
*
* @参数: @return
* @return String
* @throws
*/
@RequestMapping(value = "/view", method = RequestMethod.GET)
public String view(Model model, @RequestParam("id") String id) {
RpSettRecord settRecord = rpSettQueryService.getDataById(id);
model.addAttribute("settRecord", settRecord);
return "sett/view";
}
/**
* 函数功能说明 :根据支付产品获取支付方式
*
* @参数: @return
* @return String
* @throws
*/
@RequestMapping(value = "/getSettAmount", method = RequestMethod.GET)
@ResponseBody
public RpAccount getSettAmount(@RequestParam("userNo") String userNo) {
RpAccount rpAccount = rpAccountService.getDataByUserNo(userNo);
return rpAccount;
}
} | repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\controller\sett\SettController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class PersistenceConfig {
@Autowired
private Environment env;
public PersistenceConfig() {
super();
}
@Bean
public AnnotationSessionFactoryBean sessionFactory() {
final AnnotationSessionFactoryBean sessionFactory = new AnnotationSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.baeldung.persistence.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public DataSource dataSource() {
final BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
} | @Bean
@Autowired
public HibernateTransactionManager transactionManager(final SessionFactory sessionFactory) {
final HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory);
return txManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
final Properties hibernateProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
// hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
return hibernateProperties;
}
} | repos\tutorials-master\persistence-modules\spring-hibernate-3\src\main\java\com\baeldung\spring\PersistenceConfig.java | 2 |
请完成以下Java代码 | public DmnDeploymentHelper getDmnDeploymentHelper() {
return dmnDeploymentHelper;
}
public void setDmnDeploymentHelper(DmnDeploymentHelper dmnDeploymentHelper) {
this.dmnDeploymentHelper = dmnDeploymentHelper;
}
public CachingAndArtifactsManager getCachingAndArtifcatsManager() {
return cachingAndArtifactsManager;
}
public void setCachingAndArtifactsManager(CachingAndArtifactsManager manager) {
this.cachingAndArtifactsManager = manager;
} | public boolean isUsePrefixId() {
return usePrefixId;
}
public void setUsePrefixId(boolean usePrefixId) {
this.usePrefixId = usePrefixId;
}
public DecisionRequirementsDiagramHelper getDecisionRequirementsDiagramHelper() {
return decisionRequirementsDiagramHelper;
}
public void setDecisionRequirementsDiagramHelper(DecisionRequirementsDiagramHelper decisionRequirementsDiagramHelper) {
this.decisionRequirementsDiagramHelper = decisionRequirementsDiagramHelper;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\deployer\DmnDeployer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private boolean isLineLevelPickTarget(final PickingJob pickingJob) {return pickingJob.isLineLevelPickTarget();}
@Nullable
private LUPickingTarget reinitializeLUPickingTarget(@Nullable final LUPickingTarget luPickingTarget)
{
if (luPickingTarget == null)
{
return null;
}
final HuId luId = luPickingTarget.getLuId();
if (luId == null)
{
return luPickingTarget;
}
final I_M_HU lu = huService.getById(luId);
if (!huService.isDestroyedOrEmptyStorage(lu))
{
return luPickingTarget;
}
final HuPackingInstructionsIdAndCaption luPI = huService.getEffectivePackingInstructionsIdAndCaption(lu); | return LUPickingTarget.ofPackingInstructions(luPI);
}
//
//
//
@Value
@Builder
private static class StepUnpickInstructions
{
@NonNull PickingJobStepId stepId;
@NonNull PickingJobStepPickFromKey pickFromKey;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\PickingJobUnPickCommand.java | 2 |
请完成以下Java代码 | public List<Integer> copyListByCopyMethod(List<Integer> source, List<Integer> dest) {
Collections.copy(dest, source);
return dest;
}
public List<Flower> copyListByStream(List<Flower> source) {
return source.stream().collect(Collectors.toList());
}
public List<Flower> copyListByStreamAndSkipFirstElement(List<Flower> source) {
return source.stream().skip(1).collect(Collectors.toList());
}
public List<Flower> copyListByStreamWithFilter(List<Flower> source, Integer moreThanPetals) {
return source.stream().filter(f -> f.getPetals() > moreThanPetals).collect(Collectors.toList());
} | public List<Flower> copyListByStreamWithOptional(List<Flower> source) {
return Optional.ofNullable(source)
.map(List::stream)
.orElseGet(Stream::empty)
.collect(Collectors.toList());
}
public List<Flower> copyListByStreamWithOptionalAndSkip(List<Flower> source) {
return Optional.ofNullable(source)
.map(List::stream)
.orElseGet(Stream::empty)
.skip(1)
.collect(Collectors.toList());
}
} | repos\tutorials-master\core-java-modules\core-java-collections-list-3\src\main\java\com\baeldung\java\list\CopyListService.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.