instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public String getGln()
{
return gln;
}
public void setGln(final String gln)
{
this.gln = gln;
}
public String getSenderGln()
{
return senderGln;
}
public void setSenderGln(final String senderGln)
{
this.senderGln = senderGln;
}
public String getInterchangeReferenceNo()
{
return interchangeReferenceNo;
}
public void setInterchangeReferenceNo(final String interchangeReferenceNo)
{
this.interchangeReferenceNo = interchangeReferenceNo;
}
public String getIsTest()
{
return isTest;
}
public void setIsTest(final String isTest)
{
this.isTest = isTest;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (cbPartnerLocationID == null ? 0 : cbPartnerLocationID.hashCode());
result = prime * result + (gln == null ? 0 : gln.hashCode());
result = prime * result + (interchangeReferenceNo == null ? 0 : interchangeReferenceNo.hashCode());
result = prime * result + (isTest == null ? 0 : isTest.hashCode());
result = prime * result + (senderGln == null ? 0 : senderGln.hashCode());
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final Cctop000V other = (Cctop000V)obj;
if (cbPartnerLocationID == null)
{
if (other.cbPartnerLocationID != null)
{
return false;
}
}
else if (!cbPartnerLocationID.equals(other.cbPartnerLocationID))
{
return false;
}
if (gln == null)
{
if (other.gln != null)
{
return false;
}
} | else if (!gln.equals(other.gln))
{
return false;
}
if (interchangeReferenceNo == null)
{
if (other.interchangeReferenceNo != null)
{
return false;
}
}
else if (!interchangeReferenceNo.equals(other.interchangeReferenceNo))
{
return false;
}
if (isTest == null)
{
if (other.isTest != null)
{
return false;
}
}
else if (!isTest.equals(other.isTest))
{
return false;
}
if (senderGln == null)
{
if (other.senderGln != null)
{
return false;
}
}
else if (!senderGln.equals(other.senderGln))
{
return false;
}
return true;
}
@Override
public String toString()
{
return "Cctop000V [cbPartnerLocationID=" + cbPartnerLocationID + ", gln=" + gln + ", senderGln=" + senderGln + ", interchangeReferenceNo=" + interchangeReferenceNo
+ ", isTest=" + isTest
+ "]";
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\invoicexport\compudata\Cctop000V.java | 2 |
请完成以下Java代码 | public class WorkpackageProcessorFactoryJMX implements WorkpackageProcessorFactoryJMXMBean
{
private final WorkpackageProcessorFactory factory;
public WorkpackageProcessorFactoryJMX(final WorkpackageProcessorFactory factory)
{
super();
this.factory = factory;
}
@Override
public String[] getBlackListItemsInfo()
{
final List<BlackListItem> blacklistItems = factory.getBlackList().getItems();
final String[] info = new String[blacklistItems.size()];
for (int i = 0; i < info.length; i++)
{
info[i] = blacklistItems.get(i).toString();
} | return info;
}
@Override
public void removeFromBlackList(final int packageProcessorId)
{
factory.getBlackList().removeFromBlacklist(packageProcessorId);
}
@Override
public void clearBlackList()
{
factory.getBlackList().clear();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\WorkpackageProcessorFactoryJMX.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public void setTenantIdLike(String tenantIdLike) {
this.tenantIdLike = tenantIdLike; | }
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Set<String> getProcessInstanceIds() {
return processInstanceIds;
}
public void setProcessInstanceIds(Set<String> processInstanceIds) {
this.processInstanceIds = processInstanceIds;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ExecutionQueryRequest.java | 2 |
请完成以下Java代码 | public class X_RV_M_HU_Storage_InvoiceHistory extends org.compiere.model.PO implements I_RV_M_HU_Storage_InvoiceHistory, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 284018895L;
/** Standard Constructor */
public X_RV_M_HU_Storage_InvoiceHistory (final Properties ctx, final int RV_M_HU_Storage_InvoiceHistory_ID, @Nullable final String trxName)
{
super (ctx, RV_M_HU_Storage_InvoiceHistory_ID, trxName);
}
/** Load Constructor */
public X_RV_M_HU_Storage_InvoiceHistory (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setHUStorageASIKey (final @Nullable java.lang.String HUStorageASIKey)
{
set_ValueNoCheck (COLUMNNAME_HUStorageASIKey, HUStorageASIKey);
}
@Override
public java.lang.String getHUStorageASIKey()
{
return get_ValueAsString(COLUMNNAME_HUStorageASIKey);
}
@Override
public void setM_Locator_ID (final int M_Locator_ID)
{
if (M_Locator_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Locator_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Locator_ID, M_Locator_ID);
}
@Override
public int getM_Locator_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Locator_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setQtyOnHand (final @Nullable BigDecimal QtyOnHand)
{ | set_ValueNoCheck (COLUMNNAME_QtyOnHand, QtyOnHand);
}
@Override
public BigDecimal getQtyOnHand()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHand);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyOrdered (final @Nullable BigDecimal QtyOrdered)
{
set_ValueNoCheck (COLUMNNAME_QtyOrdered, QtyOrdered);
}
@Override
public BigDecimal getQtyOrdered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyReserved (final @Nullable BigDecimal QtyReserved)
{
set_ValueNoCheck (COLUMNNAME_QtyReserved, QtyReserved);
}
@Override
public BigDecimal getQtyReserved()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved);
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_RV_M_HU_Storage_InvoiceHistory.java | 1 |
请完成以下Java代码 | public RawMaterialsIssueLine withChangedRawMaterialsIssueStep(
@NonNull final PPOrderIssueScheduleId issueScheduleId,
@NonNull UnaryOperator<RawMaterialsIssueStep> mapper)
{
final ImmutableList<RawMaterialsIssueStep> stepsNew = CollectionUtils.map(
steps,
step -> PPOrderIssueScheduleId.equals(step.getId(), issueScheduleId) ? mapper.apply(step) : step);
return withSteps(stepsNew);
}
@NonNull
public RawMaterialsIssueLine withSteps(final ImmutableList<RawMaterialsIssueStep> stepsNew)
{
return !Objects.equals(this.steps, stepsNew)
? toBuilder().steps(stepsNew).build()
: this;
}
public boolean containsRawMaterialsIssueStep(final PPOrderIssueScheduleId issueScheduleId)
{
return steps.stream().anyMatch(step -> PPOrderIssueScheduleId.equals(step.getId(), issueScheduleId));
}
@NonNull
public ITranslatableString getProductValueAndProductName()
{ | final TranslatableStringBuilder message = TranslatableStrings.builder()
.append(getProductValue())
.append(" ")
.append(getProductName());
return message.build();
}
@NonNull
public Quantity getQtyLeftToIssue()
{
return qtyToIssue.subtract(qtyIssued);
}
public boolean isAllowManualIssue()
{
return !issueMethod.isIssueOnlyForReceived();
}
public boolean isIssueOnlyForReceived() {return issueMethod.isIssueOnlyForReceived();}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\model\RawMaterialsIssueLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DatabaseBackedSecurPharmConfigRespository implements SecurPharmConfigRespository
{
private final CCache<Integer, Optional<SecurPharmConfigId>> defaultConfigIdCache = CCache.<Integer, Optional<SecurPharmConfigId>> builder()
.tableName(I_M_Securpharm_Config.Table_Name)
.build();
private final CCache<SecurPharmConfigId, SecurPharmConfig> configsCache = CCache.<SecurPharmConfigId, SecurPharmConfig> builder()
.tableName(I_M_Securpharm_Config.Table_Name)
.build();
@Override
public Optional<SecurPharmConfig> getDefaultConfig()
{
return getDefaultConfigId().map(this::getById);
}
private Optional<SecurPharmConfigId> getDefaultConfigId()
{
return defaultConfigIdCache.getOrLoad(0, this::retrieveDefaultConfigId);
}
private Optional<SecurPharmConfigId> retrieveDefaultConfigId()
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final SecurPharmConfigId configId = queryBL
.createQueryBuilder(I_M_Securpharm_Config.class)
.addOnlyActiveRecordsFilter()
.create()
.firstIdOnly(SecurPharmConfigId::ofRepoIdOrNull);
return Optional.ofNullable(configId);
}
@Override
public SecurPharmConfig getById(@NonNull final SecurPharmConfigId configId)
{
return configsCache.getOrLoad(configId, this::retrieveById);
} | private SecurPharmConfig retrieveById(@NonNull final SecurPharmConfigId configId)
{
final I_M_Securpharm_Config record = loadOutOfTrx(configId, I_M_Securpharm_Config.class);
return ofRecord(record);
}
private static SecurPharmConfig ofRecord(@NonNull final I_M_Securpharm_Config config)
{
return SecurPharmConfig.builder()
.id(SecurPharmConfigId.ofRepoId(config.getM_Securpharm_Config_ID()))
.certificatePath(config.getCertificatePath())
.applicationUUID(config.getApplicationUUID())
.authBaseUrl(config.getAuthPharmaRestApiBaseURL())
.pharmaAPIBaseUrl(config.getPharmaRestApiBaseURL())
.keystorePassword(config.getTanPassword())
.supportUserId(UserId.ofRepoId(config.getSupport_User_ID()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\config\DatabaseBackedSecurPharmConfigRespository.java | 2 |
请完成以下Java代码 | public int getPort() {
return this.port;
}
/**
* Throw a {@link PortInUseException} if the given exception was caused by a "port in
* use" {@link BindException}.
* @param ex the source exception
* @param port a supplier used to provide the port
* @since 2.2.7
*/
public static void throwIfPortBindingException(Exception ex, IntSupplier port) {
ifPortBindingException(ex, (bindException) -> {
throw new PortInUseException(port.getAsInt(), ex);
});
}
/**
* Perform an action if the given exception was caused by a "port in use"
* {@link BindException}.
* @param ex the source exception
* @param action the action to perform
* @since 2.2.7
*/
public static void ifPortBindingException(Exception ex, Consumer<BindException> action) {
ifCausedBy(ex, BindException.class, (bindException) -> {
// bind exception can be also thrown because an address can't be assigned
String message = bindException.getMessage();
if (message != null && message.toLowerCase(Locale.ROOT).contains("in use")) {
action.accept(bindException);
}
});
}
/** | * Perform an action if the given exception was caused by a specific exception type.
* @param <E> the cause exception type
* @param ex the source exception
* @param causedBy the required cause type
* @param action the action to perform
* @since 2.2.7
*/
@SuppressWarnings("unchecked")
public static <E extends Exception> void ifCausedBy(Exception ex, Class<E> causedBy, Consumer<E> action) {
Throwable candidate = ex;
while (candidate != null) {
if (causedBy.isInstance(candidate)) {
action.accept((E) candidate);
return;
}
candidate = candidate.getCause();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\PortInUseException.java | 1 |
请完成以下Java代码 | public void setM_CostElement_ID (final int M_CostElement_ID)
{
if (M_CostElement_ID < 1)
set_Value (COLUMNNAME_M_CostElement_ID, null);
else
set_Value (COLUMNNAME_M_CostElement_ID, M_CostElement_ID);
}
@Override
public int getM_CostElement_ID()
{
return get_ValueAsInt(COLUMNNAME_M_CostElement_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setName (final String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override | public String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setValue (final String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Cost_Type.java | 1 |
请完成以下Java代码 | protected Void execute(CommandContext commandContext, TaskEntity task) {
CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext);
String oldAssigneeId = task.getAssignee();
String oldOwnerId = task.getOwner();
boolean assignedToNoOne = false;
if (IdentityLinkType.ASSIGNEE.equals(identityType)) {
if (oldAssigneeId == null && identityId == null) {
return null;
}
if (oldAssigneeId != null && oldAssigneeId.equals(identityId)) {
return null;
}
TaskHelper.changeTaskAssignee(task, identityId, cmmnEngineConfiguration);
assignedToNoOne = identityId == null;
} else if (IdentityLinkType.OWNER.equals(identityType)) {
if (oldOwnerId == null && identityId == null) {
return null;
}
if (oldOwnerId != null && oldOwnerId.equals(identityId)) {
return null;
}
TaskHelper.changeTaskOwner(task, identityId, cmmnEngineConfiguration);
assignedToNoOne = identityId == null;
} else if (IDENTITY_USER == identityIdType) {
IdentityLinkEntity identityLinkEntity = cmmnEngineConfiguration.getIdentityLinkServiceConfiguration().getIdentityLinkService()
.createTaskIdentityLink(task.getId(), identityId, null, identityType);
IdentityLinkUtil.handleTaskIdentityLinkAddition(task, identityLinkEntity, cmmnEngineConfiguration);
} else if (IDENTITY_GROUP == identityIdType) { | IdentityLinkEntity identityLinkEntity = cmmnEngineConfiguration.getIdentityLinkServiceConfiguration().getIdentityLinkService()
.createTaskIdentityLink(task.getId(), null, identityId, identityType);
IdentityLinkUtil.handleTaskIdentityLinkAddition(task, identityLinkEntity, cmmnEngineConfiguration);
}
if (assignedToNoOne) {
if (IdentityLinkType.ASSIGNEE.equals(identityType)) {
identityId = oldAssigneeId;
} else {
identityId = oldOwnerId;
}
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\AddIdentityLinkCmd.java | 1 |
请完成以下Java代码 | public String getActivityType() {
return activityType;
}
public String getActivityDescription() {
return activityDescription;
}
public String getParentId() {
return parentId;
}
public String getTenantId() {
return tenantId;
}
public boolean isRequired() {
return required;
}
public boolean isEnabled() {
return enabled;
}
public boolean isActive() {
return active;
}
public boolean isDisabled() {
return disabled;
}
public static CaseExecutionDto fromCaseExecution(CaseExecution caseExecution) {
CaseExecutionDto dto = new CaseExecutionDto(); | dto.id = caseExecution.getId();
dto.caseInstanceId = caseExecution.getCaseInstanceId();
dto.caseDefinitionId = caseExecution.getCaseDefinitionId();
dto.activityId = caseExecution.getActivityId();
dto.activityName = caseExecution.getActivityName();
dto.activityType = caseExecution.getActivityType();
dto.activityDescription = caseExecution.getActivityDescription();
dto.parentId = caseExecution.getParentId();
dto.tenantId = caseExecution.getTenantId();
dto.required = caseExecution.isRequired();
dto.active = caseExecution.isActive();
dto.enabled = caseExecution.isEnabled();
dto.disabled = caseExecution.isDisabled();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\CaseExecutionDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SkipExceptionJobDemo {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Autowired
private MySkipListener mySkipListener;
@Bean
public Job skipExceptionJob() {
return jobBuilderFactory.get("skipExceptionJob")
.start(step())
.build();
}
private Step step() {
return stepBuilderFactory.get("step")
.<String, String>chunk(2)
.reader(listItemReader())
.processor(myProcessor())
.writer(list -> list.forEach(System.out::println))
.faultTolerant() // 配置错误容忍
.skip(MyJobExecutionException.class) // 配置跳过的异常类型
.skipLimit(1) // 最多跳过1次,1次过后还是异常的话,则任务会结束,
// 异常的次数为reader,processor和writer中的总数,这里仅在processor里演示异常跳过
.listener(mySkipListener)
.build();
} | private ListItemReader<String> listItemReader() {
ArrayList<String> datas = new ArrayList<>();
IntStream.range(0, 5).forEach(i -> datas.add(String.valueOf(i)));
return new ListItemReader<>(datas);
}
private ItemProcessor<String, String> myProcessor() {
return item -> {
System.out.println("当前处理的数据:" + item);
if ("2".equals(item)) {
throw new MyJobExecutionException("任务处理出错");
} else {
return item;
}
};
}
} | repos\SpringAll-master\72.spring-batch-exception\src\main\java\cc\mrbird\batch\job\SkipExceptionJobDemo.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void deleteComment(User me, int commentId) {
Comment comment = commentRepository
.findById(commentId)
.orElseThrow(() -> new NoSuchElementException("Comment not found by id: `%d`".formatted(commentId)));
if (!comment.isWritten(me)) {
throw new IllegalArgumentException("You can't delete comments written by others.");
}
commentRepository.delete(comment);
}
@Transactional
public ArticleVO favoriteArticle(User me, String slug) {
Article article = findBySlug(slug); | return me.favorite(article);
}
@Transactional
public ArticleVO unfavoriteArticle(User me, String slug) {
Article article = findBySlug(slug);
return me.unfavorite(article);
}
private Article findBySlug(String slug) {
return articleRepository
.findBySlug(slug)
.orElseThrow(() -> new NoSuchElementException("Article not found by slug: `%s`".formatted(slug)));
}
} | repos\realworld-spring-boot-native-master\src\main\java\com\softwaremill\realworld\application\article\service\ArticleService.java | 2 |
请完成以下Java代码 | private static void parseYAMLFile() {
SwaggerParseResult result = new OpenAPIParser().readLocation("sample.json", null, null);
OpenAPI openAPI = result.getOpenAPI();
if (openAPI != null) {
printData(openAPI);
}
}
private static void printData(OpenAPI openAPI) {
System.out.println(openAPI.getSpecVersion());
Info info = openAPI.getInfo();
System.out.println(info.getTitle());
System.out.println(info.getVersion());
List<Server> servers = openAPI.getServers();
for (Server server : servers) {
System.out.println(server.getUrl());
System.out.println(server.getDescription());
}
Paths paths = openAPI.getPaths();
paths.entrySet() | .forEach(pathEntry -> {
System.out.println(pathEntry.getKey());
PathItem path = pathEntry.getValue();
System.out.println(path.getGet()
.getSummary());
System.out.println(path.getGet()
.getDescription());
System.out.println(path.getGet()
.getOperationId());
ApiResponses responses = path.getGet()
.getResponses();
responses.entrySet()
.forEach(responseEntry -> {
System.out.println(responseEntry.getKey());
ApiResponse response = responseEntry.getValue();
System.out.println(response.getDescription());
});
});
}
} | repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\swaggerparser\SwaggerParser.java | 1 |
请完成以下Java代码 | public static String getPosition(String dbPath,String ip,boolean format) {
// 1、create searcher object
Searcher searcher = null;
try {
searcher = Searcher.newWithFileOnly(dbPath);
} catch (IOException e) {
throw new RuntimeException(e);
}
// 2、query
try {
String region = searcher.search(ip);
if (format){
return region;
}
String[] split = region.split("\\|");
String s = split[0] + split[2] + split[3];
return s;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @Description :
* @Author : mabo
*/
public static String getIndexCachePosition(String dbPath, String ip, boolean format) {
Searcher searcher = null;
byte[] vIndex;
try {
vIndex = Searcher.loadVectorIndexFromFile(dbPath);
} catch (Exception e) {
throw new RuntimeException(e);
}
try {
searcher = Searcher.newWithVectorIndex(dbPath, vIndex);
} catch (Exception e) {
throw new RuntimeException(e);
}
try {
String region = searcher.search(ip);
if (format){
return region;
}
String[] split = region.split("\\|");
String s = split[0] + split[2] + split[3];
return s;
} catch (Exception e) {
throw new RuntimeException(e);
}
} | /**
* @Description :
* @Author : mabo
*/
public static String getCachePosition(String dbPath,String ip,boolean format) {
byte[] cBuff;
try {
cBuff = Searcher.loadContentFromFile(dbPath);
} catch (Exception e) {
throw new RuntimeException(e);
}
Searcher searcher;
try {
searcher = Searcher.newWithBuffer(cBuff);
} catch (Exception e) {
throw new RuntimeException(e);
}
try {
String region = searcher.search(ip);
if (format){
return region;
}
String[] split = region.split("\\|");
String s = split[0] + split[2] + split[3];
return s;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
} | repos\springboot-demo-master\ipfilter\src\main\java\com\et\ipfilter\util\SearcherIPUtils.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class EmptyEmailParams implements IEmailParameters {
@Override
public String getAttachmentPrefix(String defaultValue) {
return null;
}
@Override
public MADBoilerPlate getDefaultTextPreset() {
return null;
}
@Override
public String getExportFilePrefix() {
return null;
}
@Override
public I_AD_User getFrom() {
return null;
}
@Override
public String getMessage() { | return null;
}
@Override
public String getSubject() {
return null;
}
@Override
public String getTitle() {
return null;
}
@Override
public String getTo() {
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\compiere\report\email\service\impl\EmptyEmailParams.java | 2 |
请完成以下Java代码 | private void syncOrderLineWithAvailableForSales(@NonNull final I_C_OrderLine orderLineRecord)
{
if (!availableForSalesUtil.isOrderLineEligibleForFeature(orderLineRecord))
{
return;
}
final boolean isOrderEligibleForFeature = availableForSalesUtil.isOrderEligibleForFeature(OrderId.ofRepoId(orderLineRecord.getC_Order_ID()));
if (!isOrderEligibleForFeature)
{
return;
}
final AvailableForSalesConfig config = getAvailableForSalesConfig(orderLineRecord);
if (!config.isFeatureEnabled()) | {
return; // nothing to do
}
availableForSalesUtil.syncAvailableForSalesForOrderLine(orderLineRecord, config);
}
@NonNull
private AvailableForSalesConfig getAvailableForSalesConfig(@NonNull final I_C_OrderLine orderLineRecord)
{
return availableForSalesConfigRepo.getConfig(
AvailableForSalesConfigRepo.ConfigQuery.builder()
.clientId(ClientId.ofRepoId(orderLineRecord.getAD_Client_ID()))
.orgId(OrgId.ofRepoId(orderLineRecord.getAD_Org_ID()))
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\availableforsales\interceptor\C_OrderLine.java | 1 |
请完成以下Java代码 | protected boolean matchesNonNull(String rawPassword, String encodedPassword) {
Argon2EncodingUtils.Argon2Hash decoded;
try {
decoded = Argon2EncodingUtils.decode(encodedPassword);
}
catch (IllegalArgumentException ex) {
this.logger.warn("Malformed password hash", ex);
return false;
}
byte[] hashBytes = new byte[decoded.getHash().length];
Argon2BytesGenerator generator = new Argon2BytesGenerator();
generator.init(decoded.getParameters());
generator.generateBytes(rawPassword.toString().toCharArray(), hashBytes);
return constantTimeArrayEquals(decoded.getHash(), hashBytes);
}
@Override
protected boolean upgradeEncodingNonNull(String encodedPassword) { | Argon2Parameters parameters = Argon2EncodingUtils.decode(encodedPassword).getParameters();
return parameters.getMemory() < this.memory || parameters.getIterations() < this.iterations;
}
private static boolean constantTimeArrayEquals(byte[] expected, byte[] actual) {
if (expected.length != actual.length) {
return false;
}
int result = 0;
for (int i = 0; i < expected.length; i++) {
result |= expected[i] ^ actual[i];
}
return result == 0;
}
} | repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\argon2\Argon2PasswordEncoder.java | 1 |
请完成以下Java代码 | public CountResultDto queryHistoricTaskInstancesCount(HistoricTaskInstanceQueryDto queryDto) {
queryDto.setObjectMapper(objectMapper);
HistoricTaskInstanceQuery query = queryDto.toQuery(processEngine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
@Override
public Response getHistoricTaskInstanceReport(UriInfo uriInfo) {
HistoricTaskInstanceReportQueryDto queryDto = new HistoricTaskInstanceReportQueryDto(objectMapper, uriInfo.getQueryParameters());
Response response;
if (AbstractReportDto.REPORT_TYPE_DURATION.equals(queryDto.getReportType())) {
List<? extends ReportResult> reportResults = queryDto.executeReport(processEngine);
response = Response.ok(generateDurationDto(reportResults)).build();
} else if (AbstractReportDto.REPORT_TYPE_COUNT.equals(queryDto.getReportType())) {
List<HistoricTaskInstanceReportResult> reportResults = queryDto.executeCompletedReport(processEngine);
response = Response.ok(generateCountDto(reportResults)).build();
} else {
throw new InvalidRequestException(Response.Status.BAD_REQUEST, "Parameter reportType is not set.");
} | return response;
}
protected List<HistoricTaskInstanceReportResultDto> generateCountDto(List<HistoricTaskInstanceReportResult> results) {
List<HistoricTaskInstanceReportResultDto> dtoList = new ArrayList<HistoricTaskInstanceReportResultDto>();
for( HistoricTaskInstanceReportResult result : results ) {
dtoList.add(HistoricTaskInstanceReportResultDto.fromHistoricTaskInstanceReportResult(result));
}
return dtoList;
}
protected List<ReportResultDto> generateDurationDto(List<? extends ReportResult> results) {
List<ReportResultDto> dtoList = new ArrayList<ReportResultDto>();
for( ReportResult result : results ) {
dtoList.add(ReportResultDto.fromReportResult(result));
}
return dtoList;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricTaskInstanceRestServiceImpl.java | 1 |
请完成以下Java代码 | public int getAD_Window_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Window_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Lesen und Schreiben.
@param IsReadWrite
Field is read / write
*/
@Override
public void setIsReadWrite (boolean IsReadWrite)
{
set_Value (COLUMNNAME_IsReadWrite, Boolean.valueOf(IsReadWrite));
} | /** Get Lesen und Schreiben.
@return Field is read / write
*/
@Override
public boolean isReadWrite ()
{
Object oo = get_Value(COLUMNNAME_IsReadWrite);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Window_Access.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
} | public boolean isEligibleToVote() {
return eligibleToVote;
}
public void setEligibleToVote(boolean eligibleToVote) {
this.eligibleToVote = eligibleToVote;
}
public boolean isPriorityVoter() {
return priorityVoter;
}
public void setPriorityVoter(boolean priorityVoter) {
this.priorityVoter = priorityVoter;
}
} | repos\tutorials-master\drools\src\main\java\com\baeldung\drools\matched_rules\Person.java | 1 |
请完成以下Java代码 | public void onPharmaPermissionChanged_Vendor(final I_C_BPartner vendor)
{
final PharmaVendorPermissions permissions = PharmaVendorPermissions.of(vendor);
if (!vendor.isVendor())
{
vendor.setReceiptPermissionPharma(null);
vendor.setReceiptPermissionChangeDate(null);
}
else if (permissions.hasPermission(PharmaVendorPermission.PHARMA_NARCOTICS))
{
vendor.setReceiptPermissionPharma(I_C_BPartner.ReceiptPermissionPharma_TypeC);
vendor.setReceiptPermissionChangeDate(SystemTime.asTimestamp());
}
else if (permissions.hasAtLeastOnePermission())
{
vendor.setReceiptPermissionPharma(I_C_BPartner.ReceiptPermissionPharma_TypeA);
vendor.setReceiptPermissionChangeDate(de.metas.common.util.time.SystemTime.asTimestamp());
}
else
{
vendor.setReceiptPermissionPharma(I_C_BPartner.ReceiptPermissionPharma_TypeB);
vendor.setReceiptPermissionChangeDate(null);
}
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = {
I_C_BPartner.COLUMNNAME_BTM,
I_C_BPartner.COLUMNNAME_IsPharmaCustomerNarcoticsPermission,
I_C_BPartner.COLUMNNAME_IsPharmaVendorNarcoticsPermission })
public void validateBTM(final I_C_BPartner partner)
{
final IMsgBL msgBL = Services.get(IMsgBL.class); | final String btm = partner.getBTM();
final boolean hasNarcoticPermission = partner.isPharmaCustomerNarcoticsPermission() || partner.isPharmaVendorNarcoticsPermission();
if (Check.isEmpty(btm))
{
if (hasNarcoticPermission)
{
throw new AdempiereException(ERR_NarcoticPermissions_Valid_BTM, partner)
.markAsUserValidationError();
}
// If the partner doesn't have permissions, BTM is not relevant.
return;
}
final boolean isValidBTM = PharmaModulo11Validator.isValid(btm);
if (!isValidBTM)
{
final ITranslatableString invalidBTMMessage = msgBL.getTranslatableMsgText(ERR_InvalidBTM, btm);
throw new AdempiereException(invalidBTMMessage)
.markAsUserValidationError();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\vertical\pharma\model\interceptor\C_BPartner.java | 1 |
请完成以下Java代码 | private Flux<String> resolveAccessTokenFromBody(ServerWebExchange exchange) {
ServerHttpRequest request = exchange.getRequest();
if (!this.allowFormEncodedBodyParameter
|| !MediaType.APPLICATION_FORM_URLENCODED.equals(request.getHeaders().getContentType())
|| !HttpMethod.POST.equals(request.getMethod())) {
return Flux.empty();
}
return exchange.getFormData().flatMapMany(ServerBearerTokenAuthenticationConverter::resolveTokens);
}
private static Flux<String> resolveTokens(MultiValueMap<String, String> parameters) {
List<String> accessTokens = parameters.get(ACCESS_TOKEN_PARAMETER_NAME);
return CollectionUtils.isEmpty(accessTokens) ? Flux.empty() : Flux.fromIterable(accessTokens);
}
/**
* Set if transport of access token using URI query parameter is supported. Defaults
* to {@code false}.
*
* The spec recommends against using this mechanism for sending bearer tokens, and
* even goes as far as stating that it was only included for completeness.
* @param allowUriQueryParameter if the URI query parameter is supported
*/
public void setAllowUriQueryParameter(boolean allowUriQueryParameter) {
this.allowUriQueryParameter = allowUriQueryParameter;
}
/**
* Set this value to configure what header is checked when resolving a Bearer Token.
* This value is defaulted to {@link HttpHeaders#AUTHORIZATION}.
*
* This allows other headers to be used as the Bearer Token source such as
* {@link HttpHeaders#PROXY_AUTHORIZATION}
* @param bearerTokenHeaderName the header to check when retrieving the Bearer Token.
* @since 5.4
*/ | public void setBearerTokenHeaderName(String bearerTokenHeaderName) {
this.bearerTokenHeaderName = bearerTokenHeaderName;
}
/**
* Set if transport of access token using form-encoded body parameter is supported.
* Defaults to {@code false}.
* @param allowFormEncodedBodyParameter if the form-encoded body parameter is
* supported
* @since 6.5
*/
public void setAllowFormEncodedBodyParameter(boolean allowFormEncodedBodyParameter) {
this.allowFormEncodedBodyParameter = allowFormEncodedBodyParameter;
}
} | repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\web\server\authentication\ServerBearerTokenAuthenticationConverter.java | 1 |
请完成以下Java代码 | protected AbstractResourceDefinitionManager<CaseDefinitionEntity> getManager() {
return Context.getCommandContext().getCaseDefinitionManager();
}
@Override
protected void checkInvalidDefinitionId(String definitionId) {
ensureNotNull("Invalid case definition id", "caseDefinitionId", definitionId);
}
@Override
protected void checkDefinitionFound(String definitionId, CaseDefinitionEntity definition) {
ensureNotNull(CaseDefinitionNotFoundException.class, "no deployed case definition found with id '" + definitionId + "'", "caseDefinition", definition);
}
@Override
protected void checkInvalidDefinitionByKey(String definitionKey, CaseDefinitionEntity definition) {
ensureNotNull(CaseDefinitionNotFoundException.class, "no case definition deployed with key '" + definitionKey + "'", "caseDefinition", definition);
}
@Override
protected void checkInvalidDefinitionByKeyAndTenantId(String definitionKey, String tenantId, CaseDefinitionEntity definition) {
ensureNotNull(CaseDefinitionNotFoundException.class, "no case definition deployed with key '" + definitionKey + "' and tenant-id '" + tenantId + "'", "caseDefinition", definition);
}
@Override
protected void checkInvalidDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId, CaseDefinitionEntity definition) {
ensureNotNull(CaseDefinitionNotFoundException.class, "no case definition deployed with key = '" + definitionKey + "', version = '" + definitionVersion + "'" | + " and tenant-id = '" + tenantId + "'", "caseDefinition", definition);
}
@Override
protected void checkInvalidDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId, CaseDefinitionEntity definition) {
throw new UnsupportedOperationException("Version tag is not implemented in case definition."); }
@Override
protected void checkInvalidDefinitionByDeploymentAndKey(String deploymentId, String definitionKey, CaseDefinitionEntity definition) {
ensureNotNull(CaseDefinitionNotFoundException.class, "no case definition deployed with key = '" + definitionKey + "' in deployment = '" + deploymentId + "'", "caseDefinition", definition);
}
@Override
protected void checkInvalidDefinitionWasCached(String deploymentId, String definitionId, CaseDefinitionEntity definition) {
ensureNotNull("deployment '" + deploymentId + "' didn't put case definition '" + definitionId + "' in the cache", "cachedCaseDefinition", definition);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\deploy\cache\CaseDefinitionCache.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public HikariDataSource getHikariDataSource(String url) {
com.zaxxer.hikari.HikariConfig config = new com.zaxxer.hikari.HikariConfig();
config.setMinimumIdle(minIdle);
config.setMaximumPoolSize(maxActive);
config.setConnectionTestQuery(validationQuery);
config.setJdbcUrl(url);
config.setUsername(userName);
config.setPassword(password);
config.setDriverClassName(driverClassName);
config.setConnectionTimeout(connectionTimeout);
config.setMaxLifetime(maxLeftTime);
config.setValidationTimeout(validationTimeout);
config.setConnectionInitSql(connectionInitSql);
return new HikariDataSource(config);
}
/**
* 用于两个库账号密码不一样的时候
*
* @param url
* @param userName
* @param passwod
* @return | */
public HikariDataSource getHikariDataSource(String url, String userName, String passwod) {
com.zaxxer.hikari.HikariConfig config = new com.zaxxer.hikari.HikariConfig();
config.setMinimumIdle(minIdle);
config.setMaximumPoolSize(maxActive);
config.setConnectionTestQuery(validationQuery);
config.setJdbcUrl(url);
config.setUsername(userName);
config.setPassword(passwod);
config.setConnectionTimeout(connectionTimeout);
config.setDriverClassName(driverClassName);
config.setMaxLifetime(maxLeftTime);
config.setValidationTimeout(validationTimeout);
config.setConnectionInitSql(connectionInitSql);
return new HikariDataSource(config);
}
} | repos\springBoot-master\springboot-dynamicDataSource\src\main\java\cn\abel\config\HikariConfig.java | 2 |
请完成以下Java代码 | public BPartnerAwareAttributeUpdater setSourceModel(final Object sourceModel)
{
this.sourceModel = sourceModel;
return this;
}
private Object getSourceModel()
{
Check.assumeNotNull(sourceModel, "sourceModel not null");
return sourceModel;
}
private String getSourceTableName()
{
return InterfaceWrapperHelper.getModelTableName(getSourceModel());
}
public BPartnerAwareAttributeUpdater setBPartnerAwareFactory(final IBPartnerAwareFactory bpartnerAwareFactory)
{
this.bpartnerAwareFactory = bpartnerAwareFactory;
return this;
}
private IBPartnerAwareFactory getBPartnerAwareFactory()
{
Check.assumeNotNull(bpartnerAwareFactory, "bpartnerAwareFactory not null");
return bpartnerAwareFactory; | }
public final BPartnerAwareAttributeUpdater setBPartnerAwareAttributeService(final IBPartnerAwareAttributeService bpartnerAwareAttributeService)
{
this.bpartnerAwareAttributeService = bpartnerAwareAttributeService;
return this;
}
private IBPartnerAwareAttributeService getBPartnerAwareAttributeService()
{
Check.assumeNotNull(bpartnerAwareAttributeService, "bpartnerAwareAttributeService not null");
return bpartnerAwareAttributeService;
}
/**
* Sets if we shall copy the attribute even if it's a sales transaction (i.e. IsSOTrx=true)
*/
public final BPartnerAwareAttributeUpdater setForceApplyForSOTrx(final boolean forceApplyForSOTrx)
{
this.forceApplyForSOTrx = forceApplyForSOTrx;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\api\impl\BPartnerAwareAttributeUpdater.java | 1 |
请完成以下Java代码 | public Advice getAdvice() {
return this;
}
@Override
public boolean isPerInstance() {
return true;
}
@Override
public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
} | private static final class FilterTarget {
private final Publisher<?> value;
private final int index;
private FilterTarget(Publisher<?> value, int index) {
this.value = value;
this.index = index;
}
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\PreFilterAuthorizationReactiveMethodInterceptor.java | 1 |
请完成以下Java代码 | public void start() {
log.info("Creating Store Procedures and Function...");
jdbcTemplate.execute(SQL_STORED_PROC);
/* Test Stored Procedure */
Book book = findById(2L).orElseThrow(IllegalArgumentException::new);
// Book{id=2, name='Mkyong in Java', price=1.99}
System.out.println(book);
}
Optional<Book> findById(Long id) {
SqlParameterSource in = new MapSqlParameterSource()
.addValue("p_id", id);
Optional result = Optional.empty();
try {
Map out = simpleJdbcCall.execute(in);
if (out != null) { | Book book = new Book();
book.setId(id);
book.setName((String) out.get("O_NAME"));
book.setPrice((BigDecimal) out.get("O_PRICE"));
result = Optional.of(book);
}
} catch (Exception e) {
// ORA-01403: no data found, or any java.sql.SQLException
System.err.println(e.getMessage());
}
return result;
}
} | repos\spring-boot-master\spring-jdbc\src\main\java\com\mkyong\sp\StoredProcedure1.java | 1 |
请完成以下Java代码 | private ViewHeaderProperties computeHeaderProperties()
{
final CurrencyCode currencyCode = viewDataService.currencyCodeConverter().getCurrencyCodeByCurrencyId(getGLJournal().getCurrencyId());
final MutableAmount totalDebit = MutableAmount.zero(currencyCode);
final MutableAmount totalCredit = MutableAmount.zero(currencyCode);
rowsHolder.stream(OIRow::isSelected)
.forEach(row -> {
final Amount openAmount = row.getOpenAmountEffective();
if (row.getPostingSign().isDebit())
{
totalDebit.add(openAmount);
}
else
{
totalCredit.add(openAmount);
}
});
final Amount balance = totalDebit.toAmount().subtract(totalCredit.toAmount());
return ViewHeaderProperties.builder()
.group(ViewHeaderPropertiesGroup.builder()
.entry(ViewHeaderProperty.builder()
.fieldName("totalDebit")
.caption(TranslatableStrings.adElementOrMessage("TotalDr"))
.value(TranslatableStrings.amount(totalDebit.toAmount()))
.build())
.entry(ViewHeaderProperty.builder()
.fieldName("totalCredit")
.caption(TranslatableStrings.adElementOrMessage("TotalCr"))
.value(TranslatableStrings.amount(totalCredit.toAmount()))
.build())
.entry(ViewHeaderProperty.builder()
.fieldName("balance")
.caption(TranslatableStrings.adElementOrMessage("Balance"))
.value(TranslatableStrings.amount(balance))
.build())
.build())
.build();
}
@Override
public void patchRow(final IEditableView.RowEditingContext ctx, final List<JSONDocumentChangedEvent> fieldChangeRequests)
{
rowsHolder.changeRowById(ctx.getRowId(), row -> applyChanges(row, fieldChangeRequests));
headerPropertiesHolder.setValue(null);
ViewChangesCollector.getCurrentOrAutoflush().collectHeaderPropertiesChanged(ctx.getViewId());
// NOTE: don't need to notify about row changed because that will be returned by the REST call
} | private static OIRow applyChanges(@NonNull final OIRow row, @NonNull final List<JSONDocumentChangedEvent> fieldChangeRequests)
{
final OIRow.OIRowBuilder changedRowBuilder = row.toBuilder();
for (final JSONDocumentChangedEvent event : fieldChangeRequests)
{
event.assertReplaceOperation();
if (OIRow.FIELD_Selected.equals(event.getPath()))
{
changedRowBuilder.selected(event.getValueAsBoolean(false));
}
}
return changedRowBuilder.build();
}
public void markRowsAsSelected(final DocumentIdsSelection rowIds)
{
rowsHolder.changeRowsByIds(rowIds, row -> row.withSelected(true));
headerPropertiesHolder.setValue(null);
}
public boolean hasSelectedRows()
{
return rowsHolder.anyMatch(OIRow::isSelected);
}
public void clearUserInput()
{
rowsHolder.changeRowsByIds(DocumentIdsSelection.ALL, OIRow::withUserInputCleared);
headerPropertiesHolder.setValue(null);
}
public OIRowUserInputParts getUserInput() {return OIRowUserInputParts.ofStream(rowsHolder.stream());}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.webui\src\main\java\de\metas\acct\gljournal_sap\select_open_items\OIViewData.java | 1 |
请完成以下Java代码 | public Criteria andTagIdIn(List<Long> values) {
addCriterion("tag_id in", values, "tagId");
return (Criteria) this;
}
public Criteria andTagIdNotIn(List<Long> values) {
addCriterion("tag_id not in", values, "tagId");
return (Criteria) this;
}
public Criteria andTagIdBetween(Long value1, Long value2) {
addCriterion("tag_id between", value1, value2, "tagId");
return (Criteria) this;
}
public Criteria andTagIdNotBetween(Long value1, Long value2) {
addCriterion("tag_id not between", value1, value2, "tagId");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
} | protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberMemberTagRelationExample.java | 1 |
请完成以下Java代码 | public void setAD_Column_ID (int AD_Column_ID)
{
if (AD_Column_ID < 1)
set_Value (COLUMNNAME_AD_Column_ID, null);
else
set_Value (COLUMNNAME_AD_Column_ID, Integer.valueOf(AD_Column_ID));
}
/** Get Column.
@return Column in the table
*/
public int getAD_Column_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Column_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Report view Column.
@param AD_ReportView_Col_ID Report view Column */
public void setAD_ReportView_Col_ID (int AD_ReportView_Col_ID)
{
if (AD_ReportView_Col_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_ReportView_Col_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_ReportView_Col_ID, Integer.valueOf(AD_ReportView_Col_ID));
}
/** Get Report view Column.
@return Report view Column */
public int getAD_ReportView_Col_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_ReportView_Col_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_AD_ReportView getAD_ReportView() throws RuntimeException
{
return (I_AD_ReportView)MTable.get(getCtx(), I_AD_ReportView.Table_Name)
.getPO(getAD_ReportView_ID(), get_TrxName()); }
/** Set Report View.
@param AD_ReportView_ID
View used to generate this report
*/
public void setAD_ReportView_ID (int AD_ReportView_ID)
{
if (AD_ReportView_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_ReportView_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_ReportView_ID, Integer.valueOf(AD_ReportView_ID));
}
/** Get Report View.
@return View used to generate this report
*/
public int getAD_ReportView_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_ReportView_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getAD_ReportView_ID()));
}
/** Set Function Column.
@param FunctionColumn
Overwrite Column with Function
*/
public void setFunctionColumn (String FunctionColumn) | {
set_Value (COLUMNNAME_FunctionColumn, FunctionColumn);
}
/** Get Function Column.
@return Overwrite Column with Function
*/
public String getFunctionColumn ()
{
return (String)get_Value(COLUMNNAME_FunctionColumn);
}
/** Set SQL Group Function.
@param IsGroupFunction
This function will generate a Group By Clause
*/
public void setIsGroupFunction (boolean IsGroupFunction)
{
set_Value (COLUMNNAME_IsGroupFunction, Boolean.valueOf(IsGroupFunction));
}
/** Get SQL Group Function.
@return This function will generate a Group By Clause
*/
public boolean isGroupFunction ()
{
Object oo = get_Value(COLUMNNAME_IsGroupFunction);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ReportView_Col.java | 1 |
请完成以下Java代码 | public class X_AD_Message_Trl extends org.compiere.model.PO implements I_AD_Message_Trl, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -923986697L;
/** Standard Constructor */
public X_AD_Message_Trl (final Properties ctx, final int AD_Message_Trl_ID, @Nullable final String trxName)
{
super (ctx, AD_Message_Trl_ID, trxName);
}
/** Load Constructor */
public X_AD_Message_Trl (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
/**
* AD_Language AD_Reference_ID=106
* Reference name: AD_Language
*/
public static final int AD_LANGUAGE_AD_Reference_ID=106;
@Override
public void setAD_Language (final java.lang.String AD_Language)
{
set_ValueNoCheck (COLUMNNAME_AD_Language, AD_Language);
}
@Override
public java.lang.String getAD_Language()
{
return get_ValueAsString(COLUMNNAME_AD_Language);
}
@Override
public void setAD_Message_ID (final int AD_Message_ID)
{
if (AD_Message_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Message_ID, null);
else | set_ValueNoCheck (COLUMNNAME_AD_Message_ID, AD_Message_ID);
}
@Override
public int getAD_Message_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Message_ID);
}
@Override
public void setIsTranslated (final boolean IsTranslated)
{
set_Value (COLUMNNAME_IsTranslated, IsTranslated);
}
@Override
public boolean isTranslated()
{
return get_ValueAsBoolean(COLUMNNAME_IsTranslated);
}
@Override
public void setMsgText (final java.lang.String MsgText)
{
set_Value (COLUMNNAME_MsgText, MsgText);
}
@Override
public java.lang.String getMsgText()
{
return get_ValueAsString(COLUMNNAME_MsgText);
}
@Override
public void setMsgTip (final @Nullable java.lang.String MsgTip)
{
set_Value (COLUMNNAME_MsgTip, MsgTip);
}
@Override
public java.lang.String getMsgTip()
{
return get_ValueAsString(COLUMNNAME_MsgTip);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Message_Trl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserServiceImpl implements IUserService {
private final UserDao userDao;
@Autowired
public UserServiceImpl(UserDao userDao) {
this.userDao = userDao;
}
/**
* 保存用户
*
* @param user 用户实体
* @return 保存成功 {@code true} 保存失败 {@code false}
*/
@Override
public Boolean save(User user) {
String rawPass = user.getPassword();
String salt = IdUtil.simpleUUID();
String pass = SecureUtil.md5(rawPass + Const.SALT_PREFIX + salt);
user.setPassword(pass);
user.setSalt(salt);
return userDao.insert(user) > 0;
}
/**
* 删除用户
*
* @param id 主键id
* @return 删除成功 {@code true} 删除失败 {@code false}
*/
@Override
public Boolean delete(Long id) {
return userDao.delete(id) > 0;
}
/**
* 更新用户
*
* @param user 用户实体
* @param id 主键id
* @return 更新成功 {@code true} 更新失败 {@code false} | */
@Override
public Boolean update(User user, Long id) {
User exist = getUser(id);
if (StrUtil.isNotBlank(user.getPassword())) {
String rawPass = user.getPassword();
String salt = IdUtil.simpleUUID();
String pass = SecureUtil.md5(rawPass + Const.SALT_PREFIX + salt);
user.setPassword(pass);
user.setSalt(salt);
}
BeanUtil.copyProperties(user, exist, CopyOptions.create().setIgnoreNullValue(true));
exist.setLastUpdateTime(new DateTime());
return userDao.update(exist, id) > 0;
}
/**
* 获取单个用户
*
* @param id 主键id
* @return 单个用户对象
*/
@Override
public User getUser(Long id) {
return userDao.findOneById(id);
}
/**
* 获取用户列表
*
* @param user 用户实体
* @return 用户列表
*/
@Override
public List<User> getUser(User user) {
return userDao.findByExample(user);
}
} | repos\spring-boot-demo-master\demo-orm-jdbctemplate\src\main\java\com\xkcoding\orm\jdbctemplate\service\impl\UserServiceImpl.java | 2 |
请完成以下Java代码 | private static class Caption
{
@Getter
@NonNull private final String columnName;
@NonNull private final String baseAD_Language;
@NonNull private final LinkedHashMap<String, String> translations;
@Nullable private transient ITranslatableString computedTrl = null;
private Caption(
@NonNull final String columnName,
@NonNull final String baseAD_Language)
{
this.columnName = columnName;
this.baseAD_Language = baseAD_Language;
this.translations = new LinkedHashMap<>(5);
}
private Caption(@NonNull final GridTabVO.Caption from)
{
this.columnName = from.columnName;
this.baseAD_Language = from.baseAD_Language;
this.translations = new LinkedHashMap<>(from.translations);
this.computedTrl = from.computedTrl;
}
public Caption copy()
{
return new Caption(this);
}
public void putTranslation(@NonNull final String adLanguage, @Nullable final String captionTrl)
{
Check.assumeNotEmpty(adLanguage, "adLanguage is not empty");
final String captionTrlNorm = captionTrl != null ? captionTrl.trim() : "";
if (!captionTrlNorm.isEmpty())
{
translations.put(adLanguage, captionTrlNorm);
}
else
{
translations.remove(adLanguage);
} | computedTrl = null;
}
public ITranslatableString toTranslatableString()
{
ITranslatableString computedTrl = this.computedTrl;
if (computedTrl == null)
{
computedTrl = this.computedTrl = computeTranslatableString();
}
return computedTrl;
}
private ITranslatableString computeTranslatableString()
{
if (translations.isEmpty())
{
return TranslatableStrings.empty();
}
else if (translations.size() == 1)
{
final Map.Entry<String, String> firstEntry = translations.entrySet().iterator().next();
final String adLanguage = firstEntry.getKey();
final String value = firstEntry.getValue();
return TranslatableStrings.singleLanguage(adLanguage, value);
}
else
{
String defaultValue = translations.get(baseAD_Language);
if (defaultValue == null)
{
defaultValue = translations.values().iterator().next();
}
return TranslatableStrings.ofMap(translations, defaultValue);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridTabVO.java | 1 |
请完成以下Java代码 | public void init(ServletConfig config) throws ServletException
{
// NOTE: actually here we are starting all servers
m_serverMgr = AdempiereServerMgr.get();
}
/**
* Destroy
*/
@Override
public void destroy()
{
log.info("destroy");
m_serverMgr = null;
} // destroy
/**
* Log error/warning
*
* @param message message
* @param e exception
*/
@Override
public void log(final String message, final Throwable e)
{
if (e == null)
{
log.warn(message);
}
log.error(message, e);
} // log
/**
* Log debug | *
* @param message message
*/
@Override
public void log(String message)
{
log.debug(message);
} // log
@Override
public String getServletName()
{
return NAME;
}
@Override
public String getServletInfo()
{
return "Server Monitor";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\adempiere\serverRoot\servlet\ServerMonitor.java | 1 |
请完成以下Java代码 | public boolean isNumericKey()
{
return false;
}
@Override
public LookupDataSourceFetcher getLookupDataSourceFetcher()
{
return this;
}
@Override
public LookupDataSourceContext.Builder newContextForFetchingById(final Object id)
{
return LookupDataSourceContext.builder(tableName)
.putFilterById(IdsToFilter.ofSingleValue(id));
}
@Override
public LookupValue retrieveLookupValueById(final @NonNull LookupDataSourceContext evalCtx)
{
final Object id = evalCtx.getSingleIdToFilterAsObject();
if (id == null)
{
throw new IllegalStateException("No ID provided in " + evalCtx);
}
return labelsValuesLookupDataSource.findById(id);
}
@Override
public LookupDataSourceContext.Builder newContextForFetchingList()
{
return LookupDataSourceContext.builder(tableName)
.setRequiredParameters(parameters)
.requiresAD_Language()
.requiresUserRolePermissionsKey();
}
@Override
public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx)
{
final String filter = evalCtx.getFilter();
return labelsValuesLookupDataSource.findEntities(evalCtx, filter);
}
public Set<Object> normalizeStringIds(final Set<String> stringIds)
{
if (stringIds.isEmpty())
{
return ImmutableSet.of(); | }
if (isLabelsValuesUseNumericKey())
{
return stringIds.stream()
.map(LabelsLookup::convertToInt)
.collect(ImmutableSet.toImmutableSet());
}
else
{
return ImmutableSet.copyOf(stringIds);
}
}
private static int convertToInt(final String stringId)
{
try
{
return Integer.parseInt(stringId);
}
catch (final Exception ex)
{
throw new AdempiereException("Failed converting `" + stringId + "` to int.", ex);
}
}
public ColumnSql getSqlForFetchingValueIdsByLinkId(@NonNull final String tableNameOrAlias)
{
final String sql = "SELECT array_agg(" + labelsValueColumnName + ")"
+ " FROM " + labelsTableName
+ " WHERE " + labelsLinkColumnName + "=" + tableNameOrAlias + "." + linkColumnName
+ " AND IsActive='Y'";
return ColumnSql.ofSql(sql, tableNameOrAlias);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\LabelsLookup.java | 1 |
请完成以下Java代码 | private Props getConfig(String fileName) {
Props props = new Props(fileName);
props.autoLoad(true);
return props;
}
/**
* 获取文件名
*/
private String getFileName(String template, String className, String packageName, String moduleName) {
// 包路径
String packagePath = GenConstants.SIGNATURE + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator;
// 资源路径
String resourcePath = GenConstants.SIGNATURE + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator;
// api路径
String apiPath = GenConstants.SIGNATURE + File.separator + "api" + File.separator;
if (StrUtil.isNotBlank(packageName)) {
packagePath += packageName.replace(".", File.separator) + File.separator + moduleName + File.separator;
}
if (template.contains(ENTITY_JAVA_VM)) {
return packagePath + "entity" + File.separator + className + ".java";
}
if (template.contains(MAPPER_JAVA_VM)) {
return packagePath + "mapper" + File.separator + className + "Mapper.java";
}
if (template.contains(SERVICE_JAVA_VM)) {
return packagePath + "service" + File.separator + className + "Service.java";
}
if (template.contains(SERVICE_IMPL_JAVA_VM)) { | return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
}
if (template.contains(CONTROLLER_JAVA_VM)) {
return packagePath + "controller" + File.separator + className + "Controller.java";
}
if (template.contains(MAPPER_XML_VM)) {
return resourcePath + "mapper" + File.separator + className + "Mapper.xml";
}
if (template.contains(API_JS_VM)) {
return apiPath + className.toLowerCase() + ".js";
}
return null;
}
} | repos\spring-boot-demo-master\demo-codegen\src\main\java\com\xkcoding\codegen\utils\CodeGenUtil.java | 1 |
请完成以下Java代码 | public final class ClearSiteDataHeaderWriter implements HeaderWriter {
private static final String CLEAR_SITE_DATA_HEADER = "Clear-Site-Data";
private final Log logger = LogFactory.getLog(getClass());
private final RequestMatcher requestMatcher;
private String headerValue;
/**
* <p>
* Creates a new instance of {@link ClearSiteDataHeaderWriter} with given sources. The
* constructor also initializes <b>requestMatcher</b> with a new instance of
* <b>SecureRequestMatcher</b> to ensure that header is only applied if and when the
* request is secure as per the <b>Incomplete Clearing</b> section.
* </p>
* @param directives (i.e. "cache", "cookies", "storage", "executionContexts" or "*")
* @throws IllegalArgumentException if sources is null or empty.
*/
public ClearSiteDataHeaderWriter(Directive... directives) {
Assert.notEmpty(directives, "directives cannot be empty or null");
this.requestMatcher = new SecureRequestMatcher();
this.headerValue = transformToHeaderValue(directives);
}
@Override
public void writeHeaders(HttpServletRequest request, HttpServletResponse response) {
if (this.requestMatcher.matches(request)) {
if (!response.containsHeader(CLEAR_SITE_DATA_HEADER)) {
response.setHeader(CLEAR_SITE_DATA_HEADER, this.headerValue);
}
return;
}
this.logger.debug(
LogMessage.format("Not injecting Clear-Site-Data header since it did not match the requestMatcher %s",
this.requestMatcher));
}
private String transformToHeaderValue(Directive... directives) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < directives.length - 1; i++) {
sb.append(directives[i].headerValue).append(", ");
}
sb.append(directives[directives.length - 1].headerValue);
return sb.toString();
}
@Override
public String toString() {
return getClass().getName() + " [headerValue=" + this.headerValue + "]";
}
/** | * Represents the directive values expected by the {@link ClearSiteDataHeaderWriter}.
*/
public enum Directive {
CACHE("cache"),
COOKIES("cookies"),
STORAGE("storage"),
EXECUTION_CONTEXTS("executionContexts"),
ALL("*");
private final String headerValue;
Directive(String headerValue) {
this.headerValue = "\"" + headerValue + "\"";
}
public String getHeaderValue() {
return this.headerValue;
}
}
private static final class SecureRequestMatcher implements RequestMatcher {
@Override
public boolean matches(HttpServletRequest request) {
return request.isSecure();
}
@Override
public String toString() {
return "Is Secure";
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\writers\ClearSiteDataHeaderWriter.java | 1 |
请完成以下Java代码 | public List<CaseExecutionDto> queryCaseExecutions(CaseExecutionQueryDto queryDto, Integer firstResult, Integer maxResults) {
ProcessEngine engine = getProcessEngine();
queryDto.setObjectMapper(getObjectMapper());
CaseExecutionQuery query = queryDto.toQuery(engine);
List<CaseExecution> matchingExecutions = QueryUtil.list(query, firstResult, maxResults);
List<CaseExecutionDto> executionResults = new ArrayList<CaseExecutionDto>();
for (CaseExecution execution : matchingExecutions) {
CaseExecutionDto resultExecution = CaseExecutionDto.fromCaseExecution(execution);
executionResults.add(resultExecution);
}
return executionResults;
}
@Override
public CountResultDto getCaseExecutionsCount(UriInfo uriInfo) {
CaseExecutionQueryDto queryDto = new CaseExecutionQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
return queryCaseExecutionsCount(queryDto);
} | @Override
public CountResultDto queryCaseExecutionsCount(CaseExecutionQueryDto queryDto) {
ProcessEngine engine = getProcessEngine();
queryDto.setObjectMapper(getObjectMapper());
CaseExecutionQuery query = queryDto.toQuery(engine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\CaseExecutionRestServiceImpl.java | 1 |
请完成以下Java代码 | public boolean isDeletionLog() {
return deletionLog;
}
public Date getRemovalTime() {
return removalTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public static HistoricExternalTaskLogDto fromHistoricExternalTaskLog(HistoricExternalTaskLog historicExternalTaskLog) {
HistoricExternalTaskLogDto result = new HistoricExternalTaskLogDto();
result.id = historicExternalTaskLog.getId();
result.timestamp = historicExternalTaskLog.getTimestamp();
result.removalTime = historicExternalTaskLog.getRemovalTime();
result.externalTaskId = historicExternalTaskLog.getExternalTaskId();
result.topicName = historicExternalTaskLog.getTopicName();
result.workerId = historicExternalTaskLog.getWorkerId();
result.priority = historicExternalTaskLog.getPriority();
result.retries = historicExternalTaskLog.getRetries();
result.errorMessage = historicExternalTaskLog.getErrorMessage();
result.activityId = historicExternalTaskLog.getActivityId(); | result.activityInstanceId = historicExternalTaskLog.getActivityInstanceId();
result.executionId = historicExternalTaskLog.getExecutionId();
result.processInstanceId = historicExternalTaskLog.getProcessInstanceId();
result.processDefinitionId = historicExternalTaskLog.getProcessDefinitionId();
result.processDefinitionKey = historicExternalTaskLog.getProcessDefinitionKey();
result.tenantId = historicExternalTaskLog.getTenantId();
result.rootProcessInstanceId = historicExternalTaskLog.getRootProcessInstanceId();
result.creationLog = historicExternalTaskLog.isCreationLog();
result.failureLog = historicExternalTaskLog.isFailureLog();
result.successLog = historicExternalTaskLog.isSuccessLog();
result.deletionLog = historicExternalTaskLog.isDeletionLog();
return result;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricExternalTaskLogDto.java | 1 |
请完成以下Java代码 | public class CommonContainerStoppingErrorHandler extends KafkaExceptionLogLevelAware implements CommonErrorHandler {
private final Executor executor;
private boolean stopContainerAbnormally = true;
/**
* Construct an instance with a default {@link SimpleAsyncTaskExecutor}.
*/
public CommonContainerStoppingErrorHandler() {
this(new SimpleAsyncTaskExecutor("containerStop-"));
}
/**
* Construct an instance with the provided {@link Executor}.
* @param executor the executor.
*/
public CommonContainerStoppingErrorHandler(Executor executor) {
Assert.notNull(executor, "'executor' cannot be null");
this.executor = executor;
}
/**
* Set to false to stop the container normally. By default, the container is stopped
* abnormally, so that {@code container.isInExpectedState()} returns false. If you
* want to container to remain "healthy" when using this error handler, set the
* property to false.
* @param stopContainerAbnormally false for normal stop.
* @since 2.8
*/
public void setStopContainerAbnormally(boolean stopContainerAbnormally) {
this.stopContainerAbnormally = stopContainerAbnormally;
}
@Override
public boolean seeksAfterHandling() {
// We don't actually do any seeks here, but stopping the container has the same effect.
return true;
}
@Override
public void handleOtherException(Exception thrownException, Consumer<?, ?> consumer,
MessageListenerContainer container, boolean batchListener) {
stopContainer(container, thrownException);
}
@Override
public void handleRemaining(Exception thrownException, List<ConsumerRecord<?, ?>> records, Consumer<?, ?> consumer,
MessageListenerContainer container) {
stopContainer(container, thrownException);
}
@Override
public void handleBatch(Exception thrownException, ConsumerRecords<?, ?> data, Consumer<?, ?> consumer,
MessageListenerContainer container, Runnable invokeListener) { | stopContainer(container, thrownException);
}
private void stopContainer(MessageListenerContainer container, Exception thrownException) {
this.executor.execute(() -> {
if (this.stopContainerAbnormally) {
container.stopAbnormally(() -> {
});
}
else {
container.stop(() -> {
});
}
});
// isRunning is false before the container.stop() waits for listener thread
try {
ListenerUtils.stoppableSleep(container, 10_000); // NOSONAR
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
throw new KafkaException("Stopped container", getLogLevel(), thrownException);
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\CommonContainerStoppingErrorHandler.java | 1 |
请完成以下Java代码 | public void layoutContainer (Container parent)
{
Insets insets = parent.getInsets();
//
int width = insets.left;
int height = insets.top;
// We need to layout
if (needLayout(parent))
{
int x = 5;
int y = 5;
// Go through all components
for (int i = 0; i < parent.getComponentCount(); i++)
{
Component comp = parent.getComponent(i);
if (comp.isVisible() && comp instanceof WFNodeComponent)
{
Dimension ps = comp.getPreferredSize();
comp.setLocation(x, y);
comp.setBounds(x, y, ps.width, ps.height);
//
width = x + ps.width;
height = y + ps.height;
// next pos
if (x == 5)
x = 230;
else
{
x = 5;
y += 100;
}
// x += ps.width-20;
// y += ps.height+20;
}
}
}
else // we have an Layout
{
// Go through all components
for (int i = 0; i < parent.getComponentCount(); i++)
{
Component comp = parent.getComponent(i);
if (comp.isVisible() && comp instanceof WFNodeComponent)
{
Dimension ps = comp.getPreferredSize();
Point loc = comp.getLocation();
int maxWidth = comp.getX() + ps.width;
int maxHeight = comp.getY() + ps.height;
if (width < maxWidth)
width = maxWidth;
if (height < maxHeight)
height = maxHeight;
comp.setBounds(loc.x, loc.y, ps.width, ps.height);
}
} // for all components
} // have layout | // Create Lines
WFContentPanel panel = (WFContentPanel)parent;
panel.createLines();
// Calculate size
width += insets.right;
height += insets.bottom;
// return size
m_size = new Dimension(width, height);
log.trace("Size=" + m_size);
} // layoutContainer
/**
* Need Layout
* @param parent parent
* @return true if we need to layout
*/
private boolean needLayout (Container parent)
{
Point p00 = new Point(0,0);
// Go through all components
for (int i = 0; i < parent.getComponentCount(); i++)
{
Component comp = parent.getComponent(i);
if (comp instanceof WFNodeComponent && comp.getLocation().equals(p00))
{
log.debug("{}", comp);
return true;
}
}
return false;
} // needLayout
/**
* Invalidates the layout, indicating that if the layout manager
* has cached information it should be discarded.
*/
private void invalidateLayout()
{
m_size = null;
} // invalidateLayout
} // WFLayoutManager | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\wf\WFLayoutManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ResponseCacheManagerFactory responseCacheManagerFactory(CacheKeyGenerator cacheKeyGenerator) {
return new ResponseCacheManagerFactory(cacheKeyGenerator);
}
@Bean
public CacheKeyGenerator cacheKeyGenerator() {
return new CacheKeyGenerator();
}
Cache responseCache(CacheManager cacheManager) {
return cacheManager.getCache(RESPONSE_CACHE_NAME);
}
public static class OnGlobalLocalResponseCacheCondition extends AllNestedConditions {
OnGlobalLocalResponseCacheCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty(value = GatewayProperties.PREFIX + ".enabled", havingValue = "true",
matchIfMissing = true)
static class OnGatewayPropertyEnabled {
} | @ConditionalOnProperty(value = GatewayProperties.PREFIX + ".filter.local-response-cache.enabled",
havingValue = "true")
static class OnLocalResponseCachePropertyEnabled {
}
@ConditionalOnProperty(name = GatewayProperties.PREFIX + ".global-filter.local-response-cache.enabled",
havingValue = "true", matchIfMissing = true)
static class OnGlobalLocalResponseCachePropertyEnabled {
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\LocalResponseCacheAutoConfiguration.java | 2 |
请完成以下Java代码 | public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
/**
* Override to extract the principal information from the current request
*/
protected abstract @Nullable Object getPreAuthenticatedPrincipal(HttpServletRequest request);
/**
* Override to extract the credentials (if applicable) from the current request.
* Should not return null for a valid principal, though some implementations may
* return a dummy value.
*/
protected abstract @Nullable Object getPreAuthenticatedCredentials(HttpServletRequest request);
/**
* Request matcher for default auth check logic
*/
private class PreAuthenticatedProcessingRequestMatcher implements RequestMatcher {
@Override
public boolean matches(HttpServletRequest request) {
Authentication currentUser = AbstractPreAuthenticatedProcessingFilter.this.securityContextHolderStrategy
.getContext()
.getAuthentication(); | if (currentUser == null) {
return true;
}
if (!AbstractPreAuthenticatedProcessingFilter.this.checkForPrincipalChanges) {
return false;
}
if (!principalChanged(request, currentUser)) {
return false;
}
AbstractPreAuthenticatedProcessingFilter.this.logger
.debug("Pre-authenticated principal has changed and will be reauthenticated");
if (AbstractPreAuthenticatedProcessingFilter.this.invalidateSessionOnPrincipalChange) {
AbstractPreAuthenticatedProcessingFilter.this.securityContextHolderStrategy.clearContext();
HttpSession session = request.getSession(false);
if (session != null) {
AbstractPreAuthenticatedProcessingFilter.this.logger.debug("Invalidating existing session");
session.invalidate();
request.getSession();
}
}
return true;
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\preauth\AbstractPreAuthenticatedProcessingFilter.java | 1 |
请完成以下Java代码 | public static TbMathArgumentValue fromMessageBody(TbMathArgument arg, String argKey, Optional<ObjectNode> jsonNodeOpt) {
Double defaultValue = arg.getDefaultValue();
if (jsonNodeOpt.isEmpty()) {
return defaultOrThrow(defaultValue, "Message body is empty!");
}
var json = jsonNodeOpt.get();
if (!json.has(argKey)) {
return defaultOrThrow(defaultValue, "Message body has no '" + argKey + "'!");
}
JsonNode valueNode = json.get(argKey);
if (valueNode.isNull()) {
return defaultOrThrow(defaultValue, "Message body has null '" + argKey + "'!");
}
double value;
if (valueNode.isNumber()) {
value = valueNode.doubleValue();
} else if (valueNode.isTextual()) {
var valueNodeText = valueNode.asText();
if (StringUtils.isNotBlank(valueNodeText)) {
try {
value = Double.parseDouble(valueNode.asText());
} catch (NumberFormatException ne) {
throw new RuntimeException("Can't convert value '" + valueNode.asText() + "' to double!");
}
} else {
return defaultOrThrow(defaultValue, "Message value is empty for '" + argKey + "'!");
}
} else {
throw new RuntimeException("Can't convert value '" + valueNode.toString() + "' to double!");
}
return new TbMathArgumentValue(value);
}
public static TbMathArgumentValue fromMessageMetadata(TbMathArgument arg, String argKey, TbMsgMetaData metaData) {
Double defaultValue = arg.getDefaultValue();
if (metaData == null) {
return defaultOrThrow(defaultValue, "Message metadata is empty!");
}
var value = metaData.getValue(argKey);
if (StringUtils.isEmpty(value)) {
return defaultOrThrow(defaultValue, "Message metadata has no '" + argKey + "'!"); | }
return fromString(value);
}
public static TbMathArgumentValue fromLong(long value) {
return new TbMathArgumentValue(value);
}
public static TbMathArgumentValue fromDouble(double value) {
return new TbMathArgumentValue(value);
}
public static TbMathArgumentValue fromString(String value) {
try {
return new TbMathArgumentValue(Double.parseDouble(value));
} catch (NumberFormatException ne) {
throw new RuntimeException("Can't convert value '" + value + "' to double!");
}
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\math\TbMathArgumentValue.java | 1 |
请完成以下Java代码 | private void traverseNodes(StringBuilder sb, String padding, String pointer, BinaryTreeModel node,
boolean hasRightSibling) {
if (node != null) {
sb.append("\n");
sb.append(padding);
sb.append(pointer);
sb.append(node.getValue());
StringBuilder paddingBuilder = new StringBuilder(padding);
if (hasRightSibling) {
paddingBuilder.append("│ ");
} else {
paddingBuilder.append(" ");
} | String paddingForBoth = paddingBuilder.toString();
String pointerRight = "└──";
String pointerLeft = (node.getRight() != null) ? "├──" : "└──";
traverseNodes(sb, paddingForBoth, pointerLeft, node.getLeft(), node.getRight() != null);
traverseNodes(sb, paddingForBoth, pointerRight, node.getRight(), false);
}
}
public void print(PrintStream os) {
os.print(traversePreOrder(tree));
}
} | repos\tutorials-master\data-structures-2\src\main\java\com\baeldung\printbinarytree\BinaryTreePrinter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void linkToOrderLine(
@NonNull final ProjectAndLineId projectLineId,
@NonNull final OrderAndLineId orderLineId)
{
projectLineRepository.linkToOrderLine(projectLineId, orderLineId);
}
public boolean isClosed(@NonNull final ProjectId projectId)
{
final I_C_Project projectRecord = getById(projectId);
return projectRecord.isProcessed();
}
public void closeProject(@NonNull final ProjectId projectId)
{
final I_C_Project projectRecord = getById(projectId);
if (projectRecord.isProcessed())
{
throw new AdempiereException("Project already closed: " + projectId);
}
projectStatusListeners.onBeforeClose(projectRecord);
projectLineRepository.markLinesAsProcessed(projectId);
projectRecord.setProcessed(true);
InterfaceWrapperHelper.saveRecord(projectRecord); | projectStatusListeners.onAfterClose(projectRecord);
}
public void uncloseProject(@NonNull final ProjectId projectId)
{
final I_C_Project projectRecord = getById(projectId);
if (!projectRecord.isProcessed())
{
throw new AdempiereException("Project not closed: " + projectId);
}
projectStatusListeners.onBeforeUnClose(projectRecord);
projectLineRepository.markLinesAsNotProcessed(projectId);
projectRecord.setProcessed(false);
InterfaceWrapperHelper.saveRecord(projectRecord);
projectStatusListeners.onAfterUnClose(projectRecord);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\project\service\ProjectService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
FilterInvocation fi = new FilterInvocation(request, response, chain);
invoke(fi);
}
public void invoke(FilterInvocation fi) throws IOException, ServletException {
//fi里面有一个被拦截的url
//里面调用MyInvocationSecurityMetadataSource的getAttributes(Object object)这个方法获取fi对应的所有权限
//再调用MyAccessDecisionManager的decide方法来校验用户的权限是否足够
InterceptorStatusToken token = super.beforeInvocation(fi);
try {
//执行下一个拦截器
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
} finally {
super.afterInvocation(token, null);
}
} | @Override
public void destroy() {
}
@Override
public Class<?> getSecureObjectClass() {
return FilterInvocation.class;
}
@Override
public SecurityMetadataSource obtainSecurityMetadataSource() {
return this.securityMetadataSource;
}
} | repos\springBoot-master\springboot-springSecurity3\src\main\java\com\us\example\service\MyFilterSecurityInterceptor.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class HumanResourceTestGroupId implements RepoIdAware
{
@JsonCreator
public static HumanResourceTestGroupId ofRepoId(final int repoId)
{
return new HumanResourceTestGroupId(repoId);
}
@Nullable
public static HumanResourceTestGroupId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new HumanResourceTestGroupId(repoId) : null;
}
public static Optional<HumanResourceTestGroupId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static int toRepoId(@Nullable final HumanResourceTestGroupId humanResourceTestGroupId)
{ | return humanResourceTestGroupId != null ? humanResourceTestGroupId.getRepoId() : -1;
}
public static boolean equals(@Nullable final HumanResourceTestGroupId o1, @Nullable final HumanResourceTestGroupId o2)
{
return Objects.equals(o1, o2);
}
int repoId;
private HumanResourceTestGroupId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "S_HumanResourceTestGroup_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\resource\HumanResourceTestGroupId.java | 2 |
请完成以下Java代码 | private String createPickingSlotLabel(@NonNull final I_M_PickingSlot pickingslot)
{
final StringBuilder result = new StringBuilder(pickingslot.getPickingSlot());
final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(pickingslot.getC_BPartner_ID());
if (bpartnerId != null)
{
final IBPartnerDAO bpartnersRepo = Services.get(IBPartnerDAO.class);
final I_C_BPartner bpartner = bpartnersRepo.getById(bpartnerId);
result.append("_").append(bpartner.getName()).append("_").append(bpartner.getValue());
}
return result.toString();
}
public Object getDefaultValue(final IProcessDefaultParameter parameter)
{
if (PARAM_M_ShipmentSchedule_ID.equals(parameter.getColumnName()))
{
final ShipmentScheduleId defaultShipmentScheduleId = getDefaultShipmentScheduleId();
if (defaultShipmentScheduleId != null) | {
return defaultShipmentScheduleId.getRepoId();
}
}
// Fallback
return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE;
}
private ShipmentScheduleId getDefaultShipmentScheduleId()
{
if (salesOrderLineId == null)
{
return null;
}
return Services.get(IShipmentSchedulePA.class).getShipmentScheduleIdByOrderLineId(salesOrderLineId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_Pick_ParametersFiller.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public CommonResult delete(Long brandId) {
int count = memberAttentionService.delete(brandId);
if(count>0){
return CommonResult.success(count);
}else{
return CommonResult.failed();
}
}
@ApiOperation("分页查询当前用户品牌关注列表")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<MemberBrandAttention>> list(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
Page<MemberBrandAttention> page = memberAttentionService.list(pageNum,pageSize);
return CommonResult.success(CommonPage.restPage(page));
}
@ApiOperation("根据品牌ID获取品牌关注详情") | @RequestMapping(value = "/detail", method = RequestMethod.GET)
@ResponseBody
public CommonResult<MemberBrandAttention> detail(@RequestParam Long brandId) {
MemberBrandAttention memberBrandAttention = memberAttentionService.detail(brandId);
return CommonResult.success(memberBrandAttention);
}
@ApiOperation("清空当前用户品牌关注列表")
@RequestMapping(value = "/clear", method = RequestMethod.POST)
@ResponseBody
public CommonResult clear() {
memberAttentionService.clear();
return CommonResult.success(null);
}
} | repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\controller\MemberAttentionController.java | 2 |
请完成以下Java代码 | public class ObjectToJsonConverter {
public String convertToJson(Object object) throws JsonSerializationException {
try {
checkIfSerializable(object);
initializeObject(object);
return getJsonString(object);
} catch (Exception e) {
throw new JsonSerializationException(e.getMessage());
}
}
private void checkIfSerializable(Object object) {
if (Objects.isNull(object)) {
throw new JsonSerializationException("Can't serialize a null object");
}
Class<?> clazz = object.getClass();
if (!clazz.isAnnotationPresent(JsonSerializable.class)) {
throw new JsonSerializationException("The class " + clazz.getSimpleName() + " is not annotated with JsonSerializable");
}
}
private void initializeObject(Object object) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Class<?> clazz = object.getClass();
for (Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(Init.class)) {
method.setAccessible(true);
method.invoke(object);
}
}
}
private String getJsonString(Object object) throws IllegalArgumentException, IllegalAccessException {
Class<?> clazz = object.getClass(); | Map<String, String> jsonElementsMap = new HashMap<>();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
if (field.isAnnotationPresent(JsonElement.class)) {
jsonElementsMap.put(getKey(field), (String) field.get(object));
}
}
String jsonString = jsonElementsMap.entrySet()
.stream()
.map(entry -> "\"" + entry.getKey() + "\":\"" + entry.getValue() + "\"")
.collect(Collectors.joining(","));
return "{" + jsonString + "}";
}
private String getKey(Field field) {
String value = field.getAnnotation(JsonElement.class)
.key();
return value.isEmpty() ? field.getName() : value;
}
} | repos\tutorials-master\core-java-modules\core-java-annotations\src\main\java\com\baeldung\customannotations\ObjectToJsonConverter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void register(Collection<Resource> resources, ResourceConfig config) {
config.registerResources(new HashSet<>(resources));
}
}
class JerseyAdditionalHealthEndpointPathsManagementResourcesRegistrar
implements ManagementContextResourceConfigCustomizer {
private final @Nullable ExposableWebEndpoint healthEndpoint;
private final HealthEndpointGroups groups;
JerseyAdditionalHealthEndpointPathsManagementResourcesRegistrar(@Nullable ExposableWebEndpoint healthEndpoint,
HealthEndpointGroups groups) {
this.healthEndpoint = healthEndpoint;
this.groups = groups;
}
@Override
public void customize(ResourceConfig config) {
if (this.healthEndpoint != null) {
register(config, this.healthEndpoint);
}
}
private void register(ResourceConfig config, ExposableWebEndpoint healthEndpoint) {
EndpointMapping mapping = new EndpointMapping("");
JerseyHealthEndpointAdditionalPathResourceFactory resourceFactory = new JerseyHealthEndpointAdditionalPathResourceFactory(
WebServerNamespace.MANAGEMENT, this.groups);
Collection<Resource> endpointResources = resourceFactory
.createEndpointResources(mapping, Collections.singletonList(healthEndpoint))
.stream()
.filter(Objects::nonNull)
.toList();
register(endpointResources, config);
}
private void register(Collection<Resource> resources, ResourceConfig config) {
config.registerResources(new HashSet<>(resources));
}
}
/** | * {@link ContextResolver} used to obtain the {@link ObjectMapper} that should be used
* for {@link OperationResponseBody} instances.
*/
@SuppressWarnings("removal")
@Priority(Priorities.USER - 100)
private static final class EndpointJackson2ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
private final org.springframework.boot.actuate.endpoint.jackson.EndpointJackson2ObjectMapper mapper;
private EndpointJackson2ObjectMapperContextResolver(
org.springframework.boot.actuate.endpoint.jackson.EndpointJackson2ObjectMapper mapper) {
this.mapper = mapper;
}
@Override
public @Nullable ObjectMapper getContext(Class<?> type) {
return OperationResponseBody.class.isAssignableFrom(type) ? this.mapper.get() : null;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-jersey\src\main\java\org\springframework\boot\jersey\autoconfigure\actuate\web\JerseyWebEndpointManagementContextConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class HREFE1 {
@XmlElement(name = "DOCUMENTID", required = true)
protected String documentid;
@XmlElement(name = "REFERENCEQUAL", required = true)
protected String referencequal;
@XmlElement(name = "REFERENCE", required = true)
protected String reference;
@XmlElement(name = "REFERENCEDATE1")
protected String referencedate1;
@XmlElement(name = "REFERENCEDATE2")
protected String referencedate2;
/**
* Gets the value of the documentid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDOCUMENTID() {
return documentid;
}
/**
* Sets the value of the documentid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDOCUMENTID(String value) {
this.documentid = value;
}
/**
* Gets the value of the referencequal property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getREFERENCEQUAL() {
return referencequal;
}
/**
* Sets the value of the referencequal property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setREFERENCEQUAL(String value) {
this.referencequal = value;
}
/**
* Gets the value of the reference property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getREFERENCE() {
return reference;
} | /**
* Sets the value of the reference property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setREFERENCE(String value) {
this.reference = value;
}
/**
* Gets the value of the referencedate1 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getREFERENCEDATE1() {
return referencedate1;
}
/**
* Sets the value of the referencedate1 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setREFERENCEDATE1(String value) {
this.referencedate1 = value;
}
/**
* Gets the value of the referencedate2 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getREFERENCEDATE2() {
return referencedate2;
}
/**
* Sets the value of the referencedate2 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setREFERENCEDATE2(String value) {
this.referencedate2 = 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\HREFE1.java | 2 |
请完成以下Java代码 | public int getCarrier_ShipmentOrder_Item_ID()
{
return get_ValueAsInt(COLUMNNAME_Carrier_ShipmentOrder_Item_ID);
}
@Override
public void setCarrier_ShipmentOrder_Parcel_ID (final int Carrier_ShipmentOrder_Parcel_ID)
{
if (Carrier_ShipmentOrder_Parcel_ID < 1)
set_Value (COLUMNNAME_Carrier_ShipmentOrder_Parcel_ID, null);
else
set_Value (COLUMNNAME_Carrier_ShipmentOrder_Parcel_ID, Carrier_ShipmentOrder_Parcel_ID);
}
@Override
public int getCarrier_ShipmentOrder_Parcel_ID()
{
return get_ValueAsInt(COLUMNNAME_Carrier_ShipmentOrder_Parcel_ID);
}
@Override
public void setC_Currency_ID (final int C_Currency_ID)
{
if (C_Currency_ID < 1)
set_Value (COLUMNNAME_C_Currency_ID, null);
else
set_Value (COLUMNNAME_C_Currency_ID, C_Currency_ID);
}
@Override
public int getC_Currency_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Currency_ID);
}
@Override
public void setC_UOM_ID (final int C_UOM_ID)
{
if (C_UOM_ID < 1)
set_Value (COLUMNNAME_C_UOM_ID, null);
else
set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID);
}
@Override
public int getC_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_C_UOM_ID);
}
@Override
public void setPrice (final BigDecimal Price)
{
set_Value (COLUMNNAME_Price, Price);
}
@Override
public BigDecimal getPrice()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Price);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setProductName (final @Nullable java.lang.String ProductName)
{
set_Value (COLUMNNAME_ProductName, ProductName);
}
@Override
public java.lang.String getProductName() | {
return get_ValueAsString(COLUMNNAME_ProductName);
}
@Override
public void setQtyShipped (final @Nullable BigDecimal QtyShipped)
{
set_Value (COLUMNNAME_QtyShipped, QtyShipped);
}
@Override
public BigDecimal getQtyShipped()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyShipped);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalPrice (final BigDecimal TotalPrice)
{
set_Value (COLUMNNAME_TotalPrice, TotalPrice);
}
@Override
public BigDecimal getTotalPrice()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalPrice);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalWeightInKg (final BigDecimal TotalWeightInKg)
{
set_Value (COLUMNNAME_TotalWeightInKg, TotalWeightInKg);
}
@Override
public BigDecimal getTotalWeightInKg()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalWeightInKg);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_ShipmentOrder_Item.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static DataImportConfig toDataImportConfig(@NonNull final I_C_DataImport record)
{
return DataImportConfig.builder()
.id(DataImportConfigId.ofRepoId(record.getC_DataImport_ID()))
.internalName(StringUtils.trimBlankToNull(record.getInternalName()))
.impFormatId(ImpFormatId.ofRepoId(record.getAD_ImpFormat_ID()))
.build();
}
private static class DataImportConfigsCollection
{
private final ImmutableMap<DataImportConfigId, DataImportConfig> configsById;
private final ImmutableMap<String, DataImportConfig> configsByInternalName;
public DataImportConfigsCollection(final Collection<DataImportConfig> configs)
{
configsById = Maps.uniqueIndex(configs, DataImportConfig::getId);
configsByInternalName = configs.stream()
.filter(config -> config.getInternalName() != null)
.collect(GuavaCollectors.toImmutableMapByKey(DataImportConfig::getInternalName));
}
public DataImportConfig getById(@NonNull final DataImportConfigId id) | {
final DataImportConfig config = configsById.get(id);
if (config == null)
{
throw new AdempiereException("@NotFound@ @C_DataConfig_ID@: " + id);
}
return config;
}
public Optional<DataImportConfig> getByInternalName(final String internalName)
{
Check.assumeNotEmpty(internalName, "internalName is not empty");
return Optional.ofNullable(configsByInternalName.get(internalName));
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\config\DataImportConfigRepository.java | 2 |
请完成以下Java代码 | public void setLine (int Line)
{
set_Value (COLUMNNAME_Line, Integer.valueOf(Line));
}
/** Get Zeile Nr..
@return Unique line for this document
*/
@Override
public int getLine ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Line);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Steuerbetrag.
@param TaxAmt
Tax Amount for a document
*/
@Override
public void setTaxAmt (java.math.BigDecimal TaxAmt)
{
set_ValueNoCheck (COLUMNNAME_TaxAmt, TaxAmt);
}
/** Get Steuerbetrag.
@return Tax Amount for a document
*/
@Override
public java.math.BigDecimal getTaxAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TaxAmt); | if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Bezugswert.
@param TaxBaseAmt
Base for calculating the tax amount
*/
@Override
public void setTaxBaseAmt (java.math.BigDecimal TaxBaseAmt)
{
set_ValueNoCheck (COLUMNNAME_TaxBaseAmt, TaxBaseAmt);
}
/** Get Bezugswert.
@return Base for calculating the tax amount
*/
@Override
public java.math.BigDecimal getTaxBaseAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TaxBaseAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_TaxDeclarationLine.java | 1 |
请完成以下Java代码 | public final Stream<T> streamByIds(@NonNull final ViewRowIdsSelection selection)
{
if (!Objects.equals(getViewId(), selection.getViewId()))
{
throw new AdempiereException("Selection has invalid viewId: " + selection
+ "\nExpected viewId: " + getViewId());
}
return streamByIds(selection.getRowIds());
}
@Override
public final void notifyRecordsChanged(
@NonNull final TableRecordReferenceSet recordRefs,
final boolean watchedByFrontend)
{
if (recordRefs.isEmpty())
{
return; // nothing to do, but shall not happen
}
final TableRecordReferenceSet recordRefsEligible = recordRefs.filter(this::isEligibleInvalidateEvent);
if (recordRefsEligible.isEmpty())
{
return; // nothing to do
}
final DocumentIdsSelection documentIdsToInvalidate = getDocumentIdsToInvalidate(recordRefsEligible);
if (documentIdsToInvalidate.isEmpty())
{
return; // nothing to do
}
rowsData.invalidate(documentIdsToInvalidate); | ViewChangesCollector.getCurrentOrAutoflush()
.collectRowsChanged(this, documentIdsToInvalidate);
}
protected boolean isEligibleInvalidateEvent(final TableRecordReference recordRef)
{
return true;
}
protected final DocumentIdsSelection getDocumentIdsToInvalidate(@NonNull final TableRecordReferenceSet recordRefs)
{
return rowsData.getDocumentIdsToInvalidate(recordRefs);
}
// extends IEditableView.patchViewRow
public final void patchViewRow(final RowEditingContext ctx, final List<JSONDocumentChangedEvent> fieldChangeRequests)
{
Check.assumeNotEmpty(fieldChangeRequests, "fieldChangeRequests is not empty");
if (rowsData instanceof IEditableRowsData)
{
final IEditableRowsData<T> editableRowsData = (IEditableRowsData<T>)rowsData;
editableRowsData.patchRow(ctx, fieldChangeRequests);
}
else
{
throw new AdempiereException("View is not editable");
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\template\AbstractCustomView.java | 1 |
请完成以下Java代码 | public int getAD_Role_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set AD_Workflow_Access.
@param AD_Workflow_Access_ID AD_Workflow_Access */
@Override
public void setAD_Workflow_Access_ID (int AD_Workflow_Access_ID)
{
if (AD_Workflow_Access_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Workflow_Access_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Workflow_Access_ID, Integer.valueOf(AD_Workflow_Access_ID));
}
/** Get AD_Workflow_Access.
@return AD_Workflow_Access */
@Override
public int getAD_Workflow_Access_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Workflow_Access_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Workflow getAD_Workflow() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Workflow_ID, org.compiere.model.I_AD_Workflow.class);
}
@Override
public void setAD_Workflow(org.compiere.model.I_AD_Workflow AD_Workflow)
{
set_ValueFromPO(COLUMNNAME_AD_Workflow_ID, org.compiere.model.I_AD_Workflow.class, AD_Workflow);
}
/** Set Workflow.
@param AD_Workflow_ID
Workflow or combination of tasks
*/
@Override
public void setAD_Workflow_ID (int AD_Workflow_ID)
{
if (AD_Workflow_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Workflow_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Workflow_ID, Integer.valueOf(AD_Workflow_ID));
} | /** Get Workflow.
@return Workflow or combination of tasks
*/
@Override
public int getAD_Workflow_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Workflow_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Lesen und Schreiben.
@param IsReadWrite
Field is read / write
*/
@Override
public void setIsReadWrite (boolean IsReadWrite)
{
set_Value (COLUMNNAME_IsReadWrite, Boolean.valueOf(IsReadWrite));
}
/** Get Lesen und Schreiben.
@return Field is read / write
*/
@Override
public boolean isReadWrite ()
{
Object oo = get_Value(COLUMNNAME_IsReadWrite);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Workflow_Access.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Job fileItemReaderJob() {
return jobBuilderFactory.get("fileItemReaderJob")
.start(step())
.build();
}
private Step step() {
return stepBuilderFactory.get("step")
.<TestData, TestData>chunk(2)
.reader(fileItemReader())
.writer(list -> list.forEach(System.out::println))
.build();
}
private ItemReader<TestData> fileItemReader() {
FlatFileItemReader<TestData> reader = new FlatFileItemReader<>();
reader.setResource(new ClassPathResource("file")); // 设置文件资源地址
reader.setLinesToSkip(1); // 忽略第一行
// AbstractLineTokenizer的三个实现类之一,以固定分隔符处理行数据读取,
// 使用默认构造器的时候,使用逗号作为分隔符,也可以通过有参构造器来指定分隔符
DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
// 设置属性名,类似于表头
tokenizer.setNames("id", "field1", "field2", "field3"); | // 将每行数据转换为TestData对象
DefaultLineMapper<TestData> mapper = new DefaultLineMapper<>();
mapper.setLineTokenizer(tokenizer);
// 设置映射方式
mapper.setFieldSetMapper(fieldSet -> {
TestData data = new TestData();
data.setId(fieldSet.readInt("id"));
data.setField1(fieldSet.readString("field1"));
data.setField2(fieldSet.readString("field2"));
data.setField3(fieldSet.readString("field3"));
return data;
});
reader.setLineMapper(mapper);
return reader;
}
} | repos\SpringAll-master\68.spring-batch-itemreader\src\main\java\cc\mrbird\batch\job\FileItemReaderDemo.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class SecurPharmConfigId implements RepoIdAware
{
public static SecurPharmConfigId ofRepoId(final int repoId)
{
return new SecurPharmConfigId(repoId);
}
public static SecurPharmConfigId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static Optional<SecurPharmConfigId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId)); | }
int repoId;
private SecurPharmConfigId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "repoId");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\config\SecurPharmConfigId.java | 2 |
请完成以下Java代码 | protected void onInit(@NonNull final IModelValidationEngine engine)
{
this.engine = (ModelValidationEngine)engine;
configRepository.addCacheResetListener(this::updateFromRepository);
updateFromRepository();
}
private synchronized void updateFromRepository()
{
final ImmutableSet<AdTableId> tableIdsPrev = this.tableIds;
this.tableIds = configRepository.getDistinctConfigTableIds();
if (Objects.equals(this.tableIds, tableIdsPrev))
{
return;
}
updateRegisteredInterceptors();
}
private synchronized void updateRegisteredInterceptors()
{
final HashSet<AdTableId> registeredTableIdsNoLongerNeeded = new HashSet<>(this.registeredTableIds);
for (final AdTableId tableId : this.tableIds)
{
registeredTableIdsNoLongerNeeded.remove(tableId);
if (registeredTableIds.contains(tableId))
{
// already registered
continue; | }
registerOutboundProducer(tableId);
}
//
// Remove no longer necessary interceptors
for (final AdTableId tableId : registeredTableIdsNoLongerNeeded)
{
unregisterOutboundProducer(tableId);
}
}
private void registerOutboundProducer(@NonNull final AdTableId tableId)
{
final ModelValidationEngine engine = Check.assumeNotNull(this.engine, "engine not null");
producerService.registerProducer(new DocOutboundProducerValidator(engine, tableId));
registeredTableIds.add(tableId);
logger.info("Registered producer for {}", tableId);
}
private void unregisterOutboundProducer(@NonNull final AdTableId tableId)
{
producerService.unregisterProducerByTableId(tableId);
registeredTableIds.remove(tableId);
logger.info("Unregistered trigger for {}", tableId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\interceptor\C_Doc_Outbound_Config.java | 1 |
请完成以下Java代码 | public void setIsGraphicalNotationDefined(boolean isGraphicalNotationDefined) {
this.isGraphicalNotationDefined = isGraphicalNotationDefined;
}
@Override
public void setGraphicalNotationDefined(boolean isGraphicalNotationDefined) {
this.isGraphicalNotationDefined = isGraphicalNotationDefined;
}
@Override
public int getSuspensionState() {
return suspensionState;
}
@Override
public void setSuspensionState(int suspensionState) {
this.suspensionState = suspensionState;
}
@Override
public boolean isSuspended() {
return suspensionState == SuspensionState.SUSPENDED.getStateCode();
}
@Override
public String getDerivedFrom() {
return derivedFrom;
}
@Override
public void setDerivedFrom(String derivedFrom) {
this.derivedFrom = derivedFrom;
}
@Override
public String getDerivedFromRoot() {
return derivedFromRoot;
}
@Override
public void setDerivedFromRoot(String derivedFromRoot) {
this.derivedFromRoot = derivedFromRoot;
}
@Override
public int getDerivedVersion() {
return derivedVersion;
}
@Override
public void setDerivedVersion(int derivedVersion) {
this.derivedVersion = derivedVersion;
} | @Override
public String getEngineVersion() {
return engineVersion;
}
@Override
public void setEngineVersion(String engineVersion) {
this.engineVersion = engineVersion;
}
public IOSpecification getIoSpecification() {
return ioSpecification;
}
public void setIoSpecification(IOSpecification ioSpecification) {
this.ioSpecification = ioSpecification;
}
@Override
public String toString() {
return "ProcessDefinitionEntity[" + id + "]";
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\ProcessDefinitionEntityImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void sendSms(TenantId tenantId, CustomerId customerId, String[] numbersTo, String message) throws ThingsboardException {
if (apiUsageStateService.getApiUsageState(tenantId).isSmsSendEnabled()) {
int smsCount = 0;
try {
for (String numberTo : numbersTo) {
smsCount += this.sendSms(numberTo, message);
}
} finally {
if (smsCount > 0) {
apiUsageClient.report(tenantId, customerId, ApiUsageRecordKey.SMS_EXEC_COUNT, smsCount);
}
}
} else {
throw new RuntimeException("SMS sending is disabled due to API limits!");
}
}
@Override
public void sendTestSms(TestSmsRequest testSmsRequest) throws ThingsboardException {
SmsSender testSmsSender;
try {
testSmsSender = this.smsSenderFactory.createSmsSender(testSmsRequest.getProviderConfiguration());
} catch (Exception e) {
throw handleException(e);
}
this.sendSms(testSmsSender, testSmsRequest.getNumberTo(), testSmsRequest.getMessage());
testSmsSender.destroy();
}
@Override | public boolean isConfigured(TenantId tenantId) {
return smsSender != null;
}
private int sendSms(SmsSender smsSender, String numberTo, String message) throws ThingsboardException {
try {
int sentSms = smsSender.sendSms(numberTo, message);
log.trace("Successfully sent sms to number: {}", numberTo);
return sentSms;
} catch (Exception e) {
throw handleException(e);
}
}
private ThingsboardException handleException(Exception exception) {
String message;
if (exception instanceof NestedRuntimeException) {
message = ((NestedRuntimeException) exception).getMostSpecificCause().getMessage();
} else {
message = exception.getMessage();
}
log.warn("Unable to send SMS: {}", message);
return new ThingsboardException(String.format("Unable to send SMS: %s", message),
ThingsboardErrorCode.GENERAL);
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sms\DefaultSmsService.java | 2 |
请完成以下Java代码 | private static DateRangeValue convertToDateRangeValue(final Object value)
{
if (value == null)
{
return null;
}
else if (value instanceof DateRangeValue)
{
return (DateRangeValue)value;
}
else if (value instanceof Map)
{
@SuppressWarnings("unchecked") final Map<String, String> map = (Map<String, String>)value;
return JSONRange.dateRangeFromJSONMap(map);
}
else
{
throw new ValueConversionException();
}
}
@Nullable
private static ColorValue convertToColorValue(final Object value)
{
if (value == null)
{
return null;
}
else if (value instanceof ColorValue)
{
return (ColorValue)value;
}
else if (value instanceof String)
{
return ColorValue.ofHexString(value.toString());
}
else
{
throw new ValueConversionException();
}
}
private static class ValueConversionException extends AdempiereException
{
public static ValueConversionException wrapIfNeeded(final Throwable ex)
{
if (ex instanceof ValueConversionException)
{
return (ValueConversionException)ex;
}
final Throwable cause = extractCause(ex);
if (cause instanceof ValueConversionException)
{
return (ValueConversionException)cause;
}
else | {
return new ValueConversionException(cause);
}
}
public ValueConversionException()
{
this("no conversion rule defined to convert the value to target type");
}
public ValueConversionException(final String message)
{
super(message);
appendParametersToMessage();
}
public ValueConversionException(final Throwable cause)
{
super("Conversion failed because: " + cause.getLocalizedMessage(), cause);
appendParametersToMessage();
}
public ValueConversionException setFieldName(@Nullable final String fieldName)
{
setParameter("fieldName", fieldName);
return this;
}
public ValueConversionException setWidgetType(@Nullable final DocumentFieldWidgetType widgetType)
{
setParameter("widgetType", widgetType);
return this;
}
public ValueConversionException setFromValue(@Nullable final Object fromValue)
{
setParameter("value", fromValue);
setParameter("valueClass", fromValue != null ? fromValue.getClass() : null);
return this;
}
public ValueConversionException setTargetType(@Nullable final Class<?> targetType)
{
setParameter("targetType", targetType);
return this;
}
public ValueConversionException setLookupDataSource(@Nullable final LookupValueByIdSupplier lookupDataSource)
{
setParameter("lookupDataSource", lookupDataSource);
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DataTypes.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getRevision() {
return revision;
}
public void setRevision(int revision) {
this.revision = revision;
}
public void setPermissions(int permissions) {
this.permissions = permissions;
}
public int getPermissions() {
return permissions;
}
public Set<Permission> getCachedPermissions() {
return cachedPermissions;
}
public int getRevisionNext() {
return revision + 1;
}
public Object getPersistentState() {
HashMap<String, Object> state = new HashMap<String, Object>();
state.put("userId", userId);
state.put("groupId", groupId);
state.put("resourceType", resourceType);
state.put("resourceId", resourceId);
state.put("permissions", permissions);
state.put("removalTime", removalTime);
state.put("rootProcessInstanceId", rootProcessInstanceId);
return state;
}
@Override
public Date getRemovalTime() {
return removalTime;
}
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime;
} | @Override
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
@Override
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<String>();
return referencedEntityIds;
}
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<String, Class>();
return referenceIdAndClass;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", revision=" + revision
+ ", authorizationType=" + authorizationType
+ ", permissions=" + permissions
+ ", userId=" + userId
+ ", groupId=" + groupId
+ ", resourceType=" + resourceType
+ ", resourceId=" + resourceId
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AuthorizationEntity.java | 1 |
请完成以下Java代码 | private List<Integer> concatenateSortedBuckets(List<List<Integer>> buckets){
List<Integer> sortedArray = new LinkedList<>();
for(List<Integer> bucket : buckets){
sortedArray.addAll(bucket);
}
return sortedArray;
}
private List<List<Integer>> splitIntoUnsortedBuckets(List<Integer> initialList){
final int max = findMax(initialList);
final int numberOfBuckets = (int) Math.sqrt(initialList.size());
List<List<Integer>> buckets = new ArrayList<>();
for(int i = 0; i < numberOfBuckets; i++) buckets.add(new ArrayList<>());
//distribute the data
for (int i : initialList) {
buckets.get(hash(i, max, numberOfBuckets)).add(i);
}
return buckets; | }
private int findMax(List<Integer> input){
int m = Integer.MIN_VALUE;
for (int i : input){
m = Math.max(i, m);
}
return m;
}
private static int hash(int i, int max, int numberOfBuckets) {
return (int) ((double) i / max * (numberOfBuckets - 1));
}
} | repos\tutorials-master\algorithms-modules\algorithms-sorting-3\src\main\java\com\baeldung\algorithms\bucketsort\IntegerBucketSorter.java | 1 |
请完成以下Java代码 | private static PPMaturingCandidateV toPPMaturingCandidateV(@NonNull final I_PP_Maturing_Candidates_v ppMaturingCandidatesV)
{
final ClientAndOrgId clientAndOrgId = ClientAndOrgId.ofClientAndOrg(ppMaturingCandidatesV.getAD_Client_ID(), ppMaturingCandidatesV.getAD_Org_ID());
final PPOrderCandidateId ppOrderCandidateId = PPOrderCandidateId.ofRepoIdOrNull(ppMaturingCandidatesV.getPP_Order_Candidate_ID());
final MaturingConfigId maturingConfigId = MaturingConfigId.ofRepoId(ppMaturingCandidatesV.getM_Maturing_Configuration_ID());
final MaturingConfigLineId maturingConfigLineId = MaturingConfigLineId.ofRepoId(ppMaturingCandidatesV.getM_Maturing_Configuration_Line_ID());
final ProductBOMVersionsId productBOMVersionsId = ProductBOMVersionsId.ofRepoId(ppMaturingCandidatesV.getPP_Product_BOMVersions_ID());
final ProductId productId = ProductId.ofRepoId(ppMaturingCandidatesV.getM_Product_ID());
final ProductId issueProductId = ProductId.ofRepoId(ppMaturingCandidatesV.getIssue_M_Product_ID());
final WarehouseId warehouseId = WarehouseId.ofRepoId(ppMaturingCandidatesV.getM_Warehouse_ID());
final ProductPlanningId productPlanningId = ProductPlanningId.ofRepoId(ppMaturingCandidatesV.getPP_Product_Planning_ID());
final Quantity quantity = Quantitys.of(ppMaturingCandidatesV.getQty(), UomId.ofRepoId(ppMaturingCandidatesV.getC_UOM_ID()));
final AttributeSetInstanceId attributeSetInstanceId = AttributeSetInstanceId.ofRepoIdOrNone(ppMaturingCandidatesV.getM_AttributeSetInstance_ID());
final Instant dateStartSchedule = Objects.requireNonNull(ppMaturingCandidatesV.getDateStartSchedule()).toInstant();
final HuId huId = HuId.ofRepoId(ppMaturingCandidatesV.getM_HU_ID());
return PPMaturingCandidateV.builder()
.clientAndOrgId(clientAndOrgId)
.ppOrderCandidateId(ppOrderCandidateId)
.maturingConfigId(maturingConfigId)
.maturingConfigLineId(maturingConfigLineId)
.productBOMVersionsId(productBOMVersionsId)
.productId(productId)
.issueProductId(issueProductId) | .warehouseId(warehouseId)
.productPlanningId(productPlanningId)
.qtyRequired(quantity)
.attributeSetInstanceId(attributeSetInstanceId)
.dateStartSchedule(dateStartSchedule)
.issueHuId(huId)
.build();
}
public int deleteStaleCandidates()
{
final IQuery<I_PP_Maturing_Candidates_v> ppMaturingCandidatesVQuery = queryBL.createQueryBuilder(I_PP_Maturing_Candidates_v.class)
.create();
return queryBL.createQueryBuilder(I_PP_Order_Candidate.class)
.addNotEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_Processed, true)
.addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_IsMaturing, true)
.addNotInSubQueryFilter(I_PP_Order_Candidate.COLUMNNAME_PP_Order_Candidate_ID, I_PP_Maturing_Candidates_v.COLUMNNAME_PP_Order_Candidate_ID, ppMaturingCandidatesVQuery)
.create()
.delete();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\model\dao\PPMaturingCandidatesViewRepo.java | 1 |
请完成以下Java代码 | protected HistoryCleanupRemovalTime getTimeBasedHandler() {
return new HistoryCleanupRemovalTime();
}
protected HistoryCleanupHandler initCleanupHandler(HistoryCleanupJobHandlerConfiguration configuration, CommandContext commandContext) {
HistoryCleanupHandler cleanupHandler = null;
if (isHistoryCleanupStrategyRemovalTimeBased(commandContext)) {
cleanupHandler = getTimeBasedHandler();
} else {
cleanupHandler = new HistoryCleanupBatch();
}
CommandExecutor commandExecutor = commandContext.getProcessEngineConfiguration()
.getCommandExecutorTxRequiresNew();
String jobId = commandContext.getCurrentJob().getId();
return cleanupHandler
.setConfiguration(configuration)
.setCommandExecutor(commandExecutor)
.setJobId(jobId);
}
protected boolean isHistoryCleanupStrategyRemovalTimeBased(CommandContext commandContext) { | String historyRemovalTimeStrategy = commandContext.getProcessEngineConfiguration()
.getHistoryCleanupStrategy();
return HISTORY_CLEANUP_STRATEGY_REMOVAL_TIME_BASED.equals(historyRemovalTimeStrategy);
}
protected boolean isWithinBatchWindow(CommandContext commandContext) {
return HistoryCleanupHelper.isWithinBatchWindow(ClockUtil.getCurrentTime(), commandContext.getProcessEngineConfiguration());
}
public HistoryCleanupJobHandlerConfiguration newConfiguration(String canonicalString) {
JsonObject jsonObject = JsonUtil.asObject(canonicalString);
return HistoryCleanupJobHandlerConfiguration.fromJson(jsonObject);
}
public String getType() {
return TYPE;
}
public void onDelete(HistoryCleanupJobHandlerConfiguration configuration, JobEntity jobEntity) {
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\historycleanup\HistoryCleanupJobHandler.java | 1 |
请完成以下Java代码 | public class TransientVariableInstance implements VariableInstance {
public static String TYPE_TRANSIENT = "transient";
protected String variableName;
protected Object variableValue;
public TransientVariableInstance(String variableName, Object variableValue) {
this.variableName = variableName;
this.variableValue = variableValue;
}
@Override
public String getName() {
return variableName;
}
@Override
public String getTextValue() {
return null;
}
@Override
public void setTextValue(String textValue) {}
@Override
public String getTextValue2() {
return null;
}
@Override
public void setTextValue2(String textValue2) {}
@Override
public Long getLongValue() {
return null;
}
@Override
public void setLongValue(Long longValue) {}
@Override
public Double getDoubleValue() {
return null;
}
@Override
public void setDoubleValue(Double doubleValue) {}
@Override
public byte[] getBytes() {
return null;
}
@Override
public void setBytes(byte[] bytes) {}
@Override
public Object getCachedValue() {
return null;
}
@Override
public void setCachedValue(Object cachedValue) {}
@Override
public String getId() {
return null;
}
@Override
public void setId(String id) {}
@Override
public boolean isInserted() {
return false;
}
@Override
public void setInserted(boolean inserted) {}
@Override
public boolean isUpdated() {
return false;
}
@Override
public void setUpdated(boolean updated) {} | @Override
public boolean isDeleted() {
return false;
}
@Override
public void setDeleted(boolean deleted) {}
@Override
public Object getPersistentState() {
return null;
}
@Override
public void setRevision(int revision) {}
@Override
public int getRevision() {
return 0;
}
@Override
public int getRevisionNext() {
return 0;
}
@Override
public void setName(String name) {}
@Override
public void setProcessInstanceId(String processInstanceId) {}
@Override
public void setExecutionId(String executionId) {}
@Override
public Object getValue() {
return variableValue;
}
@Override
public void setValue(Object value) {
variableValue = value;
}
@Override
public String getTypeName() {
return TYPE_TRANSIENT;
}
@Override
public void setTypeName(String typeName) {}
@Override
public String getProcessInstanceId() {
return null;
}
@Override
public String getTaskId() {
return null;
}
@Override
public void setTaskId(String taskId) {}
@Override
public String getExecutionId() {
return null;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TransientVariableInstance.java | 1 |
请完成以下Java代码 | private void addIfMissing(List<String> list, String value) {
if (!list.contains(value)) {
list.add(value);
}
}
@Override
public ConfigurationPropertyName map(String propertySourceName) {
ConfigurationPropertyName configurationPropertyName = this.propertySourceNameCache.get(propertySourceName);
if (configurationPropertyName == null) {
configurationPropertyName = convertName(propertySourceName);
this.propertySourceNameCache.put(propertySourceName, configurationPropertyName);
}
return configurationPropertyName;
}
private ConfigurationPropertyName convertName(String propertySourceName) {
try {
return ConfigurationPropertyName.adapt(propertySourceName, '_', this::processElementValue);
}
catch (Exception ex) {
return ConfigurationPropertyName.EMPTY;
}
}
private CharSequence processElementValue(CharSequence value) {
String result = value.toString().toLowerCase(Locale.ENGLISH); | return isNumber(result) ? "[" + result + "]" : result;
}
private static boolean isNumber(String string) {
return string.chars().allMatch(Character::isDigit);
}
@Override
public BiPredicate<ConfigurationPropertyName, ConfigurationPropertyName> getAncestorOfCheck() {
return this::isAncestorOf;
}
private boolean isAncestorOf(ConfigurationPropertyName name, ConfigurationPropertyName candidate) {
return name.isAncestorOf(candidate) || isLegacyAncestorOf(name, candidate);
}
private boolean isLegacyAncestorOf(ConfigurationPropertyName name, ConfigurationPropertyName candidate) {
if (!name.hasDashedElement()) {
return false;
}
ConfigurationPropertyName legacyCompatibleName = name.asSystemEnvironmentLegacyName();
return legacyCompatibleName != null && legacyCompatibleName.isAncestorOf(candidate);
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\SystemEnvironmentPropertyMapper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean isTimerJobAcquisitionEnabled() {
return configuration.isTimerJobAcquisitionEnabled();
}
public void setTimerJobAcquisitionEnabled(boolean isTimerJobAcquisitionEnabled) {
configuration.setTimerJobAcquisitionEnabled(isTimerJobAcquisitionEnabled);
}
public boolean isResetExpiredJobEnabled() {
return configuration.isResetExpiredJobEnabled();
}
public void setResetExpiredJobEnabled(boolean isResetExpiredJobEnabled) {
configuration.setResetExpiredJobEnabled(isResetExpiredJobEnabled);
}
public Thread getTimerJobAcquisitionThread() {
return timerJobAcquisitionThread;
}
public void setTimerJobAcquisitionThread(Thread timerJobAcquisitionThread) {
this.timerJobAcquisitionThread = timerJobAcquisitionThread;
}
public Thread getAsyncJobAcquisitionThread() {
return asyncJobAcquisitionThread;
}
public void setAsyncJobAcquisitionThread(Thread asyncJobAcquisitionThread) {
this.asyncJobAcquisitionThread = asyncJobAcquisitionThread;
}
public Thread getResetExpiredJobThread() { | return resetExpiredJobThread;
}
public void setResetExpiredJobThread(Thread resetExpiredJobThread) {
this.resetExpiredJobThread = resetExpiredJobThread;
}
public boolean isUnlockOwnedJobs() {
return configuration.isUnlockOwnedJobs();
}
public void setUnlockOwnedJobs(boolean unlockOwnedJobs) {
configuration.setUnlockOwnedJobs(unlockOwnedJobs);
}
@Override
public AsyncTaskExecutor getTaskExecutor() {
return taskExecutor;
}
@Override
public void setTaskExecutor(AsyncTaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\DefaultAsyncJobExecutor.java | 2 |
请完成以下Java代码 | static Quantity extractQtyEntered(final I_C_OrderLine orderLine)
{
final UomId uomId = UomId.ofRepoId(orderLine.getC_UOM_ID());
return Quantitys.of(orderLine.getQtyEntered(), uomId);
}
default boolean isCompleted(@NonNull final I_C_Order order)
{
return DocStatus.ofCode(order.getDocStatus()).isCompleted();
}
DocStatus getDocStatus(OrderId orderId);
void save(I_C_OrderLine orderLine);
de.metas.interfaces.I_C_OrderLine createOrderLine(I_C_Order order);
void setProductId(
@NonNull I_C_OrderLine orderLine,
@NonNull ProductId productId,
boolean setUOM);
CurrencyConversionContext getCurrencyConversionContext(I_C_Order order);
void deleteLineById(final OrderAndLineId orderAndLineId);
String getDescriptionBottomById(@NonNull OrderId orderId);
String getDescriptionById(@NonNull OrderId orderId);
void setShipperId(@NonNull I_C_Order order); | default boolean isLUQtySet(final @NonNull de.metas.interfaces.I_C_OrderLine orderLine)
{
final BigDecimal luQty = orderLine.getQtyLU();
return luQty != null && luQty.signum() > 0;
}
PaymentTermId getPaymentTermId(@NonNull I_C_Order orderRecord);
Money getGrandTotal(@NonNull I_C_Order order);
void save(I_C_Order order);
void syncDatesFromTransportOrder(@NonNull OrderId orderId, @NonNull I_M_ShipperTransportation transportOrder);
void syncDateInvoicedFromInvoice(@NonNull OrderId orderId, @NonNull I_C_Invoice invoice);
List<I_C_Order> getByQueryFilter(final IQueryFilter<I_C_Order> queryFilter);
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\IOrderBL.java | 1 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (!getView().hasEditableRow())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("view does not have an editable row");
}
if (!isSingleSelectedRow())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("not a single selected row");
}
final PricingConditionsRow row = getSingleSelectedRow();
if (row.isEditable())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("select other row than editable row");
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
patchEditableRow(createChangeRequest(getSingleSelectedRow()));
return MSG_OK;
}
@Override
protected void postProcess(final boolean success)
{
invalidateView();
}
private PricingConditionsRowChangeRequest createChangeRequest(@NonNull final PricingConditionsRow templateRow)
{
final PricingConditionsBreak templatePricingConditionsBreak = templateRow.getPricingConditionsBreak();
PriceSpecification price = templatePricingConditionsBreak.getPriceSpecification();
if (price.isNoPrice())
{
// In case row does not have a price then use BPartner's pricing system
final BPartnerId bpartnerId = templateRow.getBpartnerId();
final SOTrx soTrx = SOTrx.ofBoolean(templateRow.isCustomer());
price = createBasePricingSystemPrice(bpartnerId, soTrx);
}
final Percent discount = templatePricingConditionsBreak.getDiscount(); | final PaymentTermId paymentTermIdOrNull = templatePricingConditionsBreak.getPaymentTermIdOrNull();
final Percent paymentDiscountOverrideOrNull = templatePricingConditionsBreak.getPaymentDiscountOverrideOrNull();
return PricingConditionsRowChangeRequest.builder()
.priceChange(CompletePriceChange.of(price))
.discount(discount)
.paymentTermId(Optional.ofNullable(paymentTermIdOrNull))
.paymentDiscount(Optional.ofNullable(paymentDiscountOverrideOrNull))
.sourcePricingConditionsBreakId(templatePricingConditionsBreak.getId())
.build();
}
private PriceSpecification createBasePricingSystemPrice(final BPartnerId bpartnerId, final SOTrx soTrx)
{
final PricingSystemId pricingSystemId = bpartnersRepo.retrievePricingSystemIdOrNull(bpartnerId, soTrx);
if (pricingSystemId == null)
{
return PriceSpecification.none();
}
return PriceSpecification.basePricingSystem(pricingSystemId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\process\PricingConditionsView_CopyRowToEditable.java | 1 |
请完成以下Java代码 | protected Medicine doRead() {
if (expiringMedicineList != null && !expiringMedicineList.isEmpty()) {
return expiringMedicineList.get(getCurrentItemCount() - 1);
}
return null;
}
@Override
protected void doOpen() {
expiringMedicineList = jdbcTemplate.query(FIND_EXPIRING_SOON_MEDICINE, ps -> ps.setLong(1, defaultExpiration), (rs, row) -> getMedicine(rs));
log.info("Trace = {}. Found {} meds that expires soon", traceId, expiringMedicineList.size());
if (!expiringMedicineList.isEmpty()) {
setMaxItemCount(expiringMedicineList.size());
}
}
private static Medicine getMedicine(ResultSet rs) throws SQLException {
return new Medicine(UUID.fromString(rs.getString(1)), rs.getString(2), MedicineCategory.valueOf(rs.getString(3)), rs.getTimestamp(4), rs.getDouble(5), rs.getObject(6, Double.class));
} | @Override
protected void doClose() {
}
@PostConstruct
public void init() {
setName(ClassUtils.getShortName(getClass()));
}
@BeforeStep
public void beforeStep(StepExecution stepExecution) {
JobParameters parameters = stepExecution.getJobExecution()
.getJobParameters();
log.info("Before step params: {}", parameters);
}
} | repos\tutorials-master\spring-batch\src\main\java\com\baeldung\batchreaderproperties\job\ExpiresSoonMedicineReader.java | 1 |
请完成以下Java代码 | public class JsonAuthResponse
{
@JsonProperty("access_token")
private String accessToken;
@JsonProperty("expires_in")
private long expiresInSeconds;
@JsonProperty("refresh_expires_in")
private long refreshExpiresIn;
@JsonProperty("refresh_token")
private String refreshToken;
@JsonProperty("token_type")
private String tokenType;
@JsonProperty("not-before-policy")
private String notBeforePolicy;
@JsonProperty("session_stat") | private String sessionState;
@JsonProperty("error")
private String error;
@JsonProperty("error_description")
private String errorDescription;
@JsonIgnore
private final Instant acquiredTimestamp = Instant.now();
@JsonIgnore
public boolean isExpired()
{
return Duration.between(acquiredTimestamp, Instant.now()).getSeconds() >= getExpiresInSeconds();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\client\schema\JsonAuthResponse.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WorkflowLaunchersFacetGroupList
{
public static final WorkflowLaunchersFacetGroupList EMPTY = new WorkflowLaunchersFacetGroupList(ImmutableList.of());
@NonNull ImmutableList<WorkflowLaunchersFacetGroup> groups;
private WorkflowLaunchersFacetGroupList(@NonNull final ImmutableList<WorkflowLaunchersFacetGroup> groups)
{
this.groups = groups;
}
public static WorkflowLaunchersFacetGroupList of(final WorkflowLaunchersFacetGroup... groups)
{
if (groups == null || groups.length == 0)
{
return EMPTY;
} | return new WorkflowLaunchersFacetGroupList(ImmutableList.copyOf(groups));
}
public static WorkflowLaunchersFacetGroupList ofList(@Nullable final List<WorkflowLaunchersFacetGroup> groups)
{
if (groups == null || groups.isEmpty())
{
return EMPTY;
}
return new WorkflowLaunchersFacetGroupList(ImmutableList.copyOf(groups));
}
public Stream<WorkflowLaunchersFacetGroup> stream() {return groups.stream();}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\rest_workflows\facets\WorkflowLaunchersFacetGroupList.java | 2 |
请完成以下Java代码 | private void invokeDelegateOnMessage(ConsumerRecord<K, V> consumerRecord, Acknowledgment acknowledgment, Consumer<?, ?> consumer) {
switch (this.delegateType) {
case ACKNOWLEDGING_CONSUMER_AWARE:
this.delegate.onMessage(consumerRecord, acknowledgment, consumer);
break;
case ACKNOWLEDGING:
this.delegate.onMessage(consumerRecord, acknowledgment);
break;
case CONSUMER_AWARE:
this.delegate.onMessage(consumerRecord, consumer);
break;
case SIMPLE:
this.delegate.onMessage(consumerRecord);
}
}
private KafkaConsumerBackoffManager.Context createContext(ConsumerRecord<K, V> data, long nextExecutionTimestamp, Consumer<?, ?> consumer) {
return this.kafkaConsumerBackoffManager.createContext(nextExecutionTimestamp, this.listenerId, new TopicPartition(data.topic(), data.partition()),
consumer);
} | @Override
public void onMessage(ConsumerRecord<K, V> data) {
onMessage(data, null, null);
}
@Override
public void onMessage(ConsumerRecord<K, V> data, Acknowledgment acknowledgment) {
onMessage(data, acknowledgment, null);
}
@Override
public void onMessage(ConsumerRecord<K, V> data, Consumer<?, ?> consumer) {
onMessage(data, null, consumer);
}
} | repos\tutorials-master\spring-kafka-3\src\main\java\com\baeldung\spring\kafka\delay\DelayedMessageListenerAdapter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Builder wantAuthnRequestsSigned(boolean wantAuthnRequestsSigned) {
return (Builder) super.wantAuthnRequestsSigned(wantAuthnRequestsSigned);
}
/**
* {@inheritDoc}
*/
@Override
public Builder signingAlgorithms(Consumer<List<String>> signingMethodAlgorithmsConsumer) {
return (Builder) super.signingAlgorithms(signingMethodAlgorithmsConsumer);
}
/**
* {@inheritDoc}
*/
@Override
public Builder verificationX509Credentials(Consumer<Collection<Saml2X509Credential>> credentialsConsumer) {
return (Builder) super.verificationX509Credentials(credentialsConsumer);
}
/**
* {@inheritDoc}
*/
@Override
public Builder encryptionX509Credentials(Consumer<Collection<Saml2X509Credential>> credentialsConsumer) {
return (Builder) super.encryptionX509Credentials(credentialsConsumer);
}
/**
* {@inheritDoc}
*/
@Override
public Builder singleSignOnServiceLocation(String singleSignOnServiceLocation) {
return (Builder) super.singleSignOnServiceLocation(singleSignOnServiceLocation);
}
/**
* {@inheritDoc}
*/
@Override
public Builder singleSignOnServiceBinding(Saml2MessageBinding singleSignOnServiceBinding) { | return (Builder) super.singleSignOnServiceBinding(singleSignOnServiceBinding);
}
/**
* {@inheritDoc}
*/
@Override
public Builder singleLogoutServiceLocation(String singleLogoutServiceLocation) {
return (Builder) super.singleLogoutServiceLocation(singleLogoutServiceLocation);
}
/**
* {@inheritDoc}
*/
@Override
public Builder singleLogoutServiceResponseLocation(String singleLogoutServiceResponseLocation) {
return (Builder) super.singleLogoutServiceResponseLocation(singleLogoutServiceResponseLocation);
}
/**
* {@inheritDoc}
*/
@Override
public Builder singleLogoutServiceBinding(Saml2MessageBinding singleLogoutServiceBinding) {
return (Builder) super.singleLogoutServiceBinding(singleLogoutServiceBinding);
}
/**
* Build an
* {@link org.springframework.security.saml2.provider.service.registration.OpenSamlAssertingPartyDetails}
* @return
*/
@Override
public OpenSamlAssertingPartyDetails build() {
return new OpenSamlAssertingPartyDetails(super.build(), this.descriptor);
}
}
} | repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\registration\OpenSamlAssertingPartyDetails.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private String getCountryCodeById(@NonNull final String countryId)
{
final String isoCountryCode = countryIdToISOCode.get(countryId);
if (!Check.isEmpty(isoCountryCode))
{
return isoCountryCode;
}
final String isoCode = shopwareClient.getCountryDetails(countryId)
.map(JsonCountry::getIso)
.orElseThrow(() -> new RuntimeException("Missing country code for countryId: " + countryId));
countryIdToISOCode.put(countryId, isoCode);
return isoCode;
}
@NonNull
private JsonRequestLocationUpsertItem getBillingLocationUpsertRequest()
{
return getUpsertLocationItemRequest(
billingAddress,
true /*isBillingAddress*/, | isBillingAddressSameAsShippingAddress());
}
private boolean isBillingAddressSameAsShippingAddress()
{
return Objects.equals(shippingAddress.getJsonAddress().getId(), billingAddress.getJsonAddress().getId())
|| (shippingAddress.getCustomMetasfreshId() != null && Objects.equals(shippingAddress.getCustomMetasfreshId(), billingAddress.getCustomMetasfreshId()));
}
@NonNull
private String computeBPartnerName()
{
final BiFunction<String, String, String> prepareNameSegment = (segment, separator) -> Optional.ofNullable(segment)
.map(StringUtils::trimBlankToNull)
.map(s -> s + separator)
.orElse("");
final JsonCustomerBasicInfo customer = customerCandidate.getCustomerBasicInfo();
return prepareNameSegment.apply(customer.getCompany(), ", ")
+ prepareNameSegment.apply(customer.getFirstName(), " ")
+ prepareNameSegment.apply(customer.getLastName(), "");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\order\processor\BPartnerUpsertRequestProducer.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Vehicle {
@Id
private long vehicleId;
private String manufacturer;
public Vehicle() {
}
public Vehicle(long vehicleId, String manufacturer) {
this.vehicleId = vehicleId;
this.manufacturer = manufacturer;
}
public long getVehicleId() {
return vehicleId; | }
public void setVehicleId(long vehicleId) {
this.vehicleId = vehicleId;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
} | repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\hibernate\pojo\inheritance\Vehicle.java | 2 |
请完成以下Java代码 | public void setPA_Measure_ID (int PA_Measure_ID)
{
if (PA_Measure_ID < 1)
set_Value (COLUMNNAME_PA_Measure_ID, null);
else
set_Value (COLUMNNAME_PA_Measure_ID, Integer.valueOf(PA_Measure_ID));
}
/** Get Measure.
@return Concrete Performance Measurement
*/
public int getPA_Measure_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Measure_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Relative Weight.
@param RelativeWeight
Relative weight of this step (0 = ignored)
*/
public void setRelativeWeight (BigDecimal RelativeWeight)
{
set_Value (COLUMNNAME_RelativeWeight, RelativeWeight);
}
/** Get Relative Weight.
@return Relative weight of this step (0 = ignored)
*/
public BigDecimal getRelativeWeight () | {
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RelativeWeight);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_Goal.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CompanyController {
Map<Long, Company> companyMap = new HashMap<>();
@RequestMapping(value = "/company", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("companyHome", "company", new Company());
}
@RequestMapping(value = "/company/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET)
public @ResponseBody Company getCompanyById(@PathVariable final long Id) {
return companyMap.get(Id);
}
@RequestMapping(value = "/addCompany", method = RequestMethod.POST)
public String submit(@ModelAttribute("company") final Company company, final BindingResult result, final ModelMap model) {
if (result.hasErrors()) {
return "error";
}
model.addAttribute("name", company.getName());
model.addAttribute("id", company.getId()); | companyMap.put(company.getId(), company);
return "companyView";
}
@RequestMapping(value = "/companyEmployee/{company}/employeeData/{employee}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Map<String, String>> getEmployeeDataFromCompany(@MatrixVariable(pathVar = "employee") final Map<String, String> matrixVars) {
return new ResponseEntity<>(matrixVars, HttpStatus.OK);
}
@RequestMapping(value = "/companyData/{company}/employeeData/{employee}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Map<String, String>> getCompanyName(@MatrixVariable(value = "name", pathVar = "company") final String name) {
final Map<String, String> result = new HashMap<>();
result.put("name", name);
return new ResponseEntity<>(result, HttpStatus.OK);
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-java-2\src\main\java\com\baeldung\matrix\controller\CompanyController.java | 2 |
请完成以下Java代码 | public Integer getNumber1() {
return number1;
}
public void setNumber1(Integer number1) {
this.number1 = number1;
}
public Integer getNumber2() {
return number2;
}
public void setNumber2(Integer number2) {
this.number2 = number2;
} | public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
@Override
public String toString() {
return "Operation{" +
"number1=" + number1 +
", number2=" + number2 +
", operator='" + operator + '\'' +
'}';
}
} | repos\tutorials-master\libraries-server-2\src\main\java\com\baeldung\netty\Operation.java | 1 |
请完成以下Java代码 | public final class ReferrerPolicyServerHttpHeadersWriter implements ServerHttpHeadersWriter {
public static final String REFERRER_POLICY = "Referrer-Policy";
private ServerHttpHeadersWriter delegate;
public ReferrerPolicyServerHttpHeadersWriter() {
this.delegate = createDelegate(ReferrerPolicy.NO_REFERRER);
}
@Override
public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) {
return this.delegate.writeHttpHeaders(exchange);
}
/**
* Set the policy to be used in the response header.
* @param policy the policy
* @throws IllegalArgumentException if policy is {@code null}
*/
public void setPolicy(ReferrerPolicy policy) {
Assert.notNull(policy, "policy must not be null");
this.delegate = createDelegate(policy);
}
private static ServerHttpHeadersWriter createDelegate(ReferrerPolicy policy) {
Builder builder = StaticServerHttpHeadersWriter.builder();
builder.header(REFERRER_POLICY, policy.getPolicy());
return builder.build();
}
public enum ReferrerPolicy {
NO_REFERRER("no-referrer"),
NO_REFERRER_WHEN_DOWNGRADE("no-referrer-when-downgrade"), | SAME_ORIGIN("same-origin"),
ORIGIN("origin"),
STRICT_ORIGIN("strict-origin"),
ORIGIN_WHEN_CROSS_ORIGIN("origin-when-cross-origin"),
STRICT_ORIGIN_WHEN_CROSS_ORIGIN("strict-origin-when-cross-origin"),
UNSAFE_URL("unsafe-url");
private static final Map<String, ReferrerPolicy> REFERRER_POLICIES;
static {
Map<String, ReferrerPolicy> referrerPolicies = new HashMap<>();
for (ReferrerPolicy referrerPolicy : values()) {
referrerPolicies.put(referrerPolicy.getPolicy(), referrerPolicy);
}
REFERRER_POLICIES = Collections.unmodifiableMap(referrerPolicies);
}
private final String policy;
ReferrerPolicy(String policy) {
this.policy = policy;
}
public String getPolicy() {
return this.policy;
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\header\ReferrerPolicyServerHttpHeadersWriter.java | 1 |
请完成以下Java代码 | public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public List<String> getComments() {
return comments; | }
public void setComments(List<String> comments) {
this.comments = comments;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
} | repos\tutorials-master\mapstruct\src\main\java\com\baeldung\unmappedproperties\dto\DocumentDTO.java | 1 |
请完成以下Java代码 | public List<Document> complete()
{
final ITrxManager trxManager = Services.get(ITrxManager.class);
trxManager.assertThreadInheritedTrxExists();
final IQuickInputProcessor processor = descriptor.createProcessor();
final DocumentIdsSelection documentLineIds = DocumentIdsSelection.of(processor.process(this));
final Document rootDocument = getRootDocument();
final OrderedDocumentsList includedDocumentsJustCreated = rootDocument.getIncludedDocuments(targetDetailId, documentLineIds);
this.completed = true;
return includedDocumentsJustCreated.toList();
}
public boolean isCompleted()
{
return completed;
}
public JSONLookupValuesList getFieldDropdownValues(final String fieldName, final String adLanguage)
{
return getQuickInputDocument()
.getFieldLookupValues(fieldName)
.transform(lookupValuesList -> JSONLookupValuesList.ofLookupValuesList(lookupValuesList, adLanguage));
}
public JSONLookupValuesPage getFieldTypeaheadValues(final String fieldName, final String query, final String adLanguage)
{
return getQuickInputDocument()
.getFieldLookupValuesForQuery(fieldName, query)
.transform(page -> JSONLookupValuesPage.of(page, adLanguage));
}
public boolean hasField(final String fieldName)
{
return getQuickInputDocument().hasField(fieldName);
}
//
//
// ------
//
//
//
public static final class Builder
{
private static final AtomicInteger nextQuickInputDocumentId = new AtomicInteger(1);
private DocumentPath _rootDocumentPath;
private QuickInputDescriptor _quickInputDescriptor;
private Builder()
{
super();
}
public QuickInput build()
{
return new QuickInput(this);
}
public Builder setRootDocumentPath(final DocumentPath rootDocumentPath)
{
_rootDocumentPath = Preconditions.checkNotNull(rootDocumentPath, "rootDocumentPath");
return this;
} | private DocumentPath getRootDocumentPath()
{
Check.assumeNotNull(_rootDocumentPath, "Parameter rootDocumentPath is not null");
return _rootDocumentPath;
}
public Builder setQuickInputDescriptor(final QuickInputDescriptor quickInputDescriptor)
{
_quickInputDescriptor = quickInputDescriptor;
return this;
}
private QuickInputDescriptor getQuickInputDescriptor()
{
Check.assumeNotNull(_quickInputDescriptor, "Parameter quickInputDescriptor is not null");
return _quickInputDescriptor;
}
private DetailId getTargetDetailId()
{
final DetailId targetDetailId = getQuickInputDescriptor().getDetailId();
Check.assumeNotNull(targetDetailId, "Parameter targetDetailId is not null");
return targetDetailId;
}
private Document buildQuickInputDocument()
{
return Document.builder(getQuickInputDescriptor().getEntityDescriptor())
.initializeAsNewDocument(nextQuickInputDocumentId::getAndIncrement, VERSION_DEFAULT);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\QuickInput.java | 1 |
请完成以下Java代码 | public class StructManager implements Serializable {
private String firstName;
private String lastName;
private String qualification;
@Override
public String toString() {
return "Manager{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", qualification='" + qualification + '\'' +
'}';
}
public StructManager(String firstName, String lastName, String qualification) {
this.firstName = firstName;
this.lastName = lastName;
this.qualification = qualification;
}
public String getFirstName() {
return firstName; | }
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getQualification() {
return qualification;
}
public void setQualification(String qualification) {
this.qualification = qualification;
}
} | repos\tutorials-master\persistence-modules\hibernate-jpa-2\src\main\java\com\baeldung\hibernate\struct\entities\StructManager.java | 1 |
请完成以下Java代码 | public void setM_Demand_ID (int M_Demand_ID)
{
if (M_Demand_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Demand_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Demand_ID, Integer.valueOf(M_Demand_ID));
}
/** Get Demand.
@return Material Demand
*/
public int getM_Demand_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Demand_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Demand Line.
@param M_DemandLine_ID
Material Demand Line
*/
public void setM_DemandLine_ID (int M_DemandLine_ID)
{
if (M_DemandLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DemandLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DemandLine_ID, Integer.valueOf(M_DemandLine_ID));
}
/** Get Demand Line.
@return Material Demand Line
*/
public int getM_DemandLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_DemandLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Quantity.
@param Qty
Quantity
*/
public void setQty (BigDecimal Qty)
{ | set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Quantity.
@return Quantity
*/
public BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Calculated Quantity.
@param QtyCalculated
Calculated Quantity
*/
public void setQtyCalculated (BigDecimal QtyCalculated)
{
set_Value (COLUMNNAME_QtyCalculated, QtyCalculated);
}
/** Get Calculated Quantity.
@return Calculated Quantity
*/
public BigDecimal getQtyCalculated ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyCalculated);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DemandLine.java | 1 |
请完成以下Java代码 | public Object execute(CommandContext commandContext) {
checkQueryOk();
if (resultType == ResultType.LIST) {
return executeList(commandContext);
} else if (resultType == ResultType.SINGLE_RESULT) {
return executeSingleResult(commandContext);
} else if (resultType == ResultType.LIST_PAGE) {
return executeList(commandContext);
} else {
return executeCount(commandContext);
}
}
public abstract long executeCount(CommandContext commandContext);
/** | * Executes the actual query to retrieve the list of results.
*/
public abstract List<U> executeList(CommandContext commandContext);
public U executeSingleResult(CommandContext commandContext) {
List<U> results = executeList(commandContext);
if (results.size() == 1) {
return results.get(0);
} else if (results.size() > 1) {
throw new FlowableException("Query return " + results.size() + " results instead of max 1");
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\query\AbstractQuery.java | 1 |
请完成以下Java代码 | default int getFieldValueAsInt(final String fieldName, final int defaultValue)
{
final Object value = getFieldValue(fieldName);
return value != null ? (int)value : defaultValue;
}
@Nullable
default <T extends RepoIdAware> T getFieldValueAsRepoId(final String fieldName, final Function<Integer, T> idMapper)
{
final int id = getFieldValueAsInt(fieldName, -1);
if (id > 0)
{
return idMapper.apply(id);
}
else
{
return null;
}
}
static SourceDocument toSourceDocumentOrNull(final Object obj)
{
if (obj == null)
{
return null;
}
if (obj instanceof SourceDocument)
{
return (SourceDocument)obj;
}
final PO po = getPO(obj);
return new POSourceDocument(po);
}
}
@AllArgsConstructor
private static final class POSourceDocument implements SourceDocument
{
@NonNull
private final PO po;
@Override
public boolean hasFieldValue(final String fieldName)
{ | return po.get_ColumnIndex(fieldName) >= 0;
}
@Override
public Object getFieldValue(final String fieldName)
{
return po.get_Value(fieldName);
}
}
@AllArgsConstructor
private static final class GridTabSourceDocument implements SourceDocument
{
@NonNull
private final GridTab gridTab;
@Override
public boolean hasFieldValue(final String fieldName)
{
return gridTab.getField(fieldName) != null;
}
@Override
public Object getFieldValue(final String fieldName)
{
return gridTab.getValue(fieldName);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\letters\model\MADBoilerPlate.java | 1 |
请完成以下Java代码 | public void setA_RegistrationAttribute_ID (int A_RegistrationAttribute_ID)
{
if (A_RegistrationAttribute_ID < 1)
set_ValueNoCheck (COLUMNNAME_A_RegistrationAttribute_ID, null);
else
set_ValueNoCheck (COLUMNNAME_A_RegistrationAttribute_ID, Integer.valueOf(A_RegistrationAttribute_ID));
}
/** Get Registration Attribute.
@return Asset Registration Attribute
*/
public int getA_RegistrationAttribute_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_RegistrationAttribute_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getA_RegistrationAttribute_ID()));
}
public I_A_Registration getA_Registration() throws RuntimeException
{
return (I_A_Registration)MTable.get(getCtx(), I_A_Registration.Table_Name)
.getPO(getA_Registration_ID(), get_TrxName()); }
/** Set Registration.
@param A_Registration_ID
User Asset Registration
*/
public void setA_Registration_ID (int A_Registration_ID)
{
if (A_Registration_ID < 1)
set_ValueNoCheck (COLUMNNAME_A_Registration_ID, null);
else
set_ValueNoCheck (COLUMNNAME_A_Registration_ID, Integer.valueOf(A_Registration_ID));
}
/** Get Registration. | @return User Asset Registration
*/
public int getA_Registration_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_Registration_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 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);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_RegistrationValue.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void init() {
pageCounter = randomIntGen.nextInt();
FacesContext.getCurrentInstance()
.getApplication()
.addELContextListener(new ELContextListener() {
@Override
public void contextCreated(ELContextEvent evt) {
evt.getELContext()
.getImportHandler()
.importClass("com.baeldung.springintegration.controllers.ELSampleBean");
}
});
}
public void save() {
}
public static String constantField() {
return constantField;
}
public void saveFirstName(String firstName) {
this.firstName = firstName;
}
public Long multiplyValue(LambdaExpression expr) {
Long theResult = (Long) expr.invoke(FacesContext.getCurrentInstance()
.getELContext(), pageCounter);
return theResult;
}
public void saveByELEvaluation() {
firstName = (String) evaluateEL("#{firstName.value}", String.class);
FacesContext ctx = FacesContext.getCurrentInstance();
FacesMessage theMessage = new FacesMessage("Name component Evaluated: " + firstName);
theMessage.setSeverity(FacesMessage.SEVERITY_INFO);
ctx.addMessage(null, theMessage);
}
private Object evaluateEL(String elExpression, Class<?> clazz) {
Object toReturn = null;
FacesContext ctx = FacesContext.getCurrentInstance();
Application app = ctx.getApplication();
toReturn = app.evaluateExpressionGet(ctx, elExpression, clazz);
return toReturn;
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
} | /**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @return the pageDescription
*/
public String getPageDescription() {
return pageDescription;
}
/**
* @param pageDescription the pageDescription to set
*/
public void setPageDescription(String pageDescription) {
this.pageDescription = pageDescription;
}
/**
* @return the pageCounter
*/
public int getPageCounter() {
return pageCounter;
}
/**
* @param pageCounter the pageCounter to set
*/
public void setPageCounter(int pageCounter) {
this.pageCounter = pageCounter;
}
} | repos\tutorials-master\web-modules\jsf\src\main\java\com\baeldung\springintegration\controllers\ELSampleBean.java | 2 |
请完成以下Java代码 | public boolean containsKey(Object key) {
if(wrappedBindings.containsKey(key)) {
return true;
}
if (key instanceof String) {
return variableContext.containsVariable((String) key);
}
else {
return false;
}
}
/**
* Dedicated implementation which does not fall back on the {@link #calculateBindingMap()} for performance reasons
*/
public Object get(Object key) {
Object result = null;
if(wrappedBindings.containsKey(key)) {
result = wrappedBindings.get(key);
}
else {
if (key instanceof String) {
TypedValue resolvedValue = variableContext.resolve((String) key);
result = unpack(resolvedValue);
}
}
return result;
}
/**
* Dedicated implementation which does not fall back on the {@link #calculateBindingMap()} for performance reasons
*/
public Object put(String name, Object value) {
// only write to the wrapped bindings
return wrappedBindings.put(name, value);
}
public Set<Entry<String, Object>> entrySet() {
return calculateBindingMap().entrySet();
}
public Set<String> keySet() {
return calculateBindingMap().keySet();
}
public int size() {
return calculateBindingMap().size();
}
public Collection<Object> values() {
return calculateBindingMap().values();
}
public void putAll(Map< ? extends String, ?> toMerge) {
for (Entry<? extends String, ?> entry : toMerge.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
public Object remove(Object key) { | return wrappedBindings.remove(key);
}
public void clear() {
wrappedBindings.clear();
}
public boolean containsValue(Object value) {
return calculateBindingMap().containsValue(value);
}
public boolean isEmpty() {
return calculateBindingMap().isEmpty();
}
protected Map<String, Object> calculateBindingMap() {
Map<String, Object> bindingMap = new HashMap<String, Object>();
Set<String> keySet = variableContext.keySet();
for (String variableName : keySet) {
bindingMap.put(variableName, unpack(variableContext.resolve(variableName)));
}
Set<Entry<String, Object>> wrappedBindingsEntries = wrappedBindings.entrySet();
for (Entry<String, Object> entry : wrappedBindingsEntries) {
bindingMap.put(entry.getKey(), entry.getValue());
}
return bindingMap;
}
protected Object unpack(TypedValue resolvedValue) {
if(resolvedValue != null) {
return resolvedValue.getValue();
}
return null;
}
public static VariableContextScriptBindings wrap(Bindings wrappedBindings, VariableContext variableContext) {
return new VariableContextScriptBindings(wrappedBindings, variableContext);
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\el\VariableContextScriptBindings.java | 1 |
请完成以下Java代码 | private static void addOrderBy(
@NonNull final IQueryBuilder<I_DD_Order> queryBuilder,
@NonNull final DDOrderQuery.OrderBy orderBy)
{
final DDOrderQuery.OrderByField field = orderBy.getField();
final String sqlColumnName;
if (field == DDOrderQuery.OrderByField.PriorityRule)
{
sqlColumnName = I_DD_Order.COLUMNNAME_PriorityRule;
}
else if (field == DDOrderQuery.OrderByField.DatePromised)
{
sqlColumnName = I_DD_Order.COLUMNNAME_DatePromised;
}
else if (field == DDOrderQuery.OrderByField.SeqNo)
{
sqlColumnName = I_DD_Order.COLUMNNAME_SeqNo;
}
else
{
throw new AdempiereException("Unknown order by: " + orderBy);
}
final IQueryOrderBy.Direction direction = orderBy.getDirection();
if (direction.isAscending())
{
queryBuilder.orderBy(sqlColumnName);
}
else
{
queryBuilder.orderByDescending(sqlColumnName);
}
}
private void deleteLines(@NonNull final I_DD_Order order)
{
queryBL.createQueryBuilder(I_DD_OrderLine.class)
.addEqualsFilter(I_DD_OrderLine.COLUMNNAME_DD_Order_ID, order.getDD_Order_ID())
.create()
.deleteDirectly();
}
public void updateForwardPPOrderByIds(@NonNull final Set<DDOrderId> ddOrderIds, @Nullable final PPOrderId newPPOrderId)
{
if (ddOrderIds.isEmpty())
{
return;
} | queryBL.createQueryBuilder(I_DD_Order.class)
.addInArrayFilter(I_DD_Order.COLUMNNAME_DD_Order_ID, ddOrderIds)
.addNotEqualsFilter(I_DD_Order.COLUMNNAME_Forward_PP_Order_ID, newPPOrderId)
.create()
.update(ddOrder -> {
ddOrder.setForward_PP_Order_ID(PPOrderId.toRepoId(newPPOrderId));
return IQueryUpdater.MODEL_UPDATED;
});
}
public Set<ProductId> getProductIdsByDDOrderIds(final Collection<DDOrderId> ddOrderIds)
{
if (ddOrderIds.isEmpty())
{
return ImmutableSet.of();
}
final List<ProductId> productIds = queryBL.createQueryBuilder(I_DD_OrderLine.class)
.addInArrayFilter(I_DD_Order.COLUMNNAME_DD_Order_ID, ddOrderIds)
.addOnlyActiveRecordsFilter()
.create()
.listDistinct(I_DD_OrderLine.COLUMNNAME_M_Product_ID, ProductId.class);
return ImmutableSet.copyOf(productIds);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddorder\lowlevel\DDOrderLowLevelDAO.java | 1 |
请完成以下Java代码 | public void prepare()
{
// Just opening the ResultSet if is not already opened.
// Following method will make sure that the ResultSet was not already opened and closed.
getResultSet();
}
@Override
public List<String> getFieldNames()
{
return fields;
}
@Override
public void close()
{
DB.close(rs, pstmt);
rs = null;
pstmt = null;
DB.close(conn);
conn = null;
currentRow = null;
closed = true;
}
@Override
public boolean hasNext()
{
if (currentRow == null)
{
currentRow = retrieveNextOrNull();
}
return currentRow != null;
}
@Override
public List<Object> next()
{
if (currentRow != null)
{
final List<Object> rowToReturn = currentRow;
currentRow = null;
return rowToReturn;
}
currentRow = retrieveNextOrNull();
if (currentRow == null)
{
throw new NoSuchElementException();
}
return currentRow;
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
private List<Object> readLine(ResultSet rs, List<String> sqlFields) throws SQLException
{
final List<Object> values = new ArrayList<Object>();
for (final String columnName : sqlFields)
{
final Object value = rs.getObject(columnName);
values.add(value);
}
return values;
}
private Integer rowsCount = null;
@Override
public int size()
{
if (Check.isEmpty(sqlCount, true)) | {
throw new IllegalStateException("Counting is not supported");
}
if (rowsCount == null)
{
logger.info("SQL: {}", sqlCount);
logger.info("SQL Params: {}", sqlParams);
rowsCount = DB.getSQLValueEx(Trx.TRXNAME_None, sqlCount, sqlParams);
logger.info("Rows Count: {}" + rowsCount);
}
return rowsCount;
}
public String getSqlSelect()
{
return sqlSelect;
}
public List<Object> getSqlParams()
{
if (sqlParams == null)
{
return Collections.emptyList();
}
return sqlParams;
}
public String getSqlWhereClause()
{
return sqlWhereClause;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\JdbcExportDataSource.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ExternalSystemGRSSignumConfig implements IExternalSystemChildConfig
{
@NonNull
ExternalSystemGRSSignumConfigId id;
@NonNull
ExternalSystemParentConfigId parentId;
@NonNull
String value;
@NonNull
String baseUrl;
@NonNull
String tenantId;
@Nullable
String camelHttpResourceAuthKey;
@Nullable
String authToken;
@Nullable
String basePathForExportDirectories;
@Nullable
String bPartnerExportDirectories;
boolean syncBPartnersToRestEndpoint;
boolean autoSendVendors;
boolean autoSendCustomers;
boolean syncHUsOnMaterialReceipt;
boolean syncHUsOnProductionReceipt;
boolean createBPartnerFolders;
@Builder
ExternalSystemGRSSignumConfig(
@NonNull final ExternalSystemGRSSignumConfigId id,
@NonNull final ExternalSystemParentConfigId parentId,
@NonNull final String value,
@NonNull final String baseUrl,
@NonNull final String tenantId,
@Nullable final String camelHttpResourceAuthKey,
@Nullable final String authToken,
@Nullable final String basePathForExportDirectories,
@Nullable final String bPartnerExportDirectories,
final boolean syncBPartnersToRestEndpoint,
final boolean autoSendVendors,
final boolean autoSendCustomers,
final boolean syncHUsOnMaterialReceipt, | final boolean syncHUsOnProductionReceipt,
final boolean createBPartnerFolders)
{
this.id = id;
this.parentId = parentId;
this.value = value;
this.baseUrl = baseUrl;
this.tenantId = tenantId;
this.camelHttpResourceAuthKey = camelHttpResourceAuthKey;
this.authToken = authToken;
this.bPartnerExportDirectories = bPartnerExportDirectories;
this.basePathForExportDirectories = basePathForExportDirectories;
this.syncBPartnersToRestEndpoint = syncBPartnersToRestEndpoint;
this.autoSendVendors = autoSendVendors;
this.autoSendCustomers = autoSendCustomers;
this.syncHUsOnMaterialReceipt = syncHUsOnMaterialReceipt;
this.syncHUsOnProductionReceipt = syncHUsOnProductionReceipt;
this.createBPartnerFolders = createBPartnerFolders;
}
public static ExternalSystemGRSSignumConfig cast(@NonNull final IExternalSystemChildConfig childConfig)
{
return (ExternalSystemGRSSignumConfig)childConfig;
}
@JsonIgnore
public boolean isHUsSyncEnabled()
{
return syncHUsOnMaterialReceipt || syncHUsOnProductionReceipt;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\grssignum\ExternalSystemGRSSignumConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable Integer getPort() {
return this.port;
}
public void setPort(@Nullable Integer port) {
this.port = port;
}
public @Nullable InetAddress getAddress() {
return this.address;
}
public void setAddress(@Nullable InetAddress address) {
this.address = address;
}
public RSocketServer.Transport getTransport() {
return this.transport;
}
public void setTransport(RSocketServer.Transport transport) {
this.transport = transport;
}
public @Nullable String getMappingPath() {
return this.mappingPath;
}
public void setMappingPath(@Nullable String mappingPath) {
this.mappingPath = mappingPath;
}
public @Nullable DataSize getFragmentSize() {
return this.fragmentSize;
}
public void setFragmentSize(@Nullable DataSize fragmentSize) {
this.fragmentSize = fragmentSize;
}
public @Nullable Ssl getSsl() {
return this.ssl;
}
public void setSsl(@Nullable Ssl ssl) {
this.ssl = ssl;
}
public Spec getSpec() {
return this.spec;
}
public static class Spec {
/**
* Sub-protocols to use in websocket handshake signature.
*/
private @Nullable String protocols; | /**
* Maximum allowable frame payload length.
*/
private DataSize maxFramePayloadLength = DataSize.ofBytes(65536);
/**
* Whether to proxy websocket ping frames or respond to them.
*/
private boolean handlePing;
/**
* Whether the websocket compression extension is enabled.
*/
private boolean compress;
public @Nullable String getProtocols() {
return this.protocols;
}
public void setProtocols(@Nullable String protocols) {
this.protocols = protocols;
}
public DataSize getMaxFramePayloadLength() {
return this.maxFramePayloadLength;
}
public void setMaxFramePayloadLength(DataSize maxFramePayloadLength) {
this.maxFramePayloadLength = maxFramePayloadLength;
}
public boolean isHandlePing() {
return this.handlePing;
}
public void setHandlePing(boolean handlePing) {
this.handlePing = handlePing;
}
public boolean isCompress() {
return this.compress;
}
public void setCompress(boolean compress) {
this.compress = compress;
}
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-rsocket\src\main\java\org\springframework\boot\rsocket\autoconfigure\RSocketProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | abstract static class AbstractGrantedAuthorityDefaultsBeanFactory implements ApplicationContextAware {
protected String rolePrefix = "ROLE_";
@Override
public final void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
applicationContext.getBeanProvider(GrantedAuthorityDefaults.class)
.ifUnique((grantedAuthorityDefaults) -> this.rolePrefix = grantedAuthorityDefaults.getRolePrefix());
}
}
/**
* Delays setting a bean of a given name to be lazyily initialized until after all the
* beans are registered.
*
* @author Rob Winch
* @since 3.2
*/
private static final class LazyInitBeanDefinitionRegistryPostProcessor
implements BeanDefinitionRegistryPostProcessor {
private final String beanName; | private LazyInitBeanDefinitionRegistryPostProcessor(String beanName) {
this.beanName = beanName;
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
if (!registry.containsBeanDefinition(this.beanName)) {
return;
}
BeanDefinition beanDefinition = registry.getBeanDefinition(this.beanName);
beanDefinition.setLazyInit(true);
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\method\GlobalMethodSecurityBeanDefinitionParser.java | 2 |
请完成以下Java代码 | public ProjectTypeId getFirstIdByProjectCategoryAndOrg(
@NonNull final ProjectCategory projectCategory,
@NonNull final OrgId orgId,
final boolean onlyCurrentOrg)
{
final ProjectTypeId projectTypeId = getFirstIdByProjectCategoryAndOrgOrNull(projectCategory, orgId, onlyCurrentOrg);
if (projectTypeId == null)
{
throw new AdempiereException("@NotFound@ @C_ProjectType_ID@")
.appendParametersToMessage()
.setParameter("ProjectCategory", projectCategory)
.setParameter("AD_Org_ID", orgId.getRepoId());
}
return projectTypeId;
}
@Nullable
public ProjectTypeId getFirstIdByProjectCategoryAndOrgOrNull(
@NonNull final ProjectCategory projectCategory,
@NonNull final OrgId orgId,
final boolean onlyCurrentOrg)
{
final IQueryBuilder<I_C_ProjectType> builder = queryBL.createQueryBuilderOutOfTrx(I_C_ProjectType.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_ProjectType.COLUMNNAME_ProjectCategory, projectCategory.getCode())
.orderByDescending(I_C_ProjectType.COLUMNNAME_AD_Org_ID)
.orderBy(I_C_ProjectType.COLUMNNAME_C_ProjectType_ID);
if (onlyCurrentOrg)
{
builder.addInArrayFilter(I_C_ProjectType.COLUMNNAME_AD_Org_ID, orgId); | }
else
{
builder.addInArrayFilter(I_C_ProjectType.COLUMNNAME_AD_Org_ID, OrgId.ANY, orgId);
}
return builder
.create()
.firstId(ProjectTypeId::ofRepoIdOrNull);
}
public I_C_ProjectType getByName(final @NonNull String projectTypeValue)
{
return queryBL.createQueryBuilderOutOfTrx(I_C_ProjectType.class)
.addEqualsFilter(I_C_ProjectType.COLUMNNAME_Name, projectTypeValue)
.create()
.firstOnlyNotNull(I_C_ProjectType.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\project\ProjectTypeRepository.java | 1 |
请完成以下Java代码 | public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
@Override
public org.compiere.model.I_C_ElementValue getUser1()
{
return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser1(org.compiere.model.I_C_ElementValue User1)
{
set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1);
}
/** Set User List 1.
@param User1_ID
User defined list element #1
*/
@Override
public void setUser1_ID (int User1_ID)
{
if (User1_ID < 1)
set_Value (COLUMNNAME_User1_ID, null);
else
set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID));
}
/** Get User List 1.
@return User defined list element #1
*/
@Override
public int getUser1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ElementValue getUser2()
{
return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser2(org.compiere.model.I_C_ElementValue User2)
{
set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2);
}
/** Set User List 2.
@param User2_ID
User defined list element #2
*/
@Override
public void setUser2_ID (int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID));
}
/** Get User List 2.
@return User defined list element #2
*/
@Override
public int getUser2_ID ()
{ | Integer ii = (Integer)get_Value(COLUMNNAME_User2_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set User Element 1.
@param UserElement1_ID
User defined accounting Element
*/
@Override
public void setUserElement1_ID (int UserElement1_ID)
{
if (UserElement1_ID < 1)
set_Value (COLUMNNAME_UserElement1_ID, null);
else
set_Value (COLUMNNAME_UserElement1_ID, Integer.valueOf(UserElement1_ID));
}
/** Get User Element 1.
@return User defined accounting Element
*/
@Override
public int getUserElement1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UserElement1_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set User Element 2.
@param UserElement2_ID
User defined accounting Element
*/
@Override
public void setUserElement2_ID (int UserElement2_ID)
{
if (UserElement2_ID < 1)
set_Value (COLUMNNAME_UserElement2_ID, null);
else
set_Value (COLUMNNAME_UserElement2_ID, Integer.valueOf(UserElement2_ID));
}
/** Get User Element 2.
@return User defined accounting Element
*/
@Override
public int getUserElement2_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UserElement2_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Fact_Acct_Summary.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.