instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public void updateTaskTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().directUpdate("updateTaskTenantIdForDeployment", params);
}
@Override
public void updateAllTaskRelatedEntityCountFlags(boolean newValue) {
getDbSqlSession().directUpdate("updateTaskRelatedEntityCountEnabled", newValue);
}
@Override
public void deleteTasksByExecutionId(String executionId) {
DbSqlSession dbSqlSession = getDbSqlSession();
if (isEntityInserted(dbSqlSession, "execution", executionId)) {
deleteCachedEntities(dbSqlSession, tasksByExecutionIdMatcher, executionId);
} else {
bulkDelete("deleteTasksByExecutionId", tasksByExecutionIdMatcher, executionId);
}
}
@Override
|
protected IdGenerator getIdGenerator() {
return taskServiceConfiguration.getIdGenerator();
}
protected void setSafeInValueLists(TaskQueryImpl taskQuery) {
if (taskQuery.getCandidateGroups() != null) {
taskQuery.setSafeCandidateGroups(createSafeInValuesList(taskQuery.getCandidateGroups()));
}
if (taskQuery.getInvolvedGroups() != null) {
taskQuery.setSafeInvolvedGroups(createSafeInValuesList(taskQuery.getInvolvedGroups()));
}
if (taskQuery.getScopeIds() != null) {
taskQuery.setSafeScopeIds(createSafeInValuesList(taskQuery.getScopeIds()));
}
if (taskQuery.getOrQueryObjects() != null && !taskQuery.getOrQueryObjects().isEmpty()) {
for (TaskQueryImpl orTaskQuery : taskQuery.getOrQueryObjects()) {
setSafeInValueLists(orTaskQuery);
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\data\impl\MybatisTaskDataManager.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class TimerJobServiceImpl extends ServiceImpl implements TimerJobService {
public TimerJobServiceImpl(JobServiceConfiguration jobServiceConfiguration) {
super(jobServiceConfiguration);
}
@Override
public TimerJobEntity findTimerJobById(String jobId) {
return getTimerJobEntityManager().findById(jobId);
}
@Override
public List<TimerJobEntity> findTimerJobsByExecutionId(String executionId) {
return getTimerJobEntityManager().findJobsByExecutionId(executionId);
}
@Override
public List<TimerJobEntity> findTimerJobsByProcessInstanceId(String processInstanceId) {
return getTimerJobEntityManager().findJobsByProcessInstanceId(processInstanceId);
}
@Override
public List<TimerJobEntity> findJobsByTypeAndProcessDefinitionId(String type, String processDefinitionId) {
return getTimerJobEntityManager().findJobsByTypeAndProcessDefinitionId(type, processDefinitionId);
}
@Override
public List<TimerJobEntity> findJobsByTypeAndProcessDefinitionKeyNoTenantId(String type, String processDefinitionKey) {
return getTimerJobEntityManager().findJobsByTypeAndProcessDefinitionKeyNoTenantId(type, processDefinitionKey);
}
@Override
public List<TimerJobEntity> findJobsByTypeAndProcessDefinitionKeyAndTenantId(String type, String processDefinitionKey, String tenantId) {
return getTimerJobEntityManager().findJobsByTypeAndProcessDefinitionKeyAndTenantId(type, processDefinitionKey, tenantId);
}
@Override
public void scheduleTimerJob(TimerJobEntity timerJob) {
getJobManager().scheduleTimerJob(timerJob);
}
|
@Override
public AbstractRuntimeJobEntity moveJobToTimerJob(JobEntity job) {
return getJobManager().moveJobToTimerJob(job);
}
@Override
public TimerJobEntity createTimerJob() {
return getTimerJobEntityManager().create();
}
@Override
public void insertTimerJob(TimerJobEntity timerJob) {
getTimerJobEntityManager().insert(timerJob);
}
@Override
public void deleteTimerJob(TimerJobEntity timerJob) {
getTimerJobEntityManager().delete(timerJob);
}
@Override
public void deleteTimerJobsByExecutionId(String executionId) {
TimerJobEntityManager timerJobEntityManager = getTimerJobEntityManager();
Collection<TimerJobEntity> timerJobsForExecution = timerJobEntityManager.findJobsByExecutionId(executionId);
for (TimerJobEntity job : timerJobsForExecution) {
timerJobEntityManager.delete(job);
if (getEventDispatcher() != null && getEventDispatcher().isEnabled()) {
getEventDispatcher().dispatchEvent(FlowableJobEventBuilder.createEntityEvent(
FlowableEngineEventType.JOB_CANCELED, job), configuration.getEngineName());
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\TimerJobServiceImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class CleanUpService {
private final Optional<HousekeeperClient> housekeeperClient;
private final RelationService relationService;
private final Set<EntityType> skippedEntities = EnumSet.of(
EntityType.ALARM, EntityType.QUEUE, EntityType.TB_RESOURCE, EntityType.OTA_PACKAGE,
EntityType.NOTIFICATION_REQUEST, EntityType.NOTIFICATION_TEMPLATE,
EntityType.NOTIFICATION_TARGET, EntityType.NOTIFICATION_RULE, EntityType.AI_MODEL
);
@TransactionalEventListener(fallbackExecution = true) // after transaction commit
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void handleEntityDeletionEvent(DeleteEntityEvent<?> event) {
TenantId tenantId = event.getTenantId();
EntityId entityId = event.getEntityId();
EntityType entityType = entityId.getEntityType();
try {
log.trace("[{}][{}][{}] Handling entity deletion event", tenantId, entityType, entityId.getId());
if (!skippedEntities.contains(entityType)) {
cleanUpRelatedData(tenantId, entityId);
}
if (entityType == EntityType.USER && event.getCause() != ActionCause.TENANT_DELETION) {
submitTask(HousekeeperTask.unassignAlarms((User) event.getEntity()));
}
} catch (Throwable e) {
log.error("[{}][{}][{}] Failed to handle entity deletion event", tenantId, entityType, entityId.getId(), e);
}
}
public void cleanUpRelatedData(TenantId tenantId, EntityId entityId) {
log.debug("[{}][{}][{}] Cleaning up related data", tenantId, entityId.getEntityType(), entityId.getId());
relationService.deleteEntityRelations(tenantId, entityId);
|
submitTask(HousekeeperTask.deleteAttributes(tenantId, entityId));
submitTask(HousekeeperTask.deleteTelemetry(tenantId, entityId));
submitTask(HousekeeperTask.deleteEvents(tenantId, entityId));
submitTask(HousekeeperTask.deleteAlarms(tenantId, entityId));
submitTask(HousekeeperTask.deleteCalculatedFields(tenantId, entityId));
if (Job.SUPPORTED_ENTITY_TYPES.contains(entityId.getEntityType())) {
submitTask(HousekeeperTask.deleteJobs(tenantId, entityId));
}
}
public void removeTenantEntities(TenantId tenantId, EntityType... entityTypes) {
for (EntityType entityType : entityTypes) {
submitTask(HousekeeperTask.deleteTenantEntities(tenantId, entityType));
}
}
private void submitTask(HousekeeperTask task) {
housekeeperClient.ifPresent(housekeeperClient -> {
housekeeperClient.submitTask(task);
});
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\housekeeper\CleanUpService.java
| 2
|
请完成以下Java代码
|
public String getCauseIncidentId() {
return causeIncidentId;
}
public void setCauseIncidentId(String causeIncidentId) {
this.causeIncidentId = causeIncidentId;
}
public String getRootCauseIncidentId() {
return rootCauseIncidentId;
}
public void setRootCauseIncidentId(String rootCauseIncidentId) {
this.rootCauseIncidentId = rootCauseIncidentId;
}
public String getConfiguration() {
return configuration;
}
public void setConfiguration(String configuration) {
this.configuration = configuration;
}
public String getHistoryConfiguration() {
return historyConfiguration;
}
public void setHistoryConfiguration(String historyConfiguration) {
this.historyConfiguration = historyConfiguration;
}
public String getIncidentMessage() {
return incidentMessage;
}
public void setIncidentMessage(String incidentMessage) {
this.incidentMessage = incidentMessage;
}
public void setIncidentState(int incidentState) {
this.incidentState = incidentState;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getJobDefinitionId() {
return jobDefinitionId;
}
|
public void setJobDefinitionId(String jobDefinitionId) {
this.jobDefinitionId = jobDefinitionId;
}
public boolean isOpen() {
return IncidentState.DEFAULT.getStateCode() == incidentState;
}
public boolean isDeleted() {
return IncidentState.DELETED.getStateCode() == incidentState;
}
public boolean isResolved() {
return IncidentState.RESOLVED.getStateCode() == incidentState;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public String getFailedActivityId() {
return failedActivityId;
}
public void setFailedActivityId(String failedActivityId) {
this.failedActivityId = failedActivityId;
}
public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricIncidentEventEntity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class GLCategoryRepository
{
public static GLCategoryRepository get() {return SpringContextHolder.instance.getBean(GLCategoryRepository.class);}
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private static final CCache<ClientId, DefaultGLCategories> defaultsCache = CCache.<ClientId, DefaultGLCategories>builder()
.tableName(I_GL_Category.Table_Name)
.build();
public Optional<GLCategoryId> getDefaultId(@NonNull final ClientId clientId, @NonNull final GLCategoryType categoryType)
{
return getDefaults(clientId).getByCategoryType(categoryType);
}
public Optional<GLCategoryId> getDefaultId(@NonNull final ClientId clientId)
{
return getDefaults(clientId).getDefaultId();
}
private DefaultGLCategories getDefaults(final ClientId clientId)
{
return defaultsCache.getOrLoad(clientId, this::retrieveDefaults);
}
private DefaultGLCategories retrieveDefaults(final ClientId clientId)
{
final ImmutableList<GLCategory> list = queryBL.createQueryBuilder(I_GL_Category.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_GL_Category.COLUMNNAME_AD_Client_ID, clientId)
.addEqualsFilter(I_GL_Category.COLUMNNAME_IsDefault, true)
.orderBy(I_GL_Category.COLUMNNAME_GL_Category_ID) // just to have a predictable order
.create()
.stream()
.map(GLCategoryRepository::fromRecord)
.collect(ImmutableList.toImmutableList());
return new DefaultGLCategories(list);
}
private static GLCategory fromRecord(@NonNull final I_GL_Category record)
{
return GLCategory.builder()
.id(GLCategoryId.ofRepoId(record.getGL_Category_ID()))
.name(record.getName())
.categoryType(GLCategoryType.ofCode(record.getCategoryType()))
.isDefault(record.isDefault())
.clientId(ClientId.ofRepoId(record.getAD_Client_ID()))
.build();
|
}
private static class DefaultGLCategories
{
private final ImmutableMap<GLCategoryType, GLCategory> byCategoryType;
private final ImmutableList<GLCategory> list;
DefaultGLCategories(final ImmutableList<GLCategory> list)
{
this.byCategoryType = Maps.uniqueIndex(list, GLCategory::getCategoryType);
this.list = list;
}
public Optional<GLCategoryId> getByCategoryType(@NonNull final GLCategoryType categoryType)
{
final GLCategory category = byCategoryType.get(categoryType);
if (category != null)
{
return Optional.of(category.getId());
}
return getDefaultId();
}
public Optional<GLCategoryId> getDefaultId()
{
return !list.isEmpty()
? Optional.of(list.get(0).getId())
: Optional.empty();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\GLCategoryRepository.java
| 2
|
请完成以下Java代码
|
public int getAD_PInstance_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_PInstance_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Message Text.
@param MsgText
Textual Informational, Menu or Error Message
*/
@Override
public void setMsgText (java.lang.String MsgText)
{
set_ValueNoCheck (COLUMNNAME_MsgText, MsgText);
}
/** Get Message Text.
@return Textual Informational, Menu or Error Message
*/
@Override
public java.lang.String getMsgText ()
{
return (java.lang.String)get_Value(COLUMNNAME_MsgText);
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
@Override
public void setSeqNo (int SeqNo)
|
{
set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\letters\model\X_T_BoilerPlate_Spool.java
| 1
|
请完成以下Java代码
|
private final void load()
{
URLClassLoader classLoader = null;
try
{
classLoader = (URLClassLoader)getClass().getClassLoader();
}
catch (final Exception e)
{
logger.warn("Cannot load manifests. Only URLClassLoader is supported");
return;
}
final URL resource = classLoader.findResource(RESOURCENAME_MANIFEST);
if (resource == null)
{
logger.warn("No " + RESOURCENAME_MANIFEST + " found. Skip version info loading");
return;
}
logger.debug("Loading version info from {}", resource);
InputStream in = null;
try
{
in = resource.openStream();
final Manifest manifest = new Manifest(in);
load(manifest);
}
catch (final IOException e)
{
logger.error("Error while loading " + RESOURCENAME_MANIFEST, e);
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (final IOException e)
{
// nothing
}
}
}
}
private final void load(final Manifest manifest)
{
final Attributes attributes = manifest.getMainAttributes();
if (attributes.containsKey(Name.IMPLEMENTATION_VENDOR))
{
implementationVendor = attributes.getValue(Name.IMPLEMENTATION_VENDOR);
}
if (attributes.containsKey(Name.IMPLEMENTATION_TITLE))
{
implementationTitle = attributes.getValue(Name.IMPLEMENTATION_TITLE);
|
}
if (attributes.containsKey(Name.IMPLEMENTATION_VERSION))
{
implementationVersion = attributes.getValue(Name.IMPLEMENTATION_VERSION);
}
if (attributes.containsKey(NAME_CI_BUILD_NO))
{
ciBuildNo = attributes.getValue(NAME_CI_BUILD_NO.toString());
}
if (attributes.containsKey(NAME_CI_BUILD_TAG))
{
ciBuildTag = attributes.getValue(NAME_CI_BUILD_TAG);
}
}
@Override
public String toString()
{
return "implementationVendor=" + implementationVendor
+ ", implementationTitle=" + implementationTitle
+ ", implementationVersion=" + implementationVersion
+ ", ciBuildNo=" + ciBuildNo
+ ", ciBuildTag=" + ciBuildTag;
}
public String getImplementationVendor()
{
return implementationVendor;
}
public String getImplementationTitle()
{
return implementationTitle;
}
public String getImplementationVersion()
{
return implementationVersion;
}
public String getCiBuildNo()
{
return ciBuildNo;
}
public String getCiBuildTag()
{
return ciBuildTag;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\rollout_migrate\BinaryVersion.java
| 1
|
请完成以下Java代码
|
public final boolean isNumericValue()
{
return X_M_Attribute.ATTRIBUTEVALUETYPE_Number.equals(valueType);
}
@Override
public final boolean isStringValue()
{
return X_M_Attribute.ATTRIBUTEVALUETYPE_StringMax40.equals(valueType);
}
@Override
public final boolean isDateValue()
{
return X_M_Attribute.ATTRIBUTEVALUETYPE_Date.equals(valueType);
}
@Override
public final boolean isList()
{
return _attributeValuesProvider != null;
}
@Override
public final boolean isEmpty()
{
return Objects.equals(getValue(), getEmptyValue());
}
@Nullable
@Override
public final Object getEmptyValue()
{
final Object value = getValue();
if (value == null)
{
return null;
}
if (value instanceof BigDecimal)
{
return BigDecimal.ZERO;
}
else if (value instanceof String)
{
return null;
}
else if (TimeUtil.isDateOrTimeObject(value))
{
return null;
}
else
{
throw new InvalidAttributeValueException("Value type '" + value.getClass() + "' not supported for " + attribute);
}
}
@Override
public final void addAttributeValueListener(final IAttributeValueListener listener)
{
listeners.addAttributeValueListener(listener);
}
@Override
public final void removeAttributeValueListener(final IAttributeValueListener listener)
{
listeners.removeAttributeValueListener(listener);
}
@Override
public I_C_UOM getC_UOM()
{
final int uomId = attribute.getC_UOM_ID();
if (uomId > 0)
{
return Services.get(IUOMDAO.class).getById(uomId);
}
else
{
return null;
}
|
}
private IAttributeValueCallout _attributeValueCallout = null;
@Override
public IAttributeValueCallout getAttributeValueCallout()
{
if (_attributeValueCallout == null)
{
final IAttributeValueGenerator attributeValueGenerator = getAttributeValueGeneratorOrNull();
if (attributeValueGenerator instanceof IAttributeValueCallout)
{
_attributeValueCallout = (IAttributeValueCallout)attributeValueGenerator;
}
else
{
_attributeValueCallout = NullAttributeValueCallout.instance;
}
}
return _attributeValueCallout;
}
@Override
public IAttributeValueGenerator getAttributeValueGeneratorOrNull()
{
final I_M_Attribute attribute = getM_Attribute();
final IAttributeValueGenerator attributeValueGenerator = Services.get(IAttributesBL.class).getAttributeValueGeneratorOrNull(attribute);
return attributeValueGenerator;
}
/**
* @return true if NOT disposed
* @see IAttributeStorage#assertNotDisposed()
*/
protected final boolean assertNotDisposed()
{
return getAttributeStorage().assertNotDisposed();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\AbstractAttributeValue.java
| 1
|
请完成以下Java代码
|
public void close() {
EventRegistryEngines.unregister(this);
if (engineConfiguration.getEventRegistryChangeDetectionExecutor() != null) {
engineConfiguration.getEventRegistryChangeDetectionExecutor().shutdown();
}
engineConfiguration.close();
if (engineConfiguration.getEngineLifecycleListeners() != null) {
for (EngineLifecycleListener engineLifecycleListener : engineConfiguration.getEngineLifecycleListeners()) {
engineLifecycleListener.onEngineClosed(this);
}
}
}
// getters and setters
// //////////////////////////////////////////////////////
@Override
public String getName() {
return name;
}
|
@Override
public EventRepositoryService getEventRepositoryService() {
return repositoryService;
}
@Override
public EventManagementService getEventManagementService() {
return managementService;
}
@Override
public EventRegistry getEventRegistry() {
return eventRegistry;
}
@Override
public EventRegistryEngineConfiguration getEventRegistryEngineConfiguration() {
return engineConfiguration;
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\EventRegistryEngineImpl.java
| 1
|
请完成以下Java代码
|
public void setS_Resource(final org.compiere.model.I_S_Resource S_Resource)
{
set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource);
}
@Override
public void setS_Resource_ID (final int S_Resource_ID)
{
if (S_Resource_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, S_Resource_ID);
}
@Override
public int getS_Resource_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Resource_ID);
}
@Override
public org.compiere.model.I_C_ElementValue getUser1()
{
return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser1(final org.compiere.model.I_C_ElementValue User1)
{
set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1);
}
@Override
public void setUser1_ID (final int User1_ID)
{
if (User1_ID < 1)
set_Value (COLUMNNAME_User1_ID, null);
else
set_Value (COLUMNNAME_User1_ID, User1_ID);
}
@Override
public int getUser1_ID()
{
return get_ValueAsInt(COLUMNNAME_User1_ID);
}
@Override
public org.compiere.model.I_C_ElementValue getUser2()
{
return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser2(final org.compiere.model.I_C_ElementValue User2)
{
set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2);
}
@Override
public void setUser2_ID (final int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, User2_ID);
}
@Override
public int getUser2_ID()
{
return get_ValueAsInt(COLUMNNAME_User2_ID);
}
|
@Override
public org.compiere.model.I_S_Resource getWorkStation()
{
return get_ValueAsPO(COLUMNNAME_WorkStation_ID, org.compiere.model.I_S_Resource.class);
}
@Override
public void setWorkStation(final org.compiere.model.I_S_Resource WorkStation)
{
set_ValueFromPO(COLUMNNAME_WorkStation_ID, org.compiere.model.I_S_Resource.class, WorkStation);
}
@Override
public void setWorkStation_ID (final int WorkStation_ID)
{
if (WorkStation_ID < 1)
set_Value (COLUMNNAME_WorkStation_ID, null);
else
set_Value (COLUMNNAME_WorkStation_ID, WorkStation_ID);
}
@Override
public int getWorkStation_ID()
{
return get_ValueAsInt(COLUMNNAME_WorkStation_ID);
}
@Override
public void setYield (final BigDecimal Yield)
{
set_Value (COLUMNNAME_Yield, Yield);
}
@Override
public BigDecimal getYield()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Yield);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order.java
| 1
|
请完成以下Java代码
|
private Authentication getAuthentication(@Nullable Object user) {
if ((user instanceof Authentication)) {
return (Authentication) user;
}
return this.anonymous;
}
private void cleanup() {
Stack<SecurityContext> contextStack = originalContext.get();
if (contextStack == null || contextStack.isEmpty()) {
this.securityContextHolderStrategy.clearContext();
originalContext.remove();
return;
}
SecurityContext context = contextStack.pop();
|
try {
if (SecurityContextChannelInterceptor.this.empty.equals(context)) {
this.securityContextHolderStrategy.clearContext();
originalContext.remove();
}
else {
this.securityContextHolderStrategy.setContext(context);
}
}
catch (Throwable ex) {
this.securityContextHolderStrategy.clearContext();
}
}
}
|
repos\spring-security-main\messaging\src\main\java\org\springframework\security\messaging\context\SecurityContextChannelInterceptor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void delete(Set<String> ids) {
for (String id : ids) {
databaseRepository.deleteById(id);
}
}
@Override
public boolean testConnection(Database resources) {
try {
return SqlUtils.testConnection(resources.getJdbcUrl(), resources.getUserName(), resources.getPwd());
} catch (Exception e) {
log.error(e.getMessage());
return false;
}
}
|
@Override
public void download(List<DatabaseDto> queryAll, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (DatabaseDto databaseDto : queryAll) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("数据库名称", databaseDto.getName());
map.put("数据库连接地址", databaseDto.getJdbcUrl());
map.put("用户名", databaseDto.getUserName());
map.put("创建日期", databaseDto.getCreateTime());
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\service\impl\DatabaseServiceImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class ImperativeHttpClientsProperties {
/**
* Default factory used for a client HTTP request.
*/
private @Nullable Factory factory;
public @Nullable Factory getFactory() {
return this.factory;
}
public void setFactory(@Nullable Factory factory) {
this.factory = factory;
}
/**
* Supported factory types.
*/
public enum Factory {
/**
* Apache HttpComponents HttpClient.
*/
HTTP_COMPONENTS(ClientHttpRequestFactoryBuilder::httpComponents),
/**
* Jetty's HttpClient.
*/
JETTY(ClientHttpRequestFactoryBuilder::jetty),
/**
* Reactor-Netty.
|
*/
REACTOR(ClientHttpRequestFactoryBuilder::reactor),
/**
* Java's HttpClient.
*/
JDK(ClientHttpRequestFactoryBuilder::jdk),
/**
* Standard JDK facilities.
*/
SIMPLE(ClientHttpRequestFactoryBuilder::simple);
private final Supplier<ClientHttpRequestFactoryBuilder<?>> builderSupplier;
Factory(Supplier<ClientHttpRequestFactoryBuilder<?>> builderSupplier) {
this.builderSupplier = builderSupplier;
}
ClientHttpRequestFactoryBuilder<?> builder() {
return this.builderSupplier.get();
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\autoconfigure\imperative\ImperativeHttpClientsProperties.java
| 2
|
请完成以下Java代码
|
public I_M_HU_Item retrieveParentItem(final I_M_HU hu)
{
return db.retrieveParentItem(hu);
}
@Override
public ArrayList<I_M_HU> retrieveIncludedHUs(@NonNull final I_M_HU_Item huItem)
{
final HuItemId huItemKey = mkHUItemKey(huItem);
ArrayList<I_M_HU> includedHUs = huItemKey2includedHUs.get(huItemKey);
if (includedHUs == null)
{
includedHUs = new ArrayList<>(db.retrieveIncludedHUs(huItem));
for (final I_M_HU includedHU : includedHUs)
{
includedHU.setM_HU_Item_Parent(huItem);
}
huItemKey2includedHUs.put(huItemKey, includedHUs);
}
return new ArrayList<>(includedHUs);
}
@Override
public void setParentItem(final I_M_HU hu, final I_M_HU_Item parentItem)
{
// TODO: Skip if no actual change; shall not happen because the caller it's already checking this
final HuId huId = HuId.ofRepoId(hu.getM_HU_ID());
final HuItemId parentHUItemIdOld = HuItemId.ofRepoIdOrNull(hu.getM_HU_Item_Parent_ID());
//
// Perform database change
db.setParentItem(hu, parentItem);
//
// Remove HU from included HUs list of old parent (if any)
if (parentHUItemIdOld != null)
{
final ArrayList<I_M_HU> includedHUs = huItemKey2includedHUs.get(parentHUItemIdOld);
if (includedHUs != null)
{
boolean removed = false;
for (final Iterator<I_M_HU> it = includedHUs.iterator(); it.hasNext(); )
{
final I_M_HU includedHU = it.next();
final HuId includedHUId = HuId.ofRepoId(includedHU.getM_HU_ID());
if (HuId.equals(includedHUId, huId))
{
it.remove();
removed = true;
break;
}
}
if (!removed)
{
throw new HUException("Included HU not found in cached included HUs list of old parent"
+ "\n HU: " + Services.get(IHandlingUnitsBL.class).getDisplayName(hu)
+ "\n Included HUs (cached): " + includedHUs);
}
}
}
|
//
// Add HU to include HUs list of new parent (if any)
final HuItemId parentHUItemIdNew = HuItemId.ofRepoIdOrNull(hu.getM_HU_Item_Parent_ID());
if (parentHUItemIdNew != null)
{
final ArrayList<I_M_HU> includedHUs = huItemKey2includedHUs.get(parentHUItemIdNew);
if (includedHUs != null)
{
boolean added = false;
for (final ListIterator<I_M_HU> it = includedHUs.listIterator(); it.hasNext(); )
{
final I_M_HU includedHU = it.next();
final HuId includedHUId = HuId.ofRepoId(includedHU.getM_HU_ID());
if (HuId.equals(includedHUId, huId))
{
it.set(hu);
added = true;
break;
}
}
if (!added)
{
includedHUs.add(hu);
}
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\CachedHUAndItemsDAO.java
| 1
|
请完成以下Java代码
|
public DecisionEvaluationBuilder decisionDefinitionTenantId(String tenantId) {
this.decisionDefinitionTenantId = tenantId;
isTenantIdSet = true;
return this;
}
public DecisionEvaluationBuilder decisionDefinitionWithoutTenantId() {
this.decisionDefinitionTenantId = null;
isTenantIdSet = true;
return this;
}
public DmnDecisionTableResult evaluate() {
ensureOnlyOneNotNull(NotValidException.class, "either decision definition id or key must be set", decisionDefinitionId, decisionDefinitionKey);
if (isTenantIdSet && decisionDefinitionId != null) {
throw LOG.exceptionEvaluateDecisionDefinitionByIdAndTenantId();
}
try {
return commandExecutor.execute(new EvaluateDecisionTableCmd(this));
}
catch (NullValueException e) {
throw new NotValidException(e.getMessage(), e);
}
catch (DecisionDefinitionNotFoundException e) {
throw new NotFoundException(e.getMessage(), e);
}
}
public static DecisionEvaluationBuilder evaluateDecisionTableByKey(CommandExecutor commandExecutor, String decisionDefinitionKey) {
DecisionTableEvaluationBuilderImpl builder = new DecisionTableEvaluationBuilderImpl(commandExecutor);
builder.decisionDefinitionKey = decisionDefinitionKey;
return builder;
}
|
public static DecisionEvaluationBuilder evaluateDecisionTableById(CommandExecutor commandExecutor, String decisionDefinitionId) {
DecisionTableEvaluationBuilderImpl builder = new DecisionTableEvaluationBuilderImpl(commandExecutor);
builder.decisionDefinitionId = decisionDefinitionId;
return builder;
}
// getters ////////////////////////////////////
public String getDecisionDefinitionKey() {
return decisionDefinitionKey;
}
public String getDecisionDefinitionId() {
return decisionDefinitionId;
}
public Integer getVersion() {
return version;
}
public Map<String, Object> getVariables() {
return variables;
}
public String getDecisionDefinitionTenantId() {
return decisionDefinitionTenantId;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\DecisionTableEvaluationBuilderImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ConfigTreeConfigDataLocationResolver implements ConfigDataLocationResolver<ConfigTreeConfigDataResource> {
private static final String PREFIX = "configtree:";
private final LocationResourceLoader resourceLoader;
public ConfigTreeConfigDataLocationResolver(ResourceLoader resourceLoader) {
this.resourceLoader = new LocationResourceLoader(resourceLoader);
}
@Override
public boolean isResolvable(ConfigDataLocationResolverContext context, ConfigDataLocation location) {
return location.hasPrefix(PREFIX);
}
@Override
public List<ConfigTreeConfigDataResource> resolve(ConfigDataLocationResolverContext context,
ConfigDataLocation location) {
try {
return resolve(location.getNonPrefixedValue(PREFIX));
}
catch (IOException ex) {
|
throw new ConfigDataLocationNotFoundException(location, ex);
}
}
private List<ConfigTreeConfigDataResource> resolve(String location) throws IOException {
Assert.state(location.endsWith("/"),
() -> String.format("Config tree location '%s' must end with '/'", location));
if (!this.resourceLoader.isPattern(location)) {
return Collections.singletonList(new ConfigTreeConfigDataResource(location));
}
Resource[] resources = this.resourceLoader.getResources(location, ResourceType.DIRECTORY);
List<ConfigTreeConfigDataResource> resolved = new ArrayList<>(resources.length);
for (Resource resource : resources) {
resolved.add(new ConfigTreeConfigDataResource(resource.getFile().toPath()));
}
return resolved;
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigTreeConfigDataLocationResolver.java
| 2
|
请完成以下Java代码
|
public void updateEventSubscriptionTenantId(String oldTenantId, String newTenantId) {
Map<String, String> params = new HashMap<String, String>();
params.put("oldTenantId", oldTenantId);
params.put("newTenantId", newTenantId);
getDbSqlSession().update("updateTenantIdOfEventSubscriptions", params);
}
@Override
public void deleteEventSubscriptionsForProcessDefinition(String processDefinitionId) {
getDbSqlSession().delete(
"deleteEventSubscriptionsForProcessDefinition",
processDefinitionId,
EventSubscriptionEntityImpl.class
);
}
protected List<SignalEventSubscriptionEntity> toSignalEventSubscriptionEntityList(
List<EventSubscriptionEntity> result
) {
List<SignalEventSubscriptionEntity> signalEventSubscriptionEntities = new ArrayList<
SignalEventSubscriptionEntity
>(result.size());
for (EventSubscriptionEntity eventSubscriptionEntity : result) {
signalEventSubscriptionEntities.add((SignalEventSubscriptionEntity) eventSubscriptionEntity);
}
|
return signalEventSubscriptionEntities;
}
protected List<MessageEventSubscriptionEntity> toMessageEventSubscriptionEntityList(
List<EventSubscriptionEntity> result
) {
List<MessageEventSubscriptionEntity> messageEventSubscriptionEntities = new ArrayList<
MessageEventSubscriptionEntity
>(result.size());
for (EventSubscriptionEntity eventSubscriptionEntity : result) {
messageEventSubscriptionEntities.add((MessageEventSubscriptionEntity) eventSubscriptionEntity);
}
return messageEventSubscriptionEntities;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisEventSubscriptionDataManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UmsResourceCategoryController {
@Autowired
private UmsResourceCategoryService resourceCategoryService;
@ApiOperation("查询所有后台资源分类")
@RequestMapping(value = "/listAll", method = RequestMethod.GET)
@ResponseBody
public CommonResult<List<UmsResourceCategory>> listAll() {
List<UmsResourceCategory> resourceList = resourceCategoryService.listAll();
return CommonResult.success(resourceList);
}
@ApiOperation("添加后台资源分类")
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
public CommonResult create(@RequestBody UmsResourceCategory umsResourceCategory) {
int count = resourceCategoryService.create(umsResourceCategory);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
@ApiOperation("修改后台资源分类")
@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult update(@PathVariable Long id,
@RequestBody UmsResourceCategory umsResourceCategory) {
int count = resourceCategoryService.update(id, umsResourceCategory);
if (count > 0) {
|
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
@ApiOperation("根据ID删除后台资源分类")
@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult delete(@PathVariable Long id) {
int count = resourceCategoryService.delete(id);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
}
|
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\UmsResourceCategoryController.java
| 2
|
请完成以下Java代码
|
public class MInOutHUDocumentFactory extends AbstractHUDocumentFactory<I_M_InOut>
{
private final IUOMDAO uomDAO = Services.get(IUOMDAO.class);
public MInOutHUDocumentFactory()
{
super(I_M_InOut.class);
}
@Override
protected void createHUDocumentsFromTypedModel(final HUDocumentsCollector documentsCollector, final I_M_InOut inout)
{
// 05089: HU Editor shall be displayed only for Receipts
if (inout.isSOTrx())
{
throw new AdempiereException("@M_InOut_ID@ @IsSOTrx@=@Y@");
}
final String docStatus = inout.getDocStatus();
final List<String> expectedDocStatuses = Arrays.asList(
X_M_InOut.DOCSTATUS_Completed,
X_M_InOut.DOCSTATUS_Reversed
);
if (!expectedDocStatuses.contains(docStatus))
{
throw new AdempiereException("@Invalid@ @M_InOut_ID@ @DocStatus@: "
+ "Actual: " + docStatus
+ ", Expected: " + expectedDocStatuses
+ ")");
}
final List<IHUDocumentLine> docLines = createHUDocumentLines(documentsCollector, inout);
final IHUDocument doc = new MInOutHUDocument(inout, docLines);
documentsCollector.getHUDocuments().add(doc);
}
private List<IHUDocumentLine> createHUDocumentLines(final HUDocumentsCollector documentsCollector, final I_M_InOut inOut)
{
final List<I_M_InOutLine> ioLines = Services.get(IInOutDAO.class).retrieveLines(inOut);
if (ioLines.isEmpty())
{
throw AdempiereException.newWithTranslatableMessage("@NoLines@ (@M_InOut_ID@: " + inOut.getDocumentNo() + ")");
}
final List<IHUDocumentLine> sourceLines = new ArrayList<>(ioLines.size());
for (final I_M_InOutLine ioLine : ioLines)
{
//
// Create HU Document Line
|
final List<I_M_Transaction> mtrxs = Services.get(IMTransactionDAO.class).retrieveReferenced(ioLine);
for (final I_M_Transaction mtrx : mtrxs)
{
final MInOutLineHUDocumentLine sourceLine = new MInOutLineHUDocumentLine(ioLine, mtrx);
sourceLines.add(sourceLine);
}
//
// Create Target Qty
final Capacity targetCapacity = Capacity.createCapacity(
ioLine.getMovementQty(), // qty
ProductId.ofRepoId(ioLine.getM_Product_ID()),
uomDAO.getById(ioLine.getC_UOM_ID()),
false // allowNegativeCapacity
);
documentsCollector.getTargetCapacities().add(targetCapacity);
}
return sourceLines;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\impl\MInOutHUDocumentFactory.java
| 1
|
请完成以下Java代码
|
public Mono<Void> onAuthenticationSuccess(WebFilterExchange exchange, Authentication authentication) {
return this.sessionLimit.apply(authentication)
.flatMap((maxSessions) -> handleConcurrency(exchange, authentication, maxSessions));
}
private Mono<Void> handleConcurrency(WebFilterExchange exchange, Authentication authentication,
Integer maximumSessions) {
return this.sessionRegistry.getAllSessions(Objects.requireNonNull(authentication.getPrincipal()))
.collectList()
.flatMap((registeredSessions) -> exchange.getExchange()
.getSession()
.map((currentSession) -> Tuples.of(currentSession, registeredSessions)))
.flatMap((sessionTuple) -> {
WebSession currentSession = sessionTuple.getT1();
List<ReactiveSessionInformation> registeredSessions = sessionTuple.getT2();
int registeredSessionsCount = registeredSessions.size();
if (registeredSessionsCount < maximumSessions) {
return Mono.empty();
}
if (registeredSessionsCount == maximumSessions) {
for (ReactiveSessionInformation registeredSession : registeredSessions) {
|
if (registeredSession.getSessionId().equals(currentSession.getId())) {
return Mono.empty();
}
}
}
return this.maximumSessionsExceededHandler.handle(new MaximumSessionsContext(authentication,
registeredSessions, maximumSessions, currentSession));
});
}
/**
* Sets the strategy used to resolve the maximum number of sessions that are allowed
* for a specific {@link Authentication}. By default, it returns {@code 1} for any
* authentication.
* @param sessionLimit the {@link SessionLimit} to use
*/
public void setSessionLimit(SessionLimit sessionLimit) {
Assert.notNull(sessionLimit, "sessionLimit cannot be null");
this.sessionLimit = sessionLimit;
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\authentication\ConcurrentSessionControlServerAuthenticationSuccessHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setName(String name) {
this.name = name;
}
@ApiModelProperty(example = "2010-10-13T14:54:26.750+02:00")
public Date getDeploymentTime() {
return deploymentTime;
}
public void setDeploymentTime(Date deploymentTime) {
this.deploymentTime = deploymentTime;
}
@ApiModelProperty(example = "examples")
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
@ApiModelProperty(example = "12")
public String getParentDeploymentId() {
return parentDeploymentId;
}
public void setParentDeploymentId(String parentDeploymentId) {
this.parentDeploymentId = parentDeploymentId;
}
|
public void setUrl(String url) {
this.url = url;
}
@ApiModelProperty(example = "http://localhost:8081/flowable-rest/service/cmmn-repository/deployments/10")
public String getUrl() {
return url;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "")
public String getTenantId() {
return tenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\CmmnDeploymentResponse.java
| 2
|
请完成以下Java代码
|
public int hashCode() {
return this.value.hashCode();
}
@Override
public String toString() {
return this.value;
}
/**
* Factory method to create a new {@link WebServerNamespace} from a value. If the
* context is {@code null} or not a web server context then {@link #SERVER} is
* returned.
* @param context the application context
* @return the web server namespace
* @since 4.0.1
*/
public static WebServerNamespace from(@Nullable ApplicationContext context) {
if (!ClassUtils.isPresent(WEB_SERVER_CONTEXT_CLASS, null)) {
return SERVER;
|
}
return from(WebServerApplicationContext.getServerNamespace(context));
}
/**
* Factory method to create a new {@link WebServerNamespace} from a value. If the
* value is empty or {@code null} then {@link #SERVER} is returned.
* @param value the namespace value or {@code null}
* @return the web server namespace
*/
public static WebServerNamespace from(@Nullable String value) {
if (StringUtils.hasText(value)) {
return new WebServerNamespace(value);
}
return SERVER;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\web\WebServerNamespace.java
| 1
|
请完成以下Java代码
|
public static void main(String[] args) throws SQLException {
//1. 全局配置
GlobalConfig config = new GlobalConfig();
config.setActiveRecord(true) // 是否支持AR模式
.setAuthor("yuhao.wang3") // 作者
//.setOutputDir("D:\\workspace_mp\\mp03\\src\\main\\java") // 生成路径
.setOutputDir("D:\\mybatis-plus") // 生成路径
.setFileOverride(true) // 文件覆盖
.setIdType(IdType.AUTO) // 主键策略
.setServiceName("%sService") // 设置生成的service接口的名字的首字母是否为I
// IEmployeeService
.setBaseResultMap(true)//生成基本的resultMap
.setEnableCache(false)//是否开启缓存
.setBaseColumnList(true);//生成基本的SQL片段
//2. 数据源配置
DataSourceConfig dsConfig = new DataSourceConfig();
dsConfig.setDbType(DbType.MYSQL) // 设置数据库类型
.setDriverName("com.mysql.jdbc.Driver")
.setUrl("jdbc:mysql://host:3306/db")
.setUsername("admin")
.setPassword("admin");
//3. 策略配置globalConfiguration中
StrategyConfig stConfig = new StrategyConfig();
stConfig.setCapitalMode(true) //全局大写命名
// .setSuperEntityClass("com.wlqq.insurance.claim.pojo.po.base.BaseEntity")
|
.setControllerMappingHyphenStyle(true)
.setRestControllerStyle(true)
.setEntityLombokModel(true)
.setColumnNaming(NamingStrategy.underline_to_camel)
.setNaming(NamingStrategy.underline_to_camel) // 数据库表映射到实体的命名策略
// .setTablePrefix("tbl_")
.setInclude("fis_record_ext"); // 生成的表
//4. 包名策略配置
PackageConfig pkConfig = new PackageConfig();
pkConfig.setParent("com.wlqq.insurance")
.setMapper("mybatis.mapper.withSharding")//dao
.setService("service")//servcie
.setController("controller")//controller
.setEntity("mybatis.domain")
.setXml("mapper-xml");//mapper.xml
//5. 整合配置
AutoGenerator ag = new AutoGenerator();
ag.setGlobalConfig(config)
.setDataSource(dsConfig)
.setStrategy(stConfig)
.setPackageInfo(pkConfig);
//6. 执行
ag.execute();
}
}
|
repos\spring-boot-student-master\spring-boot-student-mybatis-plus\src\main\java\com\xiaolyuh\MyBatisPlusGenerator.java
| 1
|
请完成以下Java代码
|
public Map<Integer, Integer> getTranslatedPortMappings() {
return this.httpsPortMappings;
}
@Override
public @Nullable Integer lookupHttpPort(Integer httpsPort) {
for (Integer httpPort : this.httpsPortMappings.keySet()) {
if (this.httpsPortMappings.get(httpPort).equals(httpsPort)) {
return httpPort;
}
}
return null;
}
@Override
public @Nullable Integer lookupHttpsPort(Integer httpPort) {
return this.httpsPortMappings.get(httpPort);
}
/**
* Set to override the default HTTP port to HTTPS port mappings of 80:443, and
* 8080:8443. In a Spring XML ApplicationContext, a definition would look something
* like this:
*
* <pre>
* <property name="portMappings">
* <map>
* <entry key="80"><value>443</value></entry>
* <entry key="8080"><value>8443</value></entry>
* </map>
* </property>
* </pre>
* @param newMappings A Map consisting of String keys and String values, where for
* each entry the key is the string representation of an integer HTTP port number, and
* the value is the string representation of the corresponding integer HTTPS port
|
* number.
* @throws IllegalArgumentException if input map does not consist of String keys and
* values, each representing an integer port number in the range 1-65535 for that
* mapping.
*/
public void setPortMappings(Map<String, String> newMappings) {
Assert.notNull(newMappings, "A valid list of HTTPS port mappings must be provided");
this.httpsPortMappings.clear();
for (Map.Entry<String, String> entry : newMappings.entrySet()) {
Integer httpPort = Integer.valueOf(entry.getKey());
Integer httpsPort = Integer.valueOf(entry.getValue());
Assert.isTrue(isInPortRange(httpPort) && isInPortRange(httpsPort),
() -> "one or both ports out of legal range: " + httpPort + ", " + httpsPort);
this.httpsPortMappings.put(httpPort, httpsPort);
}
Assert.isTrue(!this.httpsPortMappings.isEmpty(), "must map at least one port");
}
private boolean isInPortRange(int port) {
return port >= 1 && port <= 65535;
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\PortMapperImpl.java
| 1
|
请完成以下Java代码
|
public class EventSubscriptionsByNameMatcher extends CachedEntityMatcherAdapter<EventSubscriptionEntity> {
@Override
@SuppressWarnings("unchecked")
public boolean isRetained(EventSubscriptionEntity eventSubscriptionEntity, Object parameter) {
Map<String, String> params = (Map<String, String>) parameter;
String type = params.get("eventType");
String eventName = params.get("eventName");
String tenantId = params.get("tenantId");
if (
eventSubscriptionEntity.getEventType() != null &&
eventSubscriptionEntity.getEventType().equals(type) &&
eventSubscriptionEntity.getEventName() != null &&
eventSubscriptionEntity.getEventName().equals(eventName)
) {
|
if (tenantId != null && !tenantId.equals(ProcessEngineConfiguration.NO_TENANT_ID)) {
return (
eventSubscriptionEntity.getTenantId() != null &&
eventSubscriptionEntity.getTenantId().equals(tenantId)
);
} else {
return (
ProcessEngineConfiguration.NO_TENANT_ID.equals(eventSubscriptionEntity.getTenantId()) ||
eventSubscriptionEntity.getTenantId() == null
);
}
}
return false;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\cachematcher\EventSubscriptionsByNameMatcher.java
| 1
|
请完成以下Java代码
|
protected String getTargetTableName()
{
return org.compiere.model.I_M_Product.Table_Name;
}
@Override
protected String getImportOrderBySql()
{
return I_I_Pharma_Product.COLUMNNAME_A01GDAT;
}
@Override
public I_I_Pharma_Product retrieveImportRecord(final Properties ctx, final ResultSet rs)
{
return new X_I_Pharma_Product(ctx, rs, ITrx.TRXNAME_ThreadInherited);
}
@Override
protected void updateAndValidateImportRecordsImpl()
{
final ImportRecordsSelection selection = getImportRecordsSelection();
MProductImportTableSqlUpdater.builder()
.selection(selection)
.ctx(getCtx())
.tableName(getImportTableName())
.valueName(I_I_Pharma_Product.COLUMNNAME_A00PZN)
.build()
.updateIPharmaProduct();
}
@Override
protected ImportRecordResult importRecord(@NonNull final IMutable<Object> state,
@NonNull final I_I_Pharma_Product importRecord,
final boolean isInsertOnly) throws Exception
{
final org.compiere.model.I_M_Product existentProduct = productDAO.retrieveProductByValue(importRecord.getA00PZN());
final String operationCode = importRecord.getA00SSATZ();
if (DEACTIVATE_OPERATION_CODE.equals(operationCode) && existentProduct != null)
{
IFAProductImportHelper.deactivateProduct(existentProduct);
return ImportRecordResult.Updated;
}
else if (!DEACTIVATE_OPERATION_CODE.equals(operationCode))
{
final I_M_Product product;
final boolean newProduct = existentProduct == null || importRecord.getM_Product_ID() <= 0;
|
if (!newProduct && isInsertOnly)
{
// #4994 do not update entries
return ImportRecordResult.Nothing;
}
if (newProduct)
{
product = IFAProductImportHelper.createProduct(importRecord);
}
else
{
product = IFAProductImportHelper.updateProduct(importRecord, existentProduct);
}
importRecord.setM_Product_ID(product.getM_Product_ID());
ModelValidationEngine.get().fireImportValidate(this, importRecord, importRecord.getM_Product(), IImportInterceptor.TIMING_AFTER_IMPORT);
IFAProductImportHelper.importPrices(importRecord, true);
return newProduct ? ImportRecordResult.Inserted : ImportRecordResult.Updated;
}
return ImportRecordResult.Nothing;
}
@Override
protected void markImported(@NonNull final I_I_Pharma_Product importRecord)
{
//set this to Yes because in initial import we don't want the prices to be copied
importRecord.setIsPriceCopied(true);
importRecord.setI_IsImported(X_I_Pharma_Product.I_ISIMPORTED_Imported);
importRecord.setProcessed(true);
InterfaceWrapperHelper.save(importRecord);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\impexp\product\IFAInitialImportProcess2.java
| 1
|
请完成以下Java代码
|
public void columnRemoved(TableColumnModelEvent e)
{
markPopupStaled();
}
/** Tells listeners that a column was repositioned. */
@Override
public void columnMoved(TableColumnModelEvent e)
{
if (e.getFromIndex() == e.getToIndex())
{
// not actually a change
return;
}
// mark popup stalled because we want to have the same ordering there as we have in table column
markPopupStaled();
}
|
/** Tells listeners that a column was moved due to a margin change. */
@Override
public void columnMarginChanged(ChangeEvent e)
{
// nothing to do
}
/**
* Tells listeners that the selection model of the TableColumnModel changed.
*/
@Override
public void columnSelectionChanged(ListSelectionEvent e)
{
// nothing to do
}
};
}
} // end class ColumnControlButton
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CColumnControlButton.java
| 1
|
请完成以下Java代码
|
public void setUserCache(UserCache userCache) {
Assert.notNull(userCache, "userCache cannot be null");
this.userCache = userCache;
}
/**
* Sets whether the {@link #updatePassword(UserDetails, String)} method should
* actually update the password.
* <p>
* Defaults to {@code false} to prevent accidental password updates that might produce
* passwords that are too large for the current database schema. Users must explicitly
* set this to {@code true} to enable password updates.
* @param enableUpdatePassword {@code true} to enable password updates, {@code false}
* otherwise.
* @since 7.0
*/
public void setEnableUpdatePassword(boolean enableUpdatePassword) {
this.enableUpdatePassword = enableUpdatePassword;
}
private void validateUserDetails(UserDetails user) {
Assert.hasText(user.getUsername(), "Username may not be empty or null");
validateAuthorities(user.getAuthorities());
}
private void validateAuthorities(Collection<? extends GrantedAuthority> authorities) {
Assert.notNull(authorities, "Authorities list must not be null");
for (GrantedAuthority authority : authorities) {
Assert.notNull(authority, "Authorities list contains a null entry");
Assert.hasText(authority.getAuthority(), "getAuthority() method must return a non-empty string");
}
}
|
/**
* Conditionally updates password based on the setting from
* {@link #setEnableUpdatePassword(boolean)}. {@inheritDoc}
* @since 7.0
*/
@Override
public UserDetails updatePassword(UserDetails user, @Nullable String newPassword) {
if (this.enableUpdatePassword) {
// @formatter:off
UserDetails updated = User.withUserDetails(user)
.password(newPassword)
.build();
// @formatter:on
updateUser(updated);
return updated;
}
return user;
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\provisioning\JdbcUserDetailsManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ModelRequest {
protected String name;
protected String key;
protected String category;
protected Integer version;
protected String metaInfo;
protected String deploymentId;
protected String tenantId;
protected boolean nameChanged;
protected boolean keyChanged;
protected boolean categoryChanged;
protected boolean versionChanged;
protected boolean metaInfoChanged;
protected boolean deploymentChanged;
protected boolean tenantChanged;
@ApiModelProperty(example = "Model name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
this.nameChanged = true;
}
@ApiModelProperty(example = "Model key")
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
this.keyChanged = true;
}
@ApiModelProperty(example = "Model category")
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
this.categoryChanged = true;
}
@ApiModelProperty(example = "2")
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
this.versionChanged = true;
}
@ApiModelProperty(example = "Model metainfo")
public String getMetaInfo() {
return metaInfo;
|
}
public void setMetaInfo(String metaInfo) {
this.metaInfo = metaInfo;
this.metaInfoChanged = true;
}
@ApiModelProperty(example = "7")
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
this.deploymentChanged = true;
}
public void setTenantId(String tenantId) {
tenantChanged = true;
this.tenantId = tenantId;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
@JsonIgnore
public boolean isCategoryChanged() {
return categoryChanged;
}
@JsonIgnore
public boolean isKeyChanged() {
return keyChanged;
}
@JsonIgnore
public boolean isMetaInfoChanged() {
return metaInfoChanged;
}
@JsonIgnore
public boolean isNameChanged() {
return nameChanged;
}
@JsonIgnore
public boolean isVersionChanged() {
return versionChanged;
}
@JsonIgnore
public boolean isDeploymentChanged() {
return deploymentChanged;
}
@JsonIgnore
public boolean isTenantIdChanged() {
return tenantChanged;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\repository\ModelRequest.java
| 2
|
请完成以下Java代码
|
public class WebsocketTopicNames
{
static final String TOPIC_UserSession = "/userSession";
static final String TOPIC_Notifications = "/notifications";
static final String TOPIC_View = "/view";
static final String TOPIC_Document = "/document";
static final String TOPIC_Board = "/board";
public static final String TOPIC_Dashboard = "/dashboard";
public static final DeviceWebsocketNamingStrategy DEVICES_NAMING_STRATEGY = new DeviceWebsocketNamingStrategy("/devices");
public static WebsocketTopicName buildUserSessionTopicName(@NonNull final UserId adUserId)
{
return WebsocketTopicName.ofString(TOPIC_UserSession + "/" + adUserId.getRepoId());
}
public static WebsocketTopicName buildNotificationsTopicName(@NonNull final UserId adUserId)
{
return WebsocketTopicName.ofString(TOPIC_Notifications + "/" + adUserId.getRepoId());
}
public static WebsocketTopicName buildViewNotificationsTopicName(@NonNull final String viewId)
{
Check.assumeNotEmpty(viewId, "viewId is not empty");
|
return WebsocketTopicName.ofString(TOPIC_View + "/" + viewId);
}
public static WebsocketTopicName buildDocumentTopicName(
@NonNull final WindowId windowId,
@NonNull final DocumentId documentId)
{
return WebsocketTopicName.ofString(TOPIC_Document + "/" + windowId.toJson() + "/" + documentId.toJson());
}
public static WebsocketTopicName buildBoardTopicName(final int boardId)
{
Preconditions.checkArgument(boardId > 0);
return WebsocketTopicName.ofString(TOPIC_Board + "/" + boardId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\websocket\WebsocketTopicNames.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
application:
name: demo-consumer # Spring 应用名
cloud:
nacos:
# Nacos 作为注册中心的配置项,对应 NacosDiscoveryProperties 配置类
discovery:
server-addr: 127.0.0.1:8848 # Nacos 服务器地址
server:
port: 28080 # 服务器端口。默认为 80
|
80
feign:
httpclient:
enabled: false # 是否开启。默认为 true
okhttp:
enabled: true # 是否开启。默认为 false
|
repos\SpringBoot-Labs-master\labx-03-spring-cloud-feign\labx-03-sc-feign-demo06B-consumer\src\main\resources\application.yaml
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class EntityManagerSessionFactory implements SessionFactory {
protected EntityManagerFactory entityManagerFactory;
protected boolean handleTransactions;
protected boolean closeEntityManager;
public EntityManagerSessionFactory(Object entityManagerFactory, boolean handleTransactions, boolean closeEntityManager) {
if (entityManagerFactory == null) {
throw new FlowableIllegalArgumentException("entityManagerFactory is null");
}
if (!(entityManagerFactory instanceof EntityManagerFactory)) {
throw new FlowableIllegalArgumentException("EntityManagerFactory must implement 'jakarta.persistence.EntityManagerFactory'");
}
this.entityManagerFactory = (EntityManagerFactory) entityManagerFactory;
this.handleTransactions = handleTransactions;
|
this.closeEntityManager = closeEntityManager;
}
@Override
public Class<?> getSessionType() {
return EntityManagerSession.class;
}
@Override
public Session openSession(CommandContext commandContext) {
return new EntityManagerSessionImpl(entityManagerFactory, handleTransactions, closeEntityManager);
}
public EntityManagerFactory getEntityManagerFactory() {
return entityManagerFactory;
}
}
|
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\EntityManagerSessionFactory.java
| 2
|
请完成以下Java代码
|
@Nullable ExpressionAttribute resolveAttribute(Method method, @Nullable Class<?> targetClass) {
PostAuthorize postAuthorize = findPostAuthorizeAnnotation(method, targetClass);
if (postAuthorize == null) {
return null;
}
Expression expression = getExpressionHandler().getExpressionParser().parseExpression(postAuthorize.value());
MethodAuthorizationDeniedHandler deniedHandler = resolveHandler(method, targetClass);
return new PostAuthorizeExpressionAttribute(expression, deniedHandler);
}
private MethodAuthorizationDeniedHandler resolveHandler(Method method, @Nullable Class<?> targetClass) {
Class<?> targetClassToUse = targetClass(method, targetClass);
HandleAuthorizationDenied deniedHandler = this.handleAuthorizationDeniedScanner.scan(method, targetClassToUse);
if (deniedHandler != null) {
return this.handlerResolver.apply(deniedHandler.handlerClass());
}
return this.defaultHandler;
}
private @Nullable PostAuthorize findPostAuthorizeAnnotation(Method method, @Nullable Class<?> targetClass) {
Class<?> targetClassToUse = targetClass(method, targetClass);
return this.postAuthorizeScanner.scan(method, targetClassToUse);
}
/**
* Uses the provided {@link ApplicationContext} to resolve the
* {@link MethodAuthorizationDeniedHandler} from {@link PostAuthorize}
* @param context the {@link ApplicationContext} to use
*/
void setApplicationContext(ApplicationContext context) {
Assert.notNull(context, "context cannot be null");
this.handlerResolver = (clazz) -> resolveHandler(context, clazz);
}
void setTemplateDefaults(AnnotationTemplateExpressionDefaults templateDefaults) {
this.postAuthorizeScanner = SecurityAnnotationScanners.requireUnique(PostAuthorize.class, templateDefaults);
}
|
private MethodAuthorizationDeniedHandler resolveHandler(ApplicationContext context,
Class<? extends MethodAuthorizationDeniedHandler> handlerClass) {
if (handlerClass == this.defaultHandler.getClass()) {
return this.defaultHandler;
}
String[] beanNames = context.getBeanNamesForType(handlerClass);
if (beanNames.length == 0) {
throw new IllegalStateException("Could not find a bean of type " + handlerClass.getName());
}
if (beanNames.length > 1) {
throw new IllegalStateException("Expected to find a single bean of type " + handlerClass.getName()
+ " but found " + Arrays.toString(beanNames));
}
return context.getBean(beanNames[0], handlerClass);
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\PostAuthorizeExpressionAttributeRegistry.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AsyncBatchTypeId implements RepoIdAware
{
int repoId;
private AsyncBatchTypeId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_Async_Batch_Type_ID");
}
@JsonCreator
public static AsyncBatchTypeId ofRepoId(final int repoId)
{
return new AsyncBatchTypeId(repoId);
}
public static AsyncBatchTypeId ofRepoIdOrNull(final int repoId)
{
|
return repoId > 0 ? new AsyncBatchTypeId(repoId) : null;
}
public static Optional<AsyncBatchTypeId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\AsyncBatchTypeId.java
| 2
|
请完成以下Java代码
|
private void initPanel()
{
BoxLayout layout = new BoxLayout(this, BoxLayout.PAGE_AXIS);
MGoal[] goals = MGoal.getGoals(Env.getCtx());
for (int i = 0; i < goals.length; i++)
{
PerformanceIndicator pi = new PerformanceIndicator(goals[i]);
pi.addActionListener(this);
add (pi);
}
} // initPanel
/**
* Action Listener for Drill Down
* @param e event
|
*/
@Override
public void actionPerformed (ActionEvent e)
{
if (e.getActionCommand().equals(ConfirmPanel.A_OK))
dispose();
else if (e.getSource() instanceof PerformanceIndicator)
{
PerformanceIndicator pi = (PerformanceIndicator)e.getSource();
log.info(pi.getName());
MGoal goal = pi.getGoal();
if (goal.getMeasure() != null)
new PerformanceDetail(goal);
}
} // actionPerformed
} // ViewPI
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\adempiere\apps\graph\ViewPI.java
| 1
|
请完成以下Java代码
|
public GridFieldVOsLoader setTabReadOnly(final boolean tabReadOnly)
{
_tabReadOnly = tabReadOnly;
return this;
}
private boolean isTabReadOnly()
{
return _tabReadOnly;
}
public GridFieldVOsLoader setLoadAllLanguages(final boolean loadAllLanguages)
{
_loadAllLanguages = loadAllLanguages;
return this;
}
private boolean isLoadAllLanguages()
|
{
return _loadAllLanguages;
}
public GridFieldVOsLoader setApplyRolePermissions(final boolean applyRolePermissions)
{
this._applyRolePermissions = applyRolePermissions;
return this;
}
private boolean isApplyRolePermissions()
{
return _applyRolePermissions;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridFieldVOsLoader.java
| 1
|
请完成以下Java代码
|
public class ViewPI extends CPanel
implements FormPanel, ActionListener
{
/**
*
*/
private static final long serialVersionUID = 8022906851004145960L;
/**
* Init
* @param WindowNo
* @param frame
*/
@Override
public void init (int WindowNo, FormFrame frame)
{
log.debug("");
m_WindowNo = WindowNo;
m_frame = frame;
try
{
// Top Selection Panel
// m_frame.getContentPane().add(selectionPanel, BorderLayout.NORTH);
// Center
initPanel();
CScrollPane scroll = new CScrollPane (this);
m_frame.getContentPane().add(scroll, BorderLayout.CENTER);
// South
confirmPanel.setActionListener(this);
m_frame.getContentPane().add(confirmPanel, BorderLayout.SOUTH);
}
catch(Exception e)
{
log.error("", e);
}
sizeIt();
} // init
/**
* Size Window
*/
private void sizeIt()
{
// Frame
m_frame.pack();
// Dimension size = m_frame.getPreferredSize();
// size.width = WINDOW_WIDTH;
// m_frame.setSize(size);
} // size
/**
* Dispose
*/
@Override
public void dispose()
{
if (m_frame != null)
m_frame.dispose();
m_frame = null;
removeAll();
} // dispose
/** Window No */
private int m_WindowNo = 0;
|
/** FormFrame */
private FormFrame m_frame;
/** Logger */
private static Logger log = LogManager.getLogger(ViewPI.class);
/** Confirmation Panel */
private ConfirmPanel confirmPanel = ConfirmPanel.newWithOK();
/**
* Init Panel
*/
private void initPanel()
{
BoxLayout layout = new BoxLayout(this, BoxLayout.PAGE_AXIS);
MGoal[] goals = MGoal.getGoals(Env.getCtx());
for (int i = 0; i < goals.length; i++)
{
PerformanceIndicator pi = new PerformanceIndicator(goals[i]);
pi.addActionListener(this);
add (pi);
}
} // initPanel
/**
* Action Listener for Drill Down
* @param e event
*/
@Override
public void actionPerformed (ActionEvent e)
{
if (e.getActionCommand().equals(ConfirmPanel.A_OK))
dispose();
else if (e.getSource() instanceof PerformanceIndicator)
{
PerformanceIndicator pi = (PerformanceIndicator)e.getSource();
log.info(pi.getName());
MGoal goal = pi.getGoal();
if (goal.getMeasure() != null)
new PerformanceDetail(goal);
}
} // actionPerformed
} // ViewPI
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\adempiere\apps\graph\ViewPI.java
| 1
|
请完成以下Java代码
|
private boolean checkNonEssentialData(String currentTableName, Map<String, Object> afterMap,
Map<String, Object> beforeMap, List<String> filterColumnList) {
Map<String, Boolean> filterMap = new HashMap<>(16);
for (String key : afterMap.keySet()) {
Object afterValue = afterMap.get(key);
Object beforeValue = beforeMap.get(key);
filterMap.put(key, !Objects.equals(beforeValue, afterValue));
}
filterColumnList.parallelStream().forEach(filterMap::remove);
if (filterMap.values().stream().noneMatch(x -> x)) {
log.info("表:{}无核心资料变更,忽略此次操作!", currentTableName);
return true;
}
return false;
}
public String getChangeData(Struct sourceRecordChangeValue, String record) {
Map<String, Object> changeDataMap = getChangeDataMap(sourceRecordChangeValue, record);
if (CollectionUtils.isEmpty(changeDataMap)) {
return null;
}
return JSON.toJSONString(changeDataMap);
}
public Map<String, Object> getChangeDataMap(Struct sourceRecordChangeValue, String record) {
Struct struct = (Struct) sourceRecordChangeValue.get(record);
// 将变更的行封装为Map
|
Map<String, Object> changeData = struct.schema().fields().stream()
.map(Field::name)
.filter(fieldName -> struct.get(fieldName) != null)
.map(fieldName -> Pair.of(fieldName, struct.get(fieldName)))
.collect(toMap(Pair::getKey, Pair::getValue));
if (CollectionUtils.isEmpty(changeData)) {
return null;
}
return changeData;
}
private Map<String, Object> getChangeTableInfo(Struct sourceRecordChangeValue) {
Struct struct = (Struct) sourceRecordChangeValue.get(SOURCE);
Map<String, Object> map = struct.schema().fields().stream()
.map(Field::name)
.filter(fieldName -> struct.get(fieldName) != null && FilterJsonFieldEnum.filterJsonField(fieldName))
.map(fieldName -> Pair.of(fieldName, struct.get(fieldName)))
.collect(toMap(Pair::getKey, Pair::getValue));
if (map.containsKey(FilterJsonFieldEnum.ts_ms.name())) {
map.put("changeTime", map.get(FilterJsonFieldEnum.ts_ms.name()));
map.remove(FilterJsonFieldEnum.ts_ms.name());
}
return map;
}
}
|
repos\springboot-demo-master\debezium\src\main\java\com\et\debezium\handler\ChangeEventHandler.java
| 1
|
请完成以下Java代码
|
public int getPP_Order_Qty_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Qty_ID);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
|
}
@Override
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_PP_Order_Qty.java
| 1
|
请完成以下Java代码
|
public class Order {
@JsonView(Views.Public.class)
private UUID id;
@JsonView(Views.Public.class)
private Type type;
@JsonView(Views.Internal.class)
private int internalAudit;
public static class Type {
public long id;
public String name;
}
public Order() {
this.id = UUID.randomUUID();
}
public Order(Type type) {
this();
this.type = type;
}
|
public Order(int internalAudit) {
this();
this.type = new Type();
this.type.id = 20;
this.type.name = "Order";
this.internalAudit = internalAudit;
}
public UUID getId() {
return id;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
}
|
repos\tutorials-master\video-tutorials\jackson-annotations-video\src\main\java\com\baeldung\jacksonannotation\general\jsonview\Order.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public SyncUser createSyncUser(final String email, final String password, @Nullable final String language)
{
return SyncUser.builder()
.uuid(randomUUID())
.email(email)
.password(password)
.language(language)
.build();
}
public SyncProduct createSyncProduct(final String name, final String packingInfo)
{
final SyncProduct.SyncProductBuilder product = SyncProduct.builder()
.uuid(randomUUID())
.name(name)
.packingInfo(packingInfo)
.shared(true);
for (final String language : languages)
{
product.nameTrl(language, name + " " + language);
}
return product.build();
}
private static String randomUUID()
{
return UUID.randomUUID().toString();
}
@Transactional
void createDummyProductSupplies()
{
for (final BPartner bpartner : bpartnersRepo.findAll())
{
for (final Contract contract : contractsRepo.findByBpartnerAndDeletedFalse(bpartner))
{
final List<ContractLine> contractLines = contract.getContractLines();
if (contractLines.isEmpty())
{
|
continue;
}
final ContractLine contractLine = contractLines.get(0);
final Product product = contractLine.getProduct();
productSuppliesService.reportSupply(IProductSuppliesService.ReportDailySupplyRequest.builder()
.bpartner(bpartner)
.contractLine(contractLine)
.productId(product.getId())
.date(LocalDate.now()) // today
.qty(new BigDecimal("10"))
.qtyConfirmedByUser(true)
.build());
productSuppliesService.reportSupply(IProductSuppliesService.ReportDailySupplyRequest.builder()
.bpartner(bpartner)
.contractLine(contractLine)
.productId(product.getId())
.date(LocalDate.now().plusDays(1)) // tomorrow
.qty(new BigDecimal("3"))
.qtyConfirmedByUser(true)
.build());
}
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\util\DummyDataProducer.java
| 2
|
请完成以下Java代码
|
private static long getParameterValue(Map<String, Object> parameters, String parameterName, long defaultValue) {
long parameterValue = defaultValue;
Object obj = parameters.get(parameterName);
if (obj != null) {
// Final classes Long and Integer do not need to be coerced
if (obj.getClass() == Long.class) {
parameterValue = (Long) obj;
}
else if (obj.getClass() == Integer.class) {
parameterValue = (Integer) obj;
}
else {
// Attempt to coerce to a long (typically from a String)
try {
parameterValue = Long.parseLong(obj.toString());
}
catch (NumberFormatException ignored) {
}
}
}
return parameterValue;
}
}
private static final class DefaultOAuth2DeviceAuthorizationResponseMapConverter
implements Converter<OAuth2DeviceAuthorizationResponse, Map<String, Object>> {
@Override
|
public Map<String, Object> convert(OAuth2DeviceAuthorizationResponse deviceAuthorizationResponse) {
Map<String, Object> parameters = new HashMap<>();
parameters.put(OAuth2ParameterNames.DEVICE_CODE,
deviceAuthorizationResponse.getDeviceCode().getTokenValue());
parameters.put(OAuth2ParameterNames.USER_CODE, deviceAuthorizationResponse.getUserCode().getTokenValue());
parameters.put(OAuth2ParameterNames.VERIFICATION_URI, deviceAuthorizationResponse.getVerificationUri());
if (StringUtils.hasText(deviceAuthorizationResponse.getVerificationUriComplete())) {
parameters.put(OAuth2ParameterNames.VERIFICATION_URI_COMPLETE,
deviceAuthorizationResponse.getVerificationUriComplete());
}
parameters.put(OAuth2ParameterNames.EXPIRES_IN, getExpiresIn(deviceAuthorizationResponse));
if (deviceAuthorizationResponse.getInterval() > 0) {
parameters.put(OAuth2ParameterNames.INTERVAL, deviceAuthorizationResponse.getInterval());
}
if (!CollectionUtils.isEmpty(deviceAuthorizationResponse.getAdditionalParameters())) {
parameters.putAll(deviceAuthorizationResponse.getAdditionalParameters());
}
return parameters;
}
private static long getExpiresIn(OAuth2DeviceAuthorizationResponse deviceAuthorizationResponse) {
if (deviceAuthorizationResponse.getDeviceCode().getExpiresAt() != null) {
Instant issuedAt = (deviceAuthorizationResponse.getDeviceCode().getIssuedAt() != null)
? deviceAuthorizationResponse.getDeviceCode().getIssuedAt() : Instant.now();
return ChronoUnit.SECONDS.between(issuedAt, deviceAuthorizationResponse.getDeviceCode().getExpiresAt());
}
return -1;
}
}
}
|
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\http\converter\OAuth2DeviceAuthorizationResponseHttpMessageConverter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Path getPath() {
return path;
}
public void setPath(Path path) {
this.path = path;
}
public DomainUrl getDomainUrl() {
return domainUrl;
}
public void setDomainUrl(DomainUrl domainUrl) {
this.domainUrl = domainUrl;
}
public String getSignUrls() {
return signUrls;
}
public void setSignUrls(String signUrls) {
this.signUrls = signUrls;
}
public String getFileViewDomain() {
return fileViewDomain;
}
public void setFileViewDomain(String fileViewDomain) {
|
this.fileViewDomain = fileViewDomain;
}
public String getUploadType() {
return uploadType;
}
public void setUploadType(String uploadType) {
this.uploadType = uploadType;
}
public WeiXinPay getWeiXinPay() {
return weiXinPay;
}
public void setWeiXinPay(WeiXinPay weiXinPay) {
this.weiXinPay = weiXinPay;
}
public BaiduApi getBaiduApi() {
return baiduApi;
}
public void setBaiduApi(BaiduApi baiduApi) {
this.baiduApi = baiduApi;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\JeecgBaseConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void onRepartitionEvent() {
lastGaugesByServiceId.clear();
gaugesReportCycles.clear();
}
public ApiUsageStateValue getFeatureValue(ApiFeature feature) {
switch (feature) {
case TRANSPORT:
return apiUsageState.getTransportState();
case RE:
return apiUsageState.getReExecState();
case DB:
return apiUsageState.getDbStorageState();
case JS:
return apiUsageState.getJsExecState();
case TBEL:
return apiUsageState.getTbelExecState();
case EMAIL:
return apiUsageState.getEmailExecState();
case SMS:
return apiUsageState.getSmsExecState();
case ALARM:
return apiUsageState.getAlarmExecState();
default:
return ApiUsageStateValue.ENABLED;
}
}
public boolean setFeatureValue(ApiFeature feature, ApiUsageStateValue value) {
ApiUsageStateValue currentValue = getFeatureValue(feature);
switch (feature) {
case TRANSPORT:
apiUsageState.setTransportState(value);
break;
case RE:
apiUsageState.setReExecState(value);
break;
case DB:
apiUsageState.setDbStorageState(value);
break;
case JS:
apiUsageState.setJsExecState(value);
break;
case TBEL:
apiUsageState.setTbelExecState(value);
break;
|
case EMAIL:
apiUsageState.setEmailExecState(value);
break;
case SMS:
apiUsageState.setSmsExecState(value);
break;
case ALARM:
apiUsageState.setAlarmExecState(value);
break;
}
return !currentValue.equals(value);
}
public abstract EntityType getEntityType();
public TenantId getTenantId() {
return getApiUsageState().getTenantId();
}
public EntityId getEntityId() {
return getApiUsageState().getEntityId();
}
@Override
public String toString() {
return "BaseApiUsageState{" +
"apiUsageState=" + apiUsageState +
", currentCycleTs=" + currentCycleTs +
", nextCycleTs=" + nextCycleTs +
", currentHourTs=" + currentHourTs +
'}';
}
@Data
@Builder
public static class StatsCalculationResult {
private final long newValue;
private final boolean valueChanged;
private final long newHourlyValue;
private final boolean hourlyValueChanged;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\apiusage\BaseApiUsageState.java
| 2
|
请完成以下Java代码
|
public static <TERM> Map<TERM, Double> tfIdf(Map<TERM, Double> tf, Map<TERM, Double> idf,
Normalization normalization)
{
Map<TERM, Double> tfIdf = new HashMap<TERM, Double>();
for (TERM term : tf.keySet())
{
Double TF = tf.get(term);
if (TF == null) TF = 1.;
Double IDF = idf.get(term);
if (IDF == null) IDF = 1.;
tfIdf.put(term, TF * IDF);
}
if (normalization == Normalization.COSINE)
{
double n = 0.0;
for (double x : tfIdf.values())
{
n += x * x;
}
n = Math.sqrt(n);
for (TERM term : tfIdf.keySet())
{
tfIdf.put(term, tfIdf.get(term) / n);
}
}
return tfIdf;
}
/**
* 计算文档的tf-idf(不正规化)
*
* @param tf 词频
* @param idf 倒排频率
* @param <TERM> 词语类型
* @return 一个词语->tf-idf的Map
*/
public static <TERM> Map<TERM, Double> tfIdf(Map<TERM, Double> tf, Map<TERM, Double> idf)
{
return tfIdf(tf, idf, Normalization.NONE);
}
/**
* 从词频集合建立倒排频率
*
* @param tfs 次品集合
* @param smooth 平滑参数,视作额外有一个文档,该文档含有smooth个每个词语
* @param addOne tf-idf加一平滑
* @param <TERM> 词语类型
* @return 一个词语->倒排文档的Map
*/
public static <TERM> Map<TERM, Double> idfFromTfs(Iterable<Map<TERM, Double>> tfs, boolean smooth, boolean addOne)
{
return idf(new KeySetIterable<TERM, Double>(tfs), smooth, addOne);
}
/**
* 从词频集合建立倒排频率(默认平滑词频,且加一平滑tf-idf)
*
* @param tfs 次品集合
* @param <TERM> 词语类型
* @return 一个词语->倒排文档的Map
*/
public static <TERM> Map<TERM, Double> idfFromTfs(Iterable<Map<TERM, Double>> tfs)
{
return idfFromTfs(tfs, true, true);
}
|
/**
* Map的迭代器
*
* @param <KEY> map 键类型
* @param <VALUE> map 值类型
*/
static private class KeySetIterable<KEY, VALUE> implements Iterable<Iterable<KEY>>
{
final private Iterator<Map<KEY, VALUE>> maps;
public KeySetIterable(Iterable<Map<KEY, VALUE>> maps)
{
this.maps = maps.iterator();
}
@Override
public Iterator<Iterable<KEY>> iterator()
{
return new Iterator<Iterable<KEY>>()
{
@Override
public boolean hasNext()
{
return maps.hasNext();
}
@Override
public Iterable<KEY> next()
{
return maps.next().keySet();
}
@Override
public void remove()
{
}
};
}
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word\TfIdf.java
| 1
|
请完成以下Java代码
|
public class ScriptHttpHandler extends AbstractScriptEvaluator implements HttpRequestHandler, HttpResponseHandler {
public ScriptHttpHandler(Expression language, String script) {
super(language, script);
}
@Override
protected ScriptingEngines getScriptingEngines() {
return CommandContextUtil.getProcessEngineConfiguration().getScriptingEngines();
}
@Override
public void handleHttpRequest(VariableContainer execution, HttpRequest httpRequest, FlowableHttpClient client) {
if (execution instanceof VariableScope) {
((VariableScope) execution).setTransientVariableLocal("httpRequest", httpRequest);
evaluateScriptRequest(createScriptRequest(execution).traceEnhancer(trace -> trace.addTraceTag("type", "httpRequestHandler")));
|
} else {
throw new FlowableIllegalStateException(
"The given execution " + execution.getClass().getName() + " is not of type " + VariableScope.class.getName());
}
}
@Override
public void handleHttpResponse(VariableContainer execution, HttpResponse httpResponse) {
if (execution instanceof VariableScope) {
((VariableScope) execution).setTransientVariableLocal("httpResponse", httpResponse);
evaluateScriptRequest(createScriptRequest(execution).traceEnhancer(trace -> trace.addTraceTag("type", "httpResponseHandler")));
} else {
throw new FlowableIllegalStateException(
"The given execution " + execution.getClass().getName() + " is not of type " + VariableScope.class.getName());
}
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\http\handler\ScriptHttpHandler.java
| 1
|
请完成以下Java代码
|
private static DDOrderRef extractDDOrderRef(final I_MD_Candidate_Dist_Detail record)
{
final int ddOrderCandidateId = record.getDD_Order_Candidate_ID();
final int ddOrderId = record.getDD_Order_ID();
if (ddOrderCandidateId <= 0 && ddOrderId <= 0)
{
return null;
}
return DDOrderRef.builder()
.ddOrderCandidateId(ddOrderCandidateId)
.ddOrderId(ddOrderId)
.ddOrderLineId(record.getDD_OrderLine_ID())
.build();
}
@Nullable
private static PPOrderRef extractForwardPPOrderRef(final I_MD_Candidate_Dist_Detail record)
{
final PPOrderCandidateId ppOrderCandidateId = PPOrderCandidateId.ofRepoIdOrNull(record.getPP_Order_Candidate_ID());
final PPOrderId ppOrderId = PPOrderId.ofRepoIdOrNull(record.getPP_Order_ID());
if (ppOrderCandidateId == null && ppOrderId == null)
{
return null;
}
return PPOrderRef.builder()
.ppOrderCandidateId(ppOrderCandidateId)
.ppOrderLineCandidateId(record.getPP_OrderLine_Candidate_ID())
.ppOrderId(ppOrderId)
.ppOrderBOMLineId(PPOrderBOMLineId.ofRepoIdOrNull(record.getPP_Order_BOMLine_ID()))
.build();
}
public static DistributionDetail castOrNull(@Nullable final BusinessCaseDetail businessCaseDetail)
{
final boolean canBeCast = businessCaseDetail instanceof DistributionDetail;
if (canBeCast)
{
return cast(businessCaseDetail);
}
return null;
}
public static DistributionDetail cast(@NonNull final BusinessCaseDetail businessCaseDetail)
{
return (DistributionDetail)businessCaseDetail;
}
@Override
public CandidateBusinessCase getCandidateBusinessCase()
{
return CandidateBusinessCase.DISTRIBUTION;
}
|
public BusinessCaseDetail withPPOrderId(@Nullable final PPOrderId newPPOrderId)
{
final PPOrderRef ppOrderRefNew = PPOrderRef.withPPOrderId(forwardPPOrderRef, newPPOrderId);
if (Objects.equals(this.forwardPPOrderRef, ppOrderRefNew))
{
return this;
}
return toBuilder().forwardPPOrderRef(ppOrderRefNew).build();
}
public DistributionDetail withDdOrderCandidateId(final int ddOrderCandidateIdNew)
{
return withDDOrderRef(DDOrderRef.withDdOrderCandidateId(ddOrderRef, ddOrderCandidateIdNew));
}
private DistributionDetail withDDOrderRef(final DDOrderRef ddOrderRefNew)
{
return Objects.equals(this.ddOrderRef, ddOrderRefNew)
? this
: toBuilder().ddOrderRef(ddOrderRefNew).build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\businesscase\DistributionDetail.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Long getId() {
return this.id;
}
public Car id(Long id) {
this.setId(id);
return this;
}
public void setId(Long id) {
this.id = id;
}
public Double getPrice() {
return this.price;
}
public Car price(Double price) {
this.setPrice(price);
return this;
}
public void setPrice(Double price) {
this.price = price;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
@Override
public boolean equals(Object o) {
if (this == o) {
|
return true;
}
if (!(o instanceof Car)) {
return false;
}
return getId() != null && getId().equals(((Car) o).getId());
}
@Override
public int hashCode() {
// see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
return getClass().hashCode();
}
// prettier-ignore
@Override
public String toString() {
return "Car{" +
"id=" + getId() +
", price=" + getPrice() +
"}";
}
}
|
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\car-app\src\main\java\com\cars\app\domain\Car.java
| 2
|
请完成以下Java代码
|
public class UidGenerateException extends RuntimeException {
/**
* Serial Version UID
*/
private static final long serialVersionUID = -27048199131316992L;
/**
* Default constructor
*/
public UidGenerateException() {
super();
}
/**
* Constructor with message & cause
*
* @param message
* @param cause
*/
public UidGenerateException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructor with message
*
* @param message
*/
public UidGenerateException(String message) {
super(message);
}
|
/**
* Constructor with message format
*
* @param msgFormat
* @param args
*/
public UidGenerateException(String msgFormat, Object... args) {
super(String.format(msgFormat, args));
}
/**
* Constructor with cause
*
* @param cause
*/
public UidGenerateException(Throwable cause) {
super(cause);
}
}
|
repos\Spring-Boot-In-Action-master\id-spring-boot-starter\src\main\java\com\baidu\fsg\uid\exception\UidGenerateException.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getPath() {
return this.path;
}
public void setPath(String path) {
this.path = path;
}
public boolean isIncludeException() {
return this.includeException;
}
public void setIncludeException(boolean includeException) {
this.includeException = includeException;
}
public IncludeAttribute getIncludeStacktrace() {
return this.includeStacktrace;
}
public void setIncludeStacktrace(IncludeAttribute includeStacktrace) {
this.includeStacktrace = includeStacktrace;
}
public IncludeAttribute getIncludeMessage() {
return this.includeMessage;
}
public void setIncludeMessage(IncludeAttribute includeMessage) {
this.includeMessage = includeMessage;
}
public IncludeAttribute getIncludeBindingErrors() {
return this.includeBindingErrors;
}
public void setIncludeBindingErrors(IncludeAttribute includeBindingErrors) {
this.includeBindingErrors = includeBindingErrors;
}
public IncludeAttribute getIncludePath() {
return this.includePath;
}
public void setIncludePath(IncludeAttribute includePath) {
this.includePath = includePath;
}
public Whitelabel getWhitelabel() {
return this.whitelabel;
|
}
/**
* Include error attributes options.
*/
public enum IncludeAttribute {
/**
* Never add error attribute.
*/
NEVER,
/**
* Always add error attribute.
*/
ALWAYS,
/**
* Add error attribute when the appropriate request parameter is not "false".
*/
ON_PARAM
}
public static class Whitelabel {
/**
* Whether to enable the default error page displayed in browsers in case of a
* server error.
*/
private boolean enabled = true;
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\web\ErrorProperties.java
| 2
|
请完成以下Java代码
|
public class ChatSendParams {
public ChatSendParams(String content, String conversationId, String topicId, String appId) {
this.content = content;
this.conversationId = conversationId;
this.topicId = topicId;
this.appId = appId;
}
/**
* 用户输入的聊天内容
*/
private String content;
/**
* 对话会话ID
*/
private String conversationId;
/**
* 对话主题ID(用于关联历史记录)
*/
private String topicId;
|
/**
* 应用id
*/
private String appId;
/**
* 图片列表
*/
private List<String> images;
/**
* 工作流额外入参配置
* key: 参数field, value: 参数值
* for [issues/8545]新建AI应用的时候只能选择没有自定义参数的AI流程
*/
private Map<String, Object> flowInputs;
/**
* 是否开启网络搜索(仅千问模型支持)
*/
private Boolean enableSearch;
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\app\vo\ChatSendParams.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 8081
spring:
boot:
admin:
client:
url: http://localhost:8088
management:
endpoints:
web:
exposure:
include: '*'
info:
|
env:
enabled: true
logging:
file:
name: ./logs/sba-client.log
|
repos\spring-boot-best-practice-master\spring-boot-admin-client\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public int retrieveLastLineNo(final DocumentQuery query)
{
throw new UnsupportedOperationException();
}
private static final class ProcessInfoParameterDocumentValuesSupplier implements DocumentValuesSupplier
{
private final DocumentId adPInstanceId;
private final Map<String, ProcessInfoParameter> processInfoParameters;
public ProcessInfoParameterDocumentValuesSupplier(final DocumentId adPInstanceId, final Map<String, ProcessInfoParameter> processInfoParameters)
{
this.adPInstanceId = adPInstanceId;
this.processInfoParameters = processInfoParameters;
}
@Override
public DocumentId getDocumentId()
|
{
return adPInstanceId;
}
@Override
public String getVersion()
{
return VERSION_DEFAULT;
}
@Override
public Object getValue(final DocumentFieldDescriptor parameterDescriptor)
{
return extractParameterValue(processInfoParameters, parameterDescriptor);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\adprocess\ADProcessParametersRepository.java
| 1
|
请完成以下Java代码
|
public void setAnfragePzn(long value) {
this.anfragePzn = value;
}
/**
* Gets the value of the substitution property.
*
* @return
* possible object is
* {@link VerfuegbarkeitSubstitution }
*
*/
public VerfuegbarkeitSubstitution getSubstitution() {
return substitution;
}
/**
* Sets the value of the substitution property.
*
* @param value
* allowed object is
* {@link VerfuegbarkeitSubstitution }
*
*/
public void setSubstitution(VerfuegbarkeitSubstitution value) {
this.substitution = value;
}
/**
* Gets the value of the anteile property.
*
* <p>
* This accessor method returns a reference to the live list,
|
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the anteile property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAnteile().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link VerfuegbarkeitAnteil }
*
*
*/
public List<VerfuegbarkeitAnteil> getAnteile() {
if (anteile == null) {
anteile = new ArrayList<VerfuegbarkeitAnteil>();
}
return this.anteile;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\VerfuegbarkeitsantwortArtikel.java
| 1
|
请完成以下Java代码
|
public class AppResourceEntityImpl extends AbstractAppEngineNoRevisionEntity implements AppResourceEntity, Serializable {
private static final long serialVersionUID = 1L;
protected String name;
protected byte[] bytes;
protected String deploymentId;
protected boolean generated;
public AppResourceEntityImpl() {
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public byte[] getBytes() {
return bytes;
}
@Override
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
@Override
public String getDeploymentId() {
return deploymentId;
}
@Override
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@Override
|
public Object getPersistentState() {
return AppResourceEntityImpl.class;
}
@Override
public boolean isGenerated() {
return false;
}
@Override
public void setGenerated(boolean generated) {
this.generated = generated;
}
@Override
public String toString() {
return "CmmnResourceEntity[id=" + id + ", name=" + name + "]";
}
}
|
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\persistence\entity\AppResourceEntityImpl.java
| 1
|
请完成以下Java代码
|
private boolean isProcessCandidates()
{
final ProcessIssueCandidatesPolicy processCandidatesPolicy = this.processCandidatesPolicy;
if (ProcessIssueCandidatesPolicy.NEVER.equals(processCandidatesPolicy))
{
return false;
}
else if (ProcessIssueCandidatesPolicy.ALWAYS.equals(processCandidatesPolicy))
{
return true;
}
else if (ProcessIssueCandidatesPolicy.IF_ORDER_PLANNING_STATUS_IS_COMPLETE.equals(processCandidatesPolicy))
{
final I_PP_Order ppOrder = getPpOrder();
final PPOrderPlanningStatus orderPlanningStatus = PPOrderPlanningStatus.ofCode(ppOrder.getPlanningStatus());
return PPOrderPlanningStatus.COMPLETE.equals(orderPlanningStatus);
}
else
{
throw new AdempiereException("Unknown processCandidatesPolicy: " + processCandidatesPolicy);
}
|
}
public HUPPOrderIssueProducer changeHUStatusToIssued(final boolean changeHUStatusToIssued)
{
this.changeHUStatusToIssued = changeHUStatusToIssued;
return this;
}
public HUPPOrderIssueProducer generatedBy(final IssueCandidateGeneratedBy generatedBy)
{
this.generatedBy = generatedBy;
return this;
}
public HUPPOrderIssueProducer failIfIssueOnlyForReceived(final boolean fail)
{
this.failIfIssueOnlyForReceived = fail;
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\HUPPOrderIssueProducer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class HomeController {
//
@Autowired
private JWTUtility jwtUtility;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserService userService;
@GetMapping("/")
public String home() {
return "Welcome to Security ";
}
@PostMapping("/authenticate")
public JwtResponse authenticate(@RequestBody JwtRequest jwtRequest) throws Exception {
//
|
try {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
jwtRequest.getUsername(),
jwtRequest.getPassword()));
} catch (DisabledException e) {
throw new Exception("USER_DISABLED", e);
} catch (BadCredentialsException e) {
throw new Exception("Invalid_Credentials", e);
}
final UserDetails userDetails = userService.loadUserByUsername(jwtRequest.getUsername());
final String token = jwtUtility.generateToken(userDetails);
return new JwtResponse(token);
}
}
|
repos\SpringBoot-Projects-FullStack-master\Advanced-SpringSecure\secure-jwt-project\secure-jwt-project\src\main\java\uz\bepro\securejwtproject\controller\HomeController.java
| 2
|
请完成以下Java代码
|
public Long getTopicId() {
return topicId;
}
public void setTopicId(Long topicId) {
this.topicId = topicId;
}
public String getMemberIcon() {
return memberIcon;
}
public void setMemberIcon(String memberIcon) {
this.memberIcon = memberIcon;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
|
public Integer getShowStatus() {
return showStatus;
}
public void setShowStatus(Integer showStatus) {
this.showStatus = showStatus;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", memberNickName=").append(memberNickName);
sb.append(", topicId=").append(topicId);
sb.append(", memberIcon=").append(memberIcon);
sb.append(", content=").append(content);
sb.append(", createTime=").append(createTime);
sb.append(", showStatus=").append(showStatus);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsTopicComment.java
| 1
|
请完成以下Java代码
|
public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws RestClientException {
return uploadFileWithHttpInfo(petId, additionalMetadata, file).getBody();
}
/**
* uploads an image
*
* <p><b>200</b> - successful operation
* @param petId ID of pet to update (required)
* @param additionalMetadata Additional data to pass to server (optional)
* @param file file to upload (optional)
* @return ResponseEntity<ModelApiResponse>
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws RestClientException {
Object postBody = null;
// verify the required parameter 'petId' is set
if (petId == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling uploadFile");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("petId", petId);
String path = apiClient.expandPath("/pet/{petId}/uploadImage", uriVariables);
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
final MultiValueMap formParams = new LinkedMultiValueMap();
if (additionalMetadata != null)
formParams.add("additionalMetadata", additionalMetadata);
if (file != null)
|
formParams.add("file", new FileSystemResource(file));
final String[] accepts = {
"application/json"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"multipart/form-data"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { "petstore_auth" };
ParameterizedTypeReference<ModelApiResponse> returnType = new ParameterizedTypeReference<ModelApiResponse>() {};
return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
}
|
repos\tutorials-master\spring-swagger-codegen-modules\spring-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\api\PetApi.java
| 1
|
请完成以下Java代码
|
public class CRFLexicalAnalyzer extends AbstractLexicalAnalyzer
{
/**
* 构造CRF词法分析器
*
* @param segmenter CRF分词器
*/
public CRFLexicalAnalyzer(CRFSegmenter segmenter)
{
this.segmenter = segmenter;
}
/**
* 构造CRF词法分析器
*
* @param segmenter CRF分词器
* @param posTagger CRF词性标注器
*/
public CRFLexicalAnalyzer(CRFSegmenter segmenter, CRFPOSTagger posTagger)
{
this.segmenter = segmenter;
this.posTagger = posTagger;
config.speechTagging = true;
}
/**
* 构造CRF词法分析器
*
* @param segmenter CRF分词器
* @param posTagger CRF词性标注器
* @param neRecognizer CRF命名实体识别器
*/
public CRFLexicalAnalyzer(CRFSegmenter segmenter, CRFPOSTagger posTagger, CRFNERecognizer neRecognizer)
{
this.segmenter = segmenter;
this.posTagger = posTagger;
this.neRecognizer = neRecognizer;
config.speechTagging = true;
config.nameRecognize = true;
}
/**
* 构造CRF词法分析器
*
* @param cwsModelPath CRF分词器模型路径
*/
public CRFLexicalAnalyzer(String cwsModelPath) throws IOException
{
this(new CRFSegmenter(cwsModelPath));
}
|
/**
* 构造CRF词法分析器
*
* @param cwsModelPath CRF分词器模型路径
* @param posModelPath CRF词性标注器模型路径
*/
public CRFLexicalAnalyzer(String cwsModelPath, String posModelPath) throws IOException
{
this(new CRFSegmenter(cwsModelPath), new CRFPOSTagger(posModelPath));
}
/**
* 构造CRF词法分析器
*
* @param cwsModelPath CRF分词器模型路径
* @param posModelPath CRF词性标注器模型路径
* @param nerModelPath CRF命名实体识别器模型路径
*/
public CRFLexicalAnalyzer(String cwsModelPath, String posModelPath, String nerModelPath) throws IOException
{
this(new CRFSegmenter(cwsModelPath), new CRFPOSTagger(posModelPath), new CRFNERecognizer(nerModelPath));
}
/**
* 加载配置文件指定的模型
*
* @throws IOException
*/
public CRFLexicalAnalyzer() throws IOException
{
this(new CRFSegmenter(), new CRFPOSTagger(), new CRFNERecognizer());
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\CRFLexicalAnalyzer.java
| 1
|
请完成以下Java代码
|
private static String extractAppliesOnTableName(final ImmutableList<ViewHeaderPropertiesProvider> providers)
{
final ImmutableSet<String> tableNames = providers.stream()
.map(ViewHeaderPropertiesProvider::getAppliesOnlyToTableName)
.filter(Objects::nonNull)
.distinct()
.collect(ImmutableSet.toImmutableSet());
if (tableNames.isEmpty())
{
return null;
}
else if (tableNames.size() == 1)
{
return tableNames.iterator().next();
}
else
{
throw new AdempiereException("Generic providers and providers for same table can be groupped: " + providers);
}
}
@Override
public String getAppliesOnlyToTableName()
{
return appliesOnTableName;
}
@Override
public @NonNull ViewHeaderProperties computeHeaderProperties(@NonNull final IView view)
{
ViewHeaderProperties result = ViewHeaderProperties.EMPTY;
for (final ViewHeaderPropertiesProvider provider : providers)
{
final ViewHeaderProperties properties = provider.computeHeaderProperties(view);
result = result.combine(properties);
}
return result;
}
@Override
public ViewHeaderPropertiesIncrementalResult computeIncrementallyOnRowsChanged(
@NonNull final ViewHeaderProperties currentHeaderProperties,
@NonNull final IView view,
@NonNull final Set<DocumentId> changedRowIds,
final boolean watchedByFrontend)
|
{
ViewHeaderProperties computedHeaderProperties = currentHeaderProperties;
for (final ViewHeaderPropertiesProvider provider : providers)
{
final ViewHeaderPropertiesIncrementalResult partialResult = provider.computeIncrementallyOnRowsChanged(
computedHeaderProperties,
view,
changedRowIds,
watchedByFrontend);
if (partialResult.isComputed())
{
computedHeaderProperties = partialResult.getComputeHeaderProperties();
}
else if (partialResult.isFullRecomputeRequired())
{
return ViewHeaderPropertiesIncrementalResult.fullRecomputeRequired();
}
else
{
throw new AdempiereException("Unknow partial result type: " + partialResult);
}
}
return ViewHeaderPropertiesIncrementalResult.computed(computedHeaderProperties);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\CompositeViewHeaderPropertiesProvider.java
| 1
|
请完成以下Spring Boot application配置
|
spring.datasource.url=jdbc:mysql://127.0.0.1/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.
|
jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true
spring.thymeleaf.cache=false
|
repos\spring-boot-leaning-master\1.x\第06课:Jpa 和 Thymeleaf 实践\spring-boot-jpa-thymeleaf\src\main\resources\application.properties
| 2
|
请在Spring Boot框架中完成以下Java代码
|
default Page<ESProductDO> search(Integer cid, String keyword, Pageable pageable) {
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
// 筛选条件 cid
if (cid != null) {
nativeSearchQueryBuilder.withFilter(QueryBuilders.termQuery("cid", cid));
}
// 筛选
if (StringUtils.hasText(keyword)) {
FunctionScoreQueryBuilder.FilterFunctionBuilder[] functions = { // TODO 芋艿,分值随便打的
new FunctionScoreQueryBuilder.FilterFunctionBuilder(matchQuery("name", keyword),
ScoreFunctionBuilders.weightFactorFunction(10)),
new FunctionScoreQueryBuilder.FilterFunctionBuilder(matchQuery("sellPoint", keyword),
ScoreFunctionBuilders.weightFactorFunction(2)),
new FunctionScoreQueryBuilder.FilterFunctionBuilder(matchQuery("categoryName", keyword),
ScoreFunctionBuilders.weightFactorFunction(3)),
// new FunctionScoreQueryBuilder.FilterFunctionBuilder(matchQuery("description", keyword),
// ScoreFunctionBuilders.weightFactorFunction(2)), // TODO 芋艿,目前这么做,如果商品描述很长,在按照价格降序,会命中超级多的关键字。
};
FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(functions)
.scoreMode(FunctionScoreQuery.ScoreMode.SUM)
.setMinScore(2F); // TODO 芋艿,需要考虑下 score
nativeSearchQueryBuilder.withQuery(functionScoreQueryBuilder);
}
// 排序
|
if (StringUtils.hasText(keyword)) { // 关键字,使用打分
nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
} else if (pageable.getSort().isSorted()) { // 有排序,则进行拼接
pageable.getSort().get().forEach(sortField -> nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(sortField.getProperty())
.order(sortField.getDirection().isAscending() ? SortOrder.ASC : SortOrder.DESC)));
} else { // 无排序,则按照 ID 倒序
nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("id").order(SortOrder.DESC));
}
// 分页
nativeSearchQueryBuilder.withPageable(PageRequest.of(pageable.getPageNumber(), pageable.getPageSize())); // 避免
// 执行查询
return search(nativeSearchQueryBuilder.build());
}
}
|
repos\SpringBoot-Labs-master\lab-15-spring-data-es\lab-15-spring-data-jest\src\main\java\cn\iocoder\springboot\lab15\springdatajest\repository\ProductRepository03.java
| 2
|
请完成以下Java代码
|
public List<Integer> getValueAsIntList()
{
return getValueAsList(DocumentFilterParam::convertToInt);
}
@Nullable
private static Integer convertToInt(final Object itemObj)
{
if (itemObj == null)
{
// pass-through, even though it will produce an exception when the list will be converted to immutable list
return null;
}
else if (itemObj instanceof Number)
{
return ((Number)itemObj).intValue();
}
else if (itemObj instanceof LookupValue)
{
return ((LookupValue)itemObj).getIdAsInt();
}
else if (itemObj instanceof RepoIdAware)
{
return ((RepoIdAware)itemObj).getRepoId();
}
else
{
final String itemStr = itemObj.toString();
return Integer.parseInt(itemStr);
}
}
@Nullable
public <T extends RepoIdAware> T getValueAsRepoIdOrNull(final @NonNull IntFunction<T> repoIdMapper)
{
final int idInt = getValueAsInt(-1);
if (idInt < 0)
{
return null;
}
return repoIdMapper.apply(idInt);
}
public <T extends ReferenceListAwareEnum> T getValueAsRefListOrNull(@NonNull final Function<String, T> mapper)
{
final String value = StringUtils.trimBlankToNull(getValueAsString());
if (value == null)
{
return null;
}
return mapper.apply(value);
}
public boolean isNullValues()
{
return value == null
&& (!isRangeOperator() || valueTo == null)
&& sqlWhereClause == null;
}
private boolean isRangeOperator() {return operator != null && operator.isRangeOperator();}
//
//
// ------------------
//
//
|
public static final class Builder
{
private boolean joinAnd = true;
private String fieldName;
private Operator operator = Operator.EQUAL;
@Nullable private Object value;
@Nullable private Object valueTo;
private Builder()
{
super();
}
public DocumentFilterParam build()
{
return new DocumentFilterParam(this);
}
public Builder setJoinAnd(final boolean joinAnd)
{
this.joinAnd = joinAnd;
return this;
}
public Builder setFieldName(final String fieldName)
{
this.fieldName = fieldName;
return this;
}
public Builder setOperator(@NonNull final Operator operator)
{
this.operator = operator;
return this;
}
public Builder setOperator()
{
operator = valueTo != null ? Operator.BETWEEN : Operator.EQUAL;
return this;
}
public Builder setValue(@Nullable final Object value)
{
this.value = value;
return this;
}
public Builder setValueTo(@Nullable final Object valueTo)
{
this.valueTo = valueTo;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\DocumentFilterParam.java
| 1
|
请完成以下Java代码
|
private int getPageLength(final LookupDataSourceContext evalCtxParam)
{
final int ctxPageLength = evalCtxParam.getLimit(0);
if (ctxPageLength > 0)
{
return ctxPageLength;
}
if (this.pageLength > 0)
{
return this.pageLength;
}
else
{
return DEFAULT_PAGE_SIZE;
}
}
@Override
public final LookupValue retrieveLookupValueById(final @NonNull LookupDataSourceContext evalCtx)
{
final SqlAndParams sqlAndParams = this.sqlForFetchingLookupById.evaluate(evalCtx).orElse(null);
if (sqlAndParams == null)
{
throw new AdempiereException("No ID provided in " + evalCtx);
}
final String adLanguage = evalCtx.getAD_Language();
final ImmutableList<LookupValue> rows = DB.retrieveRows(
sqlAndParams.getSql(),
sqlAndParams.getSqlParams(),
rs -> SqlForFetchingLookupById.retrieveLookupValue(rs, isNumericKey(), isTranslatable, adLanguage));
if (rows.isEmpty())
{
return LOOKUPVALUE_NULL;
}
else if (rows.size() == 1)
{
return rows.get(0);
}
else
{
// shall not happen
throw new AdempiereException("More than one row found for " + evalCtx + ": " + rows);
}
}
@Override
public LookupValuesList retrieveLookupValueByIdsInOrder(@NonNull final LookupDataSourceContext evalCtx)
|
{
final SqlAndParams sqlAndParams = this.sqlForFetchingLookupById.evaluate(evalCtx).orElse(null);
if (sqlAndParams == null)
{
return LookupValuesList.EMPTY;
}
final String adLanguage = evalCtx.getAD_Language();
final ImmutableList<LookupValue> rows = DB.retrieveRows(
sqlAndParams.getSql(),
sqlAndParams.getSqlParams(),
rs -> SqlForFetchingLookupById.retrieveLookupValue(rs, numericKey, isTranslatable, adLanguage));
if (rows.isEmpty())
{
return LookupValuesList.EMPTY;
}
else if (rows.size() == 1)
{
return LookupValuesList.fromNullable(rows.get(0));
}
else
{
return rows.stream()
.sorted(FixedOrderByKeyComparator.<LookupValue, Object>builder()
.fixedOrderKeys(LookupValue.normalizeIds(evalCtx.getIdsToFilter().toImmutableList(), numericKey))
.keyMapper(LookupValue::getId)
.build())
.collect(LookupValuesList.collect());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\GenericSqlLookupDataSourceFetcher.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public PatientHospital dischargeDate(LocalDate dischargeDate) {
this.dischargeDate = dischargeDate;
return this;
}
/**
* letztes Entlassdatum aus der Klinik
* @return dischargeDate
**/
@Schema(example = "Thu Nov 21 00:00:00 GMT 2019", description = "letztes Entlassdatum aus der Klinik")
public LocalDate getDischargeDate() {
return dischargeDate;
}
public void setDischargeDate(LocalDate dischargeDate) {
this.dischargeDate = dischargeDate;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PatientHospital patientHospital = (PatientHospital) o;
return Objects.equals(this.hospitalId, patientHospital.hospitalId) &&
Objects.equals(this.dischargeDate, patientHospital.dischargeDate);
}
@Override
public int hashCode() {
return Objects.hash(hospitalId, dischargeDate);
}
|
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PatientHospital {\n");
sb.append(" hospitalId: ").append(toIndentedString(hospitalId)).append("\n");
sb.append(" dischargeDate: ").append(toIndentedString(dischargeDate)).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-patient-api\src\main\java\io\swagger\client\model\PatientHospital.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private BigDecimal calcTotalAmount(List<CartPromotionItem> cartItemList) {
BigDecimal total = new BigDecimal("0");
for (CartPromotionItem item : cartItemList) {
BigDecimal realPrice = item.getPrice().subtract(item.getReduceAmount());
total=total.add(realPrice.multiply(new BigDecimal(item.getQuantity())));
}
return total;
}
private BigDecimal calcTotalAmountByproductCategoryId(List<CartPromotionItem> cartItemList,List<Long> productCategoryIds) {
BigDecimal total = new BigDecimal("0");
for (CartPromotionItem item : cartItemList) {
if(productCategoryIds.contains(item.getProductCategoryId())){
BigDecimal realPrice = item.getPrice().subtract(item.getReduceAmount());
total=total.add(realPrice.multiply(new BigDecimal(item.getQuantity())));
}
|
}
return total;
}
private BigDecimal calcTotalAmountByProductId(List<CartPromotionItem> cartItemList,List<Long> productIds) {
BigDecimal total = new BigDecimal("0");
for (CartPromotionItem item : cartItemList) {
if(productIds.contains(item.getProductId())){
BigDecimal realPrice = item.getPrice().subtract(item.getReduceAmount());
total=total.add(realPrice.multiply(new BigDecimal(item.getQuantity())));
}
}
return total;
}
}
|
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\service\impl\UmsMemberCouponServiceImpl.java
| 2
|
请完成以下Spring Boot application配置
|
quarkus.http.auth.basic=true
quarkus.security.users.embedded.enabled=true
quarkus.security.users.embedded.plain-text=true
quarkus.security.users.embedded.users.john=secret1
quarkus.security.users.embedded.roles.john=admin,use
|
r
quarkus.security.users.embedded.users.reza=test
quarkus.security.users.embedded.roles.reza=user
|
repos\tutorials-master\quarkus-modules\quarkus-clientbasicauth\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public class MapValueProvider implements ParameterValueProvider {
protected TreeMap<ParameterValueProvider, ParameterValueProvider> providerMap;
public MapValueProvider(TreeMap<ParameterValueProvider, ParameterValueProvider> providerMap) {
this.providerMap = providerMap;
}
public Object getValue(VariableScope variableScope) {
Map<Object, Object> valueMap = new TreeMap<Object, Object>();
for (Entry<ParameterValueProvider, ParameterValueProvider> entry : providerMap.entrySet()) {
valueMap.put(entry.getKey().getValue(variableScope), entry.getValue().getValue(variableScope));
}
return valueMap;
}
public TreeMap<ParameterValueProvider, ParameterValueProvider> getProviderMap() {
|
return providerMap;
}
public void setProviderMap(TreeMap<ParameterValueProvider, ParameterValueProvider> providerMap) {
this.providerMap = providerMap;
}
/**
* @return this method currently always returns false, but that might change in the future.
*/
@Override
public boolean isDynamic() {
// This implementation is currently not needed and therefore returns a defensive default value
return true;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\variable\mapping\value\MapValueProvider.java
| 1
|
请完成以下Java代码
|
public class FutureValue<T> implements Future<T>
{
private T value = null;
private Exception exception = null;
private boolean done = false;
private boolean canceled = false;
private final CountDownLatch latch = new CountDownLatch(1);
public void set(final T value)
{
if (done)
{
throw new IllegalStateException("Value was already set");
}
this.value = value;
this.exception = null;
this.done = true;
this.canceled = false;
latch.countDown();
}
public void setError(final Exception e)
{
if (done)
{
throw new IllegalStateException("Value was already set");
}
Check.assumeNotNull(e, "exception not null");
this.value = null;
this.exception = e;
this.done = true;
this.canceled = false;
latch.countDown();
}
public void setCanceled(final Exception e)
{
if (done)
{
throw new IllegalStateException("Value was already set");
}
Check.assumeNotNull(e, "exception not null");
this.value = null;
this.exception = e;
this.done = true;
this.canceled = true;
latch.countDown();
}
@Override
public boolean cancel(boolean mayInterruptIfRunning)
{
throw new UnsupportedOperationException();
}
@Override
|
public boolean isCancelled()
{
return canceled;
}
@Override
public boolean isDone()
{
return done;
}
@Override
public T get() throws InterruptedException, ExecutionException
{
latch.await();
return get0();
}
@Override
public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
{
latch.await(timeout, unit);
return get0();
}
private T get0() throws ExecutionException
{
if (!done)
{
throw new IllegalStateException("Value not available");
}
//
// We got a cancellation
if (canceled)
{
final CancellationException cancelException = new CancellationException(exception.getLocalizedMessage());
cancelException.initCause(exception);
throw cancelException;
}
//
// We got an error
if (exception != null)
{
throw new ExecutionException(exception);
}
return value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\concurrent\FutureValue.java
| 1
|
请完成以下Java代码
|
public void сhangeOil(String oil) {
Assert.notNull(oil, "oil mustn't be null");
// ...
}
public void replaceBattery(CarBattery carBattery) {
Assert.isNull(carBattery.getCharge(), "to replace battery the charge must be null");
// ...
}
public void сhangeEngine(Engine engine) {
Assert.isInstanceOf(ToyotaEngine.class, engine);
// ...
}
public void repairEngine(Engine engine) {
Assert.isAssignable(Engine.class, ToyotaEngine.class);
// ...
}
public void startWithHasLength(String key) {
Assert.hasLength(key, "key must not be null and must not the empty");
// ...
}
public void startWithHasText(String key) {
Assert.hasText(key, "key must not be null and must contain at least one non-whitespace character");
// ...
}
public void startWithNotContain(String key) {
Assert.doesNotContain(key, "123", "key must not contain 123");
// ...
}
public void repair(Collection<String> repairParts) {
Assert.notEmpty(repairParts, "collection of repairParts mustn't be empty");
// ...
}
public void repair(Map<String, String> repairParts) {
Assert.notEmpty(repairParts, "map of repairParts mustn't be empty");
// ...
}
public void repair(String[] repairParts) {
Assert.notEmpty(repairParts, "array of repairParts must not be empty");
// ...
}
public void repairWithNoNull(String[] repairParts) {
Assert.noNullElements(repairParts, "array of repairParts must not contain null elements");
// ...
|
}
public static void main(String[] args) {
Car car = new Car();
car.drive(50);
car.stop();
car.fuel();
car.сhangeOil("oil");
CarBattery carBattery = new CarBattery();
car.replaceBattery(carBattery);
car.сhangeEngine(new ToyotaEngine());
car.startWithHasLength(" ");
car.startWithHasText("t");
car.startWithNotContain("132");
List<String> repairPartsCollection = new ArrayList<>();
repairPartsCollection.add("part");
car.repair(repairPartsCollection);
Map<String, String> repairPartsMap = new HashMap<>();
repairPartsMap.put("1", "part");
car.repair(repairPartsMap);
String[] repairPartsArray = { "part" };
car.repair(repairPartsArray);
}
}
|
repos\tutorials-master\spring-5\src\main\java\com\baeldung\assertions\Car.java
| 1
|
请完成以下Java代码
|
public SetRemovalTimeToHistoricDecisionInstancesBuilder absoluteRemovalTime(Date removalTime) {
ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode);
this.mode = Mode.ABSOLUTE_REMOVAL_TIME;
this.removalTime = removalTime;
return this;
}
@Override
public SetRemovalTimeToHistoricDecisionInstancesBuilder calculatedRemovalTime() {
ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode);
this.mode = Mode.CALCULATED_REMOVAL_TIME;
return this;
}
public SetRemovalTimeToHistoricDecisionInstancesBuilder clearedRemovalTime() {
ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode);
mode = Mode.CLEARED_REMOVAL_TIME;
return this;
}
public SetRemovalTimeToHistoricDecisionInstancesBuilder hierarchical() {
isHierarchical = true;
return this;
}
public Batch executeAsync() {
return commandExecutor.execute(new SetRemovalTimeToHistoricDecisionInstancesCmd(this));
}
|
public HistoricDecisionInstanceQuery getQuery() {
return query;
}
public List<String> getIds() {
return ids;
}
public Date getRemovalTime() {
return removalTime;
}
public Mode getMode() {
return mode;
}
public enum Mode {
CALCULATED_REMOVAL_TIME,
ABSOLUTE_REMOVAL_TIME,
CLEARED_REMOVAL_TIME;
}
public boolean isHierarchical() {
return isHierarchical;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\SetRemovalTimeToHistoricDecisionInstancesBuilderImpl.java
| 1
|
请完成以下Spring Boot application配置
|
okta.oauth2.issuer= //Auth server issuer URL
okta.oauth2.client-id= //Client ID of our Okta application
okta.oauth2.client-secret= //Client secret of our Okta application
okta.oauth2.redirect-uri=/authorization-code/callb
|
ack
#Okta Spring SDK configs
okta.client.orgUrl= //orgURL
okta.client.token= //token generated
|
repos\tutorials-master\spring-security-modules\spring-security-okta\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
protected List<ExecutableScript> getEnvScripts(ExecutableScript script, ScriptEngine scriptEngine) {
List<ExecutableScript> envScripts = getEnvScripts(script.getLanguage().toLowerCase());
if (envScripts.isEmpty()) {
envScripts = getEnvScripts(scriptEngine.getFactory().getLanguageName().toLowerCase());
}
return envScripts;
}
/**
* Returns the env scripts for the given language. Performs lazy initialization of the env scripts.
*
* @param scriptLanguage the language
* @return a list of executable environment scripts. Never null.
*/
protected List<ExecutableScript> getEnvScripts(String scriptLanguage) {
Map<String, List<ExecutableScript>> environment = getEnv(scriptLanguage);
List<ExecutableScript> envScripts = environment.get(scriptLanguage);
if(envScripts == null) {
synchronized (this) {
envScripts = environment.get(scriptLanguage);
if(envScripts == null) {
envScripts = initEnvForLanguage(scriptLanguage);
environment.put(scriptLanguage, envScripts);
}
}
}
return envScripts;
}
/**
* Initializes the env scripts for a given language.
|
*
* @param language the language
* @return the list of env scripts. Never null.
*/
protected List<ExecutableScript> initEnvForLanguage(String language) {
List<ExecutableScript> scripts = new ArrayList<>();
for (ScriptEnvResolver resolver : envResolvers) {
String[] resolvedScripts = resolver.resolve(language);
if(resolvedScripts != null) {
for (String resolvedScript : resolvedScripts) {
scripts.add(scriptFactory.createScriptFromSource(language, resolvedScript));
}
}
}
return scripts;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\scripting\env\ScriptingEnvironment.java
| 1
|
请完成以下Java代码
|
public void setVariableType(VariableType variableType) {
this.variableType = variableType;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getLastUpdatedTime() {
return lastUpdatedTime;
}
public void setLastUpdatedTime(Date lastUpdatedTime) {
this.lastUpdatedTime = lastUpdatedTime;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
|
public Date getTime() {
return getCreateTime();
}
public ByteArrayRef getByteArrayRef() {
return byteArrayRef;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("HistoricVariableInstanceEntity[");
sb.append("id=").append(id);
sb.append(", name=").append(name);
sb.append(", revision=").append(revision);
sb.append(", type=").append(variableType != null ? variableType.getTypeName() : "null");
if (longValue != null) {
sb.append(", longValue=").append(longValue);
}
if (doubleValue != null) {
sb.append(", doubleValue=").append(doubleValue);
}
if (textValue != null) {
sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40));
}
if (textValue2 != null) {
sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40));
}
if (byteArrayRef != null && byteArrayRef.getId() != null) {
sb.append(", byteArrayValueId=").append(byteArrayRef.getId());
}
sb.append("]");
return sb.toString();
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricVariableInstanceEntityImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MainApplication {
private final BookstoreService bookstoreService;
public MainApplication(BookstoreService bookstoreService) {
this.bookstoreService = bookstoreService;
}
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
@Bean
public ApplicationRunner init() {
return args -> {
|
System.out.println("\nCount 'Anthology' authors: \n"
+ bookstoreService.countByGenre()
+ "\n\n");
System.out.println("\nDelete 'History' authors: \n"
+ bookstoreService.deleteByGenre()
+ "\n\n");
System.out.println("\nDelete and return 'Horror' authors: \n"
+ bookstoreService.removeByGenre()
+ "\n\n");
};
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootDerivedCountAndDelete\src\main\java\com\bookstore\MainApplication.java
| 2
|
请完成以下Java代码
|
public class ExecutionContextHolder {
protected static ThreadLocal<Stack<ExecutionContext>> executionContextStackThreadLocal = new ThreadLocal<>();
public static ExecutionContext getExecutionContext() {
return getStack(executionContextStackThreadLocal).peek();
}
public static boolean isExecutionContextActive() {
Stack<ExecutionContext> stack = executionContextStackThreadLocal.get();
return stack != null && !stack.isEmpty();
}
public static void setExecutionContext(ExecutionEntity execution) {
getStack(executionContextStackThreadLocal).push(new ExecutionContext(execution));
|
}
public static void removeExecutionContext() {
getStack(executionContextStackThreadLocal).pop();
}
protected static <T> Stack<T> getStack(ThreadLocal<Stack<T>> threadLocal) {
Stack<T> stack = threadLocal.get();
if (stack == null) {
stack = new Stack<>();
threadLocal.set(stack);
}
return stack;
}
}
|
repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\impl\context\ExecutionContextHolder.java
| 1
|
请完成以下Java代码
|
public int getM_Pricelist_Version_Base_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Pricelist_Version_Base_ID);
}
@Override
public void setM_PriceList_Version_ID (final int M_PriceList_Version_ID)
{
if (M_PriceList_Version_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PriceList_Version_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PriceList_Version_ID, M_PriceList_Version_ID);
}
@Override
public int getM_PriceList_Version_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PriceList_Version_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 setProcCreate (final @Nullable java.lang.String ProcCreate)
{
set_Value (COLUMNNAME_ProcCreate, ProcCreate);
|
}
@Override
public java.lang.String getProcCreate()
{
return get_ValueAsString(COLUMNNAME_ProcCreate);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PriceList_Version.java
| 1
|
请完成以下Java代码
|
public SpinValueType getType() {
return (SpinValueType) super.getType();
}
public boolean isDeserialized() {
return isDeserialized;
}
public String getValueSerialized() {
return serializedValue;
}
public void setValueSerialized(String serializedValue) {
this.serializedValue = serializedValue;
}
public String getSerializationDataFormat() {
return dataFormatName;
|
}
public void setSerializationDataFormat(String serializationDataFormat) {
this.dataFormatName = serializationDataFormat;
}
public DataFormat<? extends Spin<?>> getDataFormat() {
if(isDeserialized) {
return DataFormats.getDataFormat(dataFormatName);
}
else {
throw new IllegalStateException("Spin value is not deserialized.");
}
}
}
|
repos\camunda-bpm-platform-master\engine-plugins\spin-plugin\src\main\java\org\camunda\spin\plugin\variable\value\impl\SpinValueImpl.java
| 1
|
请完成以下Java代码
|
private String quoteIfNeeded(String s) {
if (s != null && s.contains(":")) { // TODO: broaded quote
return "\"" + s + "\"";
}
return s;
}
public @Nullable String get(String key) {
return this.values.get(key);
}
/* for testing */ Map<String, String> getValues() {
return this.values;
}
@Override
public String toString() {
|
return "Forwarded{" + "values=" + this.values + '}';
}
public String toHeaderValue() {
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, String> entry : this.values.entrySet()) {
if (!builder.isEmpty()) {
builder.append(SEMICOLON);
}
builder.append(entry.getKey()).append(EQUALS).append(entry.getValue());
}
return builder.toString();
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\headers\ForwardedHeadersFilter.java
| 1
|
请完成以下Java代码
|
public Integer value1() {
return getId();
}
@Override
public String value2() {
return getTitle();
}
@Override
public String value3() {
return getDescription();
}
@Override
public Integer value4() {
return getAuthorId();
}
@Override
public ArticleRecord value1(Integer value) {
setId(value);
return this;
}
@Override
public ArticleRecord value2(String value) {
setTitle(value);
return this;
}
@Override
public ArticleRecord value3(String value) {
setDescription(value);
return this;
}
@Override
public ArticleRecord value4(Integer value) {
|
setAuthorId(value);
return this;
}
@Override
public ArticleRecord values(Integer value1, String value2, String value3, Integer value4) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached ArticleRecord
*/
public ArticleRecord() {
super(Article.ARTICLE);
}
/**
* Create a detached, initialised ArticleRecord
*/
public ArticleRecord(Integer id, String title, String description, Integer authorId) {
super(Article.ARTICLE);
set(0, id);
set(1, title);
set(2, description);
set(3, authorId);
}
}
|
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\model\tables\records\ArticleRecord.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public long executeCount(CommandContext commandContext) {
return batchServiceConfiguration.getBatchEntityManager().findBatchCountByQueryCriteria(this);
}
@Override
public List<Batch> executeList(CommandContext commandContext) {
return batchServiceConfiguration.getBatchEntityManager().findBatchesByQueryCriteria(this);
}
@Override
public void delete() {
if (commandExecutor != null) {
commandExecutor.execute(context -> {
executeDelete(context);
return null;
});
} else {
executeDelete(Context.getCommandContext());
}
}
protected void executeDelete(CommandContext commandContext) {
batchServiceConfiguration.getBatchEntityManager().deleteBatches(this);
}
@Override
@Deprecated
public void deleteWithRelatedData() {
delete();
}
// getters //////////////////////////////////////////
@Override
public String getId() {
return id;
}
public String getBatchType() {
return batchType;
}
public Collection<String> getBatchTypes() {
return batchTypes;
}
|
public String getSearchKey() {
return searchKey;
}
public String getSearchKey2() {
return searchKey2;
}
public Date getCreateTimeHigherThan() {
return createTimeHigherThan;
}
public Date getCreateTimeLowerThan() {
return createTimeLowerThan;
}
public String getStatus() {
return status;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\BatchQueryImpl.java
| 2
|
请完成以下Java代码
|
public void setExpirationListener(ExpirationListener listener) {
this.expirationListener = listener;
}
/**
* start the registration store, will start regular cleanup of dead registrations.
*/
@Override
public synchronized void start() {
if (!started) {
started = true;
cleanerTask = schedExecutor.scheduleAtFixedRate(new TbInMemoryRegistrationStore.Cleaner(), cleanPeriod, cleanPeriod, TimeUnit.SECONDS);
}
}
/**
* Stop the underlying cleanup of the registrations.
*/
@Override
public synchronized void stop() {
if (started) {
started = false;
if (cleanerTask != null) {
cleanerTask.cancel(false);
cleanerTask = null;
}
}
}
/**
* Destroy "cleanup" scheduler.
*/
@Override
public synchronized void destroy() {
started = false;
schedExecutor.shutdownNow();
try {
schedExecutor.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
log.warn("Destroying InMemoryRegistrationStore was interrupted.", e);
}
}
private class Cleaner implements Runnable {
@Override
public void run() {
try {
Collection<Registration> allRegs = new ArrayList<>();
try {
lock.readLock().lock();
allRegs.addAll(regsByEp.values());
} finally {
|
lock.readLock().unlock();
}
for (Registration reg : allRegs) {
if (!reg.isAlive()) {
// force de-registration
Deregistration removedRegistration = removeRegistration(reg.getId());
expirationListener.registrationExpired(removedRegistration.getRegistration(),
removedRegistration.getObservations());
}
}
} catch (Exception e) {
log.warn("Unexpected Exception while registration cleaning", e);
}
}
}
// boolean remove(Object key, Object value) exist only since java8
// So this method is here only while we want to support java 7
protected <K, V> boolean removeFromMap(Map<K, V> map, K key, V value) {
if (map.containsKey(key) && Objects.equals(map.get(key), value)) {
map.remove(key);
return true;
} else
return false;
}
}
|
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\store\TbInMemoryRegistrationStore.java
| 1
|
请完成以下Java代码
|
public int getPickFrom_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_PickFrom_Warehouse_ID);
}
@Override
public void setQtyRejectedToPick (final @Nullable BigDecimal QtyRejectedToPick)
{
set_Value (COLUMNNAME_QtyRejectedToPick, QtyRejectedToPick);
}
@Override
public BigDecimal getQtyRejectedToPick()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyRejectedToPick);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* RejectReason AD_Reference_ID=541422
* Reference name: QtyNotPicked RejectReason
*/
public static final int REJECTREASON_AD_Reference_ID=541422;
|
/** NotFound = N */
public static final String REJECTREASON_NotFound = "N";
/** Damaged = D */
public static final String REJECTREASON_Damaged = "D";
@Override
public void setRejectReason (final @Nullable java.lang.String RejectReason)
{
set_Value (COLUMNNAME_RejectReason, RejectReason);
}
@Override
public java.lang.String getRejectReason()
{
return get_ValueAsString(COLUMNNAME_RejectReason);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job_Step_HUAlternative.java
| 1
|
请完成以下Java代码
|
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;
}
@Override
public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setSalesRep(org.compiere.model.I_AD_User SalesRep)
{
set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep);
}
/** Set Aussendienst.
|
@param SalesRep_ID Aussendienst */
@Override
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Aussendienst.
@return Aussendienst */
@Override
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java-gen\de\metas\dunning\model\X_C_DunningDoc_Line.java
| 1
|
请完成以下Java代码
|
public void setPhone2 (final @Nullable java.lang.String Phone2)
{
set_Value (COLUMNNAME_Phone2, Phone2);
}
@Override
public java.lang.String getPhone2()
{
return get_ValueAsString(COLUMNNAME_Phone2);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setRegistry (final @Nullable java.lang.String Registry)
{
set_Value (COLUMNNAME_Registry, Registry);
}
@Override
public java.lang.String getRegistry()
{
return get_ValueAsString(COLUMNNAME_Registry);
}
@Override
public void setSecretKey_2FA (final @Nullable java.lang.String SecretKey_2FA)
{
set_Value (COLUMNNAME_SecretKey_2FA, SecretKey_2FA);
}
@Override
public java.lang.String getSecretKey_2FA()
{
return get_ValueAsString(COLUMNNAME_SecretKey_2FA);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setSupervisor_ID (final int Supervisor_ID)
{
if (Supervisor_ID < 1)
set_Value (COLUMNNAME_Supervisor_ID, null);
else
set_Value (COLUMNNAME_Supervisor_ID, Supervisor_ID);
}
@Override
public int getSupervisor_ID()
{
return get_ValueAsInt(COLUMNNAME_Supervisor_ID);
}
@Override
public void setTimestamp (final @Nullable java.sql.Timestamp Timestamp)
{
throw new IllegalArgumentException ("Timestamp is virtual column"); }
@Override
public java.sql.Timestamp getTimestamp()
{
return get_ValueAsTimestamp(COLUMNNAME_Timestamp);
}
@Override
public void setTitle (final @Nullable java.lang.String Title)
|
{
set_Value (COLUMNNAME_Title, Title);
}
@Override
public java.lang.String getTitle()
{
return get_ValueAsString(COLUMNNAME_Title);
}
@Override
public void setUnlockAccount (final @Nullable java.lang.String UnlockAccount)
{
set_Value (COLUMNNAME_UnlockAccount, UnlockAccount);
}
@Override
public java.lang.String getUnlockAccount()
{
return get_ValueAsString(COLUMNNAME_UnlockAccount);
}
@Override
public void setUserPIN (final @Nullable java.lang.String UserPIN)
{
set_Value (COLUMNNAME_UserPIN, UserPIN);
}
@Override
public java.lang.String getUserPIN()
{
return get_ValueAsString(COLUMNNAME_UserPIN);
}
@Override
public void setValue (final @Nullable java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User.java
| 1
|
请完成以下Java代码
|
class Context {
private static Map<String, List<Row>> tables = new HashMap<>();
static {
List<Row> list = new ArrayList<>();
list.add(new Row("John", "Doe"));
list.add(new Row("Jan", "Kowalski"));
list.add(new Row("Dominic", "Doom"));
tables.put("people", list);
}
private String table;
private String column;
/**
* Index of column to be shown in result.
* Calculated in {@link #setColumnMapper()}
*/
private int colIndex = -1;
/**
* Default setup, used for clearing the context for next queries.
* See {@link Context#clear()}
*/
private static final Predicate<String> matchAnyString = s -> s.length() > 0;
private static final Function<String, Stream<? extends String>> matchAllColumns = Stream::of;
/**
* Varies based on setup in subclasses of {@link Expression}
*/
private Predicate<String> whereFilter = matchAnyString;
private Function<String, Stream<? extends String>> columnMapper = matchAllColumns;
void setColumn(String column) {
this.column = column;
setColumnMapper();
}
void setTable(String table) {
this.table = table;
}
void setFilter(Predicate<String> filter) {
whereFilter = filter;
}
/**
* Clears the context to defaults.
|
* No filters, match all columns.
*/
void clear() {
column = "";
columnMapper = matchAllColumns;
whereFilter = matchAnyString;
}
List<String> search() {
List<String> result = tables.entrySet()
.stream()
.filter(entry -> entry.getKey().equalsIgnoreCase(table))
.flatMap(entry -> Stream.of(entry.getValue()))
.flatMap(Collection::stream)
.map(Row::toString)
.flatMap(columnMapper)
.filter(whereFilter)
.collect(Collectors.toList());
clear();
return result;
}
/**
* Sets column mapper based on {@link #column} attribute.
* Note: If column is unknown, will remain to look for all columns.
*/
private void setColumnMapper() {
switch (column) {
case "*":
colIndex = -1;
break;
case "name":
colIndex = 0;
break;
case "surname":
colIndex = 1;
break;
}
if (colIndex != -1) {
columnMapper = s -> Stream.of(s.split(" ")[colIndex]);
}
}
}
|
repos\tutorials-master\patterns-modules\design-patterns-behavioral-2\src\main\java\com\baeldung\interpreter\Context.java
| 1
|
请完成以下Java代码
|
public class EdgeEventEntity extends BaseSqlEntity<EdgeEvent> implements BaseEntity<EdgeEvent> {
@Column(name = EDGE_EVENT_SEQUENTIAL_ID_PROPERTY)
protected long seqId;
@Column(name = EDGE_EVENT_TENANT_ID_PROPERTY)
private UUID tenantId;
@Column(name = EDGE_EVENT_EDGE_ID_PROPERTY)
private UUID edgeId;
@Column(name = EDGE_EVENT_ENTITY_ID_PROPERTY)
private UUID entityId;
@Enumerated(EnumType.STRING)
@Column(name = EDGE_EVENT_TYPE_PROPERTY)
private EdgeEventType edgeEventType;
@Enumerated(EnumType.STRING)
@Column(name = EDGE_EVENT_ACTION_PROPERTY)
private EdgeEventActionType edgeEventAction;
@Convert(converter = JsonConverter.class)
@Column(name = EDGE_EVENT_BODY_PROPERTY)
private JsonNode entityBody;
@Column(name = EDGE_EVENT_UID_PROPERTY)
private String edgeEventUid;
@Column(name = TS_COLUMN)
private long ts;
public EdgeEventEntity(EdgeEvent edgeEvent) {
if (edgeEvent.getId() != null) {
this.setUuid(edgeEvent.getId().getId());
this.ts = getTs(edgeEvent.getId().getId());
} else {
this.ts = System.currentTimeMillis();
}
this.setCreatedTime(edgeEvent.getCreatedTime());
if (edgeEvent.getTenantId() != null) {
this.tenantId = edgeEvent.getTenantId().getId();
}
if (edgeEvent.getEdgeId() != null) {
this.edgeId = edgeEvent.getEdgeId().getId();
}
if (edgeEvent.getEntityId() != null) {
this.entityId = edgeEvent.getEntityId();
}
this.edgeEventType = edgeEvent.getType();
|
this.edgeEventAction = edgeEvent.getAction();
this.entityBody = edgeEvent.getBody();
this.edgeEventUid = edgeEvent.getUid();
}
@Override
public EdgeEvent toData() {
EdgeEvent edgeEvent = new EdgeEvent(new EdgeEventId(this.getUuid()));
edgeEvent.setCreatedTime(createdTime);
edgeEvent.setTenantId(TenantId.fromUUID(tenantId));
edgeEvent.setEdgeId(new EdgeId(edgeId));
if (entityId != null) {
edgeEvent.setEntityId(entityId);
}
edgeEvent.setType(edgeEventType);
edgeEvent.setAction(edgeEventAction);
edgeEvent.setBody(entityBody);
edgeEvent.setUid(edgeEventUid);
edgeEvent.setSeqId(seqId);
return edgeEvent;
}
private static long getTs(UUID uuid) {
return (uuid.timestamp() - EPOCH_DIFF) / 10000;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\EdgeEventEntity.java
| 1
|
请完成以下Java代码
|
private Set<EDIDesadvPackId> generateLabelsInTrx()
{
if(!p_IsDefault && p_Counter <= 0)
{
throw new FillMandatoryException(PARAM_Counter);
}
final List<I_EDI_DesadvLine> desadvLines = getSelectedLines();
if (desadvLines.isEmpty())
{
throw new AdempiereException("@NoSelection@");
}
final DesadvLineSSCC18Generator desadvLineLabelsGenerator = DesadvLineSSCC18Generator.builder()
.sscc18CodeService(sscc18CodeService)
.desadvBL(desadvBL)
.ediDesadvPackService(ediDesadvPackService)
.printExistingLabels(true)
.bpartnerId(extractBPartnerId(desadvLines))
.build();
final LinkedHashSet<EDIDesadvPackId> lineSSCCIdsToPrint = new LinkedHashSet<>();
for (final I_EDI_DesadvLine desadvLine : desadvLines)
{
final PrintableDesadvLineSSCC18Labels desadvLineLabels = PrintableDesadvLineSSCC18Labels.builder()
.setEDI_DesadvLine(desadvLine)
.setRequiredSSCC18Count(!p_IsDefault ? p_Counter : null)
.build();
desadvLineLabelsGenerator.generateAndEnqueuePrinting(desadvLineLabels);
lineSSCCIdsToPrint.addAll(desadvLineLabelsGenerator.getLineSSCCIdsToPrint());
}
return lineSSCCIdsToPrint;
}
private static BPartnerId extractBPartnerId(@NonNull final List<I_EDI_DesadvLine> desadvLines)
{
final I_EDI_Desadv ediDesadvRecord = desadvLines.get(0).getEDI_Desadv();
final int bpartnerRepoId = CoalesceUtil.firstGreaterThanZero(
|
ediDesadvRecord.getDropShip_BPartner_ID(),
ediDesadvRecord.getC_BPartner_ID());
return BPartnerId.ofRepoId(bpartnerRepoId);
}
private List<I_EDI_DesadvLine> getSelectedLines()
{
final Set<Integer> lineIds = getSelectedLineIds();
return desadvBL.retrieveLinesByIds(lineIds);
}
private I_EDI_DesadvLine getSingleSelectedLine()
{
return CollectionUtils.singleElement(getSelectedLines());
}
private Set<Integer> getSelectedLineIds()
{
return getSelectedIncludedRecordIds(I_EDI_DesadvLine.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\EDI_Desadv_GenerateSSCCLabels.java
| 1
|
请完成以下Java代码
|
public void setPosted (boolean Posted)
{
set_ValueNoCheck (COLUMNNAME_Posted, Boolean.valueOf(Posted));
}
/** Get Verbucht.
@return Posting status
*/
@Override
public boolean isPosted ()
{
Object oo = get_Value(COLUMNNAME_Posted);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Price Match Difference.
@param PriceMatchDifference
Difference between Purchase and Invoice Price per matched line
*/
@Override
public void setPriceMatchDifference (java.math.BigDecimal PriceMatchDifference)
{
set_Value (COLUMNNAME_PriceMatchDifference, PriceMatchDifference);
}
/** Get Price Match Difference.
@return Difference between Purchase and Invoice Price per matched line
*/
@Override
public java.math.BigDecimal getPriceMatchDifference ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceMatchDifference);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_ValueNoCheck (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Verarbeiten.
@param Processing Verarbeiten */
@Override
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Verarbeiten.
@return Verarbeiten */
|
@Override
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Menge.
@param Qty
Quantity
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_ValueNoCheck (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Quantity
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_MatchPO.java
| 1
|
请完成以下Java代码
|
public void cancelReservedItems(Order order) {
log.info("cancelReservedItems: order={}", order);
for (OrderItem item : order.items()) {
inventoryService.cancelInventoryReservation(item.sku(), item.quantity());
}
}
@Override
public void returnOrderItems(Order order) {
log.info("returnOrderItems: order={}", order);
for (OrderItem item : order.items()) {
inventoryService.addInventory(item.sku(), item.quantity());
}
}
@Override
public void dispatchOrderItems(Order order) {
log.info("deliverOrderItems: order={}", order);
for(OrderItem item : order.items()) {
inventoryService.addInventory(item.sku(), -item.quantity());
}
}
@Override
public PaymentAuthorization createPaymentRequest(Order order, BillingInfo billingInfo) {
log.info("createPaymentRequest: order={}, billingInfo={}", order, billingInfo);
var request = new PaymentAuthorization(
billingInfo,
PaymentStatus.PENDING,
order.orderId().toString(),
UUID.randomUUID().toString(),
null,
|
null);
return paymentService.processPaymentRequest(request);
}
@Override
public RefundRequest createRefundRequest(PaymentAuthorization payment) {
log.info("createRefundRequest: payment={}", payment);
return paymentService.createRefundRequest(payment);
}
@Override
public Shipping createShipping(Order order) {
return shippingService.createShipping(order);
}
@Override
public Shipping updateShipping(Shipping shipping, ShippingStatus status) {
return shippingService.updateStatus(shipping,status);
}
}
|
repos\tutorials-master\saas-modules\temporal\src\main\java\com\baeldung\temporal\workflows\sboot\order\activities\OrderActivitiesImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ProductLoader implements ApplicationListener<ContextRefreshedEvent> {
private ProductRepository productRepository;
private Logger log = LogManager.getLogger(ProductLoader.class);
@Autowired
public void setProductRepository(ProductRepository productRepository) {
this.productRepository = productRepository;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
Product shirt = new Product();
shirt.setDescription("Spring Framework Guru Shirt");
|
shirt.setPrice(new BigDecimal("18.95"));
shirt.setImageUrl("https://springframework.guru/wp-content/uploads/2015/04/spring_framework_guru_shirt-rf412049699c14ba5b68bb1c09182bfa2_8nax2_512.jpg");
shirt.setProductId("235268845711068308");
productRepository.save(shirt);
log.info("Saved Shirt - id: " + shirt.getId());
Product mug = new Product();
mug.setDescription("Spring Framework Guru Mug");
mug.setImageUrl("https://springframework.guru/wp-content/uploads/2015/04/spring_framework_guru_coffee_mug-r11e7694903c348e1a667dfd2f1474d95_x7j54_8byvr_512.jpg");
mug.setProductId("168639393495335947");
mug.setPrice(new BigDecimal("11.95"));
productRepository.save(mug);
log.info("Saved Mug - id:" + mug.getId());
}
}
|
repos\springbootwebapp-master\src\main\java\guru\springframework\bootstrap\ProductLoader.java
| 2
|
请完成以下Java代码
|
default @Nullable AcknowledgeMode getAckMode() {
return null;
}
/**
* Return a {@link ReplyPostProcessor} to post process a reply message before it is
* sent.
* @return the post processor.
* @since 2.2.5
*/
default @Nullable ReplyPostProcessor getReplyPostProcessor() {
return null;
}
/**
* Get the reply content type.
* @return the content type.
* @since 2.3
|
*/
default @Nullable String getReplyContentType() {
return null;
}
/**
* Return whether the content type set by a converter prevails or not.
* @return false to always apply the reply content type.
* @since 2.3
*/
default boolean isConverterWinsContentType() {
return true;
}
}
|
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\listener\RabbitListenerEndpoint.java
| 1
|
请完成以下Spring Boot application配置
|
spring.datasource.url=jdbc:h2:mem:mydb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.defer-datasource-initialization=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.validator.apply_to_ddl=false
spring.jpa.properti
|
es.hibernate.globally_quoted_identifiers=true
#spring.jpa.properties.hibernate.check_nullability=true
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
|
repos\tutorials-master\persistence-modules\spring-boot-persistence-h2\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public PageData<AuditLog> findAuditLogsByTenantId(UUID tenantId, List<ActionType> actionTypes, TimePageLink pageLink) {
return DaoUtil.toPageData(
auditLogRepository.findByTenantId(
tenantId,
pageLink.getTextSearch(),
pageLink.getStartTime(),
pageLink.getEndTime(),
actionTypes,
DaoUtil.toPageable(pageLink)));
}
@Override
public void cleanUpAuditLogs(long expTime) {
partitioningRepository.dropPartitionsBefore(AUDIT_LOG_TABLE_NAME, expTime, TimeUnit.HOURS.toMillis(partitionSizeInHours));
}
@Override
|
public void createPartition(AuditLogEntity entity) {
partitioningRepository.createPartitionIfNotExists(AUDIT_LOG_TABLE_NAME, entity.getCreatedTime(), TimeUnit.HOURS.toMillis(partitionSizeInHours));
}
@Override
protected Class<AuditLogEntity> getEntityClass() {
return AuditLogEntity.class;
}
@Override
protected JpaRepository<AuditLogEntity, UUID> getRepository() {
return auditLogRepository;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\audit\JpaAuditLogDao.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getColumnValue(Row row) {
if (row.isNull(index)) {
if (this.type == CassandraToSqlColumnType.BOOLEAN && !this.allowNullBoolean) {
return Boolean.toString(false);
} else {
return null;
}
} else {
switch (this.type) {
case ID:
return UUIDConverter.fromTimeUUID(row.getUuid(index));
case DOUBLE:
return Double.toString(row.getDouble(index));
case INTEGER:
return Integer.toString(row.getInt(index));
case FLOAT:
return Float.toString(row.getFloat(index));
case BIGINT:
return Long.toString(row.getLong(index));
case BOOLEAN:
return Boolean.toString(row.getBoolean(index));
case STRING:
case JSON:
case ENUM_TO_INT:
default:
String value = row.getString(index);
return this.replaceNullChars(value);
}
}
}
public void setColumnValue(PreparedStatement sqlInsertStatement, String value) throws SQLException {
if (value == null) {
sqlInsertStatement.setNull(this.sqlIndex, this.sqlType);
} else {
switch (this.type) {
case DOUBLE:
sqlInsertStatement.setDouble(this.sqlIndex, Double.parseDouble(value));
break;
case INTEGER:
sqlInsertStatement.setInt(this.sqlIndex, Integer.parseInt(value));
break;
case FLOAT:
sqlInsertStatement.setFloat(this.sqlIndex, Float.parseFloat(value));
break;
case BIGINT:
sqlInsertStatement.setLong(this.sqlIndex, Long.parseLong(value));
break;
|
case BOOLEAN:
sqlInsertStatement.setBoolean(this.sqlIndex, Boolean.parseBoolean(value));
break;
case ENUM_TO_INT:
@SuppressWarnings("unchecked")
Enum<?> enumVal = Enum.valueOf(this.enumClass, value);
int intValue = enumVal.ordinal();
sqlInsertStatement.setInt(this.sqlIndex, intValue);
break;
case JSON:
case STRING:
case ID:
default:
sqlInsertStatement.setString(this.sqlIndex, value);
break;
}
}
}
private String replaceNullChars(String strValue) {
if (strValue != null) {
return PATTERN_THREAD_LOCAL.get().matcher(strValue).replaceAll(EMPTY_STR);
}
return strValue;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\install\migrate\CassandraToSqlColumn.java
| 2
|
请完成以下Java代码
|
public class JavaSecurityPemUtils {
public static RSAPrivateKey readPKCS8PrivateKey(File file) throws GeneralSecurityException, IOException {
String key = new String(Files.readAllBytes(file.toPath()), Charset.defaultCharset());
String privateKeyPEM = key
.replace("-----BEGIN PRIVATE KEY-----", "")
.replaceAll(System.lineSeparator(), "")
.replace("-----END PRIVATE KEY-----", "");
byte[] encoded = Base64.decodeBase64(privateKeyPEM);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
}
|
public static RSAPublicKey readX509PublicKey(File file) throws GeneralSecurityException, IOException {
String key = new String(Files.readAllBytes(file.toPath()), Charset.defaultCharset());
String publicKeyPEM = key
.replace("-----BEGIN PUBLIC KEY-----", "")
.replaceAll(System.lineSeparator(), "")
.replace("-----END PUBLIC KEY-----", "");
byte[] encoded = Base64.decodeBase64(publicKeyPEM);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encoded);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
}
}
|
repos\tutorials-master\core-java-modules\core-java-security\src\main\java\com\baeldung\pem\JavaSecurityPemUtils.java
| 1
|
请完成以下Java代码
|
public void addTransactionListener(TransactionState transactionState, TransactionListener transactionListener) {
if (stateTransactionListeners==null) {
stateTransactionListeners = new HashMap<TransactionState, List<TransactionListener>>();
}
List<TransactionListener> transactionListeners = stateTransactionListeners.get(transactionState);
if (transactionListeners==null) {
transactionListeners = new ArrayList<TransactionListener>();
stateTransactionListeners.put(transactionState, transactionListeners);
}
transactionListeners.add(transactionListener);
}
public void commit() {
LOG.debugTransactionOperation("firing event committing...");
fireTransactionEvent(TransactionState.COMMITTING);
LOG.debugTransactionOperation("committing the persistence session...");
getPersistenceProvider().commit();
LOG.debugTransactionOperation("firing event committed...");
fireTransactionEvent(TransactionState.COMMITTED);
}
protected void fireTransactionEvent(TransactionState transactionState) {
this.setLastTransactionState(transactionState);
if (stateTransactionListeners==null) {
return;
}
List<TransactionListener> transactionListeners = stateTransactionListeners.get(transactionState);
if (transactionListeners==null) {
return;
}
for (TransactionListener transactionListener: transactionListeners) {
transactionListener.execute(commandContext);
}
}
protected void setLastTransactionState(TransactionState transactionState) {
this.lastTransactionState = transactionState;
}
private PersistenceSession getPersistenceProvider() {
return commandContext.getSession(PersistenceSession.class);
}
public void rollback() {
try {
try {
LOG.debugTransactionOperation("firing event rollback...");
|
fireTransactionEvent(TransactionState.ROLLINGBACK);
}
catch (Throwable exception) {
LOG.exceptionWhileFiringEvent(TransactionState.ROLLINGBACK, exception);
Context.getCommandInvocationContext().trySetThrowable(exception);
}
finally {
LOG.debugTransactionOperation("rolling back the persistence session...");
getPersistenceProvider().rollback();
}
}
catch (Throwable exception) {
LOG.exceptionWhileFiringEvent(TransactionState.ROLLINGBACK, exception);
Context.getCommandInvocationContext().trySetThrowable(exception);
}
finally {
LOG.debugFiringEventRolledBack();
fireTransactionEvent(TransactionState.ROLLED_BACK);
}
}
public boolean isTransactionActive() {
return !TransactionState.ROLLINGBACK.equals(lastTransactionState) && !TransactionState.ROLLED_BACK.equals(lastTransactionState);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\standalone\StandaloneTransactionContext.java
| 1
|
请完成以下Java代码
|
protected boolean beforeSave(boolean newRecord)
{
if (newRecord && getParent().isComplete())
{
throw new AdempiereException("@ParentComplete@ @DD_OrderLine_ID@");
}
// Get Defaults from Parent
/*
* if (getC_BPartner_ID() == 0 || getC_BPartner_Location_ID() == 0
* || getM_Warehouse_ID() == 0)
* setOrder (getParent());
*/
// if (m_M_PriceList_ID == 0)
// setHeaderInfo(getParent());
// R/O Check - Product/Warehouse Change
if (!newRecord
&& (is_ValueChanged("M_Product_ID") || is_ValueChanged("M_Locator_ID") || is_ValueChanged("M_LocatorTo_ID")))
{
if (!canChangeWarehouse())
{
throw new AdempiereException("Changing product/locator is not allowed");
}
} // Product Changed
// Charge
if (getC_Charge_ID() != 0 && getM_Product_ID() != 0)
setM_Product_ID(0);
// No Product
if (getM_Product_ID() == 0)
setM_AttributeSetInstance_ID(0);
// Product
// UOM
if (getC_UOM_ID() == 0
&& (getM_Product_ID() != 0
|| getC_Charge_ID() != 0))
{
int C_UOM_ID = MUOM.getDefault_UOM_ID(getCtx());
if (C_UOM_ID > 0)
setC_UOM_ID(C_UOM_ID);
}
// Qty Precision
if (newRecord || is_ValueChanged(COLUMNNAME_QtyEntered))
setQtyEntered(getQtyEntered());
if (newRecord || is_ValueChanged(COLUMNNAME_QtyOrdered))
setQtyOrdered(getQtyOrdered());
// FreightAmt Not used
if (BigDecimal.ZERO.compareTo(getFreightAmt()) != 0)
setFreightAmt(BigDecimal.ZERO);
// Get Line No
if (getLine() == 0)
{
|
String sql = "SELECT COALESCE(MAX(Line),0)+10 FROM DD_OrderLine WHERE DD_Order_ID=?";
int ii = DB.getSQLValue(get_TrxName(), sql, getDD_Order_ID());
setLine(ii);
}
return true;
} // beforeSave
/**
* Before Delete
*
* @return true if it can be deleted
*/
@Override
protected boolean beforeDelete()
{
// R/O Check - Something delivered. etc.
if (getQtyDelivered().signum() != 0)
{
throw new AdempiereException("@QtyDelivered@: " + getQtyDelivered());
}
if (getQtyReserved().signum() != 0)
{
// For PO should be On Order
throw new AdempiereException("@QtyReserved@: " + getQtyReserved());
}
return true;
} // beforeDelete
} // MDDOrderLine
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\eevolution\model\MDDOrderLine.java
| 1
|
请完成以下Java代码
|
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* ReplicationTrxStatus AD_Reference_ID=540491
* Reference name: EXP_ReplicationTrxStatus
*/
public static final int REPLICATIONTRXSTATUS_AD_Reference_ID=540491;
/** Vollständig = Completed */
public static final String REPLICATIONTRXSTATUS_Vollstaendig = "Completed";
/** Nicht vollständig importiert = ImportedWithIssues */
public static final String REPLICATIONTRXSTATUS_NichtVollstaendigImportiert = "ImportedWithIssues";
/** Fehler = Failed */
public static final String REPLICATIONTRXSTATUS_Fehler = "Failed";
|
/** Set Replikationsstatus.
@param ReplicationTrxStatus Replikationsstatus */
@Override
public void setReplicationTrxStatus (java.lang.String ReplicationTrxStatus)
{
set_Value (COLUMNNAME_ReplicationTrxStatus, ReplicationTrxStatus);
}
/** Get Replikationsstatus.
@return Replikationsstatus */
@Override
public java.lang.String getReplicationTrxStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_ReplicationTrxStatus);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\process\rpl\model\X_EXP_ReplicationTrxLine.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.