instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public ManagementService getManagementService() {
return managementService;
}
@Override
public TaskService getTaskService() {
return taskService;
}
@Override
public HistoryService getHistoryService() {
return historicDataService;
}
@Override
public RuntimeService getRuntimeService() {
return runtimeService;
}
@Override
public RepositoryService getRepositoryService() {
return repositoryService;
}
@Override
public FormService getFormService() {
return formService;
}
@Override
public AuthorizationService getAuthorizationService() {
return authorizationService;
}
@Override
public CaseService getCaseService() {
return caseService;
|
}
@Override
public FilterService getFilterService() {
return filterService;
}
@Override
public ExternalTaskService getExternalTaskService() {
return externalTaskService;
}
@Override
public DecisionService getDecisionService() {
return decisionService;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessEngineImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getRoleId() {
return roleId;
}
|
public void setRoleId(String roleId) {
this.roleId = roleId;
}
@Override
public String toString() {
return "AdminCreateReq{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", phone='" + phone + '\'' +
", roleId='" + roleId + '\'' +
'}';
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\user\AdminCreateReq.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyAuthenticationSucessHandler authenticationSucessHandler;
@Autowired
private MyAuthenticationFailureHandler authenticationFailureHandler;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
|
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() // 表单登录
// http.httpBasic() // HTTP Basic
.loginPage("/authentication/require") // 登录跳转 URL
.loginProcessingUrl("/login") // 处理表单登录 URL
.successHandler(authenticationSucessHandler) // 处理登录成功
.failureHandler(authenticationFailureHandler) // 处理登录失败
.and()
.authorizeRequests() // 授权配置
.antMatchers("/authentication/require", "/login.html").permitAll() // 登录跳转 URL 无需认证
.anyRequest() // 所有请求
.authenticated() // 都需要认证
.and().csrf().disable();
}
}
|
repos\SpringAll-master\35.Spring-Security-Authentication\src\main\java\cc\mrbird\security\browser\BrowserSecurityConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void setProtocols(final String protocols) {
if (protocols == null) {
this.protocols = null;
} else {
this.protocols = protocols.split("[ :,]");
}
}
// --------------------------------------------------
/**
* Copies the defaults from the given configuration. Values are considered "default" if they are null. Please
* note that the getters might return fallback values instead.
*
* @param config The config to copy the defaults from.
*/
public void copyDefaultsFrom(final Security config) {
if (this == config) {
return;
}
if (this.clientAuthEnabled == null) {
this.clientAuthEnabled = config.clientAuthEnabled;
}
if (this.certificateChain == null) {
this.certificateChain = config.certificateChain;
}
if (this.privateKey == null) {
this.privateKey = config.privateKey;
}
if (this.privateKeyPassword == null) {
this.privateKeyPassword = config.privateKeyPassword;
}
if (this.keyStoreFormat == null) {
this.keyStoreFormat = config.keyStoreFormat;
}
if (this.keyStore == null) {
this.keyStore = config.keyStore;
}
if (this.keyStorePassword == null) {
this.keyStorePassword = config.keyStorePassword;
}
if (this.trustCertCollection == null) {
this.trustCertCollection = config.trustCertCollection;
}
|
if (this.trustStoreFormat == null) {
this.trustStoreFormat = config.trustStoreFormat;
}
if (this.trustStore == null) {
this.trustStore = config.trustStore;
}
if (this.trustStorePassword == null) {
this.trustStorePassword = config.trustStorePassword;
}
if (this.authorityOverride == null) {
this.authorityOverride = config.authorityOverride;
}
if (this.ciphers == null) {
this.ciphers = config.ciphers;
}
if (this.protocols == null) {
this.protocols = config.protocols;
}
}
}
}
|
repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\config\GrpcChannelProperties.java
| 2
|
请完成以下Java代码
|
private static long buildExpiresOn(Clock clock) {
return clock.instant().plusSeconds(SAS_TOKEN_VALID_SECS).getEpochSecond();
}
public static String getDefaultCaCert() {
byte[] fileBytes;
if (Files.exists(FULL_FILE_PATH)) {
try {
fileBytes = Files.readAllBytes(FULL_FILE_PATH);
} catch (IOException e) {
log.error("Failed to load Default CaCert file!!! [{}]", FULL_FILE_PATH, e);
throw new RuntimeException("Failed to load Default CaCert file!!!");
}
} else {
Path azureDirectory = FULL_FILE_PATH.getParent();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(azureDirectory)) {
Iterator<Path> iterator = stream.iterator();
if (iterator.hasNext()) {
|
Path firstFile = iterator.next();
fileBytes = Files.readAllBytes(firstFile);
} else {
log.error("Default CaCert file not found in the directory [{}]!!!", azureDirectory);
throw new RuntimeException("Default CaCert file not found in the directory!!!");
}
} catch (IOException e) {
log.error("Failed to load Default CaCert file from the directory [{}]!!!", azureDirectory, e);
throw new RuntimeException("Failed to load Default CaCert file from the directory!!!");
}
}
return new String(fileBytes);
}
}
|
repos\thingsboard-master\common\util\src\main\java\org\thingsboard\common\util\AzureIotHubUtil.java
| 1
|
请完成以下Java代码
|
void update(char left, char right)
{
++frequency;
increaseFrequency(left, this.left);
increaseFrequency(right, this.right);
}
void computeProbabilityEntropy(int length)
{
p = frequency / (float) length;
leftEntropy = computeEntropy(left);
rightEntropy = computeEntropy(right);
entropy = Math.min(leftEntropy, rightEntropy);
}
void computeAggregation(Map<String, WordInfo> word_cands)
{
if (text.length() == 1)
|
{
aggregation = (float) Math.sqrt(p);
return;
}
for (int i = 1; i < text.length(); ++i)
{
aggregation = Math.min(aggregation,
p / word_cands.get(text.substring(0, i)).p / word_cands.get(text.substring(i)).p);
}
}
@Override
public String toString()
{
return text;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word\WordInfo.java
| 1
|
请完成以下Java代码
|
public void start() {
int randomNumber = generateRandomNumber();
while (!isFinished) {
waitASecond();
while (!isPaused && !isFinished) {
log.info("Current random number is " + randomNumber);
waitASecond();
for (Player player : players) {
int guess = player.guessNumber();
if (guess == randomNumber) {
log.info("Players " + player.getName() + " " + guess + " is correct");
player.incrementScore();
notifyAboutWinner(player);
randomNumber = generateRandomNumber();
break;
}
log.info("Player " + player.getName() + " guessed incorrectly with " + guess);
}
log.info("\n");
}
if (isPaused) {
log.info("Game is paused");
}
if (isFinished) {
log.info("Game is finished");
}
}
}
@Override
public void finishGame() {
isFinished = true;
}
@Override
public void pauseGame() {
isPaused = true;
}
|
@Override
public void unpauseGame() {
isPaused = false;
}
public List<Player> getPlayers() {
return players;
}
private void waitASecond() {
try {
Thread.sleep(SECOND);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-perf-2\src\main\java\com\baeldung\jmxterm\GuessGame.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void insert(SuspendedJobEntity jobEntity, boolean fireCreateEvent) {
if (serviceConfiguration.getInternalJobManager() != null) {
serviceConfiguration.getInternalJobManager().handleJobInsert(jobEntity);
}
jobEntity.setCreateTime(getClock().getCurrentTime());
if (jobEntity.getCorrelationId() == null) {
jobEntity.setCorrelationId(serviceConfiguration.getIdGenerator().getNextId());
}
super.insert(jobEntity, fireCreateEvent);
}
@Override
public void insert(SuspendedJobEntity jobEntity) {
insert(jobEntity, true);
}
@Override
public void delete(SuspendedJobEntity jobEntity) {
delete(jobEntity, false);
deleteByteArrayRef(jobEntity.getExceptionByteArrayRef());
deleteByteArrayRef(jobEntity.getCustomValuesByteArrayRef());
// Send event
if (getEventDispatcher() != null && getEventDispatcher().isEnabled()) {
getEventDispatcher().dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, jobEntity),
serviceConfiguration.getEngineName());
}
}
@Override
public void delete(SuspendedJobEntity jobEntity, boolean fireDeleteEvent) {
if (serviceConfiguration.getInternalJobManager() != null) {
serviceConfiguration.getInternalJobManager().handleJobDelete(jobEntity);
}
super.delete(jobEntity, fireDeleteEvent);
}
protected SuspendedJobEntity createSuspendedJob(AbstractRuntimeJobEntity job) {
|
SuspendedJobEntity newSuspendedJobEntity = create();
newSuspendedJobEntity.setJobHandlerConfiguration(job.getJobHandlerConfiguration());
newSuspendedJobEntity.setCustomValues(job.getCustomValues());
newSuspendedJobEntity.setJobHandlerType(job.getJobHandlerType());
newSuspendedJobEntity.setExclusive(job.isExclusive());
newSuspendedJobEntity.setRepeat(job.getRepeat());
newSuspendedJobEntity.setRetries(job.getRetries());
newSuspendedJobEntity.setEndDate(job.getEndDate());
newSuspendedJobEntity.setExecutionId(job.getExecutionId());
newSuspendedJobEntity.setProcessInstanceId(job.getProcessInstanceId());
newSuspendedJobEntity.setProcessDefinitionId(job.getProcessDefinitionId());
newSuspendedJobEntity.setScopeId(job.getScopeId());
newSuspendedJobEntity.setSubScopeId(job.getSubScopeId());
newSuspendedJobEntity.setScopeType(job.getScopeType());
newSuspendedJobEntity.setScopeDefinitionId(job.getScopeDefinitionId());
// Inherit tenant
newSuspendedJobEntity.setTenantId(job.getTenantId());
newSuspendedJobEntity.setJobType(job.getJobType());
return newSuspendedJobEntity;
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\SuspendedJobEntityManagerImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Builder setSQLStatement(final String sqlStatement)
{
this.sqlStatement = sqlStatement;
return this;
}
public Builder setApplySecuritySettings(final boolean applySecuritySettings)
{
this.applySecuritySettings = applySecuritySettings;
return this;
}
private ImmutableList<ProcessInfoParameter> getProcessInfoParameters()
{
return Services.get(IADPInstanceDAO.class).retrieveProcessInfoParameters(pinstanceId)
.stream()
.map(this::transformProcessInfoParameter)
.collect(ImmutableList.toImmutableList());
}
private ProcessInfoParameter transformProcessInfoParameter(final ProcessInfoParameter piParam)
{
//
// Corner case: REPORT_SQL_QUERY
|
// => replace @AD_PInstance_ID@ placeholder with actual value
if (ReportConstants.REPORT_PARAM_SQL_QUERY.equals(piParam.getParameterName()))
{
final String parameterValue = piParam.getParameterAsString();
if (parameterValue != null)
{
final String parameterValueEffective = parameterValue.replace(ReportConstants.REPORT_PARAM_SQL_QUERY_AD_PInstance_ID_Placeholder, String.valueOf(pinstanceId.getRepoId()));
return ProcessInfoParameter.of(ReportConstants.REPORT_PARAM_SQL_QUERY, parameterValueEffective);
}
}
//
// Default: don't touch the original parameter
return piParam;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\server\ReportContext.java
| 2
|
请完成以下Java代码
|
public String toString() {
return "Department{" +
"id=" + id +
", departmentName='" + departmentName + '\'' +
", manager=" + manager +
'}';
}
public StructDepartment(String departmentName, StructManager manager) {
this.departmentName = departmentName;
this.manager = manager;
}
public Integer getId() {
return id;
}
|
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public StructManager getManager() {
return manager;
}
public void setManager(StructManager manager) {
this.manager = manager;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-jpa-2\src\main\java\com\baeldung\hibernate\struct\entities\StructDepartment.java
| 1
|
请完成以下Java代码
|
protected Map<String, String> extractExternalSystemParameters(@NonNull final ExternalSystemParentConfig externalSystemParentConfig)
{
final ExternalSystemWooCommerceConfig woocommerceConfig = ExternalSystemWooCommerceConfig.cast(externalSystemParentConfig.getChildConfig());
if (EmptyUtil.isEmpty(woocommerceConfig.getCamelHttpResourceAuthKey()))
{
throw new AdempiereException("camelHttpResourceAuthKey for childConfig should not be empty at this point")
.appendParametersToMessage()
.setParameter("childConfigId", woocommerceConfig.getId());
}
final Map<String, String> parameters = new HashMap<>();
parameters.put(PARAM_CAMEL_HTTP_RESOURCE_AUTH_KEY, woocommerceConfig.getCamelHttpResourceAuthKey());
parameters.put(PARAM_CHILD_CONFIG_VALUE, woocommerceConfig.getValue());
return parameters;
}
@Override
protected String getTabName()
|
{
return ExternalSystemType.WOO.getValue();
}
@Override
protected ExternalSystemType getExternalSystemType()
{
return ExternalSystemType.WOO;
}
@Override
protected long getSelectedRecordCount(@NonNull final IProcessPreconditionsContext context)
{
return context.getSelectedIncludedRecords()
.stream()
.filter(recordRef -> I_ExternalSystem_Config_WooCommerce.Table_Name.equals(recordRef.getTableName()))
.count();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\InvokeWooCommerceAction.java
| 1
|
请完成以下Java代码
|
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
return producer.createTaskInstanceCompleteEvt(taskEntity, deleteReason);
}
});
}
}
public void createHistoricTask(final TaskEntity task) {
ProcessEngineConfigurationImpl configuration = Context.getProcessEngineConfiguration();
HistoryLevel historyLevel = configuration.getHistoryLevel();
if(historyLevel.isHistoryEventProduced(HistoryEventTypes.TASK_INSTANCE_CREATE, task)) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
return producer.createTaskInstanceCreateEvt(task);
}
});
}
}
|
protected void configureQuery(final HistoricTaskInstanceQueryImpl query) {
getAuthorizationManager().configureHistoricTaskInstanceQuery(query);
getTenantManager().configureQuery(query);
}
public DbOperation deleteHistoricTaskInstancesByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("removalTime", removalTime);
if (minuteTo - minuteFrom + 1 < 60) {
parameters.put("minuteFrom", minuteFrom);
parameters.put("minuteTo", minuteTo);
}
parameters.put("batchSize", batchSize);
return getDbEntityManager()
.deletePreserveOrder(HistoricTaskInstanceEntity.class, "deleteHistoricTaskInstancesByRemovalTime",
new ListQueryParameterObject(parameters, 0, batchSize));
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricTaskInstanceManager.java
| 1
|
请完成以下Java代码
|
public Optional<HUReservation> getByDocumentRef(
@NonNull final HUReservationDocRef documentRef,
@Nullable final ImmutableSet<HuId> onlyHuIds)
{
if (onlyHuIds == null)
{
return getByDocumentRef(documentRef);
}
return huReservationRepository.getByDocumentRef(documentRef, onlyHuIds);
}
@NonNull
public Optional<HUReservation> getByDocumentRef(@NonNull final HUReservationDocRef documentRef)
{
return huReservationRepository.getByDocumentRef(documentRef, ImmutableSet.of());
}
public ImmutableSet<HuId> getVHUIdsByDocumentRef(@NonNull final HUReservationDocRef documentRef)
{
return getByDocumentRef(documentRef).map(HUReservation::getVhuIds).orElseGet(ImmutableSet::of);
}
public ImmutableList<HUReservationEntry> getEntriesByVHUIds(@NonNull final Collection<HuId> vhuIds)
{
return huReservationRepository.getEntriesByVHUIds(vhuIds);
}
public boolean isAnyOfVHUIdsReserved(@NonNull final Collection<HuId> vhuIds)
{
return !huReservationRepository.getEntriesByVHUIds(vhuIds).isEmpty();
}
@Builder(builderMethodName = "prepareHUQuery", builderClassName = "AvailableHUQueryBuilder")
private IHUQueryBuilder createHUQuery(
@NonNull final WarehouseId warehouseId,
@NonNull final ProductId productId,
@NonNull final BPartnerId bpartnerId,
@Nullable final AttributeSetInstanceId asiId,
@Nullable final HUReservationDocRef reservedToDocumentOrNotReservedAtAll)
{
final Set<WarehouseId> pickingWarehouseIds = warehousesRepo.getWarehouseIdsOfSamePickingGroup(warehouseId);
final IHUQueryBuilder huQuery = handlingUnitsDAO
.createHUQueryBuilder()
.addOnlyInWarehouseIds(pickingWarehouseIds)
.addOnlyWithProductId(productId)
.addHUStatusToInclude(X_M_HU.HUSTATUS_Active);
// ASI
|
if (asiId != null)
{
final ImmutableAttributeSet attributeSet = asiBL.getImmutableAttributeSetById(asiId);
huQuery.addOnlyWithAttributeValuesMatchingPartnerAndProduct(bpartnerId, productId, attributeSet);
huQuery.allowSqlWhenFilteringAttributes(isAllowSqlWhenFilteringHUAttributes());
}
// Reservation
if (reservedToDocumentOrNotReservedAtAll == null)
{
huQuery.setExcludeReserved();
}
else
{
huQuery.setExcludeReservedToOtherThan(reservedToDocumentOrNotReservedAtAll);
}
return huQuery;
}
// FIXME: move it to AttributeDAO
@Deprecated
public boolean isAllowSqlWhenFilteringHUAttributes()
{
return sysConfigBL.getBooleanValue(SYSCONFIG_AllowSqlWhenFilteringHUAttributes, true);
}
public void transferReservation(
@NonNull final HUReservationDocRef from,
@NonNull final HUReservationDocRef to,
@NonNull final Set<HuId> vhuIds)
{
huReservationRepository.transferReservation(ImmutableSet.of(from), to, vhuIds);
}
public void transferReservation(
@NonNull final Collection<HUReservationDocRef> from,
@NonNull final HUReservationDocRef to)
{
final Set<HuId> vhuIds = ImmutableSet.of();
huReservationRepository.transferReservation(from, to, vhuIds);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\reservation\HUReservationService.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("\n\nREAD-WRITE MODE:");
bookstoreService.fetchAuthorReadWriteMode();
System.out.println("\n\nREAD-ONLY MODE:");
bookstoreService.fetchAuthorReadOnlyMode();
System.out.println("\n\nREAD-WRITE MODE (DTO):");
bookstoreService.fetchAuthorDtoReadWriteMode();
System.out.println("\n\nREAD-ONLY MODE (DTO):");
bookstoreService.fetchAuthorDtoReadOnlyMode();
};
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootTransactionalReadOnlyMeaning\src\main\java\com\bookstore\MainApplication.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class ColumnNameFQ
{
@NonNull TableName tableName;
@NonNull ColumnName columnName;
public static ColumnNameFQ ofTableAndColumnName(@NonNull final String tableName, @NonNull final String columnName)
{
return new ColumnNameFQ(TableName.ofString(tableName), ColumnName.ofString(columnName));
}
public static ColumnNameFQ ofTableAndColumnName(@NonNull final TableName tableName, @NonNull final String columnName)
{
return new ColumnNameFQ(tableName, ColumnName.ofString(columnName));
}
public static ColumnNameFQ ofTableAndColumnName(@NonNull final TableName tableName, @NonNull final ColumnName columnName)
{
return new ColumnNameFQ(tableName, columnName);
}
private ColumnNameFQ(@NonNull final TableName tableName, @NonNull final ColumnName columnName)
{
this.tableName = tableName;
this.columnName = columnName;
}
@Override
@Deprecated
public String toString()
{
return getAsString();
}
public String getAsString()
{
return tableName.getAsString() + "." + columnName.getAsString();
}
public static TableName extractSingleTableName(final ColumnNameFQ... columnNames)
{
if (columnNames == null || columnNames.length == 0)
{
throw new AdempiereException("Cannot extract table name from null/empty column names array");
}
TableName singleTableName = null;
|
for (final ColumnNameFQ columnNameFQ : columnNames)
{
if (columnNameFQ == null)
{
continue;
}
else if (singleTableName == null)
{
singleTableName = columnNameFQ.getTableName();
}
else if (!TableName.equals(singleTableName, columnNameFQ.getTableName()))
{
throw new AdempiereException("More than one table name found in " + Arrays.asList(columnNames));
}
}
if (singleTableName == null)
{
throw new AdempiereException("Cannot extract table name from null/empty column names array: " + Arrays.asList(columnNames));
}
return singleTableName;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\api\ColumnNameFQ.java
| 2
|
请完成以下Java代码
|
public void setDiagramResourceName(String diagramResourceName) {
this.diagramResourceName = diagramResourceName;
}
@Override
public void setHasStartFormKey(boolean hasStartFormKey) {
this.hasStartFormKey = hasStartFormKey;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public List<IdentityLinkEntity> getIdentityLinks() {
if (!isIdentityLinksInitialized) {
definitionIdentityLinkEntities = CommandContextUtil.getCmmnEngineConfiguration().getIdentityLinkServiceConfiguration()
.getIdentityLinkService().findIdentityLinksByScopeDefinitionIdAndType(id, ScopeTypes.CMMN);
isIdentityLinksInitialized = true;
}
return definitionIdentityLinkEntities;
}
public String getLocalizedName() {
return localizedName;
|
}
@Override
public void setLocalizedName(String localizedName) {
this.localizedName = localizedName;
}
public String getLocalizedDescription() {
return localizedDescription;
}
@Override
public void setLocalizedDescription(String localizedDescription) {
this.localizedDescription = localizedDescription;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\CaseDefinitionEntityImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CrmApplication {
public static void main(String[] args) {
SpringApplication.run(CrmApplication.class, args);
}
// tag::runner[]
@Bean
ApplicationRunner runner(CustomerRepository customerRepository) {
return args -> {
assertThat(customerRepository.count()).isEqualTo(0);
Customer jonDoe = Customer.newCustomer(1L, "JonDoe");
System.err.printf("Saving Customer [%s]...%n", jonDoe);
jonDoe = customerRepository.save(jonDoe);
assertThat(jonDoe).isNotNull();
assertThat(jonDoe.getId()).isEqualTo(1L);
|
assertThat(jonDoe.getName()).isEqualTo("JonDoe");
assertThat(customerRepository.count()).isEqualTo(1);
System.err.println("Querying for Customer [SELECT * FROM /Customers WHERE name LIKE '%Doe']...");
Customer queriedJonDoe = customerRepository.findByNameLike("%Doe");
assertThat(queriedJonDoe).isEqualTo(jonDoe);
System.err.printf("Customer was [%s]%n", queriedJonDoe);
};
}
// end::runner[]
}
// end::class[]
|
repos\spring-boot-data-geode-main\spring-geode-samples\intro\getting-started\src\main\java\example\app\crm\CrmApplication.java
| 2
|
请完成以下Java代码
|
protected static class PartitionRegionCacheStatistics implements CacheStatistics {
private final PartitionedRegion partitionRegion;
private float hitRatio = 0.0f;
private long hitCount = 0L;
private long lastAccessedTime = 0L;
private long lastModifiedTime = 0L;
private long missCount = 0L;
protected PartitionRegionCacheStatistics(Region<?, ?> region) {
Assert.isInstanceOf(PartitionedRegion.class, region, () ->
String.format("Region [%1$s] must be of type [%2$s]", RegionUtils.toRegionPath(region),
PartitionedRegion.class.getName()));
this.partitionRegion = computeStatistics((PartitionedRegion) region);
}
protected PartitionedRegion computeStatistics(PartitionedRegion region) {
float totalHitRatio = 0.0f;
int totalCount = 0;
long totalHitCount = 0L;
long maxLastAccessedTime = 0L;
long maxLastModifiedTime = 0L;
long totalMissCount = 0L;
Set<BucketRegion> bucketRegions = Optional.of(region)
.map(PartitionedRegion::getDataStore)
.map(PartitionedRegionDataStore::getAllLocalBucketRegions)
.orElseGet(Collections::emptySet);
for (BucketRegion bucket : bucketRegions) {
CacheStatistics bucketStatistics = bucket.getStatistics();
if (bucketStatistics != null) {
totalCount++;
totalHitCount += bucketStatistics.getHitCount();
totalHitRatio += bucketStatistics.getHitRatio();
maxLastAccessedTime = Math.max(maxLastAccessedTime, bucketStatistics.getLastAccessedTime());
maxLastModifiedTime = Math.max(maxLastModifiedTime, bucketStatistics.getLastModifiedTime());
totalMissCount += bucketStatistics.getMissCount();
}
}
if (totalCount > 0) {
this.hitCount = totalHitCount / totalCount;
this.hitRatio = totalHitRatio / totalCount;
this.lastAccessedTime = maxLastAccessedTime;
this.lastModifiedTime = maxLastModifiedTime;
this.missCount = totalMissCount / totalCount;
}
return region;
}
protected PartitionedRegion getPartitionRegion() {
return this.partitionRegion;
}
@Override
|
public long getHitCount() throws StatisticsDisabledException {
return this.hitCount;
}
@Override
public float getHitRatio() throws StatisticsDisabledException {
return this.hitRatio;
}
@Override
public long getLastAccessedTime() throws StatisticsDisabledException {
return this.lastAccessedTime;
}
@Override
public long getLastModifiedTime() {
return this.lastModifiedTime;
}
@Override
public long getMissCount() throws StatisticsDisabledException {
return this.missCount;
}
@Override
public void resetCounts() throws StatisticsDisabledException {
this.hitCount = 0L;
this.hitRatio = 0.0f;
this.lastAccessedTime = 0L;
this.lastModifiedTime = 0L;
this.missCount = 0L;
}
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-actuator\src\main\java\org\springframework\geode\boot\actuate\health\support\RegionStatisticsResolver.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected void setEntityFields(Asset entity, Map<BulkImportColumnType, String> fields) {
ObjectNode additionalInfo = getOrCreateAdditionalInfoObj(entity);
fields.forEach((columnType, value) -> {
switch (columnType) {
case NAME:
entity.setName(value);
break;
case TYPE:
entity.setType(value);
break;
case LABEL:
entity.setLabel(value);
break;
case DESCRIPTION:
additionalInfo.set("description", new TextNode(value));
break;
}
});
entity.setAdditionalInfo(additionalInfo);
}
@Override
@SneakyThrows
protected Asset saveEntity(SecurityUser user, Asset entity, Map<BulkImportColumnType, String> fields) {
AssetProfile assetProfile;
if (StringUtils.isNotEmpty(entity.getType())) {
assetProfile = assetProfileService.findOrCreateAssetProfile(entity.getTenantId(), entity.getType());
} else {
assetProfile = assetProfileService.findDefaultAssetProfile(entity.getTenantId());
}
entity.setAssetProfileId(assetProfile.getId());
return tbAssetService.save(entity, user);
}
|
@Override
protected Asset findOrCreateEntity(TenantId tenantId, String name) {
return Optional.ofNullable(assetService.findAssetByTenantIdAndName(tenantId, name))
.orElseGet(Asset::new);
}
@Override
protected void setOwners(Asset entity, SecurityUser user) {
entity.setTenantId(user.getTenantId());
entity.setCustomerId(user.getCustomerId());
}
@Override
protected EntityType getEntityType() {
return EntityType.ASSET;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\asset\AssetBulkImportService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getDecisionKey() {
return decisionKey;
}
public void setDecisionKey(String decisionKey) {
this.decisionKey = decisionKey;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getParentDeploymentId() {
return parentDeploymentId;
}
public void setParentDeploymentId(String parentDeploymentId) {
|
this.parentDeploymentId = parentDeploymentId;
}
public List<EngineRestVariable> getInputVariables() {
return inputVariables;
}
public void setInputVariables(List<EngineRestVariable> variables) {
this.inputVariables = variables;
}
public boolean isDisableHistory() {
return disableHistory;
}
public void setDisableHistory(boolean disableHistory) {
this.disableHistory = disableHistory;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-rest\src\main\java\org\flowable\dmn\rest\service\api\decision\DmnRuleServiceRequest.java
| 2
|
请完成以下Java代码
|
public void start() {
if (bufferPadSchedule != null) {
bufferPadSchedule.scheduleWithFixedDelay(() -> paddingBuffer(), scheduleInterval, scheduleInterval, TimeUnit.SECONDS);
}
}
/**
* Shutdown executors
*/
public void shutdown() {
if (!bufferPadExecutors.isShutdown()) {
bufferPadExecutors.shutdownNow();
}
if (bufferPadSchedule != null && !bufferPadSchedule.isShutdown()) {
bufferPadSchedule.shutdownNow();
}
}
/**
* Whether is padding
*
* @return
*/
public boolean isRunning() {
return running.get();
}
/**
* Padding buffer in the thread pool
*/
public void asyncPadding() {
bufferPadExecutors.submit(this::paddingBuffer);
}
/**
* Padding buffer fill the slots until to catch the cursor
*/
public void paddingBuffer() {
LOGGER.info("Ready to padding buffer lastSecond:{}. {}", lastSecond.get(), ringBuffer);
// is still running
if (!running.compareAndSet(false, true)) {
LOGGER.info("Padding buffer is still running. {}", ringBuffer);
|
return;
}
// fill the rest slots until to catch the cursor
boolean isFullRingBuffer = false;
while (!isFullRingBuffer) {
List<Long> uidList = uidProvider.provide(lastSecond.incrementAndGet());
for (Long uid : uidList) {
isFullRingBuffer = !ringBuffer.put(uid);
if (isFullRingBuffer) {
break;
}
}
}
// not running now
running.compareAndSet(true, false);
LOGGER.info("End to padding buffer lastSecond:{}. {}", lastSecond.get(), ringBuffer);
}
/**
* Setters
*/
public void setScheduleInterval(long scheduleInterval) {
Assert.isTrue(scheduleInterval > 0, "Schedule interval must positive!");
this.scheduleInterval = scheduleInterval;
}
}
|
repos\Spring-Boot-In-Action-master\id-spring-boot-starter\src\main\java\com\baidu\fsg\uid\buffer\BufferPaddingExecutor.java
| 1
|
请完成以下Java代码
|
public void clearProcessInstanceLockTime(String processInstanceId) {
HashMap<String, Object> params = new HashMap<>();
params.put("id", processInstanceId);
getDbSqlSession().directUpdate("clearProcessInstanceLockTime", params);
}
@Override
public void clearAllProcessInstanceLockTimes(String lockOwner) {
HashMap<String, Object> params = new HashMap<>();
params.put("lockOwner", lockOwner);
getDbSqlSession().directUpdate("clearAllProcessInstanceLockTimes", params);
}
protected void setSafeInValueLists(ExecutionQueryImpl executionQuery) {
if (executionQuery.getInvolvedGroups() != null) {
executionQuery.setSafeInvolvedGroups(createSafeInValuesList(executionQuery.getInvolvedGroups()));
}
if (executionQuery.getProcessInstanceIds() != null) {
executionQuery.setSafeProcessInstanceIds(createSafeInValuesList(executionQuery.getProcessInstanceIds()));
}
|
if (executionQuery.getOrQueryObjects() != null && !executionQuery.getOrQueryObjects().isEmpty()) {
for (ExecutionQueryImpl orExecutionQuery : executionQuery.getOrQueryObjects()) {
setSafeInValueLists(orExecutionQuery);
}
}
}
protected void setSafeInValueLists(ProcessInstanceQueryImpl processInstanceQuery) {
if (processInstanceQuery.getProcessInstanceIds() != null) {
processInstanceQuery.setSafeProcessInstanceIds(createSafeInValuesList(processInstanceQuery.getProcessInstanceIds()));
}
if (processInstanceQuery.getInvolvedGroups() != null) {
processInstanceQuery.setSafeInvolvedGroups(createSafeInValuesList(processInstanceQuery.getInvolvedGroups()));
}
if (processInstanceQuery.getOrQueryObjects() != null && !processInstanceQuery.getOrQueryObjects().isEmpty()) {
for (ProcessInstanceQueryImpl orProcessInstanceQuery : processInstanceQuery.getOrQueryObjects()) {
setSafeInValueLists(orProcessInstanceQuery);
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\data\impl\MybatisExecutionDataManager.java
| 1
|
请完成以下Java代码
|
public final class JwtClientAssertionAuthenticationConverter implements AuthenticationConverter {
private static final ClientAuthenticationMethod JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD = new ClientAuthenticationMethod(
"urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
@Nullable
@Override
public Authentication convert(HttpServletRequest request) {
MultiValueMap<String, String> parameters = OAuth2EndpointUtils.getFormParameters(request);
if (parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE) == null
|| parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION) == null) {
return null;
}
// client_assertion_type (REQUIRED)
String clientAssertionType = parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE);
if (parameters.get(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE).size() != 1) {
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST);
}
if (!JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD.getValue().equals(clientAssertionType)) {
return null;
}
// client_assertion (REQUIRED)
String jwtAssertion = parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION);
if (parameters.get(OAuth2ParameterNames.CLIENT_ASSERTION).size() != 1) {
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST);
}
|
// client_id (OPTIONAL as per specification but REQUIRED by this implementation)
String clientId = parameters.getFirst(OAuth2ParameterNames.CLIENT_ID);
if (!StringUtils.hasText(clientId) || parameters.get(OAuth2ParameterNames.CLIENT_ID).size() != 1) {
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST);
}
Map<String, Object> additionalParameters = OAuth2EndpointUtils
.getParametersIfMatchesAuthorizationCodeGrantRequest(request, OAuth2ParameterNames.CLIENT_ASSERTION_TYPE,
OAuth2ParameterNames.CLIENT_ASSERTION, OAuth2ParameterNames.CLIENT_ID);
return new OAuth2ClientAuthenticationToken(clientId, JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD, jwtAssertion,
additionalParameters);
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\web\authentication\JwtClientAssertionAuthenticationConverter.java
| 1
|
请完成以下Java代码
|
default FilterChain decorate(FilterChain original) {
return decorate(original, Collections.emptyList());
}
/**
* Provide a new {@link FilterChain} that accounts for the provided filters as
* well as the original filter chain.
* @param original the original {@link FilterChain}
* @param filters the security filters
* @return a security-enabled {@link FilterChain} that includes the provided
* filters
*/
FilterChain decorate(FilterChain original, List<Filter> filters);
}
/**
* A {@link FilterChainDecorator} that uses the {@link VirtualFilterChain}
*
* @author Josh Cummings
* @since 6.0
*/
public static final class VirtualFilterChainDecorator implements FilterChainDecorator {
/**
* {@inheritDoc}
*/
@Override
public FilterChain decorate(FilterChain original) {
return original;
}
/**
* {@inheritDoc}
*/
@Override
public FilterChain decorate(FilterChain original, List<Filter> filters) {
|
return new VirtualFilterChain(original, filters);
}
}
private static final class FirewallFilter implements Filter {
private final HttpFirewall firewall;
private FirewallFilter(HttpFirewall firewall) {
this.firewall = firewall;
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
filterChain.doFilter(this.firewall.getFirewalledRequest(request),
this.firewall.getFirewalledResponse(response));
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\FilterChainProxy.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
Set<String> replaceAll(Set<String> classNames) {
Set<String> replaced = new LinkedHashSet<>(classNames.size());
for (String className : classNames) {
replaced.add(replace(className));
}
return replaced;
}
String replace(String className) {
return this.replacements.getOrDefault(className, className);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
return this.replacements.equals(((AutoConfigurationReplacements) obj).replacements);
}
@Override
public int hashCode() {
return this.replacements.hashCode();
}
/**
* Loads the relocations from the classpath. Relocations are stored in files named
* {@code META-INF/spring/full-qualified-annotation-name.replacements} on the
* classpath. The file is loaded using {@link Properties#load(java.io.InputStream)}
* with each entry containing an auto-configuration class name as the key and the
* replacement class name as the value.
* @param annotation annotation to load
* @param classLoader class loader to use for loading
* @return list of names of annotated classes
*/
static AutoConfigurationReplacements load(Class<?> annotation, @Nullable ClassLoader classLoader) {
Assert.notNull(annotation, "'annotation' must not be null");
ClassLoader classLoaderToUse = decideClassloader(classLoader);
String location = String.format(LOCATION, annotation.getName());
Enumeration<URL> urls = findUrlsInClasspath(classLoaderToUse, location);
Map<String, String> replacements = new HashMap<>();
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
replacements.putAll(readReplacements(url));
}
|
return new AutoConfigurationReplacements(replacements);
}
private static ClassLoader decideClassloader(@Nullable ClassLoader classLoader) {
if (classLoader == null) {
return ImportCandidates.class.getClassLoader();
}
return classLoader;
}
private static Enumeration<URL> findUrlsInClasspath(ClassLoader classLoader, String location) {
try {
return classLoader.getResources(location);
}
catch (IOException ex) {
throw new IllegalArgumentException("Failed to load configurations from location [" + location + "]", ex);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private static Map<String, String> readReplacements(URL url) {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(new UrlResource(url).getInputStream(), StandardCharsets.UTF_8))) {
Properties properties = new Properties();
properties.load(reader);
return (Map) properties;
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load replacements from location [" + url + "]", ex);
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\AutoConfigurationReplacements.java
| 2
|
请完成以下Java代码
|
public static ExternalSystemLeichMehlConfigId ofRepoId(final int repoId)
{
return new ExternalSystemLeichMehlConfigId(repoId);
}
@Nullable
public static ExternalSystemLeichMehlConfigId ofRepoIdOrNull(@Nullable final Integer repoId)
{
return repoId != null && repoId > 0 ? new ExternalSystemLeichMehlConfigId(repoId) : null;
}
public static ExternalSystemLeichMehlConfigId cast(@NonNull final IExternalSystemChildConfigId id)
{
return (ExternalSystemLeichMehlConfigId)id;
}
|
@JsonValue
public int toJson()
{
return getRepoId();
}
private ExternalSystemLeichMehlConfigId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, I_ExternalSystem_Config_LeichMehl.COLUMNNAME_ExternalSystem_Config_LeichMehl_ID);
}
@Override
public ExternalSystemType getType()
{
return ExternalSystemType.LeichUndMehl;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\leichmehl\ExternalSystemLeichMehlConfigId.java
| 1
|
请完成以下Java代码
|
public class ActiveRecordQueryFilter<T> implements IQueryFilter<T>, ISqlQueryFilter
{
public static <T> IQueryFilter<T> getInstance()
{
@SuppressWarnings("unchecked")
final ActiveRecordQueryFilter<T> instanceCasted = instance;
return instanceCasted;
}
public static <T> IQueryFilter<T> getInstance(final Class<T> clazz)
{
return getInstance();
}
@SuppressWarnings("rawtypes")
private static final ActiveRecordQueryFilter instance = new ActiveRecordQueryFilter();
private static final String COLUMNNAME_IsActive = "IsActive";
private final String sql;
private final List<Object> sqlParams;
private ActiveRecordQueryFilter()
{
this.sql = COLUMNNAME_IsActive + "=?";
this.sqlParams = Arrays.asList((Object)true);
}
@Override
public String toString()
{
|
return "Active";
}
@Override
public String getSql()
{
return sql;
}
@Override
public List<Object> getSqlParams(final Properties ctx)
{
return sqlParams;
}
@Override
public boolean accept(final T model)
{
final Object isActiveObj = InterfaceWrapperHelper.getValueOrNull(model, COLUMNNAME_IsActive);
final boolean isActive = DisplayType.toBoolean(isActiveObj);
return isActive;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\ActiveRecordQueryFilter.java
| 1
|
请完成以下Java代码
|
public static String generateSafeToken(int length) {
byte[] bytes = new byte[length];
RANDOM.nextBytes(bytes);
Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding();
return encoder.encodeToString(bytes);
}
public static String generateSafeToken() {
return generateSafeToken(DEFAULT_TOKEN_LENGTH);
}
public static String truncate(String string, int maxLength) {
return truncate(string, maxLength, n -> "...[truncated " + n + " symbols]");
}
public static String truncate(String string, int maxLength, Function<Integer, String> truncationMarkerFunc) {
if (string == null || maxLength <= 0 || string.length() <= maxLength) {
return string;
}
int truncatedSymbols = string.length() - maxLength;
return string.substring(0, maxLength) + truncationMarkerFunc.apply(truncatedSymbols);
}
|
public static List<String> splitByCommaWithoutQuotes(String value) {
List<String> splitValues = List.of(value.trim().split("\\s*,\\s*"));
List<String> result = new ArrayList<>();
char lastWayInputValue = '#';
for (String str : splitValues) {
char startWith = str.charAt(0);
char endWith = str.charAt(str.length() - 1);
// if first value is not quote, so we return values after split
if (startWith != '\'' && startWith != '"') return splitValues;
// if value is not in quote, so we return values after split
if (startWith != endWith) return splitValues;
// if different way values, so don't replace quote and return values after split
if (lastWayInputValue != '#' && startWith != lastWayInputValue) return splitValues;
result.add(str.substring(1, str.length() - 1));
lastWayInputValue = startWith;
}
return result;
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\StringUtils.java
| 1
|
请完成以下Java代码
|
public void setI_IsImported (java.lang.String I_IsImported)
{
set_Value (COLUMNNAME_I_IsImported, I_IsImported);
}
/** Get Importiert.
@return Ist dieser Import verarbeitet worden?
*/
@Override
public java.lang.String getI_IsImported ()
{
return (java.lang.String)get_Value(COLUMNNAME_I_IsImported);
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
|
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Window Internal Name.
@param WindowInternalName Window Internal Name */
@Override
public void setWindowInternalName (java.lang.String WindowInternalName)
{
set_Value (COLUMNNAME_WindowInternalName, WindowInternalName);
}
/** Get Window Internal Name.
@return Window Internal Name */
@Override
public java.lang.String getWindowInternalName ()
{
return (java.lang.String)get_Value(COLUMNNAME_WindowInternalName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_I_DataEntry_Record.java
| 1
|
请完成以下Java代码
|
void browseB_actionPerformed(ActionEvent e) {
// Fix until Sun's JVM supports more locales...
UIManager.put("FileChooser.lookInLabelText", Local
.getString("Look in:"));
UIManager.put("FileChooser.upFolderToolTipText", Local.getString(
"Up One Level"));
UIManager.put("FileChooser.newFolderToolTipText", Local.getString(
"Create New Folder"));
UIManager.put("FileChooser.listViewButtonToolTipText", Local
.getString("List"));
UIManager.put("FileChooser.detailsViewButtonToolTipText", Local
.getString("Details"));
UIManager.put("FileChooser.fileNameLabelText", Local.getString(
"File Name:"));
UIManager.put("FileChooser.filesOfTypeLabelText", Local.getString(
"Files of Type:"));
UIManager.put("FileChooser.openButtonText", Local.getString("Open"));
UIManager.put("FileChooser.openButtonToolTipText", Local.getString(
"Open selected file"));
UIManager
.put("FileChooser.cancelButtonText", Local.getString("Cancel"));
UIManager.put("FileChooser.cancelButtonToolTipText", Local.getString(
"Cancel"));
JFileChooser chooser = new JFileChooser();
chooser.setFileHidingEnabled(false);
chooser.setDialogTitle(Local.getString("Choose an image file"));
chooser.setAcceptAllFileFilterUsed(false);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.addChoosableFileFilter(
new net.sf.memoranda.ui.htmleditor.filechooser.ImageFilter());
chooser.setAccessory(
new net.sf.memoranda.ui.htmleditor.filechooser.ImagePreview(
chooser));
chooser.setPreferredSize(new Dimension(550, 375));
java.io.File lastSel = (java.io.File) Context.get(
"LAST_SELECTED_IMG_FILE");
if (lastSel != null)
chooser.setCurrentDirectory(lastSel);
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
|
try {
fileField.setText(chooser.getSelectedFile().toURL().toString());
header.setIcon(getPreviewIcon(chooser.getSelectedFile()));
Context
.put("LAST_SELECTED_IMG_FILE", chooser
.getSelectedFile());
}
catch (Exception ex) {
fileField.setText(chooser.getSelectedFile().getPath());
}
try {
ImageIcon img = new ImageIcon(chooser.getSelectedFile()
.getPath());
widthField.setText(new Integer(img.getIconWidth()).toString());
heightField
.setText(new Integer(img.getIconHeight()).toString());
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\ImageDialog.java
| 1
|
请完成以下Java代码
|
public <T> T getDocumentAs(@NonNull final Class<T> type)
{
return type.cast(document);
}
public WFActivity getActivityById(@NonNull final WFActivityId id)
{
return getActivityByIdOptional(id)
.orElseThrow(() -> new AdempiereException(NO_ACTIVITY_ERROR_MSG)
.appendParametersToMessage()
.setParameter("ID", id)
.setParameter("WFProcess", this));
}
@NonNull
public Optional<WFActivity> getActivityByIdOptional(@NonNull final WFActivityId id)
{
return Optional.ofNullable(activitiesById.get(id));
}
public WFProcess withChangedActivityStatus(
@NonNull final WFActivityId wfActivityId,
@NonNull final WFActivityStatus newActivityStatus)
{
|
return withChangedActivityById(wfActivityId, wfActivity -> wfActivity.withStatus(newActivityStatus));
}
private WFProcess withChangedActivityById(@NonNull final WFActivityId wfActivityId, @NonNull final UnaryOperator<WFActivity> remappingFunction)
{
return withChangedActivities(wfActivity -> wfActivity.getId().equals(wfActivityId)
? remappingFunction.apply(wfActivity)
: wfActivity);
}
private WFProcess withChangedActivities(@NonNull final UnaryOperator<WFActivity> remappingFunction)
{
final ImmutableList<WFActivity> activitiesNew = CollectionUtils.map(this.activities, remappingFunction);
return !Objects.equals(this.activities, activitiesNew)
? toBuilder().activities(activitiesNew).build()
: this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\model\WFProcess.java
| 1
|
请完成以下Java代码
|
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Suchschluessel.
@param Value
|
Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschluessel.
@return Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\model\X_M_FreightCost.java
| 1
|
请完成以下Java代码
|
public void onPriceActualChanged(final I_M_RequisitionLine line)
{
updateLineNetAmt(line);
}
private void updatePrice(final I_M_RequisitionLine line)
{
final int C_BPartner_ID = line.getC_BPartner_ID();
final BigDecimal Qty = line.getQty();
final boolean isSOTrx = false;
final MProductPricing pp = new MProductPricing(
OrgId.ofRepoId(line.getAD_Org_ID()),
line.getM_Product_ID(),
C_BPartner_ID,
null,
Qty,
isSOTrx);
//
final I_M_Requisition req = line.getM_Requisition();
final int M_PriceList_ID = req.getM_PriceList_ID();
pp.setM_PriceList_ID(M_PriceList_ID);
final Timestamp orderDate = req.getDateRequired();
pp.setPriceDate(orderDate);
//
line.setPriceActual(pp.getPriceStd());
|
updateLineNetAmt(line);
}
private void updateLineNetAmt(final I_M_RequisitionLine line)
{
final BigDecimal qty = line.getQty();
final BigDecimal priceActual = line.getPriceActual();
// Multiply
final BigDecimal lineNetAmt = qty.multiply(priceActual);
// int stdPrecision = Env.getContextAsInt(ctx, WindowNo, "StdPrecision");
// if (lineNetAmt.scale() > stdPrecision)
// lineNetAmt = lineNetAmt.setScale(stdPrecision, BigDecimal.ROUND_HALF_UP);
line.setLineNetAmt(lineNetAmt);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\requisition\callout\M_RequisitionLine.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class GroupsConfiguration extends AbstractAnnotationConfigSupport implements ImportAware {
private static final String GEMFIRE_GROUPS_PROPERTY = "groups";
private String[] groups = {};
@Override
protected Class<? extends Annotation> getAnnotationType() {
return UseGroups.class;
}
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
if (isAnnotationPresent(importMetadata)) {
AnnotationAttributes inGroupsAttributes = getAnnotationAttributes(importMetadata);
setGroups(inGroupsAttributes.containsKey("value")
? inGroupsAttributes.getStringArray("value") : null);
setGroups(inGroupsAttributes.containsKey("groups")
? inGroupsAttributes.getStringArray("groups") : null);
}
}
protected void setGroups(String[] groups) {
this.groups = Optional.ofNullable(groups)
.filter(it -> it.length > 0)
.orElse(this.groups);
}
protected Optional<String[]> getGroups() {
return Optional.ofNullable(this.groups)
.filter(it -> it.length > 0);
|
}
@Bean
ClientCacheConfigurer clientCacheGroupsConfigurer() {
return (beaName, clientCacheFactoryBean) -> configureGroups(clientCacheFactoryBean);
}
@Bean
PeerCacheConfigurer peerCacheGroupsConfigurer() {
return (beaName, peerCacheFactoryBean) -> configureGroups(peerCacheFactoryBean);
}
private void configureGroups(CacheFactoryBean cacheFactoryBean) {
getGroups().ifPresent(groups -> cacheFactoryBean.getProperties()
.setProperty(GEMFIRE_GROUPS_PROPERTY, StringUtils.arrayToCommaDelimitedString(groups)));
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\GroupsConfiguration.java
| 2
|
请完成以下Java代码
|
public void setM_CostElement_ID (final int M_CostElement_ID)
{
if (M_CostElement_ID < 1)
set_Value (COLUMNNAME_M_CostElement_ID, null);
else
set_Value (COLUMNNAME_M_CostElement_ID, M_CostElement_ID);
}
@Override
public int getM_CostElement_ID()
{
return get_ValueAsInt(COLUMNNAME_M_CostElement_ID);
}
@Override
public org.compiere.model.I_M_CostRevaluation getM_CostRevaluation()
{
return get_ValueAsPO(COLUMNNAME_M_CostRevaluation_ID, org.compiere.model.I_M_CostRevaluation.class);
}
@Override
public void setM_CostRevaluation(final org.compiere.model.I_M_CostRevaluation M_CostRevaluation)
{
set_ValueFromPO(COLUMNNAME_M_CostRevaluation_ID, org.compiere.model.I_M_CostRevaluation.class, M_CostRevaluation);
}
@Override
public void setM_CostRevaluation_ID (final int M_CostRevaluation_ID)
{
if (M_CostRevaluation_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_CostRevaluation_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_CostRevaluation_ID, M_CostRevaluation_ID);
}
@Override
public int getM_CostRevaluation_ID()
{
return get_ValueAsInt(COLUMNNAME_M_CostRevaluation_ID);
}
@Override
public void setM_CostRevaluationLine_ID (final int M_CostRevaluationLine_ID)
{
if (M_CostRevaluationLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_CostRevaluationLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_CostRevaluationLine_ID, M_CostRevaluationLine_ID);
}
@Override
public int getM_CostRevaluationLine_ID()
{
return get_ValueAsInt(COLUMNNAME_M_CostRevaluationLine_ID);
}
@Override
public org.compiere.model.I_M_CostType getM_CostType()
{
return get_ValueAsPO(COLUMNNAME_M_CostType_ID, org.compiere.model.I_M_CostType.class);
}
|
@Override
public void setM_CostType(final org.compiere.model.I_M_CostType M_CostType)
{
set_ValueFromPO(COLUMNNAME_M_CostType_ID, org.compiere.model.I_M_CostType.class, M_CostType);
}
@Override
public void setM_CostType_ID (final int M_CostType_ID)
{
if (M_CostType_ID < 1)
set_Value (COLUMNNAME_M_CostType_ID, null);
else
set_Value (COLUMNNAME_M_CostType_ID, M_CostType_ID);
}
@Override
public int getM_CostType_ID()
{
return get_ValueAsInt(COLUMNNAME_M_CostType_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setNewCostPrice (final BigDecimal NewCostPrice)
{
set_Value (COLUMNNAME_NewCostPrice, NewCostPrice);
}
@Override
public BigDecimal getNewCostPrice()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_NewCostPrice);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostRevaluationLine.java
| 1
|
请完成以下Java代码
|
public Object key(String keyExpression, AnnotatedElementKey methodKey, EvaluationContext evalContext) {
return getExpression(this.keyCache, methodKey, keyExpression).getValue(evalContext);
}
public boolean condition(String conditionExpression, AnnotatedElementKey methodKey, EvaluationContext evalContext) {
return getExpression(this.conditionCache, methodKey, conditionExpression).getValue(evalContext, boolean.class);
}
public boolean unless(String unlessExpression, AnnotatedElementKey methodKey, EvaluationContext evalContext) {
return getExpression(this.unlessCache, methodKey, unlessExpression).getValue(evalContext, boolean.class);
}
/**
* Clear all caches.
*/
void clear() {
this.keyCache.clear();
this.conditionCache.clear();
this.unlessCache.clear();
this.targetMethodCache.clear();
}
|
private Method getTargetMethod(Class<?> targetClass, Method method) {
AnnotatedElementKey methodKey = new AnnotatedElementKey(method, targetClass);
Method targetMethod = this.targetMethodCache.get(methodKey);
if (targetMethod == null) {
targetMethod = AopUtils.getMostSpecificMethod(method, targetClass);
if (targetMethod == null) {
targetMethod = method;
}
this.targetMethodCache.put(methodKey, targetMethod);
}
return targetMethod;
}
}
|
repos\spring-boot-student-master\spring-boot-student-cache-redis\src\main\java\com\xiaolyuh\redis\cache\expression\CacheOperationExpressionEvaluator.java
| 1
|
请完成以下Java代码
|
public String getExecutionId() {
return executionId;
}
public boolean getExecutable() {
return executable;
}
public Date getNow() {
return Context.getProcessEngineConfiguration().getClock().getCurrentTime();
}
public boolean isWithException() {
return withException;
}
public String getExceptionMessage() {
return exceptionMessage;
|
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\TimerJobQueryImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void noAsync() {
log.info("Execute method asynchronously. " + Thread.currentThread().getName());
}
public void withAsync() {
log.info("Execute method asynchronously. " + Thread.currentThread().getName());
}
@Async("threadPoolTaskExecutor")
public void mockerror() {
int ss=12/0;
}
@Async
public Future<String> asyncMethodWithReturnType() {
log.info("Execute method asynchronously - " + Thread.currentThread().getName());
try {
Thread.sleep(5000);
return new AsyncResult<String>("hello world !!!!");
} catch (InterruptedException e) {
e.printStackTrace();
|
}
return null;
}
@Autowired
private FirstAsyncService fisrtService;
@Autowired
private SecondAsyncService secondService;
public CompletableFuture<String> asyncMergeServicesResponse() throws InterruptedException {
CompletableFuture<String> fisrtServiceResponse = fisrtService.asyncGetData();
CompletableFuture<String> secondServiceResponse = secondService.asyncGetData();
// Merge responses from FirstAsyncService and SecondAsyncService
return fisrtServiceResponse.thenCompose(fisrtServiceValue -> secondServiceResponse.thenApply(secondServiceValue -> fisrtServiceValue + secondServiceValue));
}
}
|
repos\springboot-demo-master\async\src\main\java\com\et\async\service\NotifyService.java
| 2
|
请完成以下Java代码
|
class DDOrderLineAttributeSetInstanceAware implements IAttributeSetInstanceAware
{
public static DDOrderLineAttributeSetInstanceAware ofASIFrom(final I_DD_OrderLine ddOrderLine)
{
final boolean isASITo = false;
return new DDOrderLineAttributeSetInstanceAware(ddOrderLine, isASITo);
}
public static DDOrderLineAttributeSetInstanceAware ofASITo(final I_DD_OrderLine ddOrderLine)
{
final boolean isASITo = true;
return new DDOrderLineAttributeSetInstanceAware(ddOrderLine, isASITo);
}
private final I_DD_OrderLine ddOrderLine;
private final boolean isASITo;
private DDOrderLineAttributeSetInstanceAware(@NonNull final I_DD_OrderLine ddOrderLine, final boolean isASITo)
{
this.ddOrderLine = ddOrderLine;
this.isASITo = isASITo;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("ddOrderLine", ddOrderLine)
.add("isASITo", isASITo)
.toString();
}
@Override
public I_M_Product getM_Product()
{
final IProductBL productBL = Services.get(IProductBL.class);
return productBL.getById(ProductId.ofRepoId(ddOrderLine.getM_Product_ID()));
}
@Override
public int getM_Product_ID()
{
return ddOrderLine.getM_Product_ID();
}
@Override
public I_M_AttributeSetInstance getM_AttributeSetInstance()
{
return isASITo ? ddOrderLine.getM_AttributeSetInstanceTo() : ddOrderLine.getM_AttributeSetInstance();
}
@Override
public int getM_AttributeSetInstance_ID()
{
return isASITo ? ddOrderLine.getM_AttributeSetInstanceTo_ID() : ddOrderLine.getM_AttributeSetInstance_ID();
}
@Override
|
public void setM_AttributeSetInstance(final I_M_AttributeSetInstance asi)
{
if (isASITo)
{
ddOrderLine.setM_AttributeSetInstanceTo(asi);
}
else
{
ddOrderLine.setM_AttributeSetInstance(asi);
}
}
@Override
public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID)
{
if (isASITo)
{
ddOrderLine.setM_AttributeSetInstanceTo_ID(M_AttributeSetInstance_ID);
}
else
{
ddOrderLine.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\producer\DDOrderLineAttributeSetInstanceAware.java
| 1
|
请完成以下Java代码
|
private static ITranslatableString computeCaption(final Amount writeOffAmt)
{
return TranslatableStrings.builder()
.appendADElement("PaymentWriteOffAmt").append(": ").append(writeOffAmt)
.build();
}
@Override
protected String doIt()
{
final Plan plan = creatPlan().orElseThrow();
final PaymentAmtMultiplier amtMultiplier = plan.getAmtMultiplier();
final Amount amountToWriteOff = amtMultiplier.convertToRealValue(plan.getAmountToWriteOff());
paymentBL.paymentWriteOff(
plan.getPaymentId(),
amountToWriteOff.toMoney(moneyService::getCurrencyIdByCurrencyCode),
p_DateTrx.atStartOfDay(SystemTime.zoneId()).toInstant(),
null);
return MSG_OK;
}
//
//
//
private static ExplainedOptional<Plan> createPlan(@NonNull final ImmutableList<PaymentRow> paymentRows)
{
|
if (paymentRows.size() != 1)
{
return ExplainedOptional.emptyBecause("Only one payment row can be selected for write-off");
}
final PaymentRow paymentRow = CollectionUtils.singleElement(paymentRows);
final Amount openAmt = paymentRow.getOpenAmt();
if (openAmt.signum() == 0)
{
return ExplainedOptional.emptyBecause("Zero open amount. Nothing to write-off");
}
return ExplainedOptional.of(
Plan.builder()
.paymentId(paymentRow.getPaymentId())
.amtMultiplier(paymentRow.getPaymentAmtMultiplier())
.amountToWriteOff(openAmt)
.build());
}
@Value
@Builder
private static class Plan
{
@NonNull PaymentId paymentId;
@NonNull PaymentAmtMultiplier amtMultiplier;
@NonNull Amount amountToWriteOff;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\process\PaymentsView_PaymentWriteOff.java
| 1
|
请完成以下Java代码
|
protected static double GammaCdf(double x, double a) throws IllegalArgumentException
{
if (x < 0)
{
throw new IllegalArgumentException();
}
double GI = 0;
if (a > 200)
{
double z = (x - a) / Math.sqrt(a);
double y = GaussCdf(z);
double b1 = 2 / Math.sqrt(a);
double phiz = 0.39894228 * Math.exp(-z * z / 2);
double w = y - b1 * (z * z - 1) * phiz / 6; //Edgeworth1
double b2 = 6 / a;
int zXor4 = ((int) z) ^ 4;
double u = 3 * b2 * (z * z - 3) + b1 * b1 * (zXor4 - 10 * z * z + 15);
GI = w - phiz * z * u / 72; //Edgeworth2
}
else if (x < a + 1)
{
GI = Gser(x, a);
}
else
{
GI = Gcf(x, a);
}
return GI;
}
/**
* 给定卡方分布的p值和自由度,返回卡方值。内部采用二分搜索实现,移植自JS代码:
* http://www.fourmilab.ch/rpkp/experiments/analysis/chiCalc.js
*
* @param p p值(置信度)
* @param df
* @return
|
*/
public static double ChisquareInverseCdf(double p, int df)
{
final double CHI_EPSILON = 0.000001; /* Accuracy of critchi approximation */
final double CHI_MAX = 99999.0; /* Maximum chi-square value */
double minchisq = 0.0;
double maxchisq = CHI_MAX;
double chisqval = 0.0;
if (p <= 0.0)
{
return CHI_MAX;
}
else if (p >= 1.0)
{
return 0.0;
}
chisqval = df / Math.sqrt(p); /* fair first value */
while ((maxchisq - minchisq) > CHI_EPSILON)
{
if (1 - ChisquareCdf(chisqval, df) < p)
{
maxchisq = chisqval;
}
else
{
minchisq = chisqval;
}
chisqval = (maxchisq + minchisq) * 0.5;
}
return chisqval;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\statistics\ContinuousDistributions.java
| 1
|
请完成以下Java代码
|
public <T extends Supplier<Collection<Method>>, R> void doDiscover(Class<T> supplierClass, Class<R> returnType) {
List<T> suppliers = loadSuppliers(supplierClass);
List<Method> methods = new ArrayList<>();
for (Supplier<Collection<Method>> supplier : suppliers) {
try {
methods.addAll(supplier.get());
}
catch (NoClassDefFoundError e) {
if (log.isDebugEnabled()) {
log.debug(LogMessage.format("NoClassDefFoundError discovering supplier %s for type %s",
supplierClass, returnType));
}
else if (log.isTraceEnabled()) {
log.debug(LogMessage.format("NoClassDefFoundError discovering supplier %s for type %s",
supplierClass, returnType), e);
}
}
}
for (Method method : methods) {
// TODO: replace with a BiPredicate of some kind
if (returnType.isAssignableFrom(method.getReturnType())) {
addOperationMethod(method);
}
}
}
protected void addOperationMethod(Method method) {
OperationMethod operationMethod = new DefaultOperationMethod(method);
String key = method.getName();
|
operations.add(key, operationMethod);
log.trace(LogMessage.format("Discovered %s", operationMethod));
}
public abstract void discover();
protected <T> List<T> loadSuppliers(Class<T> supplierClass) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
List<T> suppliers = SpringFactoriesLoader.loadFactories(supplierClass, classLoader);
return suppliers;
}
public MultiValueMap<String, OperationMethod> getOperations() {
if (operations == null || operations.isEmpty()) {
discover();
}
return operations;
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\common\AbstractGatewayDiscoverer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public BaseResponse<List<User>> getUserList() {
// 处理"/users/"的GET请求,用来获取用户列表
// 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递
List<User> r = new ArrayList<>(users.values());
return new BaseResponse<>(true, "查询列表成功", r);
}
@RequestMapping(value = "/", method = RequestMethod.POST)
public BaseResponse<String> postUser(@ModelAttribute User user) {
// 处理"/users/"的POST请求,用来创建User
// 除了@ModelAttribute绑定参数之外,还可以通过@RequestParam从页面中传递参数
users.put(user.getId(), user);
return new BaseResponse<>(true, "新增成功", "");
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public BaseResponse<User> getUser(@PathVariable Long id) {
// 处理"/users/{id}"的GET请求,用来获取url中id值的User信息
// url中的id可通过@PathVariable绑定到函数的参数中
return new BaseResponse<>(true, "查询成功", users.get(id));
}
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
|
public BaseResponse<String> putUser(@PathVariable Long id, @ModelAttribute User user) {
// 处理"/users/{id}"的PUT请求,用来更新User信息
User u = users.get(id);
u.setName(user.getName());
u.setAge(user.getAge());
users.put(id, u);
return new BaseResponse<>(true, "更新成功", "");
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public BaseResponse<String> deleteUser(@PathVariable Long id) {
// 处理"/users/{id}"的DELETE请求,用来删除User
users.remove(id);
return new BaseResponse<>(true, "删除成功", "");
}
}
|
repos\SpringBootBucket-master\springboot-restful\src\main\java\com\xncoding\pos\controller\UserController.java
| 2
|
请完成以下Java代码
|
public CostAmount getAmt(@NonNull final CostAmountType type)
{
final CostAmount costAmount;
switch (type)
{
case MAIN:
costAmount = mainAmt;
break;
case ADJUSTMENT:
costAmount = costAdjustmentAmt;
break;
case ALREADY_SHIPPED:
costAmount = alreadyShippedAmt;
break;
default:
throw new IllegalArgumentException();
}
return costAmount;
}
public CostAmountDetailed add(@NonNull final CostAmountDetailed amtToAdd)
{
return builder()
.mainAmt(mainAmt.add(amtToAdd.mainAmt))
.costAdjustmentAmt(costAdjustmentAmt.add(amtToAdd.costAdjustmentAmt))
.alreadyShippedAmt(alreadyShippedAmt.add(amtToAdd.alreadyShippedAmt))
.build();
}
public CostAmountDetailed negateIf(final boolean condition)
{
return condition ? negate() : this;
}
|
public CostAmountDetailed negate()
{
return builder()
.mainAmt(mainAmt.negate())
.costAdjustmentAmt(costAdjustmentAmt.negate())
.alreadyShippedAmt(alreadyShippedAmt.negate())
.build();
}
public CostAmount getAmountBeforeAdjustment() {return mainAmt.subtract(costAdjustmentAmt).subtract(alreadyShippedAmt);}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\methods\CostAmountDetailed.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JsonShipmentData
{
@JsonProperty("OverrideShpNo")
String overrideShpNo;
@JsonProperty("OrderNo")
String orderNo;
@JsonProperty("PickupDt")
LocalDate pickupDt;
@JsonProperty("ExpireDt")
LocalDate expireDt;
@JsonProperty("ActorCSID")
Integer actorCSID;
@JsonProperty("StackCSID")
Integer stackCSID;
@JsonProperty("ProdConceptID")
int prodConceptID;
@JsonProperty("ProdCSID")
Integer prodCSID;
@JsonProperty("PickupTerminal")
String pickupTerminal;
@JsonProperty("AgentNo")
String agentNo;
@JsonProperty("PayerAccountAtCarrier")
String payerAccountAtCarrier;
@JsonProperty("SenderAccountAtCarrier")
String senderAccountAtCarrier;
@JsonProperty("SenderAccountAtBank")
String senderAccountAtBank;
@JsonProperty("Services")
@Singular
|
List<Integer> services;
@JsonProperty("Addresses")
@Singular
List<JsonAddress> addresses;
@JsonProperty("Lines")
@Singular
List<JsonLine> lines;
@JsonProperty("References")
@Singular
List<JsonReference> references;
@JsonProperty("DetailGroups")
@Singular
List<JsonDetailGroup> detailGroups;
@JsonProperty("Amounts")
List<JsonAmount> amounts;
@JsonProperty("Messages")
List<JsonShipmentMessage> messages;
@JsonProperty("DangerousGoods")
@Singular
List<JsonDangerousGoods> dangerousGoods;
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.client.nshift\src\main\java\de\metas\shipper\client\nshift\json\JsonShipmentData.java
| 2
|
请完成以下Java代码
|
public HistoricMilestoneInstanceQuery milestoneInstanceWithoutTenantId() {
this.withoutTenantId = true;
return this;
}
@Override
public long executeCount(CommandContext commandContext) {
return CommandContextUtil.getHistoricMilestoneInstanceEntityManager(commandContext).findHistoricMilestoneInstanceCountByQueryCriteria(this);
}
@Override
public List<HistoricMilestoneInstance> executeList(CommandContext commandContext) {
return CommandContextUtil.getHistoricMilestoneInstanceEntityManager(commandContext).findHistoricMilestoneInstancesByQueryCriteria(this);
}
@Override
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
|
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public Date getReachedBefore() {
return reachedBefore;
}
public Date getReachedAfter() {
return reachedAfter;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\history\HistoricMilestoneInstanceQueryImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public DataSource secondaryDataSource() {
return initDruidDataSource(druidTwoConfig);
}
private DruidDataSource initDruidDataSource(DruidConfig config) {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(config.getUrl());
datasource.setUsername(config.getUsername());
datasource.setPassword(config.getPassword());
datasource.setDriverClassName(config.getDriverClassName());
datasource.setInitialSize(config.getInitialSize());
datasource.setMinIdle(config.getMinIdle());
datasource.setMaxActive(config.getMaxActive());
// common config
datasource.setMaxWait(druidConfig.getMaxWait());
datasource.setTimeBetweenEvictionRunsMillis(druidConfig.getTimeBetweenEvictionRunsMillis());
|
datasource.setMinEvictableIdleTimeMillis(druidConfig.getMinEvictableIdleTimeMillis());
datasource.setMaxEvictableIdleTimeMillis(druidConfig.getMaxEvictableIdleTimeMillis());
datasource.setValidationQuery(druidConfig.getValidationQuery());
datasource.setTestWhileIdle(druidConfig.isTestWhileIdle());
datasource.setTestOnBorrow(druidConfig.isTestOnBorrow());
datasource.setTestOnReturn(druidConfig.isTestOnReturn());
datasource.setPoolPreparedStatements(druidConfig.isPoolPreparedStatements());
datasource.setMaxPoolPreparedStatementPerConnectionSize(druidConfig.getMaxPoolPreparedStatementPerConnectionSize());
try {
datasource.setFilters(druidConfig.getFilters());
} catch (SQLException e) {
logger.error("druid configuration initialization filter : {0}", e);
}
datasource.setConnectionProperties(druidConfig.getConnectionProperties());
return datasource;
}
}
|
repos\spring-boot-leaning-master\2.x_42_courses\第 3-7 课: Spring Boot 集成 Druid 监控数据源\spring-boot-multi-Jpa-druid\src\main\java\com\neo\config\druid\DruidDBConfig.java
| 2
|
请完成以下Java代码
|
public static Instant asStartOfDayInstant(@Nullable final LocalDate localDate, @NonNull final ZoneId zoneId)
{
if (localDate == null)
{
return null;
}
final LocalDateTime startOfDay = localDate.atTime(LocalTime.MIN);
return asInstant(startOfDay, zoneId);
}
@Nullable
public static Instant asStartOfDayInstant(@Nullable final Instant instant, @NonNull final ZoneId zoneId)
{
if (instant == null)
{
return null;
}
final LocalDate localDate = asLocalDate(instant, zoneId);
return asStartOfDayInstant(localDate, zoneId);
}
@Nullable
public static Instant asEndOfDayInstant(@Nullable final Instant instant, @NonNull final ZoneId zoneId)
{
if (instant == null)
{
return null;
}
final LocalDate localDate = asLocalDate(instant, zoneId);
return asEndOfDayInstant(localDate, zoneId);
}
public static boolean isOverlapping(
@Nullable final Timestamp start1,
@Nullable final Timestamp end1,
@Nullable final Timestamp start2,
@Nullable final Timestamp end2)
{
return isOverlapping(toInstantsRange(start1, end1), toInstantsRange(start2, end2));
}
public static boolean isOverlapping(@NonNull final Range<Instant> range1, @NonNull final Range<Instant> range2)
{
if (!range1.isConnected(range2))
{
return false;
}
return !range1.intersection(range2).isEmpty();
}
/**
* Compute the days between two dates as if each year is 360 days long.
* More details and an implementation for Excel can be found in {@link org.apache.poi.ss.formula.functions.Days360}
*/
public static long getDaysBetween360(@NonNull final ZonedDateTime from, @NonNull final ZonedDateTime to)
|
{
if (from.isEqual(to))
{
return 0;
}
if (to.isBefore(from))
{
return getDaysBetween360(to, from) * -1;
}
ZonedDateTime dayFrom = from;
ZonedDateTime dayTo = to;
if (dayFrom.getDayOfMonth() == 31)
{
dayFrom = dayFrom.withDayOfMonth(30);
}
if (dayTo.getDayOfMonth() == 31)
{
dayTo = dayTo.withDayOfMonth(30);
}
final long months = ChronoUnit.MONTHS.between(
YearMonth.from(dayFrom), YearMonth.from(dayTo));
final int daysLeft = dayTo.getDayOfMonth() - dayFrom.getDayOfMonth();
return 30 * months + daysLeft;
}
/**
* Compute the days between two dates as if each year is 360 days long.
* More details and an implementation for Excel can be found in {@link org.apache.poi.ss.formula.functions.Days360}
*/
public static long getDaysBetween360(@NonNull final Instant from, @NonNull final Instant to)
{
return getDaysBetween360(asZonedDateTime(from), asZonedDateTime(to));
}
public static Instant addDays(@NonNull final Instant baseInstant, final long daysToAdd)
{
return baseInstant.plus(daysToAdd, ChronoUnit.DAYS);
}
} // TimeUtil
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\TimeUtil.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 8088
spring:
datasource:
password: 123456
username: root
url: jdbc:mysql://localhost:3306/demo?characterEncoding=utf-8&useSSL=false&serverTimezone=UT
|
C&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.cj.jdbc.Driver
|
repos\springboot-demo-master\mybatis-plus\src\main\resources\application.yaml
| 2
|
请完成以下Java代码
|
public void setISO_Code_To (String ISO_Code_To)
{
set_Value (COLUMNNAME_ISO_Code_To, ISO_Code_To);
}
/** Get ISO Currency To Code.
@return Three letter ISO 4217 Code of the To Currency
*/
public String getISO_Code_To ()
{
return (String)get_Value(COLUMNNAME_ISO_Code_To);
}
/** Set Multiply Rate.
@param MultiplyRate
Rate to multiple the source by to calculate the target.
*/
public void setMultiplyRate (BigDecimal MultiplyRate)
{
set_Value (COLUMNNAME_MultiplyRate, MultiplyRate);
}
/** Get Multiply Rate.
@return Rate to multiple the source by to calculate the target.
*/
public BigDecimal getMultiplyRate ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MultiplyRate);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
|
/** Get Process Now.
@return Process Now */
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 Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Conversion_Rate.java
| 1
|
请完成以下Java代码
|
public void onPreRemove() {
logger.info("@PreRemove");
audit(OPERATION.DELETE);
}
private void audit(final OPERATION operation) {
setOperation(operation);
setTimestamp((new Date()).getTime());
}
public enum OPERATION {
INSERT, UPDATE, DELETE;
private String value;
OPERATION() {
value = toString();
}
public static OPERATION parse(final String value) {
OPERATION operation = null;
|
for (final OPERATION op : OPERATION.values()) {
if (op.getValue().equals(value)) {
operation = op;
break;
}
}
return operation;
}
public String getValue() {
return value;
}
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\boot\domain\Bar.java
| 1
|
请完成以下Java代码
|
public Map<String, Object> configScales(
@RequestParam(name = "enabled") final boolean enabled,
@RequestParam(name = "responseMinValue", required = false, defaultValue = "-1") final int responseMinValue,
@RequestParam(name = "responseMaxValue", required = false, defaultValue = "-1") final int responseMaxValue)
{
assertLoggedIn();
setEnabled(enabled);
if (responseMinValue > 0)
{
DummyDeviceConfigPool.setResponseMinValue(responseMinValue);
}
if (responseMaxValue > 0)
{
DummyDeviceConfigPool.setResponseMaxValue(responseMaxValue);
}
return getConfigInfo();
}
private void setEnabled(final boolean enabled)
{
DummyDeviceConfigPool.setEnabled(enabled);
deviceAccessorsHubFactory.cacheReset();
}
private Map<String, Object> getConfigInfo()
{
return ImmutableMap.<String, Object>builder()
.put("enabled", DummyDeviceConfigPool.isEnabled())
.put("responseMinValue", DummyDeviceConfigPool.getResponseMinValue().doubleValue())
.put("responseMaxValue", DummyDeviceConfigPool.getResponseMaxValue().doubleValue())
.build();
}
@GetMapping("/addOrUpdate")
public void addScale(
@RequestParam("deviceName") final String deviceName,
|
@RequestParam("attributes") final String attributesStr,
@RequestParam(name = "onlyForWarehouseIds", required = false) final String onlyForWarehouseIdsStr)
{
assertLoggedIn();
final List<AttributeCode> attributes = CollectionUtils.ofCommaSeparatedList(attributesStr, AttributeCode::ofString);
final List<WarehouseId> onlyForWarehouseIds = RepoIdAwares.ofCommaSeparatedList(onlyForWarehouseIdsStr, WarehouseId.class);
DummyDeviceConfigPool.addDevice(DummyDeviceAddRequest.builder()
.deviceName(deviceName)
.assignedAttributeCodes(attributes)
.onlyWarehouseIds(onlyForWarehouseIds)
.build());
setEnabled(true);
}
@GetMapping("/removeDevice")
public void addScale(
@RequestParam("deviceName") final String deviceName)
{
assertLoggedIn();
DummyDeviceConfigPool.removeDeviceByName(deviceName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.device.webui\src\main\java\de\metas\device\rest\DummyDevicesRestControllerTemplate.java
| 1
|
请完成以下Java代码
|
public class TextFile {
private final String name;
public TextFile(String name) {
this.name = name;
}
public String open() {
return "Opening file " + name;
}
public String read() {
return "Reading file " + name;
}
public String write() {
|
return "Writing to file " + name;
}
public String save() {
return "Saving file " + name;
}
public String copy() {
return "Copying file " + name;
}
public String paste() {
return "Pasting file " + name;
}
}
|
repos\tutorials-master\patterns-modules\design-patterns-behavioral\src\main\java\com\baeldung\command\receiver\TextFile.java
| 1
|
请完成以下Java代码
|
public class EjbProcessApplicationReference implements ProcessApplicationReference {
private static ProcessApplicationLogger LOG = ProcessEngineLogger.PROCESS_APPLICATION_LOGGER;
/** this is an EjbProxy and can be cached */
protected ProcessApplicationInterface selfReference;
/** the name of the process application */
protected String processApplicationName;
public EjbProcessApplicationReference(ProcessApplicationInterface selfReference, String name) {
this.selfReference = selfReference;
this.processApplicationName = name;
}
@Override
public String getName() {
return processApplicationName;
}
@Override
|
public ProcessApplicationInterface getProcessApplication() throws ProcessApplicationUnavailableException {
try {
// check whether process application is still deployed
selfReference.getName();
} catch (EJBException e) {
throw LOG.processApplicationUnavailableException(processApplicationName, e);
}
return selfReference;
}
public void processEngineStopping(ProcessEngine processEngine) throws ProcessApplicationUnavailableException {
// do nothing.
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\EjbProcessApplicationReference.java
| 1
|
请完成以下Java代码
|
private void jbInit() throws Exception {
//this.setSize(200, 50);
this.setFocusable(false);
//this.setBackground();
this.setPreferredSize(new Dimension(200, 45));
this.setToolTipText("");
flowLayout1.setHgap(0);
flowLayout1.setVgap(0);
flowLayout1.setAlignment(FlowLayout.LEFT);
this.setLayout(flowLayout1);
//this.getContentPane().add(cal, BorderLayout.CENTER);
createButtons();
}
void createButtons() {
for (int i = 0; i < chars.length; i++) {
JButton button = new JButton(new CharAction(chars[i]));
button.setMaximumSize(new Dimension(50, 22));
//button.setMinimumSize(new Dimension(22, 22));
button.setPreferredSize(new Dimension(30, 22));
button.setRequestFocusEnabled(false);
button.setFocusable(false);
button.setBorderPainted(false);
button.setOpaque(false);
button.setMargin(new Insets(0,0,0,0));
button.setFont(new Font("serif", 0, 14));
if (i == chars.length-1) {
button.setText("nbsp");
button.setFont(new Font("Dialog",0,10));
button.setMargin(new Insets(0,0,0,0));
}
|
this.add(button, null);
}
}
class CharAction extends AbstractAction {
CharAction(String name) {
super(name);
//putValue(Action.SHORT_DESCRIPTION, name);
}
public void actionPerformed(ActionEvent e) {
String s = this.getValue(Action.NAME).toString();
editor.replaceSelection(s);
if (s.length() == 2)
editor.setCaretPosition(editor.getCaretPosition()-1);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\CharTablePanel.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public User getById(int id) {
logger.info("获取用户start...");
return userMapper.selectById(id);
}
@Cacheable(value = "allUsersCache", unless = "#result.size() == 0")
public List<User> getAllUsers() {
logger.info("获取所有用户列表");
return userMapper.selectList(null);
}
/**
* 创建用户,同时使用新的返回值的替换缓存中的值
* 创建用户后会将allUsersCache缓存全部清空
*/
@Caching(
put = {@CachePut(value = "userCache", key = "#user.id")},
evict = {@CacheEvict(value = "allUsersCache", allEntries = true)}
)
public User createUser(User user) {
logger.info("创建用户start..., user.id=" + user.getId());
userMapper.insert(user);
return user;
}
/**
* 更新用户,同时使用新的返回值的替换缓存中的值
* 更新用户后会将allUsersCache缓存全部清空
*/
@Caching(
put = {@CachePut(value = "userCache", key = "#user.id")},
evict = {@CacheEvict(value = "allUsersCache", allEntries = true)}
)
public User updateUser(User user) {
|
logger.info("更新用户start...");
userMapper.updateById(user);
return user;
}
/**
* 对符合key条件的记录从缓存中移除
* 删除用户后会将allUsersCache缓存全部清空
*/
@Caching(
evict = {
@CacheEvict(value = "userCache", key = "#id"),
@CacheEvict(value = "allUsersCache", allEntries = true)
}
)
public void deleteById(int id) {
logger.info("删除用户start...");
userMapper.deleteById(id);
}
}
|
repos\SpringBootBucket-master\springboot-cache\src\main\java\com\xncoding\trans\service\UserService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public SecurityFilterChain filterChainAllCookieClearing(HttpSecurity http) throws Exception {
http.securityMatcher("/cookies/**")
.authorizeHttpRequests(authz -> authz.anyRequest()
.permitAll())
.logout(logout -> logout.logoutUrl("/cookies/cookielogout")
.addLogoutHandler(new SecurityContextLogoutHandler())
.addLogoutHandler((request, response, auth) -> {
for (Cookie cookie : request.getCookies()) {
String cookieName = cookie.getName();
Cookie cookieToDelete = new Cookie(cookieName, null);
cookieToDelete.setMaxAge(0);
response.addCookie(cookieToDelete);
}
}));
return http.build();
}
}
|
@Order(1)
@Configuration
public static class ClearSiteDataHeaderLogoutConfiguration {
private static final ClearSiteDataHeaderWriter.Directive[] SOURCE = { CACHE, COOKIES, STORAGE, EXECUTION_CONTEXTS };
@Bean
public SecurityFilterChain filterChainClearSiteDataHeader(HttpSecurity http) throws Exception {
http.securityMatcher("/csd/**")
.authorizeHttpRequests(authz -> authz.anyRequest()
.permitAll())
.logout(logout -> logout.logoutUrl("/csd/csdlogout")
.addLogoutHandler(new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter(SOURCE))));
return http.build();
}
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-web-login-2\src\main\java\com\baeldung\manuallogout\SimpleSecurityConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class BaseDecisionResource {
@Autowired
protected ContentTypeResolver contentTypeResolver;
@Autowired
protected DmnRestResponseFactory dmnRestResponseFactory;
@Autowired
protected DmnRepositoryService dmnRepositoryService;
@Autowired(required=false)
protected DmnRestApiInterceptor restApiInterceptor;
/**
* Returns the {@link DmnDecision} that is requested. Throws the right exceptions when bad request was made or decision was not found.
*/
protected DmnDecision getDecisionFromRequest(String decisionId) {
DmnDecision decision = dmnRepositoryService.getDecision(decisionId);
if (decision == null) {
throw new FlowableObjectNotFoundException("Could not find a decision with id '" + decisionId + "'.");
}
if (restApiInterceptor != null) {
restApiInterceptor.accessDecisionTableInfoById(decision);
}
return decision;
}
protected byte[] getDeploymentResourceData(String deploymentId, String resourceId, HttpServletResponse response) {
if (deploymentId == null) {
throw new FlowableIllegalArgumentException("No deployment id provided");
}
if (resourceId == null) {
throw new FlowableIllegalArgumentException("No resource id provided");
}
// Check if deployment exists
DmnDeploymentQuery deploymentQuery = dmnRepositoryService.createDeploymentQuery().deploymentId(deploymentId);
DmnDeployment deployment = deploymentQuery.singleResult();
if (deployment == null) {
|
throw new FlowableObjectNotFoundException("Could not find a deployment with id '" + deploymentId);
}
if (restApiInterceptor != null) {
restApiInterceptor.accessDeploymentById(deployment);
}
List<String> resourceList = dmnRepositoryService.getDeploymentResourceNames(deploymentId);
if (resourceList.contains(resourceId)) {
String contentType = contentTypeResolver.resolveContentType(resourceId);
response.setContentType(contentType);
try (final InputStream resourceStream = dmnRepositoryService.getResourceAsStream(deploymentId, resourceId)) {
return IOUtils.toByteArray(resourceStream);
} catch (Exception e) {
throw new FlowableException("Error converting resource stream", e);
}
} else {
// Resource not found in deployment
throw new FlowableObjectNotFoundException("Could not find a resource with id '" + resourceId + "' in deployment '" + deploymentId);
}
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-rest\src\main\java\org\flowable\dmn\rest\service\api\repository\BaseDecisionResource.java
| 2
|
请完成以下Java代码
|
public ProcessInstanceQueryDto getProcessInstanceQuery() {
return processInstanceQuery;
}
public void setProcessInstanceQuery(ProcessInstanceQueryDto processInstanceQuery) {
this.processInstanceQuery = processInstanceQuery;
}
public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) {
this.historicProcessInstanceQuery = historicProcessInstanceQuery;
}
public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() {
return historicProcessInstanceQuery;
}
public Batch updateSuspensionStateAsync(ProcessEngine engine) {
int params = parameterCount(processInstanceIds, processInstanceQuery, historicProcessInstanceQuery);
if (params == 0) {
String message = "Either processInstanceIds, processInstanceQuery or historicProcessInstanceQuery should be set to update the suspension state.";
throw new InvalidRequestException(Status.BAD_REQUEST, message);
}
UpdateProcessInstancesSuspensionStateBuilder updateSuspensionStateBuilder = createUpdateSuspensionStateGroupBuilder(engine);
if (getSuspended()) {
return updateSuspensionStateBuilder.suspendAsync();
} else {
return updateSuspensionStateBuilder.activateAsync();
}
}
protected UpdateProcessInstancesSuspensionStateBuilder createUpdateSuspensionStateGroupBuilder(ProcessEngine engine) {
UpdateProcessInstanceSuspensionStateSelectBuilder selectBuilder = engine.getRuntimeService().updateProcessInstanceSuspensionState();
|
UpdateProcessInstancesSuspensionStateBuilder groupBuilder = null;
if (processInstanceIds != null) {
groupBuilder = selectBuilder.byProcessInstanceIds(processInstanceIds);
}
if (processInstanceQuery != null) {
if (groupBuilder == null) {
groupBuilder = selectBuilder.byProcessInstanceQuery(processInstanceQuery.toQuery(engine));
} else {
groupBuilder.byProcessInstanceQuery(processInstanceQuery.toQuery(engine));
}
}
if (historicProcessInstanceQuery != null) {
if (groupBuilder == null) {
groupBuilder = selectBuilder.byHistoricProcessInstanceQuery(historicProcessInstanceQuery.toQuery(engine));
} else {
groupBuilder.byHistoricProcessInstanceQuery(historicProcessInstanceQuery.toQuery(engine));
}
}
return groupBuilder;
}
protected int parameterCount(Object... o) {
int count = 0;
for (Object o1 : o) {
count += (o1 != null ? 1 : 0);
}
return count;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\ProcessInstanceSuspensionStateAsyncDto.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getResourceLocation() {
return resourceLocation;
}
public void setResourceLocation(String resourceLocation) {
this.resourceLocation = resourceLocation;
}
public List<String> getResourceSuffixes() {
return resourceSuffixes;
}
public void setResourceSuffixes(List<String> resourceSuffixes) {
this.resourceSuffixes = resourceSuffixes;
}
public boolean isDeployResources() {
return deployResources;
}
public void setDeployResources(boolean deployResources) {
this.deployResources = deployResources;
}
public boolean isEnableChangeDetection() {
return enableChangeDetection;
}
public void setEnableChangeDetection(boolean enableChangeDetection) {
this.enableChangeDetection = enableChangeDetection;
}
public Duration getChangeDetectionInitialDelay() {
return changeDetectionInitialDelay;
}
public void setChangeDetectionInitialDelay(Duration changeDetectionInitialDelay) {
this.changeDetectionInitialDelay = changeDetectionInitialDelay;
}
|
public Duration getChangeDetectionDelay() {
return changeDetectionDelay;
}
public void setChangeDetectionDelay(Duration changeDetectionDelay) {
this.changeDetectionDelay = changeDetectionDelay;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public FlowableServlet getServlet() {
return servlet;
}
}
|
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\eventregistry\FlowableEventRegistryProperties.java
| 2
|
请完成以下Java代码
|
private void createAndSendDeliveryOrder(
@NonNull final DeliveryOrderKey deliveryOrderKey,
@NonNull final Collection<I_M_Package> mpackages)
{
final ShipperId shipperId = deliveryOrderKey.getShipperId();
final ShipperGatewayId shipperGatewayId = getShipperGatewayId(shipperId);
final DeliveryOrderService deliveryOrderRepository = shipperRegistry.getDeliveryOrderService(shipperGatewayId);
final ImmutableSet<PackageInfo> packageInfos = mpackages.stream()
.map(mpackage -> PackageInfo.builder()
.packageId(PackageId.ofRepoId(mpackage.getM_Package_ID()))
.poReference(mpackage.getPOReference())
.description(StringUtils.trimBlankToNull(mpackage.getDescription()))
.weightInKg(extractWeightInKg(mpackage).orElse(null))
.packageDimension(extractPackageDimensions(mpackage))
.build())
.collect(ImmutableSet.toImmutableSet());
final CreateDraftDeliveryOrderRequest request = CreateDraftDeliveryOrderRequest.builder()
.deliveryOrderKey(deliveryOrderKey)
.packageInfos(packageInfos)
.build();
final DraftDeliveryOrderCreator shipperGatewayService = shipperRegistry.getShipperGatewayService(shipperGatewayId);
DeliveryOrder deliveryOrder = shipperGatewayService.createDraftDeliveryOrder(request);
deliveryOrder = deliveryOrderRepository.save(deliveryOrder);
DeliveryOrderWorkpackageProcessor.enqueueOnTrxCommit(deliveryOrder.getId(), shipperGatewayId, deliveryOrderKey.getAsyncBatchId());
}
private static PackageDimensions extractPackageDimensions(@NonNull final I_M_Package mpackage)
{
return PackageDimensions.builder()
.lengthInCM(mpackage.getLengthInCm())
.widthInCM(mpackage.getWidthInCm())
|
.heightInCM(mpackage.getHeightInCm())
.build();
}
private ShipperGatewayId getShipperGatewayId(final ShipperId shipperId)
{
return shipperDAO.getShipperGatewayId(shipperId).orElseThrow();
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean hasServiceSupport(@NonNull final ShipperGatewayId shipperGatewayId)
{
return shipperRegistry.hasServiceSupport(shipperGatewayId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\ShipperGatewayFacade.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getIban() {
return iban;
}
/**
* Sets the value of the iban property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIban(String value) {
this.iban = value;
}
/**
* Gets the value of the bic property.
*
* @return
|
* possible object is
* {@link String }
*
*/
public String getBic() {
return bic;
}
/**
* Sets the value of the bic property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBic(String value) {
this.bic = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\Cod.java
| 2
|
请完成以下Java代码
|
public void onEvent(final IEventBus eventBus, final Event event)
{
// Ignore local events because they were fired from CacheMgt.reset methods.
// If we would not do so, we would have an infinite loop here.
if (event.isLocalEvent())
{
logger.debug("onEvent - ignoring local event={}", event);
return;
}
final CacheInvalidateMultiRequest request = createRequestFromEvent(event);
if (request == null)
{
logger.debug("onEvent - ignoring event without payload; event={}", event);
return;
}
//
// Reset cache for TableName/Record_ID
logger.debug("onEvent - resetting local cache for request {} because we got remote event={}", request, event);
CacheMgt.get().reset(request, CacheMgt.ResetMode.LOCAL); // don't broadcast it anymore because else we would introduce recursion
}
@VisibleForTesting
Event createEventFromRequest(@NonNull final CacheInvalidateMultiRequest request)
{
return Event.builder()
|
.putProperty(EVENT_PROPERTY, jsonSerializer.toJson(request))
.build();
}
@Nullable
private CacheInvalidateMultiRequest createRequestFromEvent(final Event event)
{
final String jsonRequest = event.getProperty(EVENT_PROPERTY);
if (Check.isEmpty(jsonRequest, true))
{
return null;
}
return jsonSerializer.fromJson(jsonRequest);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CacheInvalidationRemoteHandler.java
| 1
|
请完成以下Java代码
|
public String getSysUserCode() {
return sysUserCode;
}
public void setSysUserCode(String sysUserCode) {
this.sysUserCode = sysUserCode;
}
public String getSysUserName() {
return sysUserName;
}
public void setSysUserName(String sysUserName) {
this.sysUserName = sysUserName;
}
public String getSysOrgCode() {
return sysOrgCode;
}
public void setSysOrgCode(String sysOrgCode) {
this.sysOrgCode = sysOrgCode;
}
public List<String> getSysMultiOrgCode() {
return sysMultiOrgCode;
}
public void setSysMultiOrgCode(List<String> sysMultiOrgCode) {
this.sysMultiOrgCode = sysMultiOrgCode;
}
public String getSysUserId() {
return sysUserId;
}
public void setSysUserId(String sysUserId) {
this.sysUserId = sysUserId;
|
}
public String getSysOrgId() {
return sysOrgId;
}
public void setSysOrgId(String sysOrgId) {
this.sysOrgId = sysOrgId;
}
public String getSysRoleCode() {
return sysRoleCode;
}
public void setSysRoleCode(String sysRoleCode) {
this.sysRoleCode = sysRoleCode;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\vo\SysUserCacheInfo.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static BPartnerBankAccount ofBankAccountRecordOrNull(
@NonNull final I_C_BP_BankAccount bankAccountRecord,
@NonNull final CompositeRelatedRecords relatedRecords)
{
final String iban = bankAccountRecord.getIBAN();
if (iban == null)
{
logger.debug("ofBankAccountRecordOrNull: Return null for {} because IBAN is not set", bankAccountRecord);
return null;
}
final RecordChangeLog changeLog = ChangeLogUtil.createBankAccountChangeLog(bankAccountRecord, relatedRecords);
final BPartnerId bpartnerId = BPartnerId.ofRepoId(bankAccountRecord.getC_BPartner_ID());
final BankId bankId = BankId.ofRepoIdOrNull(bankAccountRecord.getC_Bank_ID());
return BPartnerBankAccount.builder()
.id(BPartnerBankAccountId.ofRepoId(bpartnerId, bankAccountRecord.getC_BP_BankAccount_ID()))
.active(bankAccountRecord.isActive())
.iban(iban)
.currencyId(CurrencyId.ofRepoId(bankAccountRecord.getC_Currency_ID()))
.orgMappingId(OrgMappingId.ofRepoIdOrNull(bankAccountRecord.getAD_Org_Mapping_ID()))
.changeLog(changeLog)
.bankId(bankId)
.accountName(bankAccountRecord.getA_Name())
.accountStreet(bankAccountRecord.getA_Street())
.accountZip(bankAccountRecord.getA_Zip())
.accountCity(bankAccountRecord.getA_City())
.accountCountry(bankAccountRecord.getA_Country())
.build();
}
@Nullable
private static SalesRepContact getSalesRepContact(@NonNull final I_C_BPartner bPartnerRecord)
{
final UserId salesRepId = UserId.ofRepoIdOrNull(bPartnerRecord.getSalesRep_ID());
if (salesRepId == null || !salesRepId.isRegularUser() )
{
return null;
}
final I_AD_User salesRepContact = InterfaceWrapperHelper.load(salesRepId, I_AD_User.class);
return SalesRepContact.builder()
.id(salesRepId)
.value(salesRepContact.getValue())
.email(salesRepContact.getName())
|
.phone(salesRepContact.getPhone())
.firstName(salesRepContact.getFirstname())
.lastName(salesRepContact.getLastname())
.name(salesRepContact.getName())
.build();
}
@Nullable
private static SalesRep getSalesRep(@NonNull final I_C_BPartner bPartnerRecord)
{
final BPartnerId bPartnerSalesRepId = BPartnerId.ofRepoIdOrNull(bPartnerRecord.getC_BPartner_SalesRep_ID());
if (bPartnerSalesRepId == null)
{
return null;
}
final I_C_BPartner salesRep = InterfaceWrapperHelper.load(bPartnerSalesRepId, I_C_BPartner.class);
return SalesRep.builder()
.id(bPartnerSalesRepId)
.value(salesRep.getValue())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\composite\repository\BPartnerCompositesLoader.java
| 2
|
请完成以下Java代码
|
public class XMLStreamReaderUtil {
protected static final Logger LOGGER = LoggerFactory.getLogger(XMLStreamReaderUtil.class);
public static String moveDown(XMLStreamReader xtr) {
try {
while (xtr.hasNext()) {
int event = xtr.next();
switch (event) {
case XMLStreamConstants.END_DOCUMENT:
return null;
case XMLStreamConstants.START_ELEMENT:
return xtr.getLocalName();
case XMLStreamConstants.END_ELEMENT:
return null;
}
}
} catch (Exception e) {
LOGGER.warn("Error while moving down in XML document", e);
}
return null;
}
public static boolean moveToEndOfElement(XMLStreamReader xtr, String elementName) {
try {
|
while (xtr.hasNext()) {
int event = xtr.next();
switch (event) {
case XMLStreamConstants.END_DOCUMENT:
return false;
case XMLStreamConstants.END_ELEMENT:
if (xtr.getLocalName().equals(elementName)) return true;
break;
}
}
} catch (Exception e) {
LOGGER.warn("Error while moving to end of element {}", elementName, e);
}
return false;
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\XMLStreamReaderUtil.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Product {
@Id
private int id;
@Field(termVector = TermVector.YES)
private String productName;
@Field(termVector = TermVector.YES)
private String description;
@Field
private int memory;
public Product(int id, String productName, int memory, String description) {
this.id = id;
this.productName = productName;
this.memory = memory;
this.description = description;
}
public Product() {
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Product))
return false;
Product product = (Product) o;
if (id != product.id)
return false;
if (memory != product.memory)
return false;
if (!productName.equals(product.productName))
return false;
return description.equals(product.description);
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + productName.hashCode();
result = 31 * result + memory;
result = 31 * result + description.hashCode();
return result;
}
public int getId() {
return id;
}
|
public void setId(int id) {
this.id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getMemory() {
return memory;
}
public void setMemory(int memory) {
this.memory = memory;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
repos\tutorials-master\persistence-modules\spring-hibernate-5\src\main\java\com\baeldung\hibernatesearch\model\Product.java
| 2
|
请完成以下Spring Boot application配置
|
## master 数据源配置
master.datasource.url=jdbc:mysql://localhost:3306/springbootdb?useUnicode=true&characterEncoding=utf8
master.datasource.username=root
master.datasource.password=123456
master.datasource.driverClassName=com.mysql.jdbc.Driver
## cluster 数据源配置
cluster.datasource.url=jdbc:mysql://localhost:3306/springbootdb_cluster?useUnicode=true
|
&characterEncoding=utf8
cluster.datasource.username=root
cluster.datasource.password=123456
cluster.datasource.driverClassName=com.mysql.jdbc.Driver
|
repos\springboot-learning-example-master\springboot-mybatis-mutil-datasource\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public static JsonCountStatus ofIsCountedFlag(final boolean isCounted)
{
return isCounted ? COUNTED : NOT_COUNTED;
}
/**
* @return combined status. The following rules are applied:
* <pre>
* NOT_COUNTED + NOT_COUNTED => NOT_COUNTED
* NOT_COUNTED + COUNTING_IN_PROGRESS => COUNTING_IN_PROGRESS
* NOT_COUNTED + COUNTED => COUNTING_IN_PROGRESS
* COUNTING_IN_PROGRESS + NOT_COUNTED => COUNTING_IN_PROGRESS
* COUNTING_IN_PROGRESS + COUNTING_IN_PROGRESS => COUNTING_IN_PROGRESS
* COUNTING_IN_PROGRESS + COUNTED => COUNTING_IN_PROGRESS
* COUNTED + NOT_COUNTED => COUNTING_IN_PROGRESS
|
* COUNTED + COUNTING_IN_PROGRESS => COUNTING_IN_PROGRESS
* COUNTED + COUNTED => COUNTED
* </pre>
*/
public JsonCountStatus combine(@NonNull final JsonCountStatus other)
{
return this.equals(other) ? this : COUNTING_IN_PROGRESS;
}
public static <T> Optional<JsonCountStatus> combine(@NonNull final Collection<T> list, @NonNull final Function<T, JsonCountStatus> mapper)
{
return list.stream().map(mapper).reduce(JsonCountStatus::combine);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\rest_api\json\JsonCountStatus.java
| 1
|
请完成以下Java代码
|
private Capacity getCapacity(final IAllocationRequest request)
{
final ProductId productId = request.getProductId();
final Capacity capacityToUse;
final Capacity capacityOverride = productId2capacity.get(productId);
if (capacityOverride == null)
{
// So there was no override capacity provided for this product.
// The allocationStrategy we are creating just now might execute against the aggregate VHU which does not have any M_HU_PI_Item_Products and therefore does not know the TUs actual capacity.
// To compensate for this, we now find out the TU's capacity and make it the allocation strategy's upper bound
final List<I_M_HU_PI_Item> materialPIItems = handlingUnitsDAO.retrievePIItems(tuPI, getBPartnerId()).stream()
.filter(piItem -> Objects.equals(X_M_HU_PI_Item.ITEMTYPE_Material, piItem.getItemType()))
.collect(Collectors.toList());
Check.errorIf(materialPIItems.size() != 1, "There has to be exactly one M_HU_PI_Item for the TU's M_HU_PI and and C_BPartner;\n "
+ "M_HU_PI={};\n "
+ "C_BPartner={};\n "
+ "M_HU_PI_Item(s) found={}\n "
+ "this={}", tuPI, getBPartnerId(), materialPIItems, this);
final I_M_HU_PI_Item_Product itemProduct = hupiItemProductDAO.retrievePIMaterialItemProduct(materialPIItems.get(0), getBPartnerId(), request.getProductId(), request.getDate());
capacityToUse = capacityBL.getCapacity(itemProduct, request.getProductId(), request.getC_UOM());
}
else
{
capacityToUse = capacityOverride; // we can go with capacityOverride==null, if the given hu is a "real" one (not aggregate), because the code will use the hu's PI-item.
}
return capacityToUse;
}
|
public ArrayList<LUTUResult.TU> getResult()
{
final ArrayList<LUTUResult.TU> result = new ArrayList<>();
for (final I_M_HU tu : getCreatedHUs())
{
if (handlingUnitsBL.isAggregateHU(tu) && handlingUnitsBL.getTUsCount(tu).isPositive())
{
final QtyTU qtyTU = handlingUnitsBL.getTUsCount(tu);
result.add(LUTUResult.TU.ofAggregatedTU(tu, qtyTU));
}
else if (!handlingUnitsBL.isAggregateHU(tu))
{
result.add(LUTUResult.TU.ofSingleTU(tu));
}
}
return result;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\impl\TUProducerDestination.java
| 1
|
请完成以下Java代码
|
public static void backIterable1(BinTreeNode<String> root, List<String> list) {
if (root == null) {
return;
}
backIterable1(root.left, list);
backIterable1(root.right, list);
list.add(root.data);
}
/**
* 中序遍历递归:先左、后右、再根
* <p>
* "B","D","A","C"
*/
public static void backIterable2(BinTreeNode<String> root, List<String> list) {
Stack<BinTreeNode<String>> stack = new Stack<>();
BinTreeNode<String> prev = null, curr = root;
while (curr != null || !stack.isEmpty()) {
while (curr != null) {
// 添加根节点
stack.push(curr);
// 递归添加左节点
curr = curr.left;
}
// 已经访问到最左节点了
curr = stack.peek();
// 是否存在右节点或者右节点已经访问过的情况下,访问根节点
if (curr.right == null || curr.right == prev) {
stack.pop();
list.add(curr.data);
prev = curr;
// 不重复访问自己
curr = null;
} else {
// 右节点还没有访问过就先访问右节点
curr = curr.right;
}
}
}
/**
* 层序遍历
*
* @param root
* @return
*/
public static void layerIterable2(BinTreeNode<String> root, List<String> list) {
LinkedList<BinTreeNode<String>> queue = new LinkedList<>();
|
if (root == null) {
return;
}
queue.addLast(root);
while (!queue.isEmpty()) {
BinTreeNode<String> p = queue.poll();
list.add(p.data);
if (p.left != null) {
queue.addLast(p.left);
}
if (p.right != null) {
queue.addLast(p.right);
}
}
}
static class BinTreeNode<T> {
/**
* 数据
*/
T data;
/**
* 左节点
*/
BinTreeNode<T> left;
/**
* 右节点
*/
BinTreeNode<T> right;
public BinTreeNode(T data, BinTreeNode left, BinTreeNode right) {
this.data = data;
this.left = left;
this.right = right;
}
@Override
public String toString() {
return data.toString();
}
}
}
|
repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\BinTreeIterable.java
| 1
|
请完成以下Java代码
|
private Optional<Account> getProductAccount(final @NonNull AcctSchemaId acctSchemaId, final @NonNull ProductAcctType acctType)
{
return invoiceAccounts.getElementValueId(acctSchemaId, acctType.getAccountConceptualName(), invoiceAndLineId)
.map(elementValueId -> getOrCreateAccount(elementValueId, acctSchemaId))
.map(id -> Account.of(id, acctType));
}
@Override
@NonNull
public Optional<Account> getBPartnerCustomerAccount(@NonNull final AcctSchemaId acctSchemaId, @NonNull final BPartnerId bpartnerId, @NonNull final BPartnerCustomerAccountType acctType)
{
return Optional.empty();
}
@Override
@NonNull
public Optional<Account> getBPartnerVendorAccount(@NonNull final AcctSchemaId acctSchemaId, @NonNull final BPartnerId bpartnerId, @NonNull final BPartnerVendorAccountType acctType)
{
return Optional.empty();
}
@Override
@NonNull
public Optional<Account> getBPGroupAccount(@NonNull final AcctSchemaId acctSchemaId, @NonNull final BPGroupId bpGroupId, @NonNull final BPartnerGroupAccountType acctType)
{
|
return Optional.empty();
}
@NonNull
private AccountId getOrCreateAccount(
@NonNull final ElementValueId elementValueId,
@NonNull final AcctSchemaId acctSchemaId)
{
return accountDAO.getOrCreateOutOfTrx(
AccountDimension.builder()
.setAcctSchemaId(acctSchemaId)
.setC_ElementValue_ID(elementValueId.getRepoId())
.setAD_Client_ID(clientId.getRepoId())
.setAD_Org_ID(OrgId.ANY.getRepoId())
.build());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\accounts\InvoiceAccountProviderExtension.java
| 1
|
请完成以下Java代码
|
public void setCopies (int Copies)
{
set_Value (COLUMNNAME_Copies, Integer.valueOf(Copies));
}
@Override
public int getCopies()
{
return get_ValueAsInt(COLUMNNAME_Copies);
}
@Override
public de.metas.printing.model.I_C_Print_Job_Instructions getC_Print_Job_Instructions()
{
return get_ValueAsPO(COLUMNNAME_C_Print_Job_Instructions_ID, de.metas.printing.model.I_C_Print_Job_Instructions.class);
}
@Override
public void setC_Print_Job_Instructions(de.metas.printing.model.I_C_Print_Job_Instructions C_Print_Job_Instructions)
{
set_ValueFromPO(COLUMNNAME_C_Print_Job_Instructions_ID, de.metas.printing.model.I_C_Print_Job_Instructions.class, C_Print_Job_Instructions);
}
@Override
public void setC_Print_Job_Instructions_ID (int C_Print_Job_Instructions_ID)
{
if (C_Print_Job_Instructions_ID < 1)
set_Value (COLUMNNAME_C_Print_Job_Instructions_ID, null);
else
set_Value (COLUMNNAME_C_Print_Job_Instructions_ID, Integer.valueOf(C_Print_Job_Instructions_ID));
}
@Override
public int getC_Print_Job_Instructions_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Print_Job_Instructions_ID);
}
@Override
public void setC_Print_Package_ID (int C_Print_Package_ID)
{
if (C_Print_Package_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Print_Package_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Print_Package_ID, Integer.valueOf(C_Print_Package_ID));
}
@Override
public int getC_Print_Package_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Print_Package_ID);
}
@Override
public void setPackageInfoCount (int PackageInfoCount)
{
throw new IllegalArgumentException ("PackageInfoCount is virtual column"); }
@Override
|
public int getPackageInfoCount()
{
return get_ValueAsInt(COLUMNNAME_PackageInfoCount);
}
@Override
public void setPageCount (int PageCount)
{
set_Value (COLUMNNAME_PageCount, Integer.valueOf(PageCount));
}
@Override
public int getPageCount()
{
return get_ValueAsInt(COLUMNNAME_PageCount);
}
@Override
public void setTransactionID (java.lang.String TransactionID)
{
set_Value (COLUMNNAME_TransactionID, TransactionID);
}
@Override
public java.lang.String getTransactionID()
{
return (java.lang.String)get_Value(COLUMNNAME_TransactionID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_Package.java
| 1
|
请完成以下Java代码
|
class DirectoryChecker
{
/**
*
* @param name just for context/debuggin/loggin
* @param dir the directory to be checked
*
* @return the absolute directory
*/
public File checkDirectory(@NonNull final String name, @NonNull final String dir)
{
return checkDirectory(name, new File(dir));
}
public File checkDirectory(@NonNull final String name, @NonNull final File dir)
{
if (!dir.exists())
{
throw new IllegalArgumentException(name + " '" + dir + "' does not exist");
}
final File dirAbs;
|
try
{
dirAbs = dir.getCanonicalFile();
}
catch (final IOException e)
{
throw new IllegalArgumentException(name + " '" + dir + "' is not accessible", e);
}
if (!dirAbs.isDirectory())
{
throw new IllegalArgumentException(name + " '" + dirAbs + "' is not a directory");
}
if (!dirAbs.canRead())
{
throw new IllegalArgumentException(name + " '" + dirAbs + "' is not readable");
}
return dirAbs;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\rollout_migrate\DirectoryChecker.java
| 1
|
请完成以下Java代码
|
private static void setSummaryDataToRecord(@NonNull final I_C_CallOrderSummary record, @NonNull final CallOrderSummaryData callOrderSummaryData)
{
record.setC_Order_ID(callOrderSummaryData.getOrderId().getRepoId());
record.setC_OrderLine_ID(callOrderSummaryData.getOrderLineId().getRepoId());
record.setC_Flatrate_Term_ID(callOrderSummaryData.getFlatrateTermId().getRepoId());
record.setM_Product_ID(callOrderSummaryData.getProductId().getRepoId());
record.setC_UOM_ID(callOrderSummaryData.getUomId().getRepoId());
record.setQtyEntered(callOrderSummaryData.getQtyEntered());
record.setQtyDeliveredInUOM(callOrderSummaryData.getQtyDelivered());
record.setQtyInvoicedInUOM(callOrderSummaryData.getQtyInvoiced());
record.setPOReference(callOrderSummaryData.getPoReference());
record.setIsSOTrx(callOrderSummaryData.getSoTrx().toBoolean());
if (callOrderSummaryData.getAttributeSetInstanceId() != null)
{
record.setM_AttributeSetInstance_ID(callOrderSummaryData.getAttributeSetInstanceId().getRepoId());
}
}
@NonNull
private static CallOrderSummary ofRecord(@NonNull final I_C_CallOrderSummary record)
{
return CallOrderSummary.builder()
.summaryId(CallOrderSummaryId.ofRepoId(record.getC_CallOrderSummary_ID()))
.summaryData(ofRecordData(record))
.build();
}
@NonNull
private static CallOrderSummaryData ofRecordData(@NonNull final I_C_CallOrderSummary record)
{
return CallOrderSummaryData.builder()
|
.orderId(OrderId.ofRepoId(record.getC_Order_ID()))
.orderLineId(OrderLineId.ofRepoId(record.getC_OrderLine_ID()))
.flatrateTermId(FlatrateTermId.ofRepoId(record.getC_Flatrate_Term_ID()))
.productId(ProductId.ofRepoId(record.getM_Product_ID()))
.uomId(UomId.ofRepoId(record.getC_UOM_ID()))
.qtyEntered(record.getQtyEntered())
.attributeSetInstanceId(AttributeSetInstanceId.ofRepoIdOrNull(record.getM_AttributeSetInstance_ID()))
.qtyDelivered(record.getQtyDeliveredInUOM())
.qtyInvoiced(record.getQtyInvoicedInUOM())
.poReference(record.getPOReference())
.isActive(record.isActive())
.soTrx(SOTrx.ofBoolean(record.isSOTrx()))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\callorder\summary\CallOrderSummaryRepo.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ThreadStarvationApp {
private static final Logger LOG = LogManager.getLogger(ThreadStarvationApp.class);
public static void main(String[] args) {
SpringApplication.run(ThreadStarvationApp.class);
}
@RestController
class RestApi {
@GetMapping("/blocking")
Mono<String> getBlocking() {
return Mono.fromCallable(() -> {
try {
Thread.sleep(2_000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return "foo";
});
}
@GetMapping("/non-blocking")
Mono<String> getNonBlocking() {
return Mono.just("bar")
.delayElement(Duration.ofSeconds(2));
}
@SuppressWarnings("BlockingMethodInNonBlockingContext")
@GetMapping("/warning")
Mono<String> warning() {
Mono<String> data = fetchData();
String response = "retrieved data: " + data.block();
return Mono.just(response);
}
private Mono<String> fetchData() {
|
return Mono.just("bar");
}
@GetMapping("/blocking-with-scheduler")
Mono<String> getBlockingWithDedicatedScheduler() {
return Mono.fromCallable(this::fetchDataBlocking)
.subscribeOn(Schedulers.boundedElastic())
.map(data -> "retrieved data: " + data);
}
private String fetchDataBlocking() {
try {
Thread.sleep(2_000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return "foo";
}
}
}
|
repos\tutorials-master\spring-reactive-modules\spring-webflux-2\src\main\java\com\baeldung\webflux\threadstarvation\ThreadStarvationApp.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class ReturnsServiceFacade
{
private final IHUInOutBL huInOutBL = Services.get(IHUInOutBL.class);
private final CustomerReturnsWithoutHUsProducer customerReturnsWithoutHUsProducer;
public ReturnsServiceFacade(
@NonNull final CustomerReturnsWithoutHUsProducer customerReturnsWithoutHUsProducer)
{
this.customerReturnsWithoutHUsProducer = customerReturnsWithoutHUsProducer;
}
public boolean isCustomerReturn(@NonNull final org.compiere.model.I_M_InOut inout)
{
return huInOutBL.isCustomerReturn(inout);
}
public boolean isVendorReturn(@NonNull final org.compiere.model.I_M_InOut inout)
{
return huInOutBL.isVendorReturn(inout);
}
public boolean isEmptiesReturn(@NonNull final org.compiere.model.I_M_InOut inout)
{
return huInOutBL.isEmptiesReturn(inout);
}
public MultiCustomerHUReturnsResult createCustomerReturnInOutForHUs(final Collection<I_M_HU> shippedHUsToReturn)
{
return MultiCustomerHUReturnsInOutProducer.builder()
.shippedHUsToReturn(shippedHUsToReturn)
.build()
.create();
}
public void createVendorReturnInOutForHUs(final List<I_M_HU> hus, final Timestamp movementDate)
{
MultiVendorHUReturnsInOutProducer.newInstance()
.setMovementDate(movementDate)
.addHUsToReturn(hus)
.create();
}
public List<InOutId> createCustomerReturnsFromCandidates(@NonNull final List<CustomerReturnLineCandidate> candidates)
{
return customerReturnsWithoutHUsProducer.create(candidates);
}
public I_M_InOutLine createCustomerReturnLine(@NonNull final CreateCustomerReturnLineReq request)
{
return customerReturnsWithoutHUsProducer.createReturnLine(request);
}
|
public void assignHandlingUnitToHeaderAndLine(
@NonNull final org.compiere.model.I_M_InOutLine customerReturnLine,
@NonNull final I_M_HU hu)
{
final ImmutableList<I_M_HU> hus = ImmutableList.of(hu);
assignHandlingUnitsToHeaderAndLine(customerReturnLine, hus);
}
public void assignHandlingUnitsToHeaderAndLine(
@NonNull final org.compiere.model.I_M_InOutLine customerReturnLine,
@NonNull final List<I_M_HU> hus)
{
if (hus.isEmpty())
{
return;
}
final InOutId customerReturnId = InOutId.ofRepoId(customerReturnLine.getM_InOut_ID());
final I_M_InOut customerReturn = huInOutBL.getById(customerReturnId, I_M_InOut.class);
huInOutBL.addAssignedHandlingUnits(customerReturn, hus);
huInOutBL.setAssignedHandlingUnits(customerReturnLine, hus);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\ReturnsServiceFacade.java
| 2
|
请完成以下Java代码
|
private Mono<Void> onAuthenticationSuccess(Authentication authentication, WebFilterExchange webFilterExchange) {
OAuth2AuthorizationCodeAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(
authenticationResult.getClientRegistration(), authenticationResult.getName(),
authenticationResult.getAccessToken(), authenticationResult.getRefreshToken());
// @formatter:off
return this.authenticationSuccessHandler.onAuthenticationSuccess(webFilterExchange, authentication)
.then(ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.defaultIfEmpty(this.anonymousToken)
.flatMap((principal) -> this.authorizedClientRepository
.saveAuthorizedClient(authorizedClient, principal, webFilterExchange.getExchange())
)
);
// @formatter:on
}
private Mono<ServerWebExchangeMatcher.MatchResult> matchesAuthorizationResponse(ServerWebExchange exchange) {
// @formatter:off
return Mono.just(exchange)
.filter((exch) ->
OAuth2AuthorizationResponseUtils.isAuthorizationResponse(exch.getRequest().getQueryParams())
)
.flatMap((exch) -> this.authorizationRequestRepository.loadAuthorizationRequest(exchange)
.flatMap((authorizationRequest) -> matchesRedirectUri(exch.getRequest().getURI(),
authorizationRequest.getRedirectUri()))
)
.switchIfEmpty(ServerWebExchangeMatcher.MatchResult.notMatch());
// @formatter:on
}
private static Mono<ServerWebExchangeMatcher.MatchResult> matchesRedirectUri(URI authorizationResponseUri,
String authorizationRequestRedirectUri) {
UriComponents requestUri = UriComponentsBuilder.fromUri(authorizationResponseUri).build();
UriComponents redirectUri = UriComponentsBuilder.fromUriString(authorizationRequestRedirectUri).build();
Set<Map.Entry<String, List<String>>> requestUriParameters = new LinkedHashSet<>(
requestUri.getQueryParams().entrySet());
Set<Map.Entry<String, List<String>>> redirectUriParameters = new LinkedHashSet<>(
redirectUri.getQueryParams().entrySet());
|
// Remove the additional request parameters (if any) from the authorization
// response (request)
// before doing an exact comparison with the authorizationRequest.getRedirectUri()
// parameters (if any)
requestUriParameters.retainAll(redirectUriParameters);
if (Objects.equals(requestUri.getScheme(), redirectUri.getScheme())
&& Objects.equals(requestUri.getUserInfo(), redirectUri.getUserInfo())
&& Objects.equals(requestUri.getHost(), redirectUri.getHost())
&& Objects.equals(requestUri.getPort(), redirectUri.getPort())
&& Objects.equals(requestUri.getPath(), redirectUri.getPath())
&& Objects.equals(requestUriParameters.toString(), redirectUriParameters.toString())) {
return ServerWebExchangeMatcher.MatchResult.match();
}
return ServerWebExchangeMatcher.MatchResult.notMatch();
}
}
|
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\server\OAuth2AuthorizationCodeGrantWebFilter.java
| 1
|
请完成以下Java代码
|
public Optional<InvoiceId> getInvoiceId()
{
return I_C_Invoice.Table_Name.equals(tableName)
? InvoiceId.optionalOfRepoId(recordId)
: Optional.empty();
}
public Optional<PaymentId> getPaymentId()
{
return I_C_Payment.Table_Name.equals(tableName)
? PaymentId.optionalOfRepoId(recordId)
: Optional.empty();
}
public Optional<BankStatementId> getBankStatementId()
{
return I_C_BankStatement.Table_Name.equals(tableName)
|
? BankStatementId.optionalOfRepoId(recordId)
: Optional.empty();
}
public Optional<BankStatementLineId> getBankStatementLineId()
{
return I_C_BankStatement.Table_Name.equals(tableName)
? BankStatementLineId.optionalOfRepoId(lineId)
: Optional.empty();
}
public Optional<BankStatementLineRefId> getBankStatementLineRefId()
{
return I_C_BankStatement.Table_Name.equals(tableName)
? BankStatementLineRefId.optionalOfRepoId(subLineId)
: Optional.empty();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\open_items\FAOpenItemKey.java
| 1
|
请完成以下Java代码
|
public RequestData getRequest() {
return request;
}
public HttpResponse getResponse() {
return response;
}
public Throwable getException() {
return exception;
}
}
public static class RequestData {
protected HttpRequest httpRequest;
protected Set<String> failCodes;
protected Set<String> handleCodes;
protected boolean ignoreErrors;
protected boolean saveRequest;
protected boolean saveResponse;
protected boolean saveResponseTransient;
protected boolean saveResponseAsJson;
protected String prefix;
public HttpRequest getHttpRequest() {
return httpRequest;
}
public void setHttpRequest(HttpRequest httpRequest) {
this.httpRequest = httpRequest;
}
public Set<String> getFailCodes() {
return failCodes;
}
public void setFailCodes(Set<String> failCodes) {
this.failCodes = failCodes;
}
public Set<String> getHandleCodes() {
return handleCodes;
}
public void setHandleCodes(Set<String> handleCodes) {
this.handleCodes = handleCodes;
}
public boolean isIgnoreErrors() {
return ignoreErrors;
}
public void setIgnoreErrors(boolean ignoreErrors) {
this.ignoreErrors = ignoreErrors;
}
|
public boolean isSaveRequest() {
return saveRequest;
}
public void setSaveRequest(boolean saveRequest) {
this.saveRequest = saveRequest;
}
public boolean isSaveResponse() {
return saveResponse;
}
public void setSaveResponse(boolean saveResponse) {
this.saveResponse = saveResponse;
}
public boolean isSaveResponseTransient() {
return saveResponseTransient;
}
public void setSaveResponseTransient(boolean saveResponseTransient) {
this.saveResponseTransient = saveResponseTransient;
}
public boolean isSaveResponseAsJson() {
return saveResponseAsJson;
}
public void setSaveResponseAsJson(boolean saveResponseAsJson) {
this.saveResponseAsJson = saveResponseAsJson;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public boolean isNoRedirects() {
return httpRequest.isNoRedirects();
}
}
}
|
repos\flowable-engine-main\modules\flowable-http-common\src\main\java\org\flowable\http\common\impl\BaseHttpActivityDelegate.java
| 1
|
请完成以下Java代码
|
public void setGO_DeliveryOrder_Log_ID (int GO_DeliveryOrder_Log_ID)
{
if (GO_DeliveryOrder_Log_ID < 1)
set_ValueNoCheck (COLUMNNAME_GO_DeliveryOrder_Log_ID, null);
else
set_ValueNoCheck (COLUMNNAME_GO_DeliveryOrder_Log_ID, Integer.valueOf(GO_DeliveryOrder_Log_ID));
}
/** Get GO Delivery Order Log.
@return GO Delivery Order Log */
@Override
public int getGO_DeliveryOrder_Log_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GO_DeliveryOrder_Log_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Fehler.
@param IsError
Ein Fehler ist bei der Durchführung aufgetreten
*/
@Override
public void setIsError (boolean IsError)
{
set_Value (COLUMNNAME_IsError, Boolean.valueOf(IsError));
}
/** Get Fehler.
@return Ein Fehler ist bei der Durchführung aufgetreten
*/
@Override
public boolean isError ()
{
Object oo = get_Value(COLUMNNAME_IsError);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Request Message.
@param RequestMessage Request Message */
@Override
public void setRequestMessage (java.lang.String RequestMessage)
{
set_Value (COLUMNNAME_RequestMessage, RequestMessage);
}
|
/** Get Request Message.
@return Request Message */
@Override
public java.lang.String getRequestMessage ()
{
return (java.lang.String)get_Value(COLUMNNAME_RequestMessage);
}
/** Set Response Message.
@param ResponseMessage Response Message */
@Override
public void setResponseMessage (java.lang.String ResponseMessage)
{
set_Value (COLUMNNAME_ResponseMessage, ResponseMessage);
}
/** Get Response Message.
@return Response Message */
@Override
public java.lang.String getResponseMessage ()
{
return (java.lang.String)get_Value(COLUMNNAME_ResponseMessage);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java-gen\de\metas\shipper\gateway\go\model\X_GO_DeliveryOrder_Log.java
| 1
|
请完成以下Java代码
|
public View create(Element elem) {
View result;
result = oldFactory.create(elem);
if (result instanceof ImageView) {
String src = (String)elem.getAttributes().
getAttribute(HTML.Attribute.SRC);
if ("res:".equals(src.substring(0, 4))) {
result = new NewImageView(elem);
}
}
return result;
}
private static class NewImageView extends ImageView {
Element elem;
public NewImageView(Element elem) {
super(elem);
this.elem=elem;
}
public Image getImage() {
//return smile image
//java.awt.Toolkit.getDefaultToolkit().getImage(getImageURL()).flush();
//if (smileImage == null) {
String src = (String)elem.getAttributes().
getAttribute(HTML.Attribute.SRC);
//System.out.println("img load: " + src.substring(4));
URL url = getClass().getClassLoader().
getResource(src.substring(4));
//getResource("at/freecom/apps/images/freecom.gif");
//getResource("javax/swing/text/html/icons/image-delayed.gif");
if (url == null) return null;
smileImage = Toolkit.getDefaultToolkit().getImage(url);
if (smileImage==null) return null;
//forcing image to load synchronously
ImageIcon ii = new ImageIcon();
ii.setImage(smileImage);
//}
return smileImage;
}
public URL getImageURL() {
// here we return url to some image. It might be any
// existing image. we need to move ImageView to the
// state where it thinks that image was loaded.
// ImageView is calling getImage to get image for
|
// measurement and painting when image was loaded
if (false) {
return getClass().getClassLoader().
getResource("javax/swing/text/html/icons/image-delayed.gif");
} else {
String src = (String)elem.getAttributes().
getAttribute(HTML.Attribute.SRC);
//System.out.println("img load: " + src.substring(4));
URL url = getClass().getClassLoader().
getResource(src.substring(4));
if (url != null) {
// System.out.println("load image: " + url);
return url;
}
}
return null;
}
private static Image smileImage = null;
}
private ViewFactory oldFactory;
}
private static ViewFactory defaultFactory = null;
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\apps\graph\FCHtmlEditorKit.java
| 1
|
请完成以下Java代码
|
public PlanItem getPlanItem() {
return planItem;
}
public String getName() {
return name;
}
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public String getDerivedCaseDefinitionId() {
return derivedCaseDefinitionId;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public PlanItemInstance getStagePlanItemInstance() {
return stagePlanItemInstance;
}
public String getTenantId() {
return tenantId;
}
public Map<String, Object> getLocalVariables() {
return localVariables;
}
public boolean hasLocalVariables() {
return localVariables != null && localVariables.size() > 0;
}
|
public boolean isAddToParent() {
return addToParent;
}
public boolean isSilentNameExpressionEvaluation() {
return silentNameExpressionEvaluation;
}
protected void validateData() {
if (planItem == null) {
throw new FlowableIllegalArgumentException("The plan item must be provided when creating a new plan item instance");
}
if (caseDefinitionId == null) {
throw new FlowableIllegalArgumentException("The case definition id must be provided when creating a new plan item instance");
}
if (caseInstanceId == null) {
throw new FlowableIllegalArgumentException("The case instance id must be provided when creating a new plan item instance");
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\PlanItemInstanceEntityBuilderImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
JettyServletWebServerFactory jettyServletWebServerFactory(ObjectProvider<JettyServerCustomizer> serverCustomizers) {
JettyServletWebServerFactory factory = new JettyServletWebServerFactory();
factory.getServerCustomizers().addAll(serverCustomizers.orderedStream().toList());
return factory;
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(JakartaWebSocketServletContainerInitializer.class)
static class JettyWebSocketConfiguration {
@Bean
@ConditionalOnMissingBean(name = "websocketServletWebServerCustomizer")
WebSocketJettyServletWebServerFactoryCustomizer websocketServletWebServerCustomizer() {
return new WebSocketJettyServletWebServerFactoryCustomizer();
}
@Bean
|
@ConditionalOnNotWarDeployment
@Order(Ordered.LOWEST_PRECEDENCE)
@ConditionalOnMissingBean(name = "websocketUpgradeFilterWebServerCustomizer")
WebServerFactoryCustomizer<JettyServletWebServerFactory> websocketUpgradeFilterWebServerCustomizer() {
return (factory) -> {
factory.addInitializers((servletContext) -> {
Dynamic registration = servletContext.addFilter(WebSocketUpgradeFilter.class.getName(),
new WebSocketUpgradeFilter());
registration.setAsyncSupported(true);
registration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
});
};
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\autoconfigure\servlet\JettyServletWebServerAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public class AvroSerializer {
private static final Logger logger = LoggerFactory.getLogger(AvroSerializer.class);
public byte[] serializeAvroHttpRequestJSON(AvroHttpRequest request) {
DatumWriter<AvroHttpRequest> writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
byte[] data = new byte[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Encoder jsonEncoder = null;
try {
jsonEncoder = EncoderFactory.get()
.jsonEncoder(AvroHttpRequest.getClassSchema(), stream);
writer.write(request, jsonEncoder);
jsonEncoder.flush();
data = stream.toByteArray();
} catch (IOException e) {
logger.error("Serialization error " + e.getMessage());
}
return data;
}
public byte[] serializeAvroHttpRequestBinary(AvroHttpRequest request) {
DatumWriter<AvroHttpRequest> writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
|
byte[] data = new byte[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Encoder jsonEncoder = EncoderFactory.get()
.binaryEncoder(stream, null);
try {
writer.write(request, jsonEncoder);
jsonEncoder.flush();
data = stream.toByteArray();
} catch (IOException e) {
logger.error("Serialization error " + e.getMessage());
}
return data;
}
}
|
repos\tutorials-master\apache-libraries\src\main\java\com\baeldung\apache\avro\util\serialization\AvroSerializer.java
| 1
|
请完成以下Java代码
|
public Optional<String> getProperty(@NonNull final String name)
{
if (applicationContext != null)
{
final String springContextValue = StringUtils.trimBlankToNull(applicationContext.getEnvironment().getProperty(name));
if (springContextValue != null)
{
logger.debug("Returning the spring context's value {}={} instead of looking up the AD_SysConfig record", name, springContextValue);
return Optional.of(springContextValue);
}
}
else
{
// If there is no Spring context then go an check JVM System Properties.
// Usually we will get here when we will run some tools based on metasfresh framework.
final Properties systemProperties = System.getProperties();
final String systemPropertyValue = StringUtils.trimBlankToNull(systemProperties.getProperty(name));
if (systemPropertyValue != null)
{
logger.debug("Returning the JVM system property's value {}={} instead of looking up the AD_SysConfig record", name, systemPropertyValue);
return Optional.of(systemPropertyValue);
}
// If there is no JVM System Property then go and check environment variables
return StringUtils.trimBlankToOptional(System.getenv(name));
}
return Optional.empty();
}
//
//
|
//
@ToString
public static final class Lazy<T>
{
private final Class<T> requiredType;
private T bean;
private Lazy(@NonNull final Class<T> requiredType, @Nullable final T initialBean)
{
this.requiredType = requiredType;
this.bean = initialBean;
}
@NonNull
public T get()
{
T bean = this.bean;
if (bean == null)
{
bean = this.bean = instance.getBean(requiredType);
}
return bean;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\SpringContextHolder.java
| 1
|
请完成以下Java代码
|
protected final void addToPrivateAccess()
{
userRolePermissionsRepo.createPrivateAccess(CreateRecordPrivateAccessRequest.builder()
.recordRef(getRecordRef())
.principal(getPrincipal())
.build());
}
protected final void removeFromPrivateAccess()
{
userRolePermissionsRepo.deletePrivateAccess(RemoveRecordPrivateAccessRequest.builder()
.recordRef(getRecordRef())
.principal(getPrincipal())
.build());
}
private Principal getPrincipal()
{
final PrincipalType principalType = PrincipalType.ofCode(principalTypeCode);
|
if (PrincipalType.USER.equals(principalType))
{
return Principal.userId(userId);
}
else if (PrincipalType.USER_GROUP.equals(principalType))
{
return Principal.userGroupId(userGroupId);
}
else
{
throw new AdempiereException("@Unknown@ @PrincipalType@: " + principalType);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\process\RecordPrivateAccess_Base.java
| 1
|
请完成以下Java代码
|
public void setIsInvoiceEmailEnabled (final @Nullable java.lang.String IsInvoiceEmailEnabled)
{
set_Value (COLUMNNAME_IsInvoiceEmailEnabled, IsInvoiceEmailEnabled);
}
@Override
public java.lang.String getIsInvoiceEmailEnabled()
{
return get_ValueAsString(COLUMNNAME_IsInvoiceEmailEnabled);
}
@Override
public void setIsMembershipContact (final boolean IsMembershipContact)
{
set_Value (COLUMNNAME_IsMembershipContact, IsMembershipContact);
}
@Override
public boolean isMembershipContact()
{
return get_ValueAsBoolean(COLUMNNAME_IsMembershipContact);
}
@Override
public void setIsNewsletter (final boolean IsNewsletter)
{
set_Value (COLUMNNAME_IsNewsletter, IsNewsletter);
}
@Override
public boolean isNewsletter()
{
return get_ValueAsBoolean(COLUMNNAME_IsNewsletter);
}
@Override
public void setLastname (final @Nullable java.lang.String Lastname)
{
set_Value (COLUMNNAME_Lastname, Lastname);
}
@Override
public java.lang.String getLastname()
{
return get_ValueAsString(COLUMNNAME_Lastname);
}
@Override
public void setPhone (final @Nullable java.lang.String Phone)
{
|
set_Value (COLUMNNAME_Phone, Phone);
}
@Override
public java.lang.String getPhone()
{
return get_ValueAsString(COLUMNNAME_Phone);
}
@Override
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 setTitle (final @Nullable java.lang.String Title)
{
set_Value (COLUMNNAME_Title, Title);
}
@Override
public java.lang.String getTitle()
{
return get_ValueAsString(COLUMNNAME_Title);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Contact_QuickInput.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class GroupTemplateRegularLineId implements RepoIdAware
{
int repoId;
@JsonCreator
public static GroupTemplateRegularLineId ofRepoId(final int repoId)
{
return new GroupTemplateRegularLineId(repoId);
}
@Nullable
public static GroupTemplateRegularLineId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static int toRepoId(@Nullable final GroupTemplateLineId id)
|
{
return id != null ? id.getRepoId() : -1;
}
private GroupTemplateRegularLineId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_CompensationGroup_Schema_TemplateLine_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\compensationGroup\GroupTemplateRegularLineId.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(sessionManagement ->
sessionManagement.sessionCreationPolicy(SessionCreationPolicy.ALWAYS))
.authorizeHttpRequests(authorizeRequests ->
authorizeRequests
.requestMatchers(HttpMethod.GET, "/eureka/**").hasRole("SYSTEM")
.requestMatchers(HttpMethod.POST, "/eureka/**").hasRole("SYSTEM")
.requestMatchers(HttpMethod.PUT, "/eureka/**").hasRole("SYSTEM")
.requestMatchers(HttpMethod.DELETE, "/eureka/**").hasRole("SYSTEM")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
|
}
@Configuration
// no order tag means this is the last security filter to be evaluated
public static class AdminSecurityConfig {
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication();
}
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.NEVER)).httpBasic(basic -> basic.disable()).authorizeRequests().requestMatchers(HttpMethod.GET, "/").hasRole("ADMIN").requestMatchers("/info", "/health").authenticated().anyRequest().denyAll()
.and().csrf(csrf -> csrf.disable());
}
}
}
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-bootstrap\discovery\src\main\java\com\baeldung\spring\cloud\bootstrap\discovery\SecurityConfig.java
| 2
|
请完成以下Java代码
|
public void setM_Tour_Instance_ID (int M_Tour_Instance_ID)
{
if (M_Tour_Instance_ID < 1)
set_Value (COLUMNNAME_M_Tour_Instance_ID, null);
else
set_Value (COLUMNNAME_M_Tour_Instance_ID, Integer.valueOf(M_Tour_Instance_ID));
}
/** Get Tour Instance.
@return Tour Instance */
@Override
public int getM_Tour_Instance_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Tour_Instance_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.tourplanning.model.I_M_TourVersion getM_TourVersion() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_TourVersion_ID, de.metas.tourplanning.model.I_M_TourVersion.class);
}
@Override
public void setM_TourVersion(de.metas.tourplanning.model.I_M_TourVersion M_TourVersion)
{
set_ValueFromPO(COLUMNNAME_M_TourVersion_ID, de.metas.tourplanning.model.I_M_TourVersion.class, M_TourVersion);
}
/** Set Tour Version.
@param M_TourVersion_ID Tour Version */
@Override
public void setM_TourVersion_ID (int M_TourVersion_ID)
{
if (M_TourVersion_ID < 1)
set_Value (COLUMNNAME_M_TourVersion_ID, null);
else
set_Value (COLUMNNAME_M_TourVersion_ID, Integer.valueOf(M_TourVersion_ID));
}
/** Get Tour Version.
@return Tour Version */
@Override
public int getM_TourVersion_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_TourVersion_ID);
if (ii == null)
return 0;
return ii.intValue();
|
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\tourplanning\model\X_M_DeliveryDay.java
| 1
|
请完成以下Spring Boot application配置
|
##########################################################
################## 所有profile共有的配置 #################
##########################################################
################### spring配置 ###################
spring:
profiles:
active: dev
jpa:
properties:
hibernate:
dialect: org.hibernate.dialect.MySQLDialect
new_generator_mappings: false
format_sql: true
logging:
level:
org.hibernate.SQL: DEBUG
org.hibernate.type.descriptor.sql.BasicBinder: TRACE
---
#####################################################################
######################## 开发环境profile ##########################
#####################################################################
spring:
profiles: dev
datasource:
url: jdbc:mysql://127.0.0.1:3306/pos?serverTimezone=UTC&useSSL=false&autoReconnect=true&tinyInt1isBit=false&useUnicode=true&characterEncoding=utf8
username: root
password: 123456
logging:
level:
ROOT: INFO
com:
xncoding: DEBUG
file: E:/logs/app.log
---
######################################################
|
###############
######################## 测试环境profile ##########################
#####################################################################
spring:
profiles: test
datasource:
url: jdbc:mysql://127.0.0.1:3306/pos?serverTimezone=UTC&useSSL=false&autoReconnect=true&tinyInt1isBit=false&useUnicode=true&characterEncoding=utf8
username: root
password: 123456
logging:
level:
ROOT: INFO
com:
xncoding: DEBUG
file: /var/logs/app.log
|
repos\SpringBootBucket-master\springboot-hibernate\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the bestellSupportId property.
*
*/
public int getBestellSupportId() {
return bestellSupportId;
}
/**
* Sets the value of the bestellSupportId property.
*
*/
public void setBestellSupportId(int value) {
this.bestellSupportId = value;
}
/**
* Gets the value of the nachtBetrieb property.
|
*
*/
public boolean isNachtBetrieb() {
return nachtBetrieb;
}
/**
* Sets the value of the nachtBetrieb property.
*
*/
public void setNachtBetrieb(boolean value) {
this.nachtBetrieb = value;
}
}
|
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\BestellungAntwort.java
| 1
|
请完成以下Java代码
|
public void init()
{
final IMaterialTrackingBL materialTrackingBL = Services.get(IMaterialTrackingBL.class);
materialTrackingBL.addModelTrackingListener(
InOutLineMaterialTrackingListener.LISTENER_TableName,
InOutLineMaterialTrackingListener.instance);
}
@Override
protected final boolean isEligibleForMaterialTracking(final I_M_InOut receipt)
{
// Shipments are not eligible
if (receipt.isSOTrx())
{
return false;
}
// reversals are not eligible either, because there counterpart is also unlinked
if (Services.get(IInOutBL.class).isReversal(receipt))
{
return false;
}
return true;
}
/**
* Returns all active inout lines, including packaging lines.<br>
* We do include packaging lines, because we need them to have a <code>M_Material_Trackinf_Ref</code>. That's because we need to pass on the inout lines M_Material_Tracking_Id to its invoice
* candidate. and we want to do so in a uniform way.<br>
* Also note that the qtys from HUs with different M_Material_Trackings will never be aggregated into one packaging line.
*/
@Override
protected List<I_M_InOutLine> retrieveDocumentLines(final I_M_InOut document)
{
final IInOutDAO inoutDAO = Services.get(IInOutDAO.class);
final List<I_M_InOutLine> documentLines = new ArrayList<I_M_InOutLine>();
for (final I_M_InOutLine iol : inoutDAO.retrieveLines(document, I_M_InOutLine.class))
{
documentLines.add(iol);
}
return documentLines;
}
@Override
protected I_M_Material_Tracking getMaterialTrackingFromDocumentLineASI(final I_M_InOutLine documentLine)
{
|
final de.metas.materialtracking.model.I_M_InOutLine iolExt = InterfaceWrapperHelper.create(documentLine, de.metas.materialtracking.model.I_M_InOutLine.class);
if (iolExt.getM_Material_Tracking_ID() > 0)
{
return iolExt.getM_Material_Tracking();
}
// fall-back in case the M_Material_Tracking_ID is not (yet) set
final IMaterialTrackingAttributeBL materialTrackingAttributeBL = Services.get(IMaterialTrackingAttributeBL.class);
final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(iolExt.getM_AttributeSetInstance_ID());
final I_M_Material_Tracking materialTracking = materialTrackingAttributeBL.getMaterialTrackingOrNull(asiId);
return materialTracking;
}
@Override
protected AttributeSetInstanceId getM_AttributeSetInstance(final I_M_InOutLine documentLine)
{
// shall not be called because we implement "getMaterialTrackingFromDocumentLineASI"
throw new IllegalStateException("shall not be called");
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\model\validator\M_InOut.java
| 1
|
请完成以下Java代码
|
public class IncidentInstanceHandler implements MigratingInstanceParseHandler<IncidentEntity> {
@Override
public void handle(MigratingInstanceParseContext parseContext, IncidentEntity incident) {
if (incident.getConfiguration() != null && isFailedJobIncident(incident)) {
handleFailedJobIncident(parseContext, incident);
}
else if (incident.getConfiguration() != null && isExternalTaskIncident(incident)) {
handleExternalTaskIncident(parseContext, incident);
}
else {
handleIncident(parseContext, incident);
}
}
protected void handleIncident(MigratingInstanceParseContext parseContext, IncidentEntity incident) {
MigratingActivityInstance owningInstance = parseContext.getMigratingActivityInstanceById(incident.getExecution().getActivityInstanceId());
if (owningInstance != null) {
parseContext.consume(incident);
MigratingIncident migratingIncident = new MigratingIncident(incident, owningInstance.getTargetScope());
owningInstance.addMigratingDependentInstance(migratingIncident);
}
}
protected boolean isFailedJobIncident(IncidentEntity incident) {
return IncidentEntity.FAILED_JOB_HANDLER_TYPE.equals(incident.getIncidentType());
}
protected void handleFailedJobIncident(MigratingInstanceParseContext parseContext, IncidentEntity incident) {
MigratingJobInstance owningInstance = parseContext.getMigratingJobInstanceById(incident.getConfiguration());
if (owningInstance != null) {
|
parseContext.consume(incident);
if (owningInstance.migrates()) {
MigratingIncident migratingIncident = new MigratingIncident(incident, owningInstance.getTargetScope());
JobDefinitionEntity targetJobDefinitionEntity = owningInstance.getTargetJobDefinitionEntity();
if (targetJobDefinitionEntity != null) {
migratingIncident.setTargetJobDefinitionId(targetJobDefinitionEntity.getId());
}
owningInstance.addMigratingDependentInstance(migratingIncident);
}
}
}
protected boolean isExternalTaskIncident(IncidentEntity incident) {
return IncidentEntity.EXTERNAL_TASK_HANDLER_TYPE.equals(incident.getIncidentType());
}
protected void handleExternalTaskIncident(MigratingInstanceParseContext parseContext, IncidentEntity incident) {
MigratingExternalTaskInstance owningInstance = parseContext.getMigratingExternalTaskInstanceById(incident.getConfiguration());
if (owningInstance != null) {
parseContext.consume(incident);
MigratingIncident migratingIncident = new MigratingIncident(incident, owningInstance.getTargetScope());
owningInstance.addMigratingDependentInstance(migratingIncident);
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\parser\IncidentInstanceHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getZIP() {
return zip;
}
/**
* Sets the value of the zip property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setZIP(String value) {
this.zip = value;
}
/**
* Country information.
*
* @return
* possible object is
* {@link CountryType }
*
*/
public CountryType getCountry() {
return country;
}
/**
* Sets the value of the country property.
*
* @param value
* allowed object is
* {@link CountryType }
*
*/
public void setCountry(CountryType value) {
this.country = value;
}
/**
* Any further elements or attributes which are necessary for an address may be provided here.
* Note that extensions should be used with care and only those extensions shall be used, which are officially provided by ERPEL.
* Gets the value of the addressExtension 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 addressExtension property.
|
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAddressExtension().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getAddressExtension() {
if (addressExtension == null) {
addressExtension = new ArrayList<String>();
}
return this.addressExtension;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\AddressType.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Filter corsFilter()
{
return new CORSFilter();
}
@Bean
public Filter addMissingHeadersFilter()
{
return new Filter()
{
@Override
public void init(final FilterConfig filterConfig)
{
}
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException
{
try
{
chain.doFilter(request, response);
}
finally
{
if (response instanceof HttpServletResponse)
{
final HttpServletResponse httpResponse = (HttpServletResponse)response;
//
// If the Cache-Control is not set then set it to no-cache.
|
// In this way we precisely tell to browser that it shall not cache our REST calls.
// The Cache-Control is usually defined by features like ETag
if (!httpResponse.containsHeader("Cache-Control"))
{
httpResponse.setHeader("Cache-Control", "no-cache");
}
}
}
}
@Override
public void destroy()
{
}
};
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\config\WebConfig.java
| 2
|
请完成以下Java代码
|
public String getPostingType ()
{
return (String)get_Value(COLUMNNAME_PostingType);
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
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 Usable Life - Months.
@param UseLifeMonths
Months of the usable life of the asset
*/
public void setUseLifeMonths (int UseLifeMonths)
{
set_Value (COLUMNNAME_UseLifeMonths, Integer.valueOf(UseLifeMonths));
}
|
/** Get Usable Life - Months.
@return Months of the usable life of the asset
*/
public int getUseLifeMonths ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseLifeMonths);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Usable Life - Years.
@param UseLifeYears
Years of the usable life of the asset
*/
public void setUseLifeYears (int UseLifeYears)
{
set_Value (COLUMNNAME_UseLifeYears, Integer.valueOf(UseLifeYears));
}
/** Get Usable Life - Years.
@return Years of the usable life of the asset
*/
public int getUseLifeYears ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseLifeYears);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Group_Acct.java
| 1
|
请完成以下Java代码
|
public String getKey() {
return null;
}
@Override
public String getTenantId() {
return activiti5Deployment.getTenantId();
}
@Override
public boolean isNew() {
return ((DeploymentEntity) activiti5Deployment).isNew();
}
@Override
public Map<String, EngineResource> getResources() {
return null;
}
@Override
public String getDerivedFrom() {
return null;
|
}
@Override
public String getDerivedFromRoot() {
return null;
}
@Override
public String getParentDeploymentId() {
return null;
}
@Override
public String getEngineVersion() {
return Flowable5Util.V5_ENGINE_TAG;
}
public org.activiti.engine.repository.Deployment getRawObject() {
return activiti5Deployment;
}
}
|
repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5DeploymentWrapper.java
| 1
|
请完成以下Java代码
|
public Map<String, TypedValueField> serializeVariables(Map<String, Object> variables) {
Map<String, TypedValueField> result = new HashMap<>();
if (variables != null) {
for (String variableName : variables.keySet()) {
Object variableValue = null;
if (variables instanceof VariableMap) {
variableValue = ((VariableMap) variables).getValueTyped(variableName);
}
else {
variableValue = variables.get(variableName);
}
try {
TypedValue typedValue = createTypedValue(variableValue);
TypedValueField typedValueField = toTypedValueField(typedValue);
result.put(variableName, typedValueField);
}
catch (Throwable e) {
throw LOG.cannotSerializeVariable(variableName, e);
}
}
}
return result;
}
@SuppressWarnings("rawtypes")
public Map<String, VariableValue> wrapVariables(ExternalTask externalTask, Map<String, TypedValueField> variables) {
String executionId = externalTask.getExecutionId();
Map<String, VariableValue> result = new HashMap<>();
if (variables != null) {
variables.forEach((variableName, variableValue) -> {
String typeName = variableValue.getType();
typeName = Character.toLowerCase(typeName.charAt(0)) + typeName.substring(1);
variableValue.setType(typeName);
VariableValue value = new VariableValue(executionId, variableName, variableValue, serializers);
result.put(variableName, value);
});
}
|
return result;
}
protected <T extends TypedValue> TypedValueField toTypedValueField(T typedValue) {
ValueMapper<T> serializer = findSerializer(typedValue);
if(typedValue instanceof UntypedValueImpl) {
typedValue = serializer.convertToTypedValue((UntypedValueImpl) typedValue);
}
TypedValueField typedValueField = new TypedValueField();
serializer.writeValue(typedValue, typedValueField);
ValueType valueType = typedValue.getType();
typedValueField.setValueInfo(valueType.getValueInfo(typedValue));
String typeName = valueType.getName();
String typeNameCapitalized = Character.toUpperCase(typeName.charAt(0)) + typeName.substring(1);
typedValueField.setType(typeNameCapitalized);
return typedValueField;
}
@SuppressWarnings("unchecked")
protected <T extends TypedValue> ValueMapper<T> findSerializer(T typedValue) {
return serializers.findMapperForTypedValue(typedValue);
}
protected TypedValue createTypedValue(Object value) {
TypedValue typedValue = null;
if (value instanceof TypedValue) {
typedValue = (TypedValue) value;
}
else {
typedValue = Variables.untypedValue(value);
}
return typedValue;
}
}
|
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\TypedValues.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.