instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public String toString()
{
return "Partition [DLM_Partition_ID=" + DLM_Partition_ID + ", records.size()=" + records.size() + ", recordsChanged=" + recordsChanged + ", configChanged=" + configChanged + ", targetDLMLevel=" + targetDLMLevel + ", currentDLMLevel=" + currentDLMLevel + ", nextInspectionDate=" + nextInspectionDate + "]";
}
public static class WorkQueue
{
public static WorkQueue of(final I_DLM_Partition_Workqueue workqueueDB)
{
final ITableRecordReference tableRecordRef = TableRecordReference.ofReferencedOrNull(workqueueDB);
final WorkQueue result = new WorkQueue(tableRecordRef);
result.setDLM_Partition_Workqueue_ID(workqueueDB.getDLM_Partition_Workqueue_ID());
return result;
}
public static WorkQueue of(final ITableRecordReference tableRecordRef)
{
return new WorkQueue(tableRecordRef);
}
private final ITableRecordReference tableRecordReference;
private int dlmPartitionWorkqueueId;
private WorkQueue(final ITableRecordReference tableRecordReference)
{
this.tableRecordReference = tableRecordReference;
} | public ITableRecordReference getTableRecordReference()
{
return tableRecordReference;
}
public int getDLM_Partition_Workqueue_ID()
{
return dlmPartitionWorkqueueId;
}
public void setDLM_Partition_Workqueue_ID(final int dlm_Partition_Workqueue_ID)
{
dlmPartitionWorkqueueId = dlm_Partition_Workqueue_ID;
}
@Override
public String toString()
{
return "Partition.WorkQueue [DLM_Partition_Workqueue_ID=" + dlmPartitionWorkqueueId + ", tableRecordReference=" + tableRecordReference + "]";
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\Partition.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RedisLockService {
private Logger logger = LoggerFactory.getLogger(RedisLockService.class);
private static final long DEFAULT_EXPIRE_UNUSED = 60000L;
private final RedisLockRegistry redisLockRegistry;
public void lock(String lockKey) {
Lock lock = obtainLock(lockKey);
lock.lock();
}
public boolean tryLock(String lockKey) {
Lock lock = obtainLock(lockKey);
return lock.tryLock();
}
public boolean tryLock(String lockKey, long seconds) {
Lock lock = obtainLock(lockKey);
try {
return lock.tryLock(seconds, TimeUnit.SECONDS);
} catch (InterruptedException e) {
return false;
} | }
public void unlock(String lockKey) {
try {
Lock lock = obtainLock(lockKey);
lock.unlock();
redisLockRegistry.expireUnusedOlderThan(DEFAULT_EXPIRE_UNUSED);
} catch (Exception e) {
logger.error("分布式锁 [{}] 释放异常", lockKey, e);
}
}
private Lock obtainLock(String lockKey) {
return redisLockRegistry.obtain(lockKey);
}
} | repos\spring-boot-best-practice-master\spring-boot-redis\src\main\java\cn\javastack\springboot\redis\service\RedisLockService.java | 2 |
请完成以下Java代码 | public int getGeocodingConfig_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GeocodingConfig_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* GeocodingProvider AD_Reference_ID=541051
* Reference name: Geocoding Providers
*/
public static final int GEOCODINGPROVIDER_AD_Reference_ID=541051;
/** GoogleMaps = GoogleMaps */
public static final String GEOCODINGPROVIDER_GoogleMaps = "GoogleMaps";
/** OpenStreetMaps = OpenStreetMaps */
public static final String GEOCODINGPROVIDER_OpenStreetMaps = "OpenStreetMaps";
/** Set Geocoding Dienst Provider.
@param GeocodingProvider Geocoding Dienst Provider */
@Override
public void setGeocodingProvider (java.lang.String GeocodingProvider)
{
set_Value (COLUMNNAME_GeocodingProvider, GeocodingProvider);
}
/** Get Geocoding Dienst Provider.
@return Geocoding Dienst Provider */
@Override
public java.lang.String getGeocodingProvider ()
{
return (java.lang.String)get_Value(COLUMNNAME_GeocodingProvider);
}
/** Set Google Maps - API-Schlüssel.
@param gmaps_ApiKey Google Maps - API-Schlüssel */
@Override
public void setgmaps_ApiKey (java.lang.String gmaps_ApiKey)
{
set_Value (COLUMNNAME_gmaps_ApiKey, gmaps_ApiKey);
}
/** Get Google Maps - API-Schlüssel.
@return Google Maps - API-Schlüssel */
@Override
public java.lang.String getgmaps_ApiKey () | {
return (java.lang.String)get_Value(COLUMNNAME_gmaps_ApiKey);
}
/** Set Open Street Maps - Basis-URL.
@param osm_baseURL
The Base URL after which all parameters are added
*/
@Override
public void setosm_baseURL (java.lang.String osm_baseURL)
{
set_Value (COLUMNNAME_osm_baseURL, osm_baseURL);
}
/** Get Open Street Maps - Basis-URL.
@return The Base URL after which all parameters are added
*/
@Override
public java.lang.String getosm_baseURL ()
{
return (java.lang.String)get_Value(COLUMNNAME_osm_baseURL);
}
/** Set Open Street Maps - Millisekunden zwischen den Anfragen.
@param osm_millisBetweenRequests
How many milliseconds to wait between 2 consecutive requests
*/
@Override
public void setosm_millisBetweenRequests (int osm_millisBetweenRequests)
{
set_Value (COLUMNNAME_osm_millisBetweenRequests, Integer.valueOf(osm_millisBetweenRequests));
}
/** Get Open Street Maps - Millisekunden zwischen den Anfragen.
@return How many milliseconds to wait between 2 consecutive requests
*/
@Override
public int getosm_millisBetweenRequests ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_osm_millisBetweenRequests);
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_GeocodingConfig.java | 1 |
请完成以下Java代码 | private void action_treeAdd(ListItem item)
{
log.info("Item=" + item);
if (item != null)
{
MTreeNode info = new MTreeNode(item.id, 0, item.name, item.description, -1,
item.isSummary, item.imageIndicator, false, null);
centerTree.nodeChanged(true, info);
// May cause Error if in tree
addNode(item);
}
} // action_treeAdd
/**
* Action: Delete Node from Tree
* @param item item
*/
private void action_treeDelete(ListItem item)
{
log.info("Item=" + item);
if (item != null)
{
MTreeNode info = new MTreeNode(item.id, 0, item.name, item.description, -1,
item.isSummary, item.imageIndicator, false, null);
centerTree.nodeChanged(false, info);
deleteNode(item);
}
} // action_treeDelete
/**
* Action: Add All Nodes to Tree
*/
private void action_treeAddAll()
{
log.info("");
ListModel model = centerList.getModel();
int size = model.getSize();
int index = -1; | for (index = 0; index < size; index++)
{
ListItem item = (ListItem)model.getElementAt(index);
action_treeAdd(item);
}
} // action_treeAddAll
/**
* Action: Delete All Nodes from Tree
*/
private void action_treeDeleteAll()
{
log.info("");
ListModel model = centerList.getModel();
int size = model.getSize();
int index = -1;
for (index = 0; index < size; index++)
{
ListItem item = (ListItem)model.getElementAt(index);
action_treeDelete(item);
}
} // action_treeDeleteAll
} // VTreeMaintenance | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\VTreeMaintenance.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class User {
protected User() {
}
@Id
@GeneratedValue
private Integer id;
@Size(min=2, message = "Name should have atleast 2 characters")
//@JsonProperty("user_name")
private String name;
@Past(message = "Birth Date should be in the past")
//@JsonProperty("birth_date")
private LocalDate birthDate;
@OneToMany(mappedBy = "user")
@JsonIgnore
private List<Post> posts;
public User(Integer id, String name, LocalDate birthDate) {
super();
this.id = id;
this.name = name;
this.birthDate = birthDate;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getBirthDate() {
return birthDate;
} | public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
public List<Post> getPosts() {
return posts;
}
public void setPosts(List<Post> posts) {
this.posts = posts;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", birthDate=" + birthDate + "]";
}
} | repos\master-spring-and-spring-boot-main\12-rest-api\src\main\java\com\in28minutes\rest\webservices\restfulwebservices\user\User.java | 2 |
请完成以下Java代码 | public class AddIdentityLinkForCaseInstanceCmd implements Command<Void>, Serializable {
private static final long serialVersionUID = 1L;
protected String caseInstanceId;
protected String userId;
protected String groupId;
protected String type;
public AddIdentityLinkForCaseInstanceCmd(String caseInstanceId, String userId, String groupId, String type) {
validateParams(caseInstanceId, userId, groupId, type);
this.caseInstanceId = caseInstanceId;
this.userId = userId;
this.groupId = groupId;
this.type = type;
}
protected void validateParams(String caseInstanceId, String userId, String groupId, String type) {
if (caseInstanceId == null) {
throw new FlowableIllegalArgumentException("caseInstanceId is null");
}
if (type == null) {
throw new FlowableIllegalArgumentException("type is required when adding a new case instance identity link");
}
if (userId == null && groupId == null) {
throw new FlowableIllegalArgumentException("userId and groupId cannot both be null");
}
} | @Override
public Void execute(CommandContext commandContext) {
CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext);
CaseInstanceEntityManager caseInstanceEntityManager = cmmnEngineConfiguration.getCaseInstanceEntityManager();
CaseInstanceEntity caseInstance = caseInstanceEntityManager.findById(caseInstanceId);
if (caseInstance == null) {
throw new FlowableObjectNotFoundException("Cannot find case instance with id " + caseInstanceId, CaseInstanceEntity.class);
}
IdentityLinkUtil.createCaseInstanceIdentityLink(caseInstance, userId, groupId, type, cmmnEngineConfiguration);
return null;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\AddIdentityLinkForCaseInstanceCmd.java | 1 |
请完成以下Java代码 | public void setC_BPartner_ID (int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID));
}
/** Get Geschäftspartner.
@return Bezeichnet einen Geschäftspartner
*/
@Override
public int getC_BPartner_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Kleinunternehmer-Steuerbefreiung .
@param C_VAT_SmallBusiness_ID Kleinunternehmer-Steuerbefreiung */
@Override
public void setC_VAT_SmallBusiness_ID (int C_VAT_SmallBusiness_ID)
{
if (C_VAT_SmallBusiness_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_VAT_SmallBusiness_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_VAT_SmallBusiness_ID, Integer.valueOf(C_VAT_SmallBusiness_ID));
}
/** Get Kleinunternehmer-Steuerbefreiung .
@return Kleinunternehmer-Steuerbefreiung */
@Override
public int getC_VAT_SmallBusiness_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_VAT_SmallBusiness_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Notiz.
@param Note
Optional weitere Information für ein Dokument
*/
@Override
public void setNote (java.lang.String Note)
{
set_Value (COLUMNNAME_Note, Note);
}
/** Get Notiz.
@return Optional weitere Information für ein Dokument
*/
@Override
public java.lang.String getNote ()
{
return (java.lang.String)get_Value(COLUMNNAME_Note);
}
/** Set Gültig ab.
@param ValidFrom
Gültig ab inklusiv (erster Tag)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Gültig ab inklusiv (erster Tag)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{ | return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Gültig bis.
@param ValidTo
Gültig bis inklusiv (letzter Tag)
*/
@Override
public void setValidTo (java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Gültig bis.
@return Gültig bis inklusiv (letzter Tag)
*/
@Override
public java.sql.Timestamp getValidTo ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo);
}
/** Set Umsatzsteuer-ID.
@param VATaxID Umsatzsteuer-ID */
@Override
public void setVATaxID (java.lang.String VATaxID)
{
set_Value (COLUMNNAME_VATaxID, VATaxID);
}
/** Get Umsatzsteuer-ID.
@return Umsatzsteuer-ID */
@Override
public java.lang.String getVATaxID ()
{
return (java.lang.String)get_Value(COLUMNNAME_VATaxID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\tax\model\X_C_VAT_SmallBusiness.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public org.springframework.messaging.converter.MessageConverter messageConverter()
{
return new MappingJackson2MessageConverter();
}
@Bean
public MessageHandlerMethodFactory messageHandlerMethodFactory()
{
final DefaultMessageHandlerMethodFactory factory = new DefaultMessageHandlerMethodFactory();
factory.setMessageConverter(messageConverter());
return factory;
}
/**
* Attempt to set the application name (e.g. metasfresh-webui-api) as the rabbitmq connection name.
* Thx to <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-messaging.html#boot-features-rabbitmq">spring-boot-features-rabbitmq</a> | * <p>
* (although right now it doesn't need to work..)
*/
@Bean
public ConnectionNameStrategy connectionNameStrategy()
{
return connectionFactory -> appName;
}
@Bean
public EventBusMonitoringService eventBusMonitoringService(@NonNull final Optional<PerformanceMonitoringService> performanceMonitoringService)
{
return new EventBusMonitoringService(performanceMonitoringService.orElse(NoopPerformanceMonitoringService.INSTANCE));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\remote\rabbitmq\RabbitMQEventBusConfiguration.java | 2 |
请完成以下Java代码 | public void collectAndUpdate(final IFacetsPool<ModelType> facetsPool)
{
final IFacetCollectorResult<ModelType> result = collect();
facetsPool.updateFrom(result);
}
/**
* Sets the source from where the facets will be collected.
*
* @param dataSource
*/
public FacetCollectorRequestBuilder<ModelType> setSource(final IFacetFilterable<ModelType> dataSource)
{
this.source_filterable = dataSource;
return this;
}
/**
* @param onlyFacetCategoriesPredicate
* @return facets collecting source to be used when collecting facets.
*/
public IQueryBuilder<ModelType> getSourceToUse(final Predicate<IFacetCategory> onlyFacetCategoriesPredicate)
{
Check.assumeNotNull(source_filterable, "source_filterable not null");
final IQueryBuilder<ModelType> queryBuilder = source_filterable.createQueryBuilder(onlyFacetCategoriesPredicate);
return queryBuilder;
}
/**
* Advice to collect facets only from given included facet categories. All other facet categories will be excluded.
*
* @param facetCategory
*/
public FacetCollectorRequestBuilder<ModelType> includeFacetCategory(final IFacetCategory facetCategory)
{
facetCategoryIncludesExcludes.include(facetCategory);
return this;
}
/**
* Advice to NOT collect facets from given exclude facet categories, even if they were added to include list.
*
* @param facetCategory
*/
public FacetCollectorRequestBuilder<ModelType> excludeFacetCategory(final IFacetCategory facetCategory)
{
facetCategoryIncludesExcludes.exclude(facetCategory);
return this;
}
/**
*
* @param facetCategory
* @return true if given facet category shall be considered when collecting facets
*/ | public boolean acceptFacetCategory(final IFacetCategory facetCategory)
{
// Don't accept it if is excluded by includes/excludes list
if (!facetCategoryIncludesExcludes.build().test(facetCategory))
{
return false;
}
// Only categories which have "eager refresh" set (if asked)
if (onlyEagerRefreshCategories && !facetCategory.isEagerRefresh())
{
return false;
}
// accept the facet category
return true;
}
/**
* Collect facets only for categories which have {@link IFacetCategory#isEagerRefresh()}.
*/
public FacetCollectorRequestBuilder<ModelType> setOnlyEagerRefreshCategories()
{
this.onlyEagerRefreshCategories = true;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\FacetCollectorRequestBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SplitJobDemo {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Bean
public Job splitJob() {
return jobBuilderFactory.get("splitJob")
.start(flow1())
.split(new SimpleAsyncTaskExecutor()).add(flow2())
.end()
.build();
}
private Step step1() {
return stepBuilderFactory.get("step1")
.tasklet((stepContribution, chunkContext) -> {
System.out.println("执行步骤一操作。。。");
return RepeatStatus.FINISHED;
}).build();
}
private Step step2() {
return stepBuilderFactory.get("step2")
.tasklet((stepContribution, chunkContext) -> {
System.out.println("执行步骤二操作。。。"); | return RepeatStatus.FINISHED;
}).build();
}
private Step step3() {
return stepBuilderFactory.get("step3")
.tasklet((stepContribution, chunkContext) -> {
System.out.println("执行步骤三操作。。。");
return RepeatStatus.FINISHED;
}).build();
}
private Flow flow1() {
return new FlowBuilder<Flow>("flow1")
.start(step1())
.next(step2())
.build();
}
private Flow flow2() {
return new FlowBuilder<Flow>("flow2")
.start(step3())
.build();
}
} | repos\SpringAll-master\67.spring-batch-start\src\main\java\cc\mrbird\batch\job\SplitJobDemo.java | 2 |
请完成以下Java代码 | public int getM_InventoryLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_InventoryLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Scrapped Quantity.
@param ScrappedQty
The Quantity scrapped due to QA issues
*/
public void setScrappedQty (BigDecimal ScrappedQty)
{ | set_Value (COLUMNNAME_ScrappedQty, ScrappedQty);
}
/** Get Scrapped Quantity.
@return The Quantity scrapped due to QA issues
*/
public BigDecimal getScrappedQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Target Quantity.
@param TargetQty
Target Movement Quantity
*/
public void setTargetQty (BigDecimal TargetQty)
{
set_ValueNoCheck (COLUMNNAME_TargetQty, TargetQty);
}
/** Get Target Quantity.
@return Target Movement Quantity
*/
public BigDecimal getTargetQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TargetQty);
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_InOutLineConfirm.java | 1 |
请完成以下Java代码 | public TablePrinter ident(int ident)
{
this.ident = ident;
return this;
}
@Override
public String toString()
{
final ArrayList<String> header = table.getHeader();
final ArrayList<Row> rowsList = table.getRowsList();
if (header.isEmpty() || rowsList.isEmpty())
{
return "";
}
final TabularStringWriter writer = TabularStringWriter.builder()
.ident(ident)
.build();
//
// Header
{
for (final String columnName : header)
{
writer.appendCell(columnName, getColumnWidth(columnName));
}
writer.lineEnd();
}
//
// Rows
{
for (final Row row : rowsList)
{ | writer.lineEnd();
for (final String columnName : header)
{
writer.appendCell(row.getCellValue(columnName), getColumnWidth(columnName));
}
writer.lineEnd();
}
}
return writer.getAsString();
}
int getColumnWidth(final String columnName)
{
return columnWidths.computeIfAbsent(columnName, this::computeColumnWidth);
}
private int computeColumnWidth(final String columnName)
{
int maxWidth = columnName.length();
for (final Row row : table.getRowsList())
{
maxWidth = Math.max(maxWidth, row.getColumnWidth(columnName));
}
return maxWidth;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\text\tabular\TablePrinter.java | 1 |
请完成以下Java代码 | public class CaseExport implements CmmnXmlConstants {
public static void writeCase(CmmnModel model, Case caseModel, XMLStreamWriter xtw) throws Exception {
xtw.writeStartElement(ELEMENT_CASE);
xtw.writeAttribute(ATTRIBUTE_ID, caseModel.getId());
if (StringUtils.isNotEmpty(caseModel.getName())) {
xtw.writeAttribute(ATTRIBUTE_NAME, caseModel.getName());
}
if (StringUtils.isNotEmpty(caseModel.getInitiatorVariableName())) {
xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_INITIATOR_VARIABLE_NAME, caseModel.getInitiatorVariableName());
}
if (!caseModel.getCandidateStarterUsers().isEmpty()) {
xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_CASE_CANDIDATE_USERS, CmmnXmlUtil.convertToDelimitedString(caseModel.getCandidateStarterUsers()));
}
if (!caseModel.getCandidateStarterGroups().isEmpty()) {
xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_CASE_CANDIDATE_GROUPS, CmmnXmlUtil.convertToDelimitedString(caseModel.getCandidateStarterGroups()));
}
if (caseModel.isAsync()) {
xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_IS_ASYNCHRONOUS, "true");
}
if (StringUtils.isNotEmpty(caseModel.getDocumentation())) {
xtw.writeStartElement(ELEMENT_DOCUMENTATION);
xtw.writeCharacters(caseModel.getDocumentation());
xtw.writeEndElement();
} | if (StringUtils.isNotEmpty(caseModel.getStartEventType()) && caseModel.getExtensionElements().get("eventType") == null) {
ExtensionElement extensionElement = new ExtensionElement();
extensionElement.setNamespace(FLOWABLE_EXTENSIONS_NAMESPACE);
extensionElement.setNamespacePrefix(FLOWABLE_EXTENSIONS_PREFIX);
extensionElement.setName("eventType");
extensionElement.setElementText(caseModel.getStartEventType());
caseModel.addExtensionElement(extensionElement);
}
boolean didWriteExtensionStartElement = CmmnXmlUtil.writeExtensionElements(caseModel, false, model.getNamespaces(), xtw);
didWriteExtensionStartElement = FlowableListenerExport.writeFlowableListeners(xtw, CmmnXmlConstants.ELEMENT_CASE_LIFECYCLE_LISTENER, caseModel.getLifecycleListeners(), didWriteExtensionStartElement);
if (didWriteExtensionStartElement) {
xtw.writeEndElement();
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\export\CaseExport.java | 1 |
请完成以下Java代码 | static ImmutableMap<String, String> extractTags(@Nullable final List<String> tagKeyValuePairs)
{
if (tagKeyValuePairs == null)
{
return ImmutableMap.of();
}
final ImmutableMap.Builder<String, String> tags = ImmutableMap.builder();
final int listSize = tagKeyValuePairs.size();
final int maxIndex = listSize % 2 == 0 ? listSize : listSize - 1;
for (int i = 0; i < maxIndex; i += 2)
{
tags.put(tagKeyValuePairs.get(i), tagKeyValuePairs.get(i + 1));
}
return tags.build();
}
@VisibleForTesting
static JsonAttachment toJsonAttachment(
@NonNull final String externalReference,
@NonNull final String externalSystemCode, | @NonNull final AttachmentEntry entry)
{
final AttachmentEntryId entryId = Check.assumeNotNull(entry.getId(), "Param 'entry' needs to have a non-null id; entry={}", entry);
final String attachmentId = Integer.toString(entryId.getRepoId());
return JsonAttachment.builder()
.externalReference(externalReference)
.externalSystemCode(externalSystemCode)
.attachmentId(attachmentId)
.type(de.metas.rest_api.utils.JsonConverters.toJsonAttachmentType(entry.getType()))
.filename(entry.getFilename())
.mimeType(entry.getMimeType())
.url(entry.getUrl() != null ? entry.getUrl().toString() : null)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\ordercandidates\impl\OrderCandidatesRestController.java | 1 |
请完成以下Java代码 | public class Person implements Serializable {
private static final long serialVersionUID = -7946768337975852352L;
@Id
private Name id;
/**
* 用户id
*/
private String uidNumber;
/**
* 用户名
*/
@DnAttribute(value = "uid", index = 1)
private String uid;
/**
* 姓名
*/
@Attribute(name = "cn")
private String personName;
/**
* 密码
*/
private String userPassword;
/**
* 名字
*/
private String givenName;
/**
* 姓氏
*/
@Attribute(name = "sn")
private String surname;
/**
* 邮箱 | */
private String mail;
/**
* 职位
*/
private String title;
/**
* 部门
*/
private String departmentNumber;
/**
* 部门id
*/
private String gidNumber;
/**
* 根目录
*/
private String homeDirectory;
/**
* loginShell
*/
private String loginShell;
} | repos\spring-boot-demo-master\demo-ldap\src\main\java\com\xkcoding\ldap\entity\Person.java | 1 |
请完成以下Java代码 | public boolean evaluate(String sequenceFlowId, DelegateExecution execution) {
String conditionExpression = null;
if (Context.getProcessEngineConfiguration().isEnableProcessDefinitionInfoCache()) {
ObjectNode elementProperties = Context.getBpmnOverrideElementProperties(sequenceFlowId, execution.getProcessDefinitionId());
conditionExpression = getActiveValue(initialConditionExpression, DynamicBpmnConstants.SEQUENCE_FLOW_CONDITION, elementProperties);
} else {
conditionExpression = initialConditionExpression;
}
Expression expression = Context.getProcessEngineConfiguration().getExpressionManager().createExpression(conditionExpression);
Object result = expression.getValue(execution);
if (result == null) {
throw new ActivitiException("condition expression returns null (sequenceFlowId: " + sequenceFlowId + ")" );
}
if (!(result instanceof Boolean)) {
throw new ActivitiException("condition expression returns non-Boolean (sequenceFlowId: " + sequenceFlowId + "): " + result + " (" + result.getClass().getName() + ")");
}
return (Boolean) result;
} | protected String getActiveValue(String originalValue, String propertyName, ObjectNode elementProperties) {
String activeValue = originalValue;
if (elementProperties != null) {
JsonNode overrideValueNode = elementProperties.get(propertyName);
if (overrideValueNode != null) {
if (overrideValueNode.isNull()) {
activeValue = null;
} else {
activeValue = overrideValueNode.asString();
}
}
}
return activeValue;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\el\UelExpressionCondition.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public String getCity() {
return city;
}
public void setName(String name) {
this.name = name;
}
public void setCity(String city) {
this.city = city;
}
public ComicUniversum getUniversum() {
return universum;
}
public void setUniversum(ComicUniversum universum) {
this.universum = universum;
} | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Hero hero = (Hero) o;
return Objects.equals(name, hero.name) &&
Objects.equals(city, hero.city) &&
universum == hero.universum;
}
@Override
public int hashCode() {
return Objects.hash(name, city, universum);
}
@Override
public String toString() {
return "Hero{" +
"name='" + name + '\'' +
", city='" + city + '\'' +
", universum=" + universum.getDisplayName() +
'}';
}
} | repos\spring-boot-demo-master (1)\src\main\java\com\github\sparsick\springbootexample\hero\universum\Hero.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WEBUI_Picking_RemoveHUFromPickingSlot extends PickingSlotViewBasedProcess
{
@Autowired
private PickingCandidateService pickingCandidateService;
@Override
protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (!getSelectedRowIds().isSingleDocumentId())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
final PickingSlotRow pickingSlotRow = getSingleSelectedRow();
if (!pickingSlotRow.isPickedHURow())
{
return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_SELECT_PICKED_HU));
}
if (pickingSlotRow.isProcessed())
{
return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_NO_UNPROCESSED_RECORDS));
}
return ProcessPreconditionsResolution.accept();
} | @Override
protected String doIt()
{
final PickingSlotRow huRow = getSingleSelectedRow();
pickingCandidateService.removeHUFromPickingSlot(huRow.getHuId());
return MSG_OK;
}
@Override
protected void postProcess(final boolean success)
{
invalidatePickingSlotsView(); // right side
invalidatePackablesView(); // left side
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\process\WEBUI_Picking_RemoveHUFromPickingSlot.java | 2 |
请完成以下Java代码 | public class GetAttachmentRouteContext
{
@NonNull
private final String orgCode;
@NonNull
private final String apiKey;
@NonNull
private final String tenant;
@NonNull
private final DocumentApi documentApi;
@NonNull
private final AttachmentApi attachmentApi;
@NonNull
private final UserApi userApi;
@NonNull
private final String createdAfterDocument;
@NonNull
private final String createdAfterAttachment;
@NonNull
private final JsonMetasfreshId rootBPartnerIdForUsers;
@NonNull
private final JsonExternalSystemRequest request; | @NonNull
private Instant nextDocumentImportStartDate;
@NonNull
private Instant nextAttachmentImportStartDate;
@Nullable
private Document document;
@Nullable
private Attachment attachment;
public void setNextDocumentImportStartDate(@NonNull final Instant candidate)
{
if (candidate.isAfter(this.nextDocumentImportStartDate))
{
this.nextDocumentImportStartDate = candidate;
}
}
public void setNextAttachmentImportStartDate(@NonNull final Instant candidate)
{
if (candidate.isAfter(this.nextAttachmentImportStartDate))
{
this.nextAttachmentImportStartDate = candidate;
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\attachment\GetAttachmentRouteContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getFREETEXT() {
return freetext;
}
/**
* Sets the value of the freetext property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFREETEXT(String value) {
this.freetext = value;
}
/**
* Gets the value of the freetextlanguage property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFREETEXTLANGUAGE() {
return freetextlanguage;
}
/**
* Sets the value of the freetextlanguage property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFREETEXTLANGUAGE(String value) {
this.freetextlanguage = value;
}
/**
* Gets the value of the dplqu1 property.
* | * @return
* possible object is
* {@link DPLQU1 }
*
*/
public DPLQU1 getDPLQU1() {
return dplqu1;
}
/**
* Sets the value of the dplqu1 property.
*
* @param value
* allowed object is
* {@link DPLQU1 }
*
*/
public void setDPLQU1(DPLQU1 value) {
this.dplqu1 = 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\DLPIN1.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class LineItem {\n");
sb.append(" appliedPromotions: ").append(toIndentedString(appliedPromotions)).append("\n");
sb.append(" deliveryCost: ").append(toIndentedString(deliveryCost)).append("\n");
sb.append(" discountedLineItemCost: ").append(toIndentedString(discountedLineItemCost)).append("\n");
sb.append(" ebayCollectAndRemitTaxes: ").append(toIndentedString(ebayCollectAndRemitTaxes)).append("\n");
sb.append(" giftDetails: ").append(toIndentedString(giftDetails)).append("\n");
sb.append(" itemLocation: ").append(toIndentedString(itemLocation)).append("\n");
sb.append(" legacyItemId: ").append(toIndentedString(legacyItemId)).append("\n");
sb.append(" legacyVariationId: ").append(toIndentedString(legacyVariationId)).append("\n");
sb.append(" lineItemCost: ").append(toIndentedString(lineItemCost)).append("\n");
sb.append(" lineItemFulfillmentInstructions: ").append(toIndentedString(lineItemFulfillmentInstructions)).append("\n");
sb.append(" lineItemFulfillmentStatus: ").append(toIndentedString(lineItemFulfillmentStatus)).append("\n");
sb.append(" lineItemId: ").append(toIndentedString(lineItemId)).append("\n");
sb.append(" listingMarketplaceId: ").append(toIndentedString(listingMarketplaceId)).append("\n");
sb.append(" properties: ").append(toIndentedString(properties)).append("\n");
sb.append(" purchaseMarketplaceId: ").append(toIndentedString(purchaseMarketplaceId)).append("\n");
sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n");
sb.append(" refunds: ").append(toIndentedString(refunds)).append("\n");
sb.append(" sku: ").append(toIndentedString(sku)).append("\n");
sb.append(" soldFormat: ").append(toIndentedString(soldFormat)).append("\n");
sb.append(" taxes: ").append(toIndentedString(taxes)).append("\n");
sb.append(" title: ").append(toIndentedString(title)).append("\n");
sb.append(" total: ").append(toIndentedString(total)).append("\n");
sb.append("}"); | return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\LineItem.java | 2 |
请完成以下Java代码 | public ResponseEntity<ApiError> badCredentialsException(BadCredentialsException e){
// 打印堆栈信息
String message = "坏的凭证".equals(e.getMessage()) ? "用户名或密码不正确" : e.getMessage();
log.error(message);
return buildResponseEntity(ApiError.error(message));
}
/**
* 处理自定义异常
*/
@ExceptionHandler(value = BadRequestException.class)
public ResponseEntity<ApiError> badRequestException(BadRequestException e) {
// 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e));
return buildResponseEntity(ApiError.error(e.getStatus(),e.getMessage()));
}
/**
* 处理 EntityExist
*/
@ExceptionHandler(value = EntityExistException.class)
public ResponseEntity<ApiError> entityExistException(EntityExistException e) {
// 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e));
return buildResponseEntity(ApiError.error(e.getMessage()));
}
/**
* 处理 EntityNotFound
*/
@ExceptionHandler(value = EntityNotFoundException.class)
public ResponseEntity<ApiError> entityNotFoundException(EntityNotFoundException e) {
// 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e)); | return buildResponseEntity(ApiError.error(NOT_FOUND.value(),e.getMessage()));
}
/**
* 处理所有接口数据验证异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiError> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
// 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e));
ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
String message = objectError.getDefaultMessage();
if (objectError instanceof FieldError) {
message = ((FieldError) objectError).getField() + ": " + message;
}
return buildResponseEntity(ApiError.error(message));
}
/**
* 统一返回
*/
private ResponseEntity<ApiError> buildResponseEntity(ApiError apiError) {
return new ResponseEntity<>(apiError, HttpStatus.valueOf(apiError.getStatus()));
}
} | repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\exception\handler\GlobalExceptionHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String admitYear;
@Column(columnDefinition = "json")
private String address;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAdmitYear() { | return admitYear;
}
public void setAdmitYear(String admitYear) {
this.admitYear = admitYear;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-query-5\src\main\java\com\baeldung\spring\data\jpa\jsontypeexception\Student.java | 2 |
请完成以下Java代码 | 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 |
请在Spring Boot框架中完成以下Java代码 | private String getParentExternalIdentifier()
{
return ExternalIdentifierFormat.formatExternalId(parentPartnerCode.getPartnerCode());
}
@NonNull
private String getBPartnerExternalIdentifier(@NonNull final BPartnerRow bPartnerRow)
{
return buildExternalIdentifier(bPartnerRow.getPartnerCode().getPartnerCode(), bPartnerRow.getSection());
}
@NonNull
private String getLocationExternalIdentifier(@NonNull final BPartnerRow bPartnerRow)
{
return buildExternalIdentifier(bPartnerRow.getPartnerCode().getRawPartnerCode(), bPartnerRow.getSection());
}
@NonNull
private static JsonRequestBPartnerUpsertItem buildSectionGroupJsonRequestBPartnerUpsertItem(
@NonNull final BPartnerRow bPartnerRow,
@NonNull final String orgCode,
@NonNull final JsonMetasfreshId externalSystemConfigId
)
{
final JsonRequestBPartner jsonRequestBPartner = new JsonRequestBPartner(); | jsonRequestBPartner.setCode(bPartnerRow.getPartnerCode().getPartnerCode());
jsonRequestBPartner.setCompanyName(bPartnerRow.getName1());
jsonRequestBPartner.setName(bPartnerRow.getName1());
jsonRequestBPartner.setName2(bPartnerRow.getName2());
jsonRequestBPartner.setDescription(bPartnerRow.getSearchTerm());
final JsonRequestComposite.JsonRequestCompositeBuilder jsonRequestCompositeBuilder = JsonRequestComposite.builder()
.bpartner(jsonRequestBPartner)
.orgCode(orgCode);
return JsonRequestBPartnerUpsertItem.builder()
.bpartnerComposite(jsonRequestCompositeBuilder.build())
.bpartnerIdentifier(ExternalIdentifierFormat.formatExternalId(bPartnerRow.getPartnerCode().getPartnerCode()))
.externalSystemConfigId(externalSystemConfigId)
.isReadOnlyInMetasfresh(true)
.build();
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-sap-file-import\src\main\java\de\metas\camel\externalsystems\sap\bpartner\UpsertBPartnerRequestBuilder.java | 2 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
/** Set Zeile.
@param DataEntry_Line_ID Zeile */
@Override
public void setDataEntry_Line_ID (int DataEntry_Line_ID)
{
if (DataEntry_Line_ID < 1)
set_ValueNoCheck (COLUMNNAME_DataEntry_Line_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DataEntry_Line_ID, Integer.valueOf(DataEntry_Line_ID));
}
/** Get Zeile.
@return Zeile */
@Override
public int getDataEntry_Line_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_Line_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.dataentry.model.I_DataEntry_Section getDataEntry_Section() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_DataEntry_Section_ID, de.metas.dataentry.model.I_DataEntry_Section.class);
}
@Override
public void setDataEntry_Section(de.metas.dataentry.model.I_DataEntry_Section DataEntry_Section)
{
set_ValueFromPO(COLUMNNAME_DataEntry_Section_ID, de.metas.dataentry.model.I_DataEntry_Section.class, DataEntry_Section);
}
/** Set Sektion.
@param DataEntry_Section_ID Sektion */
@Override
public void setDataEntry_Section_ID (int DataEntry_Section_ID)
{
if (DataEntry_Section_ID < 1)
set_ValueNoCheck (COLUMNNAME_DataEntry_Section_ID, null);
else | set_ValueNoCheck (COLUMNNAME_DataEntry_Section_ID, Integer.valueOf(DataEntry_Section_ID));
}
/** Get Sektion.
@return Sektion */
@Override
public int getDataEntry_Section_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_Section_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Line.java | 1 |
请完成以下Java代码 | public void addCellEditorListener(CellEditorListener l)
{
}
@Override
public void cancelCellEditing()
{
}
@Override
public Object getCellEditorValue()
{
return m_value;
}
@Override
public boolean isCellEditable(EventObject anEvent)
{
return false;
}
@Override
public void removeCellEditorListener(CellEditorListener l)
{
} | @Override
public boolean shouldSelectCell(EventObject anEvent)
{
return false;
}
@Override
public boolean stopCellEditing()
{
return true;
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
m_value = value;
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\TableCellNone.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void pushToMetasfresh(@NonNull final Rfq rfq)
{
final ISyncAfterCommitCollector syncAfterCommitCollector = senderToMetasfreshService.syncAfterCommit();
syncAfterCommitCollector.add(rfq);
}
@Override
@Transactional
public Rfq changeActiveRfq(
@NonNull final JsonChangeRfqRequest request,
@NonNull final User loggedUser)
{
final Rfq rfq = getUserActiveRfq(
loggedUser,
Long.parseLong(request.getRfqId()));
for (final JsonChangeRfqQtyRequest qtyChangeRequest : request.getQuantities())
{
rfq.setQtyPromised(qtyChangeRequest.getDate(), qtyChangeRequest.getQtyPromised());
}
if (request.getPrice() != null)
{
rfq.setPricePromisedUserEntered(request.getPrice());
}
saveRecursively(rfq); | return rfq;
}
@Override
public long getCountUnconfirmed(@NonNull final User user)
{
return rfqRepo.countUnconfirmed(user.getBpartner());
}
@Override
@Transactional
public void confirmUserEntries(@NonNull final User user)
{
final BPartner bpartner = user.getBpartner();
final List<Rfq> rfqs = rfqRepo.findUnconfirmed(bpartner);
for (final Rfq rfq : rfqs)
{
rfq.confirmByUser();
saveRecursivelyAndPush(rfq);
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\service\impl\RfQService.java | 2 |
请完成以下Java代码 | public boolean isPrimitiveValueType() {
return false;
}
public TypedValue createValue(Object value, Map<String, Object> valueInfo) {
ObjectValueBuilder builder = Variables.objectValue(value);
if(valueInfo != null) {
applyValueInfo(builder, valueInfo);
}
return builder.create();
}
public Map<String, Object> getValueInfo(TypedValue typedValue) {
if(!(typedValue instanceof ObjectValue)) {
throw new IllegalArgumentException("Value not of type Object.");
}
ObjectValue objectValue = (ObjectValue) typedValue;
Map<String, Object> valueInfo = new HashMap<String, Object>();
String serializationDataFormat = objectValue.getSerializationDataFormat();
if(serializationDataFormat != null) {
valueInfo.put(VALUE_INFO_SERIALIZATION_DATA_FORMAT, serializationDataFormat);
}
String objectTypeName = objectValue.getObjectTypeName();
if(objectTypeName != null) {
valueInfo.put(VALUE_INFO_OBJECT_TYPE_NAME, objectTypeName);
}
if (objectValue.isTransient()) {
valueInfo.put(VALUE_INFO_TRANSIENT, objectValue.isTransient());
}
return valueInfo;
}
public SerializableValue createValueFromSerialized(String serializedValue, Map<String, Object> valueInfo) {
SerializedObjectValueBuilder builder = Variables.serializedObjectValue(serializedValue); | if(valueInfo != null) {
applyValueInfo(builder, valueInfo);
}
return builder.create();
}
protected void applyValueInfo(ObjectValueBuilder builder, Map<String, Object> valueInfo) {
String objectValueTypeName = (String) valueInfo.get(VALUE_INFO_OBJECT_TYPE_NAME);
if (builder instanceof SerializedObjectValueBuilder) {
((SerializedObjectValueBuilder) builder).objectTypeName(objectValueTypeName);
}
String serializationDataFormat = (String) valueInfo.get(VALUE_INFO_SERIALIZATION_DATA_FORMAT);
if(serializationDataFormat != null) {
builder.serializationDataFormat(serializationDataFormat);
}
builder.setTransient(isTransient(valueInfo));
}
} | repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\type\ObjectTypeImpl.java | 1 |
请完成以下Java代码 | protected static PathFilterRule createPathFilterRule(PathFilterConfig pathFilter,
String applicationPath) {
PathFilterRule pathFilterRule = new PathFilterRule();
for (PathMatcherConfig pathMatcherConfig : pathFilter.getDeniedPaths()) {
pathFilterRule.getDeniedPaths().add(transformPathMatcher(pathMatcherConfig, applicationPath));
}
for (PathMatcherConfig pathMatcherConfig : pathFilter.getAllowedPaths()) {
pathFilterRule.getAllowedPaths().add(transformPathMatcher(pathMatcherConfig, applicationPath));
}
return pathFilterRule;
}
protected static RequestMatcher transformPathMatcher(PathMatcherConfig pathMatcherConfig,
String applicationPath) {
RequestFilter requestMatcher = new RequestFilter(
pathMatcherConfig.getPath(),
applicationPath,
pathMatcherConfig.getParsedMethods());
RequestAuthorizer requestAuthorizer = RequestAuthorizer.AUTHORIZE_ANNONYMOUS;
if (pathMatcherConfig.getAuthorizer() != null) {
String authorizeCls = pathMatcherConfig.getAuthorizer();
requestAuthorizer = (RequestAuthorizer) ReflectUtil.instantiate(authorizeCls);
}
return new RequestMatcher(requestMatcher, requestAuthorizer);
}
/**
* Iterate over a number of filter rules and match them against
* the given request.
*
* @param requestMethod
* @param requestUri
* @param filterRules | *
* @return the checked request with authorization information attached
*/
public static Authorization authorize(String requestMethod, String requestUri, List<SecurityFilterRule> filterRules) {
Authorization authorization;
for (SecurityFilterRule filterRule : filterRules) {
authorization = filterRule.authorize(requestMethod, requestUri);
if (authorization != null) {
return authorization;
}
}
// grant if no filter disallows it
return Authorization.granted(Authentication.ANONYMOUS);
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\util\FilterRules.java | 1 |
请完成以下Java代码 | public Set<FlatrateTermId> retrieveAllRunningSubscriptionIds(
@NonNull final BPartnerId bPartnerId,
@NonNull final Instant date,
@NonNull final OrgId orgId)
{
return existingSubscriptionsQueryBuilder(orgId, bPartnerId, date)
.create()
.idsAsSet(FlatrateTermId::ofRepoId);
}
private IQueryBuilder<I_C_Flatrate_Term> existingSubscriptionsQueryBuilder(@NonNull final OrgId orgId, @NonNull final BPartnerId bPartnerId, @NonNull final Instant date)
{
return queryBL.createQueryBuilder(I_C_Flatrate_Term.class)
.addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_AD_Org_ID, orgId)
.addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_Bill_BPartner_ID, bPartnerId)
.addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_ContractStatus, FlatrateTermStatus.Quit.getCode())
.addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_ContractStatus, FlatrateTermStatus.Voided.getCode())
.addCompareFilter(I_C_Flatrate_Term.COLUMNNAME_EndDate, Operator.GREATER, date);
}
@Override | public boolean bpartnerHasExistingRunningTerms(@NonNull final I_C_Flatrate_Term flatrateTerm)
{
if (flatrateTerm.getC_Order_Term_ID() <= 0)
{
return true; // if this term has no C_Order_Term_ID, then it *is* one of those running terms
}
final Instant instant = TimeUtil.asInstant(flatrateTerm.getC_Order_Term().getDateOrdered());
final IQueryBuilder<I_C_Flatrate_Term> queryBuilder = //
existingSubscriptionsQueryBuilder(OrgId.ofRepoId(flatrateTerm.getAD_Org_ID()),
BPartnerId.ofRepoId(flatrateTerm.getBill_BPartner_ID()),
instant);
queryBuilder.addNotEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_C_Order_Term_ID, flatrateTerm.getC_Order_Term_ID());
return queryBuilder.create()
.anyMatch();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\FlatrateDAO.java | 1 |
请完成以下Java代码 | public Date calculateBestBeforeDate(
final Properties ctx,
final ProductId productId,
final BPartnerId vendorBPartnerId,
@NonNull final Date dateReceipt)
{
final I_M_Product product = productsService.getById(productId);
final OrgId orgId = OrgId.ofRepoId(product.getAD_Org_ID());
//
// Get Best-Before days
final I_C_BPartner_Product bpartnerProduct = bpartnerProductDAO.retrieveBPartnerProductAssociation(ctx, vendorBPartnerId, productId, orgId);
if (bpartnerProduct == null)
{
// no BPartner-Product association defined, so we cannot fetch the bestBeforeDays
return null;
}
final int bestBeforeDays = bpartnerProduct.getShelfLifeMinDays(); // TODO: i think we shall introduce BestBeforeDays
if (bestBeforeDays <= 0)
{
// BestBeforeDays was not configured
return null;
}
//
// Calculate the Best-Before date
return TimeUtil.addDays(dateReceipt, bestBeforeDays);
}
@Override
public int getNumberDisplayType(@NonNull final I_M_Attribute attribute)
{
return isInteger(UomId.ofRepoIdOrNull(attribute.getC_UOM_ID()))
? DisplayType.Integer
: DisplayType.Number; | }
public static boolean isInteger(@Nullable final UomId uomId)
{
return uomId != null && UomId.equals(uomId, UomId.EACH);
}
@Override
public boolean isStorageRelevant(@NonNull final AttributeId attributeId)
{
final I_M_Attribute attribute = getAttributeById(attributeId);
return attribute.isStorageRelevant();
}
@Override
public AttributeListValue retrieveAttributeValueOrNull(@NonNull final AttributeId attributeId, @Nullable final String value)
{
return attributesRepo.retrieveAttributeValueOrNull(attributeId, value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\AttributesBL.java | 1 |
请完成以下Java代码 | public void setUrl(String url) {
this.url = url;
}
public String getContentId() {
return contentId;
}
public void setContentId(String contentId) {
this.contentId = contentId;
}
public ByteArrayEntity getContent() {
return content;
}
public void setContent(ByteArrayEntity content) {
this.content = content;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
} | public Date getRemovalTime() {
return removalTime;
}
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", revision=" + revision
+ ", name=" + name
+ ", description=" + description
+ ", type=" + type
+ ", taskId=" + taskId
+ ", processInstanceId=" + processInstanceId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", removalTime=" + removalTime
+ ", url=" + url
+ ", contentId=" + contentId
+ ", content=" + content
+ ", tenantId=" + tenantId
+ ", createTime=" + createTime
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AttachmentEntity.java | 1 |
请完成以下Java代码 | public void cleanContainerTree(Integer ID) {
cleanContainerTree("" + ID);
}
/**
* Clean ContainerTreeCache for this WebProjectID
* @param ID for container to clean
*/
public void cleanContainerTree(String ID) {
runURLRequest("ContainerTree", ID);
}
/**
* Clean Container Element for this ID
* @param ID for container element to clean
*/
public void cleanContainerElement(Integer ID) {
cleanContainerElement("" + ID);
}
/**
* Clean Container Element for this ID
* @param ID for container element to clean
*/
public void cleanContainerElement(String ID) {
runURLRequest("ContainerElement", ID);
}
private void runURLRequest(String cache, String ID) {
String thisURL = null;
for(int i=0; i<cacheURLs.length; i++) {
try {
thisURL = "http://" + cacheURLs[i] + "/cache/Service?Cache=" + cache + "&ID=" + ID;
URL url = new URL(thisURL);
Proxy thisProxy = Proxy.NO_PROXY;
URLConnection urlConn = url.openConnection(thisProxy);
urlConn.setUseCaches(false);
urlConn.connect();
Reader stream = new java.io.InputStreamReader(
urlConn.getInputStream());
StringBuffer srvOutput = new StringBuffer();
try {
int c;
while ( (c=stream.read()) != -1 )
srvOutput.append( (char)c );
} catch (Exception E2) { | E2.printStackTrace();
}
} catch (IOException E) {
if (log!=null)
log.warn("Can't clean cache at:" + thisURL + " be carefull, your deployment server may use invalid or old cache data!");
}
}
}
/**
* Converts JNP URL to http URL for cache cleanup
* @param JNPURL String with JNP URL from Context
* @return clean servername
*/
public static String convertJNPURLToCacheURL(String JNPURL) {
if (JNPURL.indexOf("jnp://")>=0) {
JNPURL = JNPURL.substring(JNPURL.indexOf("jnp://")+6);
}
if (JNPURL.indexOf(':')>=0) {
JNPURL = JNPURL.substring(0,JNPURL.indexOf(':'));
}
if (JNPURL.length()>0) {
return JNPURL;
} else {
return null;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\cm\CacheHandler.java | 1 |
请完成以下Java代码 | public class ReflectiveOperationInvoker implements OperationInvoker {
private final Object target;
private final OperationMethod operationMethod;
private final ParameterValueMapper parameterValueMapper;
/**
* Creates a new {@code ReflectiveOperationInvoker} that will invoke the given
* {@code method} on the given {@code target}. The given {@code parameterMapper} will
* be used to map parameters to the required types and the given
* {@code parameterNameMapper} will be used map parameters by name.
* @param target the target of the reflective call
* @param operationMethod the method info
* @param parameterValueMapper the parameter mapper
*/
public ReflectiveOperationInvoker(Object target, OperationMethod operationMethod,
ParameterValueMapper parameterValueMapper) {
Assert.notNull(target, "'target' must not be null");
Assert.notNull(operationMethod, "'operationMethod' must not be null");
Assert.notNull(parameterValueMapper, "'parameterValueMapper' must not be null");
ReflectionUtils.makeAccessible(operationMethod.getMethod());
this.target = target;
this.operationMethod = operationMethod;
this.parameterValueMapper = parameterValueMapper;
}
@Override
public @Nullable Object invoke(InvocationContext context) {
validateRequiredParameters(context);
Method method = this.operationMethod.getMethod();
@Nullable Object[] resolvedArguments = resolveArguments(context);
ReflectionUtils.makeAccessible(method);
return ReflectionUtils.invokeMethod(method, this.target, resolvedArguments);
}
private void validateRequiredParameters(InvocationContext context) {
Set<OperationParameter> missing = this.operationMethod.getParameters()
.stream()
.filter((parameter) -> isMissing(context, parameter))
.collect(Collectors.toSet());
if (!missing.isEmpty()) {
throw new MissingParametersException(missing);
}
}
private boolean isMissing(InvocationContext context, OperationParameter parameter) {
if (!parameter.isMandatory()) {
return false;
}
if (context.canResolve(parameter.getType())) {
return false;
} | return context.getArguments().get(parameter.getName()) == null;
}
private @Nullable Object[] resolveArguments(InvocationContext context) {
return this.operationMethod.getParameters()
.stream()
.map((parameter) -> resolveArgument(parameter, context))
.toArray();
}
private @Nullable Object resolveArgument(OperationParameter parameter, InvocationContext context) {
Object resolvedByType = context.resolveArgument(parameter.getType());
if (resolvedByType != null) {
return resolvedByType;
}
Object value = context.getArguments().get(parameter.getName());
return this.parameterValueMapper.mapParameterValue(parameter, value);
}
@Override
public String toString() {
return new ToStringCreator(this).append("target", this.target)
.append("method", this.operationMethod)
.toString();
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\invoke\reflect\ReflectiveOperationInvoker.java | 1 |
请完成以下Java代码 | public class CookieRoutePredicateFactory extends AbstractRoutePredicateFactory<CookieRoutePredicateFactory.Config> {
/**
* Name key.
*/
public static final String NAME_KEY = "name";
/**
* Regexp key.
*/
public static final String REGEXP_KEY = "regexp";
public CookieRoutePredicateFactory() {
super(Config.class);
}
@Override
public List<String> shortcutFieldOrder() {
return Arrays.asList(NAME_KEY, REGEXP_KEY);
}
@Override
public Predicate<ServerWebExchange> apply(Config config) {
return new GatewayPredicate() {
@Override
public boolean test(ServerWebExchange exchange) {
List<HttpCookie> cookies = exchange.getRequest().getCookies().get(config.name);
if (cookies == null || config.regexp == null) {
return false;
}
return cookies.stream().anyMatch(cookie -> cookie.getValue().matches(config.regexp));
}
@Override
public Object getConfig() {
return config;
} | @Override
public String toString() {
return String.format("Cookie: name=%s regexp=%s", config.name, config.regexp);
}
};
}
public static class Config {
@NotEmpty
private @Nullable String name;
@NotEmpty
private @Nullable String regexp;
public @Nullable String getName() {
return name;
}
public Config setName(String name) {
this.name = name;
return this;
}
public @Nullable String getRegexp() {
return regexp;
}
public Config setRegexp(String regexp) {
this.regexp = regexp;
return this;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\CookieRoutePredicateFactory.java | 1 |
请完成以下Java代码 | public ShipperId getDefault(final ClientId clientId)
{
return queryBL
.createQueryBuilderOutOfTrx(I_M_Shipper.class)
.addInArrayFilter(I_M_Shipper.COLUMNNAME_AD_Client_ID, clientId, ClientId.SYSTEM)
.addEqualsFilter(I_M_Shipper.COLUMN_IsDefault, true)
.orderBy(I_M_Shipper.COLUMNNAME_AD_Client_ID)
.create()
.firstIdOnly(ShipperId::ofRepoIdOrNull);
}
@Override
public ITranslatableString getShipperName(@NonNull final ShipperId shipperId)
{
final I_M_Shipper shipper = getById(shipperId);
return InterfaceWrapperHelper.getModelTranslationMap(shipper)
.getColumnTrl(I_M_Shipper.COLUMNNAME_Name, shipper.getName());
}
@Override
public Optional<ShipperId> getShipperIdByValue(final String value, final OrgId orgId)
{
final ShipperId shipperId = queryBL.createQueryBuilderOutOfTrx(I_M_Shipper.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_Shipper.COLUMNNAME_Value, value)
.addInArrayFilter(I_M_Shipper.COLUMNNAME_AD_Org_ID, orgId, OrgId.ANY)
.orderByDescending(I_M_Shipper.COLUMNNAME_AD_Org_ID)
.create()
.firstIdOnly(ShipperId::ofRepoIdOrNull);
return Optional.ofNullable(shipperId);
}
@Override
public Optional<I_M_Shipper> getByName(@NonNull final String name)
{
return queryBL.createQueryBuilder(I_M_Shipper.class)
.addEqualsFilter(I_M_Shipper.COLUMNNAME_Name, name)
.create()
.firstOnlyOptional(I_M_Shipper.class);
}
@NonNull
public Map<ShipperId, I_M_Shipper> getByIds(@NonNull final Set<ShipperId> shipperIds)
{
if (Check.isEmpty(shipperIds))
{
return ImmutableMap.of();
}
final List<I_M_Shipper> shipperList = queryBL.createQueryBuilder(I_M_Shipper.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_M_Shipper.COLUMNNAME_M_Shipper_ID, shipperIds)
.create()
.list();
return Maps.uniqueIndex(shipperList, (shipper) -> ShipperId.ofRepoId(shipper.getM_Shipper_ID()));
}
@NonNull | public ImmutableMap<String, I_M_Shipper> getByInternalName(@NonNull final Set<String> internalNameSet)
{
if (Check.isEmpty(internalNameSet))
{
return ImmutableMap.of();
}
final List<I_M_Shipper> shipperList = queryBL.createQueryBuilder(I_M_Shipper.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_M_Shipper.COLUMNNAME_InternalName, internalNameSet)
.create()
.list();
return Maps.uniqueIndex(shipperList, I_M_Shipper::getInternalName);
}
@Override
public ExplainedOptional<ShipperGatewayId> getShipperGatewayId(@NonNull final ShipperId shipperId)
{
final I_M_Shipper shipper = getById(shipperId);
final ShipperGatewayId shipperGatewayId = ShipperGatewayId.ofNullableString(shipper.getShipperGateway());
return shipperGatewayId != null
? ExplainedOptional.of(shipperGatewayId)
: ExplainedOptional.emptyBecause("Shipper " + shipper.getName() + " has no gateway configured");
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\shipping\impl\ShipperDAO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Country2CountryAwareAttributeService implements ICountryAwareAttributeService
{
public static final Country2CountryAwareAttributeService instance = new Country2CountryAwareAttributeService();
private static final AdMessageKey MSG_NoCountryAttribute = AdMessageKey.of("de.metas.swat.CountryAttribute.error");
private Country2CountryAwareAttributeService()
{
super();
}
@Override
public AttributeId getAttributeId(final ICountryAware countryAware)
{
final int adClientId = countryAware.getAD_Client_ID();
final int adOrgId = countryAware.getAD_Org_ID();
return Services.get(ICountryAttributeDAO.class).retrieveCountryAttributeId(adClientId, adOrgId);
}
@Override
public AttributeListValue getCreateAttributeValue(final IContextAware context, final ICountryAware countryAware)
{
final Properties ctx = context.getCtx();
final String trxName = context.getTrxName();
final I_C_Country country = countryAware.getC_Country();
final SOTrx soTrx = SOTrx.ofBoolean(countryAware.isSOTrx());
final AttributeListValue attributeValue = Services.get(ICountryAttributeDAO.class).retrieveAttributeValue(ctx, country, false/* includeInactive */);
final AttributeAction attributeAction = Services.get(IAttributesBL.class).getAttributeAction(ctx);
if (attributeValue == null)
{
if (attributeAction == AttributeAction.Error)
{
throw new AdempiereException(MSG_NoCountryAttribute, country.getName());
}
else if (attributeAction == AttributeAction.GenerateNew)
{
final Attribute countryAttribute = Services.get(ICountryAttributeDAO.class).retrieveCountryAttribute(ctx);
final IAttributeValueGenerator generator = Services.get(IAttributesBL.class).getAttributeValueGenerator(countryAttribute);
return generator.generateAttributeValue(ctx, I_C_Country.Table_ID, country.getC_Country_ID(), false, trxName); // SO trx doesn't matter here
}
else if (attributeAction == AttributeAction.Ignore)
{
// Ignore: do not throw error, no not generate new attribute
}
else
{
throw new AdempiereException("@NotSupported@ AttributeAction " + attributeAction);
} | return attributeValue;
}
else
{
if (!attributeValue.isMatchingSOTrx(soTrx))
{
if (attributeAction == AttributeAction.Error)
{
throw new AttributeRestrictedException(ctx, soTrx, attributeValue, country.getCountryCode());
}
// We have an attribute value, but it is marked for a different transaction. Change type to "null", to make it available for both.
final IAttributeDAO attributesRepo = Services.get(IAttributeDAO.class);
return attributesRepo.changeAttributeValue(AttributeListValueChangeRequest.builder()
.id(attributeValue.getId())
.availableForTrx(AttributeListValueTrxRestriction.ANY_TRANSACTION)
.build());
}
else
{
return attributeValue;
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\mm\attributes\countryattribute\impl\Country2CountryAwareAttributeService.java | 2 |
请完成以下Java代码 | public static boolean hasAllRoles(String roleNames) {
boolean hasAllRole = true;
Subject subject = getSubject();
if (subject != null && roleNames != null && roleNames.length() > 0) {
for (String role : roleNames.split(NAMES_DELIMETER)) {
if (!subject.hasRole(role.trim())) {
hasAllRole = false;
break;
}
}
}
return hasAllRole;
}
/**
* 验证当前用户是否拥有指定权限,使用时与lacksPermission 搭配使用
*
* @param permission 权限名
* @return 拥有权限:true,否则false
*/
public static boolean hasPermission(String permission) {
return getSubject() != null && permission != null
&& permission.length() > 0
&& getSubject().isPermitted(permission);
}
/**
* 与hasPermission标签逻辑相反,当前用户没有制定权限时,验证通过。
*
* @param permission 权限名
* @return 拥有权限:true,否则false
*/
public static boolean lacksPermission(String permission) {
return !hasPermission(permission);
}
/**
* 已认证通过的用户,不包含已记住的用户,这是与user标签的区别所在。与notAuthenticated搭配使用
*
* @return 通过身份验证:true,否则false
*/
public static boolean isAuthenticated() {
return getSubject() != null && getSubject().isAuthenticated();
}
/**
* 未认证通过用户,与authenticated标签相对应。与guest标签的区别是,该标签包含已记住用户。。
*
* @return 没有通过身份验证:true,否则false
*/
public static boolean notAuthenticated() {
return !isAuthenticated(); | }
/**
* 认证通过或已记住的用户。与guset搭配使用。
*
* @return 用户:true,否则 false
*/
public static boolean isUser() {
return getSubject() != null && getSubject().getPrincipal() != null;
}
/**
* 验证当前用户是否为“访客”,即未认证(包含未记住)的用户。用user搭配使用
*
* @return 访客:true,否则false
*/
public static boolean isGuest() {
return !isUser();
}
/**
* 输出当前用户信息,通常为登录帐号信息。
*
* @return 当前用户信息
*/
public static String principal() {
if (getSubject() != null) {
Object principal = getSubject().getPrincipal();
return principal.toString();
}
return "";
}
} | repos\SpringBootBucket-master\springboot-shiro\src\main\java\com\xncoding\pos\shiro\ShiroKit.java | 1 |
请完成以下Java代码 | public String getClientInfo()
{
// implementation basically copied from SwingClientUI
final String javaVersion = System.getProperty("java.version");
return new StringBuilder("!! NO UI REGISTERED YET !!, java.version=").append(javaVersion).toString();
}
@Override
public void showWindow(Object model)
{
throw new UnsupportedOperationException("Not implemented: ClientUI.showWindow()");
}
@Override
public IClientUIInvoker invoke()
{
throw new UnsupportedOperationException("not implemented"); | }
@Override
public IClientUIAsyncInvoker invokeAsync()
{
throw new UnsupportedOperationException("not implemented");
}
@Override
public void showURL(String url)
{
System.err.println("Showing URL is not supported on server side: " + url);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\form\impl\ClientUI.java | 1 |
请完成以下Java代码 | public void afterPropertiesSet() throws Exception {
Assert.notNull(this.ticketValidator, "ticketValidator must be specified");
Assert.notNull(this.userDetailsService, "userDetailsService must be specified");
}
/**
* The <code>UserDetailsService</code> to use, for loading the user properties and the
* <code>GrantedAuthorities</code>.
* @param userDetailsService the new user details service
*/
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
/**
* The <code>KerberosTicketValidator</code> to use, for validating the Kerberos/SPNEGO
* tickets.
* @param ticketValidator the new ticket validator
*/
public void setTicketValidator(KerberosTicketValidator ticketValidator) {
this.ticketValidator = ticketValidator;
} | /**
* Allows subclasses to perform any additional checks of a returned
* <code>UserDetails</code> for a given authentication request.
* @param userDetails as retrieved from the {@link UserDetailsService}
* @param authentication validated {@link KerberosServiceRequestToken}
* @throws AuthenticationException AuthenticationException if the credentials could
* not be validated (generally a <code>BadCredentialsException</code>, an
* <code>AuthenticationServiceException</code>)
*/
protected void additionalAuthenticationChecks(UserDetails userDetails, KerberosServiceRequestToken authentication)
throws AuthenticationException {
}
} | repos\spring-security-main\kerberos\kerberos-core\src\main\java\org\springframework\security\kerberos\authentication\KerberosServiceAuthenticationProvider.java | 1 |
请完成以下Java代码 | public class LocatorGlobalQRCodeResolverKey
{
@NonNull String value;
private static final ConcurrentHashMap<String, LocatorGlobalQRCodeResolverKey> interner = new ConcurrentHashMap<>();
private LocatorGlobalQRCodeResolverKey(@NonNull final String value)
{
this.value = value;
}
@NonNull
public static LocatorGlobalQRCodeResolverKey ofString(@NonNull String value)
{
final LocatorGlobalQRCodeResolverKey key = ofNullableString(value);
if (key == null)
{
throw new AdempiereException("Invalid key: " + value);
}
return key;
}
@NonNull
public static LocatorGlobalQRCodeResolverKey ofClass(@NonNull Class<?> clazz)
{
return ofString(clazz.getSimpleName());
}
@JsonCreator
@Nullable
public static LocatorGlobalQRCodeResolverKey ofNullableString(@Nullable String value)
{ | final String valueNorm = StringUtils.trimBlankToNull(value);
if (valueNorm == null)
{
return null;
}
return interner.computeIfAbsent(valueNorm, LocatorGlobalQRCodeResolverKey::new);
}
@Override
@Deprecated
public String toString() {return toJson();}
@JsonValue
public String toJson() {return value;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\qrcode\resolver\LocatorGlobalQRCodeResolverKey.java | 1 |
请完成以下Java代码 | public class Company {
private Long id;
private String name;
@Relationship(type="owns")
private Car car;
public Company(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() { | return name;
}
public void setName(String name) {
this.name = name;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
} | repos\tutorials-master\persistence-modules\neo4j\src\main\java\com\baeldung\neo4j\domain\Company.java | 1 |
请完成以下Java代码 | public static ImmutableSet<HuId> extractHuIds(@NonNull final Collection<InventoryLineHU> lineHUs)
{
return extractHuIds(lineHUs.stream());
}
static ImmutableSet<HuId> extractHuIds(@NonNull final Stream<InventoryLineHU> lineHUs)
{
return lineHUs
.map(InventoryLineHU::getHuId)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
}
public InventoryLineHU convertQuantities(@NonNull final UnaryOperator<Quantity> qtyConverter)
{
return toBuilder()
.qtyCount(qtyConverter.apply(getQtyCount()))
.qtyBook(qtyConverter.apply(getQtyBook()))
.build();
}
public InventoryLineHU updatingFrom(@NonNull final InventoryLineCountRequest request)
{
return toBuilder().updatingFrom(request).build();
}
public static InventoryLineHU of(@NonNull final InventoryLineCountRequest request)
{
return builder().updatingFrom(request).build();
}
//
//
//
// -------------------------------------------------------------------------
//
// | //
@SuppressWarnings("unused")
public static class InventoryLineHUBuilder
{
InventoryLineHUBuilder updatingFrom(@NonNull final InventoryLineCountRequest request)
{
return huId(request.getHuId())
.huQRCode(HuId.equals(this.huId, request.getHuId()) ? this.huQRCode : null)
.qtyInternalUse(null)
.qtyBook(request.getQtyBook())
.qtyCount(request.getQtyCount())
.isCounted(true)
.asiId(request.getAsiId())
;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\InventoryLineHU.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BPartnerLocationAddressPart
{
@Nullable @With LocationId existingLocationId;
@Nullable String address1;
@Nullable String address2;
@Nullable String address3;
@Nullable String address4;
@Nullable String poBox;
@Nullable String postal;
@Nullable String city;
@Nullable String region;
@Nullable String district;
@Nullable String countryCode;
public static boolean equals(@Nullable final BPartnerLocationAddressPart o1, @Nullable final BPartnerLocationAddressPart o2)
{
return Objects.equals(o1, o2);
} | public boolean isOnlyExistingLocationIdSet()
{
return existingLocationId != null
&& Check.isBlank(address1)
&& Check.isBlank(address2)
&& Check.isBlank(address3)
&& Check.isBlank(address4)
&& Check.isBlank(poBox)
&& Check.isBlank(postal)
&& Check.isBlank(city)
&& Check.isBlank(region)
&& Check.isBlank(district)
&& Check.isBlank(countryCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\composite\BPartnerLocationAddressPart.java | 2 |
请完成以下Java代码 | public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) {
if (resolve(context, base, method)) {
throw new NullPointerException("Cannot invoke method " + method + " on null");
}
return null;
}
/**
* Get property value
*
* @param property
* property name
* @return value associated with the given property
*/
public Object getProperty(String property) {
return map.get(property);
}
/**
* Set property value
*
* @param property
* property name
* @param value
* property value
*/
public void setProperty(String property, Object value) {
map.put(property, value); | }
/**
* Test property
*
* @param property
* property name
* @return <code>true</code> if the given property is associated with a value
*/
public boolean isProperty(String property) {
return map.containsKey(property);
}
/**
* Get properties
*
* @return all property names (in no particular order)
*/
public Iterable<String> properties() {
return map.keySet();
}
} | repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\util\RootPropertyResolver.java | 1 |
请完成以下Java代码 | public final T getById(@NonNull final DocumentId rowId) throws EntityNotFoundException
{
return rowsData.getById(rowId);
}
@Override
public <MT> List<MT> retrieveModelsByIds(final DocumentIdsSelection rowIds, final Class<MT> modelClass)
{
throw new UnsupportedOperationException();
}
/**
* Also supports {@link DocumentIdsSelection#ALL}, because there won't be too many lines at one time.
*/
@Override
public final Stream<T> streamByIds(@NonNull final DocumentIdsSelection rowIds)
{
if (rowIds.isAll())
{
return getRows().stream();
}
else if (rowIds.isEmpty())
{
return Stream.empty();
}
else
{
return rowIds.stream().map(rowsData::getByIdOrNull).filter(Objects::nonNull);
}
}
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 |
请在Spring Boot框架中完成以下Java代码 | public PortMapperConfigurer<H> portMapper(PortMapper portMapper) {
this.portMapper = portMapper;
return this;
}
/**
* Adds a port mapping
* @param httpPort the HTTP port that maps to a specific HTTPS port.
* @return {@link HttpPortMapping} to define the HTTPS port
*/
public HttpPortMapping http(int httpPort) {
return new HttpPortMapping(httpPort);
}
@Override
public void init(H http) {
http.setSharedObject(PortMapper.class, getPortMapper());
}
/**
* Gets the {@link PortMapper} to use. If {@link #portMapper(PortMapper)} was not
* invoked, builds a {@link PortMapperImpl} using the port mappings specified with
* {@link #http(int)}.
* @return the {@link PortMapper} to use
*/
private PortMapper getPortMapper() {
if (this.portMapper == null) {
PortMapperImpl portMapper = new PortMapperImpl();
portMapper.setPortMappings(this.httpsPortMappings);
this.portMapper = portMapper;
}
return this.portMapper;
}
/**
* Allows specifying the HTTPS port for a given HTTP port when redirecting between
* HTTP and HTTPS.
*
* @author Rob Winch
* @since 3.2
*/
public final class HttpPortMapping { | private final int httpPort;
/**
* Creates a new instance
* @param httpPort
* @see PortMapperConfigurer#http(int)
*/
private HttpPortMapping(int httpPort) {
this.httpPort = httpPort;
}
/**
* Maps the given HTTP port to the provided HTTPS port and vice versa.
* @param httpsPort the HTTPS port to map to
* @return the {@link PortMapperConfigurer} for further customization
*/
public PortMapperConfigurer<H> mapsTo(int httpsPort) {
PortMapperConfigurer.this.httpsPortMappings.put(String.valueOf(this.httpPort), String.valueOf(httpsPort));
return PortMapperConfigurer.this;
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\PortMapperConfigurer.java | 2 |
请完成以下Java代码 | public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_User_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID));
}
/** Get User/Contact.
@return User within the system - Internal or Business Partner Contact
*/
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Position Assignment.
@param C_JobAssignment_ID
Assignemt of Employee (User) to Job Position
*/
public void setC_JobAssignment_ID (int C_JobAssignment_ID)
{
if (C_JobAssignment_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_JobAssignment_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_JobAssignment_ID, Integer.valueOf(C_JobAssignment_ID));
}
/** Get Position Assignment.
@return Assignemt of Employee (User) to Job Position
*/
public int getC_JobAssignment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_JobAssignment_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_Job getC_Job() throws RuntimeException
{
return (I_C_Job)MTable.get(getCtx(), I_C_Job.Table_Name)
.getPO(getC_Job_ID(), get_TrxName()); }
/** Set Position.
@param C_Job_ID
Job Position
*/
public void setC_Job_ID (int C_Job_ID)
{
if (C_Job_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Job_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Job_ID, Integer.valueOf(C_Job_ID));
}
/** Get Position.
@return Job Position
*/
public int getC_Job_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Job_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(getC_Job_ID()));
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description); | }
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_JobAssignment.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public String getProductId() {
return productId; | }
public void setProductId(String productId) {
this.productId = productId;
}
@Override
public String toString() {
return "ProdImageEntity{" +
"id='" + id + '\'' +
", imageURL='" + imageURL + '\'' +
", productId='" + productId + '\'' +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\product\ProdImageEntity.java | 2 |
请完成以下Java代码 | public void setId(String id) {
this.id = id;
}
@CamundaQueryParam("name")
public void setName(String name) {
this.name = name;
}
@CamundaQueryParam("nameLike")
public void setNameLike(String nameLike) {
this.nameLike = nameLike;
}
@CamundaQueryParam("userMember")
public void setUserMember(String userId) {
this.userId = userId;
}
@CamundaQueryParam("groupMember")
public void setGroupMember(String groupId) {
this.groupId = groupId;
}
@CamundaQueryParam(value = "includingGroupsOfUser", converter = BooleanConverter.class)
public void setIncludingGroupsOfUser(Boolean includingGroupsOfUser) {
this.includingGroupsOfUser = includingGroupsOfUser;
}
@Override
protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
@Override | protected TenantQuery createNewQuery(ProcessEngine engine) {
return engine.getIdentityService().createTenantQuery();
}
@Override
protected void applyFilters(TenantQuery query) {
if (id != null) {
query.tenantId(id);
}
if (name != null) {
query.tenantName(name);
}
if (nameLike != null) {
query.tenantNameLike(nameLike);
}
if (userId != null) {
query.userMember(userId);
}
if (groupId != null) {
query.groupMember(groupId);
}
if (Boolean.TRUE.equals(includingGroupsOfUser)) {
query.includingGroupsOfUser(true);
}
}
@Override
protected void applySortBy(TenantQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_TENANT_ID_VALUE)) {
query.orderByTenantId();
} else if (sortBy.equals(SORT_BY_TENANT_NAME_VALUE)) {
query.orderByTenantName();
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\identity\TenantQueryDto.java | 1 |
请完成以下Java代码 | void addLineItem(JpaOrderLine orderLine) {
checkNotNull(orderLine);
orderLines.add(orderLine);
}
String getCurrencyUnit() {
return currencyUnit;
}
Long getId() {
return id;
}
List<JpaOrderLine> getOrderLines() {
return new ArrayList<>(orderLines);
}
BigDecimal getTotalCost() {
return totalCost;
} | void removeLineItem(int line) {
orderLines.remove(line);
}
void setCurrencyUnit(String currencyUnit) {
this.currencyUnit = currencyUnit;
}
void setTotalCost(BigDecimal totalCost) {
this.totalCost = totalCost;
}
private static void checkNotNull(Object par) {
if (par == null) {
throw new NullPointerException("Parameter cannot be null");
}
}
} | repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\ddd\order\jpa\JpaOrder.java | 1 |
请完成以下Java代码 | private boolean isLeaf(int index) {
return !isValidIndex(leftChildIndex(index));
}
private boolean isCorrectParent(int index) {
return isCorrect(index, leftChildIndex(index)) && isCorrect(index, rightChildIndex(index));
}
private boolean isCorrectChild(int index) {
return isCorrect(parentIndex(index), index);
}
private boolean isCorrect(int parentIndex, int childIndex) {
if (!isValidIndex(parentIndex) || !isValidIndex(childIndex)) {
return true;
}
return elementAt(parentIndex).compareTo(elementAt(childIndex)) < 0;
}
private boolean isValidIndex(int index) {
return index < elements.size();
}
private void swap(int index1, int index2) {
E element1 = elementAt(index1);
E element2 = elementAt(index2);
elements.set(index1, element2);
elements.set(index2, element1);
}
private E elementAt(int index) {
return elements.get(index); | }
private int parentIndex(int index) {
return (index - 1) / 2;
}
private int leftChildIndex(int index) {
return 2 * index + 1;
}
private int rightChildIndex(int index) {
return 2 * index + 2;
}
} | repos\tutorials-master\algorithms-modules\algorithms-sorting-2\src\main\java\com\baeldung\algorithms\heapsort\Heap.java | 1 |
请完成以下Java代码 | public WeightingSpecifications getById(@NonNull final WeightingSpecificationsId id)
{
return getMap().getById(id);
}
public WeightingSpecificationsId getDefaultId()
{
return getMap().getDefaultId();
}
public WeightingSpecifications getDefault()
{
return getMap().getDefault();
}
public WeightingSpecificationsMap getMap()
{
return cache.getOrLoad(0, this::retrieveMap);
}
private WeightingSpecificationsMap retrieveMap()
{
final ImmutableList<WeightingSpecifications> list = queryBL
.createQueryBuilder(I_PP_Weighting_Spec.class)
.addEqualsFilter(I_PP_Weighting_Spec.COLUMNNAME_AD_Client_ID, ClientId.METASFRESH)
.addOnlyActiveRecordsFilter()
.create() | .stream()
.map(WeightingSpecificationsRepository::fromRecord)
.collect(ImmutableList.toImmutableList());
return new WeightingSpecificationsMap(list);
}
public static WeightingSpecifications fromRecord(I_PP_Weighting_Spec record)
{
return WeightingSpecifications.builder()
.id(WeightingSpecificationsId.ofRepoId(record.getPP_Weighting_Spec_ID()))
.weightChecksRequired(record.getWeightChecksRequired())
.tolerance(Percent.of(record.getTolerance_Perc()))
.uomId(UomId.ofRepoId(record.getC_UOM_ID()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\weighting\spec\WeightingSpecificationsRepository.java | 1 |
请完成以下Java代码 | public class MLandedCostAllocation extends X_C_LandedCostAllocation
{
/**
*
*/
private static final long serialVersionUID = -8645283018475474574L;
/**
* Get Cost Allocations for invoice Line
* @param ctx context
* @param C_InvoiceLine_ID invoice line
* @param trxName trx
* @return landed cost alloc
*/
public static MLandedCostAllocation[] getOfInvoiceLine (Properties ctx,
int C_InvoiceLine_ID, String trxName)
{
ArrayList<MLandedCostAllocation> list = new ArrayList<MLandedCostAllocation>();
String sql = "SELECT * FROM C_LandedCostAllocation WHERE C_InvoiceLine_ID=?";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, trxName);
pstmt.setInt (1, C_InvoiceLine_ID);
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
list.add (new MLandedCostAllocation (ctx, rs, trxName));
rs.close ();
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
s_log.error(sql, e);
}
try
{
if (pstmt != null)
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
MLandedCostAllocation[] retValue = new MLandedCostAllocation[list.size ()];
list.toArray (retValue);
return retValue;
} // getOfInvliceLine
/** Logger */
private static Logger s_log = LogManager.getLogger(MLandedCostAllocation.class);
/*************************************************************************** | * Standard Constructor
* @param ctx context
* @param C_LandedCostAllocation_ID id
* @param trxName trx
*/
public MLandedCostAllocation (Properties ctx, int C_LandedCostAllocation_ID, String trxName)
{
super (ctx, C_LandedCostAllocation_ID, trxName);
if (C_LandedCostAllocation_ID == 0)
{
// setM_CostElement_ID(0);
setAmt (Env.ZERO);
setQty (Env.ZERO);
setBase (Env.ZERO);
}
} // MLandedCostAllocation
/**
* Load Constructor
* @param ctx context
* @param rs result name
* @param trxName trx
*/
public MLandedCostAllocation (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MLandedCostAllocation
/**
* Parent Constructor
* @param parent parent
* @param M_CostElement_ID cost element
*/
public MLandedCostAllocation (MInvoiceLine parent, int M_CostElement_ID)
{
this (parent.getCtx(), 0, parent.get_TrxName());
setClientOrg(parent);
setC_InvoiceLine_ID(parent.getC_InvoiceLine_ID());
setM_CostElement_ID(M_CostElement_ID);
} // MLandedCostAllocation
/**
* Set Amt
* @param Amt amount
* @param precision precision
*/
public void setAmt (double Amt, CurrencyPrecision precision)
{
BigDecimal bd = precision.roundIfNeeded(new BigDecimal(Amt));
super.setAmt(bd);
} // setAmt
} // MLandedCostAllocation | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MLandedCostAllocation.java | 1 |
请完成以下Java代码 | public static class ServiceTaskExport extends AbstractServiceTaskExport<ServiceTask> {
@Override
protected Class<? extends ServiceTask> getExportablePlanItemDefinitionClass() {
return ServiceTask.class;
}
}
public static class HttpServiceTaskExport extends AbstractServiceTaskExport<HttpServiceTask> {
@Override
protected Class<? extends HttpServiceTask> getExportablePlanItemDefinitionClass() {
return HttpServiceTask.class;
}
}
public static class ScriptServiceTaskExport extends AbstractServiceTaskExport<ScriptServiceTask> {
@Override
protected Class<? extends ScriptServiceTask> getExportablePlanItemDefinitionClass() {
return ScriptServiceTask.class;
}
@Override
protected boolean writePlanItemDefinitionExtensionElements(CmmnModel model, ScriptServiceTask serviceTask, boolean didWriteExtensionElement,
XMLStreamWriter xtw) throws Exception {
boolean extensionElementWritten = super.writePlanItemDefinitionExtensionElements(model, serviceTask, didWriteExtensionElement, xtw);
extensionElementWritten = CmmnXmlUtil.writeIOParameters(ELEMENT_EXTERNAL_WORKER_IN_PARAMETER, serviceTask.getInParameters(),
extensionElementWritten, xtw);
return extensionElementWritten;
}
} | public static class FormAwareServiceTaskExport extends AbstractServiceTaskExport<FormAwareServiceTask> {
@Override
protected Class<? extends FormAwareServiceTask> getExportablePlanItemDefinitionClass() {
return FormAwareServiceTask.class;
}
@Override
public void writePlanItemDefinitionSpecificAttributes(FormAwareServiceTask formAwareServiceTask, XMLStreamWriter xtw) throws Exception {
super.writePlanItemDefinitionSpecificAttributes(formAwareServiceTask, xtw);
if (StringUtils.isNotBlank(formAwareServiceTask.getFormKey())) {
xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_FORM_KEY, formAwareServiceTask.getFormKey());
}
if (StringUtils.isNotBlank(formAwareServiceTask.getValidateFormFields())) {
xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_FORM_FIELD_VALIDATION,
formAwareServiceTask.getValidateFormFields());
}
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\export\AbstractServiceTaskExport.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public Boolean getFinished() {
return finished;
}
public void setFinished(Boolean finished) {
this.finished = finished;
}
public String getTaskAssignee() {
return taskAssignee;
}
public void setTaskAssignee(String taskAssignee) {
this.taskAssignee = taskAssignee;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
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;
}
public Set<String> getCalledProcessInstanceIds() {
return calledProcessInstanceIds;
}
public void setCalledProcessInstanceIds(Set<String> calledProcessInstanceIds) {
this.calledProcessInstanceIds = calledProcessInstanceIds;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricActivityInstanceQueryRequest.java | 2 |
请完成以下Java代码 | public static IHUQueryBuilder toHUQueryBuilderPart(final HUEditorRowFilter filter)
{
final IHUQueryBuilder huQueryBuilder = Services.get(IHandlingUnitsDAO.class).createHUQueryBuilder();
//
// Filter by row type
// IMPORTANT: don't filter out TUs/CUs because it might be that we are searching for included rows too
// and in case we are filtering them out here the included TUs/CUs won't be found later...
final Select rowType = filter.getSelect();
if (rowType == Select.ALL)
{
// nothing
}
else if (rowType == Select.ONLY_TOPLEVEL)
{
huQueryBuilder.setOnlyTopLevelHUs(true);
}
// else if (rowType == Select.LU)
// else if (rowType == Select.TU)
else
{
// throw new AdempiereException("Not supported: " + rowType);
}
// Filter by string filter
// final String stringFilter = filter.getUserInputFilter();
// if (!Check.isEmpty(stringFilter, true)) | // {
// throw new AdempiereException("String filter not supported: " + stringFilter);
// }
// Exclude M_HU_IDs
huQueryBuilder.addHUIdsToExclude(filter.getExcludeHUIds());
// Include HUStatuses
huQueryBuilder.addHUStatusesToInclude(filter.getOnlyHUStatuses());
// Exclude HUStatuses
huQueryBuilder.addHUStatusesToExclude(filter.getExcludeHUStatuses());
return huQueryBuilder;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorRowFilters.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setCurrentReplicationTrxStatus(@NonNull final EcosioOrdersRouteContext.TrxImportStatus currentTrxStatus)
{
importedTrxName2TrxStatus.put(currentReplicationTrxName, currentTrxStatus);
}
@NonNull
public Optional<NotifyReplicationTrxRequest> getStatusRequestFor(@NonNull final String trxName)
{
final Collection<TrxImportStatus> progress = importedTrxName2TrxStatus.get(trxName);
if (Check.isEmpty(progress))
{
return Optional.empty();
}
final boolean allNotOk = progress.stream().noneMatch(EcosioOrdersRouteContext.TrxImportStatus::isOk);
if (allNotOk)
{
//dev-note: no update is required when there is no C_OLCand imported in this replication trx
return Optional.empty();
}
final boolean allOk = progress.stream().allMatch(EcosioOrdersRouteContext.TrxImportStatus::isOk);
if (allOk)
{
final NotifyReplicationTrxRequest finishedRequest = NotifyReplicationTrxRequest.finished()
.clientValue(clientValue)
.trxName(trxName)
.build();
return Optional.ofNullable(finishedRequest);
}
return Optional.of(NotifyReplicationTrxRequest.error(getErrorMessage(progress))
.clientValue(clientValue)
.trxName(trxName)
.build());
}
@NonNull
private static String getErrorMessage(@NonNull final Collection<TrxImportStatus> progress)
{
return progress.stream()
.map(TrxImportStatus::getErrorMessage)
.filter(Check::isNotBlank)
.collect(Collectors.joining("\n"));
} | @Value
@Builder
public static class TrxImportStatus
{
boolean ok;
@Nullable
String errorMessage;
@NonNull
public static EcosioOrdersRouteContext.TrxImportStatus ok()
{
return TrxImportStatus.builder()
.ok(true)
.build();
}
@NonNull
public static EcosioOrdersRouteContext.TrxImportStatus error(@NonNull final String errorMessage)
{
return TrxImportStatus.builder()
.ok(false)
.errorMessage(errorMessage)
.build();
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\ordersimport\ecosio\EcosioOrdersRouteContext.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public HUQRCodeGenerateRequestBuilder attribute(@NonNull AttributeId attributeId, @Nullable LocalDate valueDate)
{
return _attribute(Attribute.builder().attributeId(attributeId).valueDate(valueDate).build());
}
public HUQRCodeGenerateRequestBuilder attribute(@NonNull AttributeId attributeId, @Nullable AttributeValueId valueListId)
{
return _attribute(Attribute.builder().attributeId(attributeId).valueListId(valueListId).build());
}
public HUQRCodeGenerateRequestBuilder lotNo(@Nullable final String lotNo, @NonNull final Function<AttributeCode, AttributeId> getAttributeIdByCode)
{
final AttributeId attributeId = getAttributeIdByCode.apply(AttributeConstants.ATTR_LotNumber);
return attribute(attributeId, StringUtils.trimBlankToNull(lotNo));
}
}
// | //
//
@Value
@Builder
public static class Attribute
{
@Nullable AttributeId attributeId;
@Nullable AttributeCode code;
@Nullable String valueString;
@Nullable BigDecimal valueNumber;
@Nullable LocalDate valueDate;
@Nullable AttributeValueId valueListId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\service\HUQRCodeGenerateRequest.java | 2 |
请完成以下Java代码 | public boolean isAvailable()
{
return true;
}
@Override
public boolean isRunnable()
{
final VEditor editor = getEditor();
final GridField gridField = editor.getField();
if (gridField == null)
{
return false;
}
if (!Env.getUserRolePermissions().isShowPreference())
{
return false; | }
return true;
}
@Override
public void run()
{
final VEditor editor = getEditor();
final GridField gridField = editor.getField();
if (gridField == null)
{
return ;
}
ValuePreference.start (gridField, editor.getValue(), editor.getDisplay());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\menu\ValuePreferenceContextEditorAction.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static String getApplicationUri(HttpServletRequest request) {
UriComponents uriComponents = UriComponentsBuilder.fromUriString(UrlUtils.buildFullRequestUrl(request))
.replacePath(request.getContextPath())
.replaceQuery(null)
.fragment(null)
.build();
return uriComponents.toUriString();
}
/**
* A class for resolving {@link RelyingPartyRegistration} URIs
*/
public static final class UriResolver {
private final Map<String, String> uriVariables; | private UriResolver(Map<String, String> uriVariables) {
this.uriVariables = uriVariables;
}
public String resolve(String uri) {
if (uri == null) {
return null;
}
return UriComponentsBuilder.fromUriString(uri).buildAndExpand(this.uriVariables).toUriString();
}
}
} | repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\web\RelyingPartyRegistrationPlaceholderResolvers.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public List<I_C_BPartner_Location_QuickInput> retrieveLocationsByQuickInputId(final BPartnerQuickInputId bpartnerQuickInputId)
{
return queryBL
.createQueryBuilder(I_C_BPartner_Location_QuickInput.class)
.addEqualsFilter(I_C_BPartner_Location_QuickInput.COLUMNNAME_C_BPartner_QuickInput_ID, bpartnerQuickInputId)
.orderBy(I_C_BPartner_Location_QuickInput.COLUMNNAME_C_BPartner_Location_QuickInput_ID)
.create()
.list();
}
public List<I_C_BPartner_Location_QuickInput> retrieveBillToLocationsByQuickInputId(final BPartnerQuickInputId bpartnerQuickInputId)
{
return queryBL
.createQueryBuilder(I_C_BPartner_Location_QuickInput.class)
.addEqualsFilter(I_C_BPartner_Location_QuickInput.COLUMNNAME_C_BPartner_QuickInput_ID, bpartnerQuickInputId)
.orderBy(I_C_BPartner_Location_QuickInput.COLUMNNAME_C_BPartner_Location_QuickInput_ID)
.create()
.list(); | }
public List<String> getOtherLocationNames(
final int bpartnerQuickInputRecordId,
final int bpartnerLocationQuickInputIdToExclude)
{
return queryBL
.createQueryBuilder(I_C_BPartner_Location_QuickInput.class)
.addEqualsFilter(I_C_BPartner_Location_QuickInput.COLUMNNAME_C_BPartner_QuickInput_ID, bpartnerQuickInputRecordId)
.addNotEqualsFilter(I_C_BPartner_Location_QuickInput.COLUMNNAME_C_BPartner_Location_QuickInput_ID, bpartnerLocationQuickInputIdToExclude)
.create()
.listDistinct(I_C_BPartner_Location_QuickInput.COLUMNNAME_Name, String.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\quick_input\service\BPartnerQuickInputRepository.java | 2 |
请完成以下Java代码 | protected boolean isEndpointTypeExposed(Class<?> beanType) {
return MergedAnnotations.from(beanType, SearchStrategy.SUPERCLASS).isPresent(ServletEndpoint.class);
}
@Override
protected ExposableServletEndpoint createEndpoint(Object endpointBean, EndpointId id, Access defaultAccess,
Collection<Operation> operations) {
String rootPath = PathMapper.getRootPath(this.endpointPathMappers, id);
return new DiscoveredServletEndpoint(this, endpointBean, id, rootPath, defaultAccess);
}
@Override
protected Operation createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod,
OperationInvoker invoker) {
throw new IllegalStateException("ServletEndpoints must not declare operations");
}
@Override
protected OperationKey createOperationKey(Operation operation) {
throw new IllegalStateException("ServletEndpoints must not declare operations"); | }
@Override
protected boolean isInvocable(ExposableServletEndpoint endpoint) {
return true;
}
static class ServletEndpointDiscovererRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.reflection().registerType(ServletEndpointFilter.class, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\web\annotation\ServletEndpointDiscoverer.java | 1 |
请完成以下Java代码 | public class SslHealthIndicator extends AbstractHealthIndicator {
private final SslInfo sslInfo;
private final Duration expiryThreshold;
public SslHealthIndicator(SslInfo sslInfo, Duration expiryThreshold) {
super("SSL health check failed");
Assert.notNull(sslInfo, "'sslInfo' must not be null");
this.sslInfo = sslInfo;
this.expiryThreshold = expiryThreshold;
}
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
List<CertificateChainInfo> validCertificateChains = new ArrayList<>();
List<CertificateChainInfo> invalidCertificateChains = new ArrayList<>();
List<CertificateChainInfo> expiringCertificateChains = new ArrayList<>();
for (BundleInfo bundle : this.sslInfo.getBundles()) {
for (CertificateChainInfo certificateChain : bundle.getCertificateChains()) {
if (containsOnlyValidCertificates(certificateChain)) {
validCertificateChains.add(certificateChain);
if (containsExpiringCertificate(certificateChain)) {
expiringCertificateChains.add(certificateChain);
}
}
else if (containsInvalidCertificate(certificateChain)) {
invalidCertificateChains.add(certificateChain);
}
}
}
builder.status((invalidCertificateChains.isEmpty()) ? Status.UP : Status.OUT_OF_SERVICE);
builder.withDetail("expiringChains", expiringCertificateChains);
builder.withDetail("invalidChains", invalidCertificateChains);
builder.withDetail("validChains", validCertificateChains);
}
private boolean containsOnlyValidCertificates(CertificateChainInfo certificateChain) {
return validatableCertificates(certificateChain).allMatch(this::isValidCertificate);
} | private boolean containsInvalidCertificate(CertificateChainInfo certificateChain) {
return validatableCertificates(certificateChain).anyMatch(this::isNotValidCertificate);
}
private boolean containsExpiringCertificate(CertificateChainInfo certificateChain) {
return validatableCertificates(certificateChain).anyMatch(this::isExpiringCertificate);
}
private Stream<CertificateInfo> validatableCertificates(CertificateChainInfo certificateChain) {
return certificateChain.getCertificates().stream().filter((certificate) -> certificate.getValidity() != null);
}
private boolean isValidCertificate(CertificateInfo certificate) {
CertificateValidityInfo validity = certificate.getValidity();
Assert.state(validity != null, "'validity' must not be null");
return validity.getStatus().isValid();
}
private boolean isNotValidCertificate(CertificateInfo certificate) {
return !isValidCertificate(certificate);
}
private boolean isExpiringCertificate(CertificateInfo certificate) {
Instant validityEnds = certificate.getValidityEnds();
Assert.state(validityEnds != null, "'validityEnds' must not be null");
return Instant.now().plus(this.expiryThreshold).isAfter(validityEnds);
}
} | repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\application\SslHealthIndicator.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_AD_User getSupervisor() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_Supervisor_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setSupervisor(org.compiere.model.I_AD_User Supervisor)
{
set_ValueFromPO(COLUMNNAME_Supervisor_ID, org.compiere.model.I_AD_User.class, Supervisor);
}
/** Set Vorgesetzter.
@param Supervisor_ID
Supervisor for this user/organization - used for escalation and approval
*/
@Override
public void setSupervisor_ID (int Supervisor_ID)
{
if (Supervisor_ID < 1)
set_Value (COLUMNNAME_Supervisor_ID, null);
else
set_Value (COLUMNNAME_Supervisor_ID, Integer.valueOf(Supervisor_ID));
}
/** Get Vorgesetzter.
@return Supervisor for this user/organization - used for escalation and approval
*/
@Override
public int getSupervisor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Supervisor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* WeekDay AD_Reference_ID=167
* Reference name: Weekdays
*/
public static final int WEEKDAY_AD_Reference_ID=167;
/** Sonntag = 7 */
public static final String WEEKDAY_Sonntag = "7";
/** Montag = 1 */
public static final String WEEKDAY_Montag = "1";
/** Dienstag = 2 */
public static final String WEEKDAY_Dienstag = "2";
/** Mittwoch = 3 */
public static final String WEEKDAY_Mittwoch = "3"; | /** Donnerstag = 4 */
public static final String WEEKDAY_Donnerstag = "4";
/** Freitag = 5 */
public static final String WEEKDAY_Freitag = "5";
/** Samstag = 6 */
public static final String WEEKDAY_Samstag = "6";
/** Set Day of the Week.
@param WeekDay
Day of the Week
*/
@Override
public void setWeekDay (java.lang.String WeekDay)
{
set_Value (COLUMNNAME_WeekDay, WeekDay);
}
/** Get Day of the Week.
@return Day of the Week
*/
@Override
public java.lang.String getWeekDay ()
{
return (java.lang.String)get_Value(COLUMNNAME_WeekDay);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Scheduler.java | 1 |
请完成以下Java代码 | public <T> T getModel(@NonNull final IContextAware context, @NonNull final Class<T> modelClass)
{
return InterfaceWrapperHelper.create(getModel(context), modelClass);
}
@NonNull
public <T> T getModelNonNull(@NonNull final IContextAware context, @NonNull final Class<T> modelClass)
{
final T model = InterfaceWrapperHelper.create(getModel(context), modelClass);
return Check.assumeNotNull(model, "Model for this TableRecordReference={} may not be null", this);
}
@Override
public void notifyModelStaled()
{
modelRef = new SoftReference<>(null);
}
/**
* Checks if underlying (and cached) model is still valid in given context. In case is no longer valid, it will be set to <code>null</code>.
*/
private void checkModelStaled(final IContextAware context)
{
final Object model = modelRef.get();
if (model == null)
{
return;
}
final String modelTrxName = InterfaceWrapperHelper.getTrxName(model);
if (!Services.get(ITrxManager.class).isSameTrxName(modelTrxName, context.getTrxName()))
{
modelRef = new SoftReference<>(null);
}
// TODO: why the ctx is not validated, like org.adempiere.ad.dao.cache.impl.TableRecordCacheLocal.getValue(Class<RT>) does?
}
@Deprecated
@Override
public Object getModel() | {
return getModel(PlainContextAware.newWithThreadInheritedTrx());
}
/**
* Deprecated: pls use appropriate DAO/Repository for loading models
* e.g. ModelDAO.getById({@link TableRecordReference#getIdAssumingTableName(String, IntFunction)})
*/
@Deprecated
@Override
public <T> T getModel(final Class<T> modelClass)
{
return getModel(PlainContextAware.newWithThreadInheritedTrx(), modelClass);
}
@NonNull
public <T> T getModelNonNull(@NonNull final Class<T> modelClass)
{
return getModelNonNull(PlainContextAware.newWithThreadInheritedTrx(), modelClass);
}
public static <T> List<T> getModels(
@NonNull final Collection<? extends ITableRecordReference> references,
@NonNull final Class<T> modelClass)
{
return references
.stream()
.map(ref -> ref.getModel(modelClass))
.collect(ImmutableList.toImmutableList());
}
public boolean isOfType(@NonNull final Class<?> modelClass)
{
final String modelTableName = InterfaceWrapperHelper.getTableNameOrNull(modelClass);
return modelTableName != null && modelTableName.equals(getTableName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\lang\impl\TableRecordReference.java | 1 |
请完成以下Java代码 | protected <DT> void exportEDI(
final Class<DT> documentType,
final String exportFormatName,
final String tableName,
final String columnName,
@Nullable final CreateAttachmentRequest attachResultRequest)
{
final String whereClause = columnName + "=?";
final Properties ctx = InterfaceWrapperHelper.getCtx(document);
final String trxName = InterfaceWrapperHelper.getTrxName(document);
final int recordId = InterfaceWrapperHelper.getId(document);
final DT viewToExport = new Query(ctx, tableName, whereClause, trxName)
.setParameters(recordId)
.firstOnly(documentType);
final PO viewToExportPO = InterfaceWrapperHelper.getPO(viewToExport);
Check.errorIf(viewToExportPO == null, "View {} has no record for document {}", tableName, document);
final MEXPFormat exportFormat = fetchExportFormat(ctx, exportFormatName, trxName);
final ExportHelper exportHelper = new ExportHelper(ctx, expClientId);
Check.errorIf(exportHelper.getAD_ReplicationStrategy() == null, "Client {} has no AD_ReplicationStrategy", expClientId);
exportHelper.exportRecord(viewToExportPO,
exportFormat,
MReplicationStrategy.REPLICATION_DOCUMENT,
X_AD_ReplicationTable.REPLICATIONTYPE_Merge,
0, // ReplicationEvent = no event
attachResultRequest
);
}
private MEXPFormat fetchExportFormat(final Properties ctx, final String exportFormatName, final String trxName)
{
MEXPFormat expFormat = MEXPFormat.getFormatByValueAD_Client_IDAndVersion(ctx,
exportFormatName,
expClientId.getRepoId(),
"*", // version
trxName);
if (expFormat == null)
{
expFormat = MEXPFormat.getFormatByValueAD_Client_IDAndVersion(ctx,
exportFormatName,
0, // AD_Client_ID | "*", // version
trxName);
}
if (expFormat == null)
{
throw new AdempiereException("@NotFound@ @EXP_Format_ID@ (@Value@: " + exportFormatName + ")");
}
return expFormat;
}
@Override
public T getDocument()
{
return document;
}
@Override
public final String getTableIdentifier()
{
return tableIdentifier;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\export\impl\AbstractExport.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setSocketTimeout(Duration socketTimeout) {
this.socketTimeout = socketTimeout;
}
public boolean isSocketKeepAlive() {
return this.socketKeepAlive;
}
public void setSocketKeepAlive(boolean socketKeepAlive) {
this.socketKeepAlive = socketKeepAlive;
}
public @Nullable String getPathPrefix() {
return this.pathPrefix;
}
public void setPathPrefix(@Nullable String pathPrefix) {
this.pathPrefix = pathPrefix;
}
public Restclient getRestclient() {
return this.restclient;
}
public static class Restclient {
private final Sniffer sniffer = new Sniffer();
private final Ssl ssl = new Ssl();
public Sniffer getSniffer() {
return this.sniffer;
}
public Ssl getSsl() {
return this.ssl;
}
public static class Sniffer {
/**
* Whether the sniffer is enabled.
*/
private boolean enabled;
/**
* Interval between consecutive ordinary sniff executions.
*/
private Duration interval = Duration.ofMinutes(5);
/**
* Delay of a sniff execution scheduled after a failure.
*/
private Duration delayAfterFailure = Duration.ofMinutes(1);
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Duration getInterval() {
return this.interval;
}
public void setInterval(Duration interval) {
this.interval = interval;
} | public Duration getDelayAfterFailure() {
return this.delayAfterFailure;
}
public void setDelayAfterFailure(Duration delayAfterFailure) {
this.delayAfterFailure = delayAfterFailure;
}
}
public static class Ssl {
/**
* SSL bundle name.
*/
private @Nullable String bundle;
public @Nullable String getBundle() {
return this.bundle;
}
public void setBundle(@Nullable String bundle) {
this.bundle = bundle;
}
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-elasticsearch\src\main\java\org\springframework\boot\elasticsearch\autoconfigure\ElasticsearchProperties.java | 2 |
请完成以下Java代码 | public abstract class AbstractRequestParameterAllowFromStrategy implements AllowFromStrategy {
private static final String DEFAULT_ORIGIN_REQUEST_PARAMETER = "x-frames-allow-from";
private String allowFromParameterName = DEFAULT_ORIGIN_REQUEST_PARAMETER;
/** Logger for use by subclasses */
protected final Log log = LogFactory.getLog(getClass());
AbstractRequestParameterAllowFromStrategy() {
}
@Override
public String getAllowFromValue(HttpServletRequest request) {
String allowFromOrigin = request.getParameter(this.allowFromParameterName);
this.log.debug(LogMessage.format("Supplied origin '%s'", allowFromOrigin));
if (StringUtils.hasText(allowFromOrigin) && allowed(allowFromOrigin)) {
return allowFromOrigin;
}
return "DENY";
}
/**
* Sets the HTTP parameter used to retrieve the value for the origin that is allowed
* from. The value of the parameter should be a valid URL. The default parameter name
* is "x-frames-allow-from". | * @param allowFromParameterName the name of the HTTP parameter to
*/
public void setAllowFromParameterName(String allowFromParameterName) {
Assert.notNull(allowFromParameterName, "allowFromParameterName cannot be null");
this.allowFromParameterName = allowFromParameterName;
}
/**
* Method to be implemented by base classes, used to determine if the supplied origin
* is allowed.
* @param allowFromOrigin the supplied origin
* @return <code>true</code> if the supplied origin is allowed.
*/
protected abstract boolean allowed(String allowFromOrigin);
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\writers\frameoptions\AbstractRequestParameterAllowFromStrategy.java | 1 |
请完成以下Java代码 | 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 java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
} | @Override
public void setPP_Product_BOMVersions_ID (final int PP_Product_BOMVersions_ID)
{
if (PP_Product_BOMVersions_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Product_BOMVersions_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Product_BOMVersions_ID, PP_Product_BOMVersions_ID);
}
@Override
public int getPP_Product_BOMVersions_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Product_BOMVersions_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Product_BOMVersions.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PickFromHUsGetRequest
{
@NonNull ImmutableSet<LocatorId> pickFromLocatorIds;
@NonNull ProductId productId;
@NonNull BPartnerId partnerId;
@NonNull AttributeSetInstanceId asiId;
@NonNull ShipmentAllocationBestBeforePolicy bestBeforePolicy;
@NonNull Optional<HUReservationDocRef> reservationRef;
@Nullable ImmutableSet<HuId> onlyHuIds;
boolean ignoreHUsScheduledInDDOrderSchedules;
/**
* If {@code true}, then check, which attributes are mandatory for the HUs' products.
* Ignore those HUs that don't have all those attributes set.
*/
boolean enforceMandatoryAttributesOnPicking;
@Builder(toBuilder = true)
private PickFromHUsGetRequest(
@NonNull @Singular final ImmutableSet<LocatorId> pickFromLocatorIds,
@NonNull final ProductId productId,
@Nullable final BPartnerId partnerId,
@NonNull final AttributeSetInstanceId asiId,
@NonNull final ShipmentAllocationBestBeforePolicy bestBeforePolicy,
@NonNull final Optional<HUReservationDocRef> reservationRef,
@Nullable final Boolean enforceMandatoryAttributesOnPicking,
@Nullable final ImmutableSet<HuId> onlyHuIds, | final boolean ignoreHUsScheduledInDDOrderSchedules)
{
Check.assumeNotEmpty(pickFromLocatorIds, "pickFromLocatorIds shall not be empty");
this.pickFromLocatorIds = pickFromLocatorIds;
this.productId = productId;
this.partnerId = partnerId;
this.asiId = asiId;
this.bestBeforePolicy = bestBeforePolicy;
this.reservationRef = reservationRef;
this.enforceMandatoryAttributesOnPicking = CoalesceUtil.coalesceNotNull(enforceMandatoryAttributesOnPicking, false);
this.onlyHuIds = onlyHuIds;
this.ignoreHUsScheduledInDDOrderSchedules = ignoreHUsScheduledInDDOrderSchedules;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\plan\generator\pickFromHUs\PickFromHUsGetRequest.java | 2 |
请在Spring Boot框架中完成以下Java代码 | class SemanticCachingService {
private final VectorStore vectorStore;
private final SemanticCacheProperties semanticCacheProperties;
SemanticCachingService(VectorStore vectorStore, SemanticCacheProperties semanticCacheProperties) {
this.vectorStore = vectorStore;
this.semanticCacheProperties = semanticCacheProperties;
}
void save(String question, String answer) {
Document document = Document
.builder()
.text(question)
.metadata(semanticCacheProperties.metadataField(), answer)
.build();
vectorStore.add(List.of(document));
}
Optional<String> search(String question) {
SearchRequest searchRequest = SearchRequest.builder()
.query(question) | .similarityThreshold(semanticCacheProperties.similarityThreshold())
.topK(1)
.build();
List<Document> results = vectorStore.similaritySearch(searchRequest);
if (results.isEmpty()) {
return Optional.empty();
}
Document result = results.getFirst();
return Optional
.ofNullable(result.getMetadata().get(semanticCacheProperties.metadataField()))
.map(String::valueOf);
}
} | repos\tutorials-master\spring-ai-modules\spring-ai-semantic-caching\src\main\java\com\baeldung\semantic\cache\SemanticCachingService.java | 2 |
请完成以下Java代码 | public void addValue (String functionColumnName, BigDecimal functionValue)
{
if (!isFunctionColumn(functionColumnName))
return;
// Group Breaks
for (int i = 0; i < m_groups.size(); i++)
{
String groupColumnName = (String)m_groups.get(i);
String key = groupColumnName + DELIMITER + functionColumnName;
PrintDataFunction pdf = (PrintDataFunction)m_groupFunction.get(key);
if (pdf == null)
pdf = new PrintDataFunction();
pdf.addValue(functionValue);
m_groupFunction.put(key, pdf);
}
} // addValue
/**
* Get Value
* @param groupColumnName group column name (or TOTAL)
* @param functionColumnName function column name
* @param function function
* @return value
*/
public BigDecimal getValue (String groupColumnName, String functionColumnName,
char function)
{
String key = groupColumnName + DELIMITER + functionColumnName;
PrintDataFunction pdf = (PrintDataFunction)m_groupFunction.get(key);
if (pdf == null)
return null;
return pdf.getValue(function);
} // getValue
/**
* Reset Function values
* @param groupColumnName group column name (or TOTAL)
* @param functionColumnName function column name
*/
public void reset (String groupColumnName, String functionColumnName)
{
String key = groupColumnName + DELIMITER + functionColumnName;
PrintDataFunction pdf = (PrintDataFunction)m_groupFunction.get(key);
if (pdf != null)
pdf.reset();
} // reset
/**************************************************************************
* String Representation
* @return info
*/
public String toString ()
{
return toString(false);
} // toString
/**
* String Representation
* @param withData with data
* @return info
*/
public String toString (boolean withData)
{
StringBuffer sb = new StringBuffer("PrintDataGroup[");
sb.append("Groups=");
for (int i = 0; i < m_groups.size(); i++)
{ | if (i != 0)
sb.append(",");
sb.append(m_groups.get(i));
}
if (withData)
{
Iterator it = m_groupMap.keySet().iterator();
while(it.hasNext())
{
Object key = it.next();
Object value = m_groupMap.get(key);
sb.append(":").append(key).append("=").append(value);
}
}
sb.append(";Functions=");
for (int i = 0; i < m_functions.size(); i++)
{
if (i != 0)
sb.append(",");
sb.append(m_functions.get(i));
}
if (withData)
{
Iterator it = m_groupFunction.keySet().iterator();
while(it.hasNext())
{
Object key = it.next();
Object value = m_groupFunction.get(key);
sb.append(":").append(key).append("=").append(value);
}
}
sb.append("]");
return sb.toString();
} // toString
} // PrintDataGroup | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\PrintDataGroup.java | 1 |
请完成以下Java代码 | public boolean isList() {return LIST.equals(this);}
public interface CaseMapper<T>
{
T string();
T number();
T date();
T list();
}
public <T> T map(@NonNull final CaseMapper<T> mapper)
{
switch (this)
{
case STRING:
{
return mapper.string();
}
case NUMBER:
{
return mapper.number();
}
case DATE:
{
return mapper.date();
}
case LIST:
{
return mapper.list();
}
default:
{
throw new AdempiereException("Unsupported value type: " + this);
}
}
}
public interface CaseConsumer
{
void string();
void number(); | void date();
void list();
}
public void apply(@NonNull final CaseConsumer consumer)
{
switch (this)
{
case STRING:
{
consumer.string();
break;
}
case NUMBER:
{
consumer.number();
break;
}
case DATE:
{
consumer.date();
break;
}
case LIST:
{
consumer.list();
break;
}
default:
{
throw new AdempiereException("Unsupported value type: " + this);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\mm\attributes\AttributeValueType.java | 1 |
请完成以下Java代码 | public void remove(AttributeKey key) {
Map<String, AttributeKvEntry> map = getMapByScope(key.getScope());
if (map != null) {
map.remove(key.getAttributeKey());
}
}
public void update(String scope, List<AttributeKvEntry> values) {
Map<String, AttributeKvEntry> map = getMapByScope(scope);
values.forEach(v -> map.put(v.getKey(), v));
}
private Map<String, AttributeKvEntry> getMapByScope(String scope) {
Map<String, AttributeKvEntry> map = null;
if (scope.equalsIgnoreCase(DataConstants.CLIENT_SCOPE)) {
map = clientSideAttributesMap; | } else if (scope.equalsIgnoreCase(DataConstants.SHARED_SCOPE)) {
map = serverPublicAttributesMap;
} else if (scope.equalsIgnoreCase(DataConstants.SERVER_SCOPE)) {
map = serverPrivateAttributesMap;
}
return map;
}
@Override
public String toString() {
return "DeviceAttributes{" +
"clientSideAttributesMap=" + clientSideAttributesMap +
", serverPrivateAttributesMap=" + serverPrivateAttributesMap +
", serverPublicAttributesMap=" + serverPublicAttributesMap +
'}';
}
} | repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\rule\engine\DeviceAttributes.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AvailableForSalesConfig
{
boolean featureEnabled;
ColorId insufficientQtyAvailableForSalesColorId;
int shipmentDateLookAheadHours;
int salesOrderLookBehindHours;
boolean runAsync;
int asyncTimeoutMillis;
boolean qtyPerWarehouse;
@Builder
private AvailableForSalesConfig(
@Nullable final ColorId insufficientQtyAvailableForSalesColorId,
final int shipmentDateLookAheadHours,
final int salesOrderLookBehindHours,
final boolean featureEnabled,
final boolean runAsync,
final int asyncTimeoutMillis,
final boolean qtyPerWarehouse)
{
this.featureEnabled = featureEnabled;
this.insufficientQtyAvailableForSalesColorId = insufficientQtyAvailableForSalesColorId; | this.shipmentDateLookAheadHours = shipmentDateLookAheadHours;
this.salesOrderLookBehindHours = salesOrderLookBehindHours;
this.runAsync = runAsync;
this.qtyPerWarehouse = qtyPerWarehouse;
// we allow zero so people can check the async-error-handling
this.asyncTimeoutMillis = assumeGreaterOrEqualToZero(asyncTimeoutMillis, "asyncTimeoutMillis");
if (featureEnabled)
{
Check.assumeNotNull(insufficientQtyAvailableForSalesColorId, "If the feature is enabled, then insufficientQtyAvailableForSalesColorId may not be null");
Check.assume(shipmentDateLookAheadHours >= 0, "If the feature is enabled, then shipmentDateLookAheadHours={} may not be < 0", shipmentDateLookAheadHours);
Check.assume(salesOrderLookBehindHours >= 0, "If the feature is enabled, then shipmentDateLookAheadHours={} may not be < 0", salesOrderLookBehindHours);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\availableforsales\AvailableForSalesConfig.java | 2 |
请完成以下Java代码 | public class ImportedValuesImpl extends ImportImpl implements ImportedValues {
protected static Attribute<String> expressionLanguageAttribute;
protected static ChildElement<ImportedElement> importedElementChild;
public ImportedValuesImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getExpressionLanguage() {
return expressionLanguageAttribute.getValue(this);
}
public void setExpressionLanguage(String expressionLanguage) {
expressionLanguageAttribute.setValue(this, expressionLanguage);
}
public ImportedElement getImportedElement() {
return importedElementChild.getChild(this);
}
public void setImportedElement(ImportedElement importedElement) {
importedElementChild.setChild(this, importedElement);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ImportedValues.class, DMN_ELEMENT_IMPORTED_VALUES)
.namespaceUri(LATEST_DMN_NS)
.extendsType(Import.class)
.instanceProvider(new ModelTypeInstanceProvider<ImportedValues>() {
public ImportedValues newInstance(ModelTypeInstanceContext instanceContext) {
return new ImportedValuesImpl(instanceContext);
} | });
expressionLanguageAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_EXPRESSION_LANGUAGE)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
importedElementChild = sequenceBuilder.element(ImportedElement.class)
.required()
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\ImportedValuesImpl.java | 1 |
请完成以下Java代码 | public Customer findUsingEnhancedForLoop(String name, List<Customer> customers) {
for (Customer customer : customers) {
if (customer.getName().equals(name)) {
return customer;
}
}
return null;
}
public Customer findUsingStream(String name, List<Customer> customers) {
return customers.stream()
.filter(customer -> customer.getName().equals(name))
.findFirst()
.orElse(null);
}
public Customer findUsingParallelStream(String name, List<Customer> customers) {
return customers.parallelStream()
.filter(customer -> customer.getName().equals(name))
.findAny()
.orElse(null);
}
public Customer findUsingGuava(String name, List<Customer> customers) {
return Iterables.tryFind(customers, new Predicate<Customer>() {
public boolean apply(Customer customer) {
return customer.getName().equals(name); | }
}).orNull();
}
public Customer findUsingApacheCommon(String name, List<Customer> customers) {
return IterableUtils.find(customers, new org.apache.commons.collections4.Predicate<Customer>() {
public boolean evaluate(Customer customer) {
return customer.getName().equals(name);
}
});
}
public boolean findUsingExists(String name, List<Customer> customers) {
return CollectionUtils.exists(customers, new org.apache.commons.collections4.Predicate<Customer>() {
public boolean evaluate(Customer customer) {
return customer.getName().equals(name);
}
});
}
} | repos\tutorials-master\core-java-modules\core-java-collections-list\src\main\java\com\baeldung\findanelement\FindACustomerInGivenList.java | 1 |
请完成以下Java代码 | Mono<String> useOauthWithAuthCode() {
Mono<String> retrievedResource = webClient.get()
.uri(RESOURCE_URI)
.retrieve()
.bodyToMono(String.class);
return retrievedResource.map(string -> "We retrieved the following resource using Oauth: " + string);
}
@GetMapping("/auth-code-no-client")
Mono<String> useOauthWithNoClient() {
// This call will fail, since we don't have the client properly set for this webClient
Mono<String> retrievedResource = otherWebClient.get()
.uri(RESOURCE_URI)
.retrieve()
.bodyToMono(String.class);
return retrievedResource.map(string -> "We retrieved the following resource using Oauth: " + string);
}
@GetMapping("/auth-code-annotated")
Mono<String> useOauthWithAuthCodeAndAnnotation(@RegisteredOAuth2AuthorizedClient("bael") OAuth2AuthorizedClient authorizedClient) {
Mono<String> retrievedResource = otherWebClient.get() | .uri(RESOURCE_URI)
.attributes(oauth2AuthorizedClient(authorizedClient))
.retrieve()
.bodyToMono(String.class);
return retrievedResource.map(string -> "We retrieved the following resource using Oauth: " + string + ". Principal associated: " + authorizedClient.getPrincipalName() + ". Token will expire at: " + authorizedClient.getAccessToken()
.getExpiresAt());
}
@GetMapping("/auth-code-explicit-client")
Mono<String> useOauthWithExpicitClient() {
Mono<String> retrievedResource = otherWebClient.get()
.uri(RESOURCE_URI)
.attributes(clientRegistrationId("bael"))
.retrieve()
.bodyToMono(String.class);
return retrievedResource.map(string -> "We retrieved the following resource using Oauth: " + string);
}
} | repos\tutorials-master\spring-reactive-modules\spring-reactive-oauth\src\main\java\com\baeldung\webclient\authorizationcodelogin\web\ClientRestController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public InsuranceContractQuantity unit(String unit) {
this.unit = unit;
return this;
}
/**
* Mengeneinheit (mögliche Werte 'Stk' oder 'Ktn')
* @return unit
**/
@Schema(example = "Stk", description = "Mengeneinheit (mögliche Werte 'Stk' oder 'Ktn')")
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public InsuranceContractQuantity archived(Boolean archived) {
this.archived = archived;
return this;
}
/**
* Maximalmenge nicht mehr gültig - archiviert
* @return archived
**/
@Schema(example = "false", description = "Maximalmenge nicht mehr gültig - archiviert")
public Boolean isArchived() {
return archived;
}
public void setArchived(Boolean archived) {
this.archived = archived;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InsuranceContractQuantity insuranceContractQuantity = (InsuranceContractQuantity) o;
return Objects.equals(this.pcn, insuranceContractQuantity.pcn) &&
Objects.equals(this.quantity, insuranceContractQuantity.quantity) &&
Objects.equals(this.unit, insuranceContractQuantity.unit) &&
Objects.equals(this.archived, insuranceContractQuantity.archived);
}
@Override | public int hashCode() {
return Objects.hash(pcn, quantity, unit, archived);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class InsuranceContractQuantity {\n");
sb.append(" pcn: ").append(toIndentedString(pcn)).append("\n");
sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n");
sb.append(" unit: ").append(toIndentedString(unit)).append("\n");
sb.append(" archived: ").append(toIndentedString(archived)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\InsuranceContractQuantity.java | 2 |
请完成以下Java代码 | public EsrAddressType getBank() {
return bank;
}
/**
* Sets the value of the bank property.
*
* @param value
* allowed object is
* {@link EsrAddressType }
*
*/
public void setBank(EsrAddressType value) {
this.bank = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
if (type == null) {
return "16or27";
} else {
return type;
}
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
/**
* Gets the value of the referenceNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReferenceNumber() {
return referenceNumber;
}
/**
* Sets the value of the referenceNumber property.
*
* @param value
* allowed object is
* {@link String } | *
*/
public void setReferenceNumber(String value) {
this.referenceNumber = value;
}
/**
* Gets the value of the participantNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getParticipantNumber() {
return participantNumber;
}
/**
* Sets the value of the participantNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setParticipantNumber(String value) {
this.participantNumber = value;
}
/**
* Gets the value of the codingLine property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCodingLine() {
return codingLine;
}
/**
* Sets the value of the codingLine property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCodingLine(String value) {
this.codingLine = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\Esr9Type.java | 1 |
请完成以下Java代码 | public void run(final String localTrxName) throws Exception
{
generate0();
}
});
}
private void generate0()
{
final OrdersCollector ordersCollector = OrdersCollector.newInstance();
final OrdersAggregator aggregator = OrdersAggregator.newInstance(ordersCollector);
for (final Iterator<I_PMM_PurchaseCandidate> it = getCandidates(); it.hasNext();)
{
final I_PMM_PurchaseCandidate candidateModel = it.next();
final PurchaseCandidate candidate = PurchaseCandidate.of(candidateModel);
aggregator.add(candidate);
}
aggregator.closeAllGroups();
} | public OrdersGenerator setCandidates(final Iterator<I_PMM_PurchaseCandidate> candidates)
{
Check.assumeNotNull(candidates, "candidates not null");
this.candidates = candidates;
return this;
}
public OrdersGenerator setCandidates(final Iterable<I_PMM_PurchaseCandidate> candidates)
{
Check.assumeNotNull(candidates, "candidates not null");
setCandidates(candidates.iterator());
return this;
}
private Iterator<I_PMM_PurchaseCandidate> getCandidates()
{
return candidates;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\OrdersGenerator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Optional<JsonRequestBPartnerUpsertItem> mapLocationToRequestItem(@NonNull final GetWarehouseFromFileRouteContext routeContext)
{
return mapLocationToJsonRequest(routeContext)
.map(jsonRequestComposite -> JsonRequestBPartnerUpsertItem.builder()
.bpartnerIdentifier(JsonMetasfreshId.toValueStr(routeContext.getOrgBPartnerId()))
.bpartnerComposite(jsonRequestComposite)
.build());
}
@NonNull
private Optional<JsonRequestComposite> mapLocationToJsonRequest(@NonNull final GetWarehouseFromFileRouteContext routeContext)
{
final WarehouseRow warehouseRow = routeContext.getWarehouseRow();
final PInstanceLogger pInstanceLogger = routeContext.getPInstanceLogger();
if (hasMissingFields(warehouseRow))
{
pInstanceLogger.logMessage("Skipping row due to missing mandatory information, see row: " + warehouseRow);
return Optional.empty();
}
return Optional.of(JsonRequestComposite.builder()
.locations(getBPartnerLocationRequest(warehouseRow))
.build());
}
@NonNull
private static JsonRequestLocationUpsert getBPartnerLocationRequest(@NonNull final WarehouseRow warehouseRow)
{
final JsonRequestLocation location = new JsonRequestLocation();
location.setName(StringUtils.trimBlankToNull(warehouseRow.getName())); | location.setAddress1(StringUtils.trimBlankToNull(warehouseRow.getAddress1()));
location.setPostal(StringUtils.trimBlankToNull(warehouseRow.getPostal()));
location.setCity(StringUtils.trimBlankToNull(warehouseRow.getCity()));
location.setGln(StringUtils.trimBlankToNull(warehouseRow.getGln()));
location.setCountryCode(DEFAULT_COUNTRY_CODE);
return JsonRequestLocationUpsert.builder()
.requestItem(JsonRequestLocationUpsertItem.builder()
.locationIdentifier(ExternalId.ofId(warehouseRow.getWarehouseIdentifier()).toExternalIdentifierString())
.location(location)
.build())
.build();
}
private static boolean hasMissingFields(@NonNull final WarehouseRow warehouseRow)
{
return Check.isBlank(warehouseRow.getWarehouseIdentifier())
|| Check.isBlank(warehouseRow.getName())
|| Check.isBlank(warehouseRow.getWarehouseValue());
}
@NonNull
private static JsonRequestBPartnerUpsert wrapUpsertItem(@NonNull final JsonRequestBPartnerUpsertItem upsertItem)
{
return JsonRequestBPartnerUpsert.builder()
.syncAdvise(SyncAdvise.CREATE_OR_MERGE)
.requestItems(ImmutableList.of(upsertItem))
.build();
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\warehouse\processor\CreateBPartnerUpsertRequestProcessor.java | 2 |
请完成以下Java代码 | public int getId(final Object model)
{
return POJOWrapper.getWrapper(model).getId();
}
@Override
public String getModelTableNameOrNull(final Object model)
{
return POJOWrapper.getWrapper(model).getTableName();
}
@Override
public boolean isNew(final Object model)
{
return POJOWrapper.isNew(model);
}
@Override
public <T> T getValue(final Object model, final String columnName, final boolean throwExIfColumnNotFound, final boolean useOverrideColumnIfAvailable)
{
final POJOWrapper wrapper = POJOWrapper.getWrapper(model);
if (useOverrideColumnIfAvailable)
{
final IModelInternalAccessor modelAccessor = wrapper.getModelInternalAccessor();
final T value = getValueOverrideOrNull(modelAccessor, columnName);
if (value != null)
{
return value;
}
}
//
if (!wrapper.hasColumnName(columnName))
{
if (throwExIfColumnNotFound)
{
throw new AdempiereException("No columnName " + columnName + " found for " + model);
}
else
{
return null;
}
}
@SuppressWarnings("unchecked")
final T value = (T)wrapper.getValuesMap().get(columnName);
return value;
}
@Override
public boolean isValueChanged(final Object model, final String columnName)
{
return POJOWrapper.isValueChanged(model, columnName);
}
@Override
public boolean isValueChanged(final Object model, final Set<String> columnNames)
{ | return POJOWrapper.isValueChanged(model, columnNames);
}
@Override
public boolean isNull(final Object model, final String columnName)
{
return POJOWrapper.isNull(model, columnName);
}
@Override
public <T> T getDynAttribute(final Object model, final String attributeName)
{
final T value = POJOWrapper.getDynAttribute(model, attributeName);
return value;
}
@Override
public Object setDynAttribute(final Object model, final String attributeName, final Object value)
{
return POJOWrapper.setDynAttribute(model, attributeName, value);
}
@Override
public <T extends PO> T getPO(final Object model, final boolean strict)
{
throw new UnsupportedOperationException("Getting PO from '" + model + "' is not supported in JUnit testing mode");
}
@Override
public Evaluatee getEvaluatee(final Object model)
{
return POJOWrapper.getWrapper(model).asEvaluatee();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POJOInterfaceWrapperHelper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static BeanMetadataElement createDefaultAuthenticationRequestResolver(
BeanMetadataElement relyingPartyRegistrationRepository) {
BeanMetadataElement defaultRelyingPartyRegistrationResolver = BeanDefinitionBuilder
.rootBeanDefinition(DefaultRelyingPartyRegistrationResolver.class)
.addConstructorArgValue(relyingPartyRegistrationRepository)
.getBeanDefinition();
if (USE_OPENSAML_5) {
return BeanDefinitionBuilder.rootBeanDefinition(OpenSaml5AuthenticationRequestResolver.class)
.addConstructorArgValue(defaultRelyingPartyRegistrationResolver)
.getBeanDefinition();
}
throw new IllegalArgumentException(
"Spring Security does not support OpenSAML " + Version.getVersion() + ". Please use OpenSAML 5");
}
static BeanDefinition createAuthenticationProvider() {
if (USE_OPENSAML_5) {
return BeanDefinitionBuilder.rootBeanDefinition(OpenSaml5AuthenticationProvider.class).getBeanDefinition();
}
throw new IllegalArgumentException(
"Spring Security does not support OpenSAML " + Version.getVersion() + ". Please use OpenSAML 5");
} | static BeanMetadataElement getAuthenticationConverter(Element element) {
String authenticationConverter = element.getAttribute(ATT_AUTHENTICATION_CONVERTER);
if (StringUtils.hasText(authenticationConverter)) {
return new RuntimeBeanReference(authenticationConverter);
}
return null;
}
static BeanDefinition createDefaultAuthenticationConverter(BeanMetadataElement relyingPartyRegistrationRepository) {
AbstractBeanDefinition resolver = BeanDefinitionBuilder
.rootBeanDefinition(DefaultRelyingPartyRegistrationResolver.class)
.addConstructorArgValue(relyingPartyRegistrationRepository)
.getBeanDefinition();
return BeanDefinitionBuilder.rootBeanDefinition(Saml2AuthenticationTokenConverter.class)
.addConstructorArgValue(resolver)
.getBeanDefinition();
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\Saml2LoginBeanDefinitionParserUtils.java | 2 |
请完成以下Java代码 | public class GetRenderedTaskFormCmd implements Command<Object>, Serializable {
private static final long serialVersionUID = 1L;
protected String taskId;
protected String formEngineName;
public GetRenderedTaskFormCmd(String taskId, String formEngineName) {
this.taskId = taskId;
this.formEngineName = formEngineName;
}
@Override
public Object execute(CommandContext commandContext) {
TaskEntity task = commandContext
.getTaskEntityManager()
.findTaskById(taskId);
if (task == null) {
throw new ActivitiObjectNotFoundException("Task '" + taskId + "' not found", Task.class);
}
if (task.getTaskDefinition() == null) { | throw new ActivitiException("Task form definition for '" + taskId + "' not found");
}
TaskFormHandler taskFormHandler = task.getTaskDefinition().getTaskFormHandler();
if (taskFormHandler == null) {
return null;
}
FormEngine formEngine = commandContext
.getProcessEngineConfiguration()
.getFormEngines()
.get(formEngineName);
if (formEngine == null) {
throw new ActivitiException("No formEngine '" + formEngineName + "' defined process engine configuration");
}
TaskFormData taskForm = taskFormHandler.createTaskForm(task);
return formEngine.renderTaskForm(taskForm);
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cmd\GetRenderedTaskFormCmd.java | 1 |
请完成以下Java代码 | private void validate(final I_PP_Product_BOMLine bomLine)
{
final BOMComponentType componentType = BOMComponentType.ofCode(bomLine.getComponentType());
//
// For Co/By Products, Qty should be always negative:
if (componentType.isCoProduct()
&& Services.get(IProductBOMBL.class).getQtyExcludingScrap(bomLine).signum() >= 0)
{
throw new LiberoException("@Qty@ > 0");
}
if (componentType.isVariant() && Check.isEmpty(bomLine.getVariantGroup()))
{
throw new LiberoException("@MandatoryVariant@");
}
final boolean valid = Services.get(IProductBOMBL.class).isValidVariantGroup(bomLine);
if (!valid)
{
throw new LiberoException("@NoSuchVariantGroup@");
}
ProductBOMDAO.extractIssuingToleranceSpec(bomLine);
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = I_PP_Order_BOMLine.COLUMNNAME_VariantGroup)
public void setVariantGroupToVA(final I_PP_Product_BOMLine bomLine)
{
final BOMComponentType currentComponentType = BOMComponentType.ofCode(bomLine.getComponentType());
if (currentComponentType.isComponent())
{
final IProductBOMDAO bomDAO = Services.get(IProductBOMDAO.class);
final List<I_PP_Product_BOMLine> bomLines = bomDAO.retrieveLines(bomLine.getPP_Product_BOM());
for (I_PP_Product_BOMLine bl : bomLines)
{
final BOMComponentType componentType = BOMComponentType.ofCode(bl.getComponentType()); | if (componentType.isVariant() && noAccordinglyVariantGroup(bl))
{
bl.setVariantGroup(bomLine.getVariantGroup());
bomDAO.save(bl);
}
}
}
}
private boolean noAccordinglyVariantGroup(final I_PP_Product_BOMLine bomLine)
{
final IProductBOMDAO bomDAO = Services.get(IProductBOMDAO.class);
final List<I_PP_Product_BOMLine> bomLines = bomDAO.retrieveLines(bomLine.getPP_Product_BOM());
for (I_PP_Product_BOMLine bl : bomLines)
{
final BOMComponentType componentType = BOMComponentType.ofCode(bl.getComponentType());
if (componentType.isComponent() && bomLine.getVariantGroup().equals(bl.getVariantGroup()))
{
return false;
}
}
return true;
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, skipIfCopying = true)
public void checkingBOMCycle(final I_PP_Product_BOMLine bomLine)
{
final ProductId productId = ProductId.ofRepoId(bomLine.getM_Product_ID());
Services.get(IProductBOMBL.class).checkCycles(productId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\validator\PP_Product_BOMLine.java | 1 |
请完成以下Java代码 | public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
final MaterialNeedsPlannerRow materialNeedsPlannerRow = MaterialNeedsPlannerRow.ofViewRow(getSingleSelectedRow());
if (PARAM_M_Product_ID.equals(parameter.getColumnName()))
{
return materialNeedsPlannerRow.getProductId();
}
else if (PARAM_M_Warehouse_ID.equals(parameter.getColumnName()))
{
return materialNeedsPlannerRow.getWarehouseId();
}
else if (PARAM_Level_Min.equals(parameter.getColumnName()))
{
return materialNeedsPlannerRow.getLevelMin();
} | else if (PARAM_Level_Max.equals(parameter.getColumnName()))
{
return materialNeedsPlannerRow.getLevelMax();
}
else
{
return DEFAULT_VALUE_NOTAVAILABLE;
}
}
@Override
protected void postProcess(final boolean success)
{
getView().invalidateSelection();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\replenish\process\WEBUI_M_Replenish_Add_Update_Demand.java | 1 |
请完成以下Java代码 | public Double getDblValue() {
return dataType == DataType.DOUBLE ? dblValue : null;
}
public void setDblValue(Double dblValue) {
this.dataType = DataType.DOUBLE;
this.dblValue = dblValue;
}
public Boolean getBoolValue() {
return dataType == DataType.BOOLEAN ? boolValue : null;
}
public void setBoolValue(Boolean boolValue) {
this.dataType = DataType.BOOLEAN;
this.boolValue = boolValue;
}
public String getStrValue() {
return dataType == DataType.STRING ? strValue : null;
}
public void setStrValue(String strValue) {
this.dataType = DataType.STRING;
this.strValue = strValue;
}
public void setJsonValue(String jsonValue) {
this.dataType = DataType.JSON;
this.strValue = jsonValue;
}
public String getJsonValue() {
return dataType == DataType.JSON ? strValue : null;
}
boolean isSet() {
return dataType != null;
}
static EntityKeyValue fromString(String s) {
EntityKeyValue result = new EntityKeyValue();
result.setStrValue(s);
return result; | }
static EntityKeyValue fromBool(boolean b) {
EntityKeyValue result = new EntityKeyValue();
result.setBoolValue(b);
return result;
}
static EntityKeyValue fromLong(long l) {
EntityKeyValue result = new EntityKeyValue();
result.setLngValue(l);
return result;
}
static EntityKeyValue fromDouble(double d) {
EntityKeyValue result = new EntityKeyValue();
result.setDblValue(d);
return result;
}
static EntityKeyValue fromJson(String s) {
EntityKeyValue result = new EntityKeyValue();
result.setJsonValue(s);
return result;
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\profile\EntityKeyValue.java | 1 |
请完成以下Java代码 | public void packTo(@Nullable final PackToSpec packToSpec)
{
assertDraft();
if (!pickStatus.isEligibleForPacking())
{
throw new AdempiereException("Invalid status when changing packing instructions: " + pickStatus);
}
this.packToSpec = packToSpec;
pickStatus = computePickOrPackStatus(this.packToSpec);
}
public void reviewPicking(final BigDecimal qtyReview)
{
assertDraft();
if (!pickStatus.isEligibleForReview())
{
throw new AdempiereException("Picking candidate cannot be approved because it's not picked or packed yet: " + this);
}
this.qtyReview = qtyReview;
approvalStatus = computeApprovalStatus(qtyPicked, this.qtyReview, pickStatus);
}
public void reviewPicking()
{
reviewPicking(qtyPicked.toBigDecimal());
}
private static PickingCandidateApprovalStatus computeApprovalStatus(final Quantity qtyPicked, final BigDecimal qtyReview, final PickingCandidatePickStatus pickStatus)
{
if (qtyReview == null)
{
return PickingCandidateApprovalStatus.TO_BE_APPROVED;
}
//
final BigDecimal qtyReviewToMatch;
if (pickStatus.isPickRejected())
{
qtyReviewToMatch = BigDecimal.ZERO;
}
else
{
qtyReviewToMatch = qtyPicked.toBigDecimal();
}
//
if (qtyReview.compareTo(qtyReviewToMatch) == 0)
{
return PickingCandidateApprovalStatus.APPROVED;
} | else
{
return PickingCandidateApprovalStatus.REJECTED;
}
}
private static PickingCandidatePickStatus computePickOrPackStatus(@Nullable final PackToSpec packToSpec)
{
return packToSpec != null ? PickingCandidatePickStatus.PACKED : PickingCandidatePickStatus.PICKED;
}
public boolean isPickFromPickingOrder()
{
return getPickFrom().isPickFromPickingOrder();
}
public void issueToPickingOrder(@Nullable final List<PickingCandidateIssueToBOMLine> issuesToPickingOrder)
{
this.issuesToPickingOrder = issuesToPickingOrder != null
? ImmutableList.copyOf(issuesToPickingOrder)
: ImmutableList.of();
}
public PickingCandidateSnapshot snapshot()
{
return PickingCandidateSnapshot.builder()
.id(getId())
.qtyReview(getQtyReview())
.pickStatus(getPickStatus())
.approvalStatus(getApprovalStatus())
.processingStatus(getProcessingStatus())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\PickingCandidate.java | 1 |
请完成以下Java代码 | public Map<String, VariableInstanceEntity> getVariableInstanceEntities() {
ensureVariableInstancesInitialized();
return variableInstances;
}
public int getSuspensionState() {
return suspensionState;
}
public void setSuspensionState(int suspensionState) {
this.suspensionState = suspensionState;
}
public String getCategory() {
return category;
}
public boolean isSuspended() {
return suspensionState == SuspensionState.SUSPENDED.getStateCode();
}
public Map<String, Object> getTaskLocalVariables() {
Map<String, Object> variables = new HashMap<String, Object>();
if (queryVariables != null) {
for (VariableInstanceEntity variableInstance : queryVariables) {
if (variableInstance.getId() != null && variableInstance.getTaskId() != null) {
variables.put(variableInstance.getName(), variableInstance.getValue());
}
}
}
return variables;
}
public Map<String, Object> getProcessVariables() {
Map<String, Object> variables = new HashMap<String, Object>();
if (queryVariables != null) {
for (VariableInstanceEntity variableInstance : queryVariables) {
if (variableInstance.getId() != null && variableInstance.getTaskId() == null) {
variables.put(variableInstance.getName(), variableInstance.getValue());
}
}
}
return variables;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public List<VariableInstanceEntity> getQueryVariables() {
if (queryVariables == null && Context.getCommandContext() != null) { | queryVariables = new VariableInitializingList();
}
return queryVariables;
}
public void setQueryVariables(List<VariableInstanceEntity> queryVariables) {
this.queryVariables = queryVariables;
}
public Date getClaimTime() {
return claimTime;
}
public void setClaimTime(Date claimTime) {
this.claimTime = claimTime;
}
public Integer getAppVersion() {
return this.appVersion;
}
public void setAppVersion(Integer appVersion) {
this.appVersion = appVersion;
}
public String toString() {
return "Task[id=" + id + ", name=" + name + "]";
}
private String truncate(String string, int maxLength) {
if (string != null) {
return string.length() > maxLength ? string.substring(0, maxLength) : string;
}
return null;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TaskEntityImpl.java | 1 |
请完成以下Java代码 | public class PersonIdentificationSEPA2 {
@XmlElement(name = "Othr", required = true)
protected RestrictedPersonIdentificationSEPA othr;
/**
* Gets the value of the othr property.
*
* @return
* possible object is
* {@link RestrictedPersonIdentificationSEPA }
*
*/
public RestrictedPersonIdentificationSEPA getOthr() {
return othr; | }
/**
* Sets the value of the othr property.
*
* @param value
* allowed object is
* {@link RestrictedPersonIdentificationSEPA }
*
*/
public void setOthr(RestrictedPersonIdentificationSEPA value) {
this.othr = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\PersonIdentificationSEPA2.java | 1 |
请完成以下Java代码 | public int getC_BP_DocLine_Sort_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BP_DocLine_Sort_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_DocLine_Sort getC_DocLine_Sort() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_DocLine_Sort_ID, org.compiere.model.I_C_DocLine_Sort.class);
}
@Override
public void setC_DocLine_Sort(org.compiere.model.I_C_DocLine_Sort C_DocLine_Sort)
{
set_ValueFromPO(COLUMNNAME_C_DocLine_Sort_ID, org.compiere.model.I_C_DocLine_Sort.class, C_DocLine_Sort);
}
/** Set Document Line Sorting Preferences.
@param C_DocLine_Sort_ID Document Line Sorting Preferences */ | @Override
public void setC_DocLine_Sort_ID (int C_DocLine_Sort_ID)
{
if (C_DocLine_Sort_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_DocLine_Sort_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_DocLine_Sort_ID, Integer.valueOf(C_DocLine_Sort_ID));
}
/** Get Document Line Sorting Preferences.
@return Document Line Sorting Preferences */
@Override
public int getC_DocLine_Sort_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DocLine_Sort_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_DocLine_Sort.java | 1 |
请完成以下Java代码 | public class JsonRequestProductTaxCategoryUpsert
{
@ApiModelProperty
private String taxCategory;
@ApiModelProperty(hidden = true)
private boolean taxCategorySet;
@ApiModelProperty(required = true)
private String countryCode;
@ApiModelProperty
private Instant validFrom;
@ApiModelProperty(hidden = true)
private boolean validFromSet;
@ApiModelProperty
private Boolean active;
@ApiModelProperty(hidden = true)
private boolean activeSet;
public void setTaxCategory(final String taxCategory)
{
this.taxCategory = taxCategory; | this.taxCategorySet = true;
}
public void setValidFrom(final Instant validFrom)
{
this.validFrom = validFrom;
this.validFromSet = true;
}
public void setCountryCode(final String countryCode)
{
this.countryCode = countryCode;
}
public void setActive(final Boolean active)
{
this.active = active;
this.activeSet = true;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-product\src\main\java\de\metas\common\product\v2\request\JsonRequestProductTaxCategoryUpsert.java | 1 |
请完成以下Java代码 | public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof JsonDataEntry)) return false;
if (!super.equals(o)) return false;
JsonDataEntry that = (JsonDataEntry) o;
return Objects.equals(value, that.value);
}
@Override
public Object getValue() {
return value;
}
@Override
public int hashCode() { | return Objects.hash(super.hashCode(), value);
}
@Override
public String toString() {
return "JsonDataEntry{" +
"value=" + value +
"} " + super.toString();
}
@Override
public String getValueAsString() {
return value;
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\kv\JsonDataEntry.java | 1 |
请完成以下Java代码 | private List<Object> formatRow(final List<Object> row)
{
final List<DATEVExportFormatColumn> formatColumns = exportFormat.getColumns();
final int rowSize = row.size();
final List<Object> rowFormatted = new ArrayList<>(rowSize);
for (int i = 0; i < rowSize; i++)
{
final Object cell = row.get(i);
final DATEVExportFormatColumn columnFormat = formatColumns.get(i);
final Object cellFormated = formatCell(cell, columnFormat);
rowFormatted.add(cellFormated);
}
return rowFormatted;
}
private Object formatCell(final Object value, final DATEVExportFormatColumn columnFormat)
{
if (value == null)
{
return null;
}
if (columnFormat.getDateFormatter() != null)
{
return formatDateCell(value, columnFormat.getDateFormatter());
}
else if (columnFormat.getNumberFormatter() != null)
{
return formatNumberCell(value, columnFormat.getNumberFormatter());
}
else
{
return value;
}
}
private static String formatDateCell(final Object value, final DateTimeFormatter dateFormatter)
{
if (value == null)
{
return null;
}
else if (value instanceof java.util.Date)
{
final java.util.Date date = (java.util.Date)value;
return dateFormatter.format(TimeUtil.asLocalDate(date)); | }
else if (value instanceof TemporalAccessor)
{
TemporalAccessor temporal = (TemporalAccessor)value;
return dateFormatter.format(temporal);
}
else
{
throw new AdempiereException("Cannot convert/format value to Date: " + value + " (" + value.getClass() + ")");
}
}
private static String formatNumberCell(final Object value, final ThreadLocalDecimalFormatter numberFormatter)
{
if (value == null)
{
return null;
}
return numberFormatter.format(value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java\de\metas\datev\DATEVCsvExporter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CustomWebSecurityConfigurerAdapter {
@Autowired private RestAuthenticationEntryPoint authenticationEntryPoint;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user1")
.password(passwordEncoder().encode("user1Pass"))
.authorities("ROLE_USER");
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/securityNone") | .permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(authenticationEntryPoint);
http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
} | repos\tutorials-master\apache-httpclient4\src\main\java\com\baeldung\filter\CustomWebSecurityConfigurerAdapter.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class RoleResourceRepository implements ResourceRepositoryV2<Role, Long> {
@Autowired private RoleRepository roleRepository;
@Override
public Role findOne(Long id, QuerySpec querySpec) {
Optional<Role> role = roleRepository.findById(id);
return role.isPresent()? role.get() : null;
}
@Override
public ResourceList<Role> findAll(QuerySpec querySpec) {
return querySpec.apply(roleRepository.findAll());
}
@Override
public ResourceList<Role> findAll(Iterable<Long> ids, QuerySpec querySpec) {
return querySpec.apply(roleRepository.findAllById(ids));
} | @Override
public <S extends Role> S save(S entity) {
return roleRepository.save(entity);
}
@Override
public void delete(Long id) {
roleRepository.deleteById(id);
}
@Override
public Class<Role> getResourceClass() {
return Role.class;
}
@Override
public <S extends Role> S create(S entity) {
return save(entity);
}
} | repos\tutorials-master\spring-katharsis\src\main\java\com\baeldung\persistence\katharsis\RoleResourceRepository.java | 2 |
请完成以下Java代码 | private Date convertFromString(String valueStr, @NonNull final ExpressionContext options)
{
if (valueStr == null)
{
return null;
}
valueStr = valueStr.trim();
//
// Use the given date format
try
{
final DateFormat dateFormat = (DateFormat)options.get(DateStringExpression.PARAM_DateFormat);
if (dateFormat != null)
{
return dateFormat.parse(valueStr);
}
}
catch (final ParseException ex1)
{
// second try
// FIXME: this is not optimum. We shall unify how we store Dates (as String)
logger.warn("Using Env.parseTimestamp to convert '{}' to Date", valueStr, ex1);
}
//
// Fallback
try
{
final Timestamp ts = Env.parseTimestamp(valueStr);
if (ts == null)
{
return null;
}
return new java.util.Date(ts.getTime());
}
catch (final Exception ex2)
{
final IllegalArgumentException exFinal = new IllegalArgumentException("Failed converting '" + valueStr + "' to date", ex2);
throw exFinal;
}
}
}
private static final class NullExpression extends NullExpressionTemplate<Date, DateStringExpression> implements DateStringExpression
{
public NullExpression(final Compiler<Date, DateStringExpression> compiler)
{
super(compiler);
}
}
private static final class ConstantExpression extends ConstantExpressionTemplate<Date, DateStringExpression> implements DateStringExpression
{
public ConstantExpression(final ExpressionContext context, final Compiler<Date, DateStringExpression> compiler, final String expressionStr, final Date constantValue)
{ | super(context, compiler, expressionStr, constantValue);
}
}
private static final class SingleParameterExpression extends SingleParameterExpressionTemplate<Date, DateStringExpression> implements DateStringExpression
{
public SingleParameterExpression(final ExpressionContext context, final Compiler<Date, DateStringExpression> compiler, final String expressionStr, final CtxName parameter)
{
super(context, compiler, expressionStr, parameter);
}
@Override
protected Object extractParameterValue(final Evaluatee ctx)
{
return parameter.getValueAsDate(ctx);
}
}
private static final class GeneralExpression extends GeneralExpressionTemplate<Date, DateStringExpression> implements DateStringExpression
{
public GeneralExpression(final ExpressionContext context, final Compiler<Date, DateStringExpression> compiler, final String expressionStr, final List<Object> expressionChunks)
{
super(context, compiler, expressionStr, expressionChunks);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\DateStringExpressionSupport.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.