instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public int mergeTable(final String TableName, final String ColumnName, final int from_ID, final int to_ID)
{
log.debug(TableName + "." + ColumnName + " - From=" + from_ID + ",To=" + to_ID);
String sql = "UPDATE " + TableName
+ " SET " + ColumnName + "=" + to_ID
+ " WHERE " + ColumnName + "=" + from_ID;
boolean delete = false;
for (final String m_deleteTable : m_deleteTables)
{
if (m_deleteTable.equals(TableName))
{
delete = true;
sql = "DELETE FROM " + TableName + " WHERE " + ColumnName + "=" + from_ID;
}
}
// Delete newly created MCost records - teo_sarca [ 1704554 ]
if (delete && X_M_Cost.Table_Name.equals(TableName) && M_PRODUCT_ID.equals(ColumnName))
{
sql += " AND " + X_M_Cost.COLUMNNAME_CurrentCostPrice + "=0"
+ " AND " + X_M_Cost.COLUMNNAME_CurrentQty + "=0"
+ " AND " + X_M_Cost.COLUMNNAME_CumulatedAmt + "=0"
+ " AND " + X_M_Cost.COLUMNNAME_CumulatedQty + "=0";
}
int count = DB.executeUpdateAndSaveErrorOnFail(sql, m_trx.getTrxName());
if (count < 0)
{
count = -1;
m_errorLog.append(Env.NL)
.append(delete ? "DELETE FROM " : "UPDATE ")
.append(TableName).append(" - ")
.append(" - ").append(sql);
log.info(m_errorLog.toString());
m_trx.rollback();
}
log.debug(count
+ (delete ? " -Delete- " : " -Update- ") + TableName);
return count;
} // mergeTable
/**
* Post Merge
*
* @param ColumnName column name
* @param to_ID ID
*/
public void postMerge(final String ColumnName, final int to_ID)
{
if (ColumnName.equals(AD_ORG_ID))
{
} | else if (ColumnName.equals(AD_USER_ID))
{
}
else if (ColumnName.equals(C_BPARTNER_ID))
{
// task FRESH-152 : Refactor
final I_C_BPartner partner = InterfaceWrapperHelper.create(Env.getCtx(), to_ID, I_C_BPartner.class, ITrx.TRXNAME_None);
if (partner != null)
{
final MPayment[] payments = MPayment.getOfBPartner(Env.getCtx(), partner.getC_BPartner_ID(), null);
for (final MPayment payment : payments)
{
if (payment.testAllocation())
{
payment.save();
}
}
final MInvoice[] invoices = MInvoice.getOfBPartner(Env.getCtx(), partner.getC_BPartner_ID(), null);
for (final MInvoice invoice : invoices)
{
if (invoice.testAllocation())
{
invoice.save();
}
}
// task FRESH-152. Update bpartner stats
Services.get(IBPartnerStatisticsUpdater.class)
.updateBPartnerStatistics(BPartnerStatisticsUpdateRequest.builder()
.bpartnerId(to_ID)
.build());
}
}
else if (ColumnName.equals(M_PRODUCT_ID))
{
}
} // postMerge
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\Merge.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BookstoreService {
private final AuthorRepository authorRepository;
private final BookRepository bookRepository;
private final PaperbackRepository paperbackRepository;
private final EbookRepository ebookRepository;
public BookstoreService(AuthorRepository authorRepository,
BookRepository bookRepository,
PaperbackRepository paperbackRepository,
EbookRepository ebookRepository) {
this.authorRepository = authorRepository;
this.bookRepository = bookRepository;
this.paperbackRepository = paperbackRepository;
this.ebookRepository = ebookRepository;
}
public void persistAuthorWithBooks() {
Author author = new Author();
author.setName("Alicia Tom");
author.setAge(38);
author.setGenre("Anthology");
Book book = new Book();
book.setIsbn("001-AT");
book.setTitle("The book of swords");
Paperback paperback = new Paperback();
paperback.setIsbn("002-AT");
paperback.setTitle("The beatles anthology");
paperback.setSizeIn("7.5 x 1.3 x 9.2");
paperback.setWeightLbs("2.7");
Ebook ebook = new Ebook();
ebook.setIsbn("003-AT");
ebook.setTitle("Anthology myths");
ebook.setFormat("kindle");
author.addBook(book);
author.addBook(paperback);
author.addBook(ebook);
authorRepository.save(author);
} | @Transactional(readOnly = true)
public void fetchBookByTitle() {
Book book = bookRepository.findByTitle("The book of swords");
System.out.println(book);
Paperback paperback = paperbackRepository.findByTitle("The beatles anthology");
System.out.println(paperback);
Ebook ebook = ebookRepository.findByTitle("Anthology myths");
System.out.println(ebook);
}
@Transactional(readOnly = true)
public void fetchBookByIsbn() {
Book book = bookRepository.fetchByIsbn("001-AT");
System.out.println(book);
Paperback paperback = paperbackRepository.fetchByIsbn("002-AT");
System.out.println(paperback);
Ebook ebook = ebookRepository.fetchByIsbn("003-AT");
System.out.println(ebook);
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootJoinTableRepositoryInheritance\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | protected ExecutionEntity resolveExecution(BatchJobContext context) {
return null;
}
@Override
protected MessageEntity newJobInstance(BatchJobContext context) {
return new MessageEntity();
}
@Override
protected JobHandlerConfiguration resolveJobHandlerConfiguration(BatchJobContext context) {
return new BatchJobConfiguration(context.getConfiguration().getId());
}
@Override
protected String resolveJobDefinitionId(BatchJobContext context) {
return context.getBatch().getBatchJobDefinitionId(); | }
@Override
public ParameterValueProvider getJobPriorityProvider() {
long batchJobPriority = Context.getProcessEngineConfiguration()
.getBatchJobPriority();
return new ConstantValueProvider(batchJobPriority);
}
@Override
public MessageEntity reconfigure(BatchJobContext context, MessageEntity job) {
super.reconfigure(context, job);
job.setJobHandlerConfiguration(new BatchJobConfiguration(context.getConfiguration().getId()));
return job;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\BatchJobDeclaration.java | 1 |
请完成以下Java代码 | public OptionalBoolean ifUnknown(@NonNull final OptionalBoolean other)
{
return isPresent() ? this : other;
}
@NonNull
public OptionalBoolean ifUnknown(@NonNull final Supplier<OptionalBoolean> otherSupplier)
{
return isPresent() ? this : otherSupplier.get();
}
@JsonValue
@Nullable
public Boolean toBooleanOrNull()
{
switch (this)
{
case TRUE:
return Boolean.TRUE;
case FALSE:
return Boolean.FALSE;
case UNKNOWN:
return null;
default:
throw new IllegalStateException("Type not handled: " + this);
}
}
@Nullable
public String toBooleanString()
{
return StringUtils.ofBoolean(toBooleanOrNull());
}
public void ifPresent(@NonNull final BooleanConsumer action)
{
if (this == TRUE) | {
action.accept(true);
}
else if (this == FALSE)
{
action.accept(false);
}
}
public void ifTrue(@NonNull final Runnable action)
{
if (this == TRUE)
{
action.run();
}
}
public <U> Optional<U> map(@NonNull final BooleanFunction<? extends U> mapper)
{
return isPresent() ? Optional.ofNullable(mapper.apply(isTrue())) : Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\OptionalBoolean.java | 1 |
请完成以下Java代码 | public class ProcessSuspendedListenerDelegate implements ActivitiEventListener {
private List<ProcessRuntimeEventListener<ProcessSuspendedEvent>> processRuntimeEventListeners;
private ToProcessSuspendedConverter processSuspendedConverter;
public ProcessSuspendedListenerDelegate(
List<ProcessRuntimeEventListener<ProcessSuspendedEvent>> listeners,
ToProcessSuspendedConverter processSuspendedConverter
) {
this.processRuntimeEventListeners = listeners;
this.processSuspendedConverter = processSuspendedConverter;
}
@Override
public void onEvent(ActivitiEvent event) {
if (event instanceof ActivitiEntityEvent) { | processSuspendedConverter
.from((ActivitiEntityEvent) event)
.ifPresent(convertedEvent -> {
for (ProcessRuntimeEventListener<ProcessSuspendedEvent> listener : processRuntimeEventListeners) {
listener.onEvent(convertedEvent);
}
});
}
}
@Override
public boolean isFailOnException() {
return false;
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\event\internal\ProcessSuspendedListenerDelegate.java | 1 |
请完成以下Java代码 | public void setPerson(List<KeyValuePair> person) {
this.person = person;
}
public static class KeyValuePair {
private String key;
private Object value;
public KeyValuePair() {
}
public KeyValuePair(String key, Object value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key; | }
public void setKey(String key) {
this.key = key;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
} | repos\tutorials-master\jackson-modules\jackson-conversions-3\src\main\java\com\baeldung\jackson\specifictype\dtos\PersonDTO.java | 1 |
请完成以下Java代码 | protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
/*
* 当没有使用缓存的时候,不断刷新页面的话,这个代码会不断执行,
* 当其实没有必要每次都重新设置权限信息,所以我们需要放到缓存中进行管理;
* 当放到缓存中时,这样的话,doGetAuthorizationInfo就只会执行一次了,
* 缓存过期之后会再次执行。
*/
_logger.info("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
ManagerInfo managerInfo = (ManagerInfo) principals.getPrimaryPrincipal();
//设置相应角色的权限信息
for (SysRole role : managerInfo.getRoles()) {
//设置角色
authorizationInfo.addRole(role.getRole());
for (Permission p : role.getPermissions()) {
//设置权限
authorizationInfo.addStringPermission(p.getPermission());
}
} | return authorizationInfo;
}
/**
* 设置认证加密方式
*/
@Override
public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
HashedCredentialsMatcher md5CredentialsMatcher = new HashedCredentialsMatcher();
md5CredentialsMatcher.setHashAlgorithmName(ShiroKit.HASH_ALGORITHM_NAME);
md5CredentialsMatcher.setHashIterations(ShiroKit.HASH_ITERATIONS);
super.setCredentialsMatcher(md5CredentialsMatcher);
}
} | repos\SpringBootBucket-master\springboot-shiro\src\main\java\com\xncoding\pos\shiro\MyShiroRealm.java | 1 |
请完成以下Java代码 | public String getDecisionKey() {
return decisionKey;
}
public void setDecisionKey(String decisionKey) {
this.decisionKey = decisionKey;
}
public String getDecisionId() {
return decisionId;
}
public void setDecisionId(String decisionId) {
this.decisionId = decisionId;
}
public int getDecisionVersion() {
return decisionVersion;
}
public void setDecisionVersion(int decisionVersion) {
this.decisionVersion = decisionVersion;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public String getParentDeploymentId() {
return parentDeploymentId;
}
public void setParentDeploymentId(String parentDeploymentId) {
this.parentDeploymentId = parentDeploymentId;
}
public String getInstanceId() {
return instanceId;
}
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public Map<String, Object> getVariables() {
return variables;
}
public void setVariables(Map<String, Object> variables) {
this.variables = variables;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) { | this.tenantId = tenantId;
}
public boolean isFallbackToDefaultTenant() {
return fallbackToDefaultTenant;
}
public void setFallbackToDefaultTenant(boolean fallbackToDefaultTenant) {
this.fallbackToDefaultTenant = fallbackToDefaultTenant;
}
public boolean isForceDMN11() {
return forceDMN11;
}
public void setForceDMN11(boolean forceDMN11) {
this.forceDMN11 = forceDMN11;
}
public boolean isDisableHistory() {
return disableHistory;
}
public void setDisableHistory(boolean disableHistory) {
this.disableHistory = disableHistory;
}
public DmnElement getDmnElement() {
return dmnElement;
}
public void setDmnElement(DmnElement dmnElement) {
this.dmnElement = dmnElement;
}
public DecisionExecutionAuditContainer getDecisionExecution() {
return decisionExecution;
}
public void setDecisionExecution(DecisionExecutionAuditContainer decisionExecution) {
this.decisionExecution = decisionExecution;
}
} | repos\flowable-engine-main\modules\flowable-dmn-api\src\main\java\org\flowable\dmn\api\ExecuteDecisionContext.java | 1 |
请完成以下Java代码 | public SingleAmqpConnectionFactory setConnectionOptions(ConnectionOptions connectionOptions) {
this.connectionOptions = connectionOptions.clone();
return this;
}
@Override
public Connection getConnection() {
Connection connectionToReturn = this.connection;
if (connectionToReturn == null) {
this.instanceLock.lock();
try {
connectionToReturn = this.connection;
if (connectionToReturn == null) {
connectionToReturn = this.protonjClient.connect(this.host, this.port, this.connectionOptions);
this.connection = connectionToReturn;
}
}
catch (ClientException ex) {
throw ProtonUtils.toAmqpException(ex);
} | finally {
this.instanceLock.unlock();
}
}
return connectionToReturn;
}
@Override
public void destroy() {
Connection connectionToClose = this.connection;
if (connectionToClose != null) {
connectionToClose.close();
this.connection = null;
}
}
} | repos\spring-amqp-main\spring-amqp-client\src\main\java\org\springframework\amqp\client\SingleAmqpConnectionFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public MonetaryAmountType getAdjustmentMonetaryAmount() {
return adjustmentMonetaryAmount;
}
/**
* Sets the value of the adjustmentMonetaryAmount property.
*
* @param value
* allowed object is
* {@link MonetaryAmountType }
*
*/
public void setAdjustmentMonetaryAmount(MonetaryAmountType value) {
this.adjustmentMonetaryAmount = value;
}
/**
* Taxes applied to the adjustment.
*
* @return
* possible object is
* {@link TaxType }
* | */
public TaxType getTax() {
return tax;
}
/**
* Sets the value of the tax property.
*
* @param value
* allowed object is
* {@link TaxType }
*
*/
public void setTax(TaxType value) {
this.tax = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\AdjustmentType.java | 2 |
请完成以下Java代码 | public Timer createTimer(String key, String... tags) {
Timer.Builder timerBuilder = Timer.builder(key)
.tags(tags)
.publishPercentiles();
if (timerPercentiles != null && timerPercentiles.length > 0) {
timerBuilder.publishPercentiles(timerPercentiles);
}
return timerBuilder.register(meterRegistry);
}
@Override
public StatsTimer createStatsTimer(String type, String name, String... tags) {
return new StatsTimer(name, Timer.builder(type)
.tags(getTags(name, tags))
.register(meterRegistry));
}
private static String[] getTags(String statsName, String[] otherTags) {
String[] tags = new String[]{STATS_NAME_TAG, statsName};
if (otherTags.length > 0) {
if (otherTags.length % 2 != 0) {
throw new IllegalArgumentException("Invalid tags array size");
}
tags = ArrayUtils.addAll(tags, otherTags);
} | return tags;
}
private static class StubCounter implements Counter {
@Override
public void increment(double amount) {
}
@Override
public double count() {
return 0;
}
@Override
public Id getId() {
return null;
}
}
} | repos\thingsboard-master\common\stats\src\main\java\org\thingsboard\server\common\stats\DefaultStatsFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}
/**
* Static resource locations including themes
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**/*")
.addResourceLocations("/", "/resources/")
.setCachePeriod(3600)
.resourceChain(true)
.addResolver(new PathResourceResolver());
}
/**
* View resolver for JSP
*/
@Bean
public UrlBasedViewResolver viewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class); | return resolver;
}
/**
* Configuration for async thread bean
*
* More: https://docs.spring.io/autorepo/docs/spring-framework/5.0.3.RELEASE/javadoc-api/org/springframework/scheduling/SchedulingTaskExecutor.html
*/
@Bean
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("CsvThread");
executor.initialize();
return executor;
}
} | repos\tutorials-master\ethereum\src\main\java\com\baeldung\web3j\config\AppConfig.java | 2 |
请完成以下Java代码 | protected void dispatchJobCanceledEvents(ExecutionEntity activityExecution) {
if (activityExecution != null) {
List<JobEntity> jobs = activityExecution.getJobs();
for (JobEntity job : jobs) {
if (Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
Context.getProcessEngineConfiguration()
.getEventDispatcher()
.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.JOB_CANCELED, job));
}
}
List<TimerJobEntity> timerJobs = activityExecution.getTimerJobs();
for (TimerJobEntity job : timerJobs) {
if (Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
Context.getProcessEngineConfiguration()
.getEventDispatcher()
.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.JOB_CANCELED, job));
}
}
}
}
/**
* Performs the default outgoing BPMN 2.0 behavior (@see {@link #performDefaultOutgoingBehavior(ExecutionEntity)}), but without checking the conditions on the outgoing sequence flow.
* <p>
* This means that every outgoing sequence flow is selected for continuing the process instance, regardless of having a condition or not. In case of multiple outgoing sequence flow, multiple
* parallel paths of executions will be created.
*/
public void performIgnoreConditionsOutgoingBehavior(ExecutionEntity activityExecution) {
performOutgoingBehavior(activityExecution, false, false);
} | /**
* Actual implementation of leaving an activity.
* @param execution The current execution context
* @param checkConditions Whether or not to check conditions before determining whether or not to take a transition.
* @param throwExceptionIfExecutionStuck If true, an {@link ActivitiException} will be thrown in case no transition could be found to leave the activity.
*/
protected void performOutgoingBehavior(
ExecutionEntity execution,
boolean checkConditions,
boolean throwExceptionIfExecutionStuck
) {
getAgenda().planTakeOutgoingSequenceFlowsOperation(execution, true);
}
protected ActivitiEngineAgenda getAgenda() {
return Context.getAgenda();
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\BpmnActivityBehavior.java | 1 |
请完成以下Java代码 | public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Quantity.
@param Qty
Quantity
*/
public void setQty (BigDecimal Qty) | {
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Quantity.
@return Quantity
*/
public BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_LandedCostAllocation.java | 1 |
请完成以下Java代码 | public ImmutableList<WebuiPickHUResult> setPackingInstruction(final List<ProductsToPickRow> selectedRows, final PackToSpec packToSpec)
{
final Map<PickingCandidateId, DocumentId> rowIdsByPickingCandidateId = streamRowsEligibleForPacking(selectedRows)
.collect(ImmutableMap.toImmutableMap(ProductsToPickRow::getPickingCandidateId, ProductsToPickRow::getId));
final Set<PickingCandidateId> pickingCandidateIds = rowIdsByPickingCandidateId.keySet();
final List<PickingCandidate> pickingCandidates = pickingCandidateService.setHuPackingInstructionId(pickingCandidateIds, packToSpec);
return pickingCandidates.stream()
.map(cand -> WebuiPickHUResult.of(rowIdsByPickingCandidateId.get(cand.getId()), cand))
.collect(ImmutableList.toImmutableList());
}
public boolean anyRowsEligibleForPacking(final List<ProductsToPickRow> selectedRows)
{
return streamRowsEligibleForPacking(selectedRows).findAny().isPresent();
}
private Stream<ProductsToPickRow> streamRowsEligibleForPacking(final List<ProductsToPickRow> selectedRows)
{
return selectedRows
.stream()
.filter(ProductsToPickRow::isEligibleForPacking);
}
public boolean noRowsEligibleForPicking(final List<ProductsToPickRow> selectedRows)
{
return !streamRowsEligibleForPicking(selectedRows).findAny().isPresent();
} | @NonNull
private Stream<ProductsToPickRow> streamRowsEligibleForPicking(final List<ProductsToPickRow> selectedRows)
{
return selectedRows
.stream()
.filter(ProductsToPickRow::isEligibleForPicking);
}
private PickRequest createPickRequest(final ProductsToPickRow row)
{
final PickingConfigV2 pickingConfig = getPickingConfig();
return createPickRequest(row, pickingConfig.isPickingReviewRequired());
}
protected final PickingConfigV2 getPickingConfig()
{
return pickingConfigRepo.getPickingConfig();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\rows\ProductsToPickRowsService.java | 1 |
请完成以下Java代码 | private void initReader() throws Exception {
ClassLoader classLoader = this
.getClass()
.getClassLoader();
if (file == null) file = new File(classLoader
.getResource(fileName)
.getFile());
if (fileReader == null) fileReader = new FileReader(file);
if (CSVReader == null) CSVReader = new CSVReader(fileReader);
}
private void initWriter() throws Exception {
if (file == null) {
file = new File(fileName);
file.createNewFile();
}
if (fileWriter == null) fileWriter = new FileWriter(file, true);
if (CSVWriter == null) CSVWriter = new CSVWriter(fileWriter);
}
public void closeWriter() {
try {
CSVWriter.close();
fileWriter.close(); | } catch (IOException e) {
logger.error("Error while closing writer.");
}
}
public void closeReader() {
try {
CSVReader.close();
fileReader.close();
} catch (IOException e) {
logger.error("Error while closing reader.");
}
}
} | repos\tutorials-master\spring-batch\src\main\java\com\baeldung\taskletsvschunks\utils\FileUtils.java | 1 |
请完成以下Java代码 | public static String email(String email) {
if (oConvertUtils.isEmpty(email)) {
return "";
}
int index = email.indexOf("@");
if (index <= 1){
return email;
}
String begin = email.substring(0, 1);
String end = email.substring(index);
String stars = "**";
return begin + stars + end;
}
/**
* [银行卡号] 前六位,后四位,其他用星号隐藏每位1个星号
* @param cardNum 银行卡号
* @return <例子:6222600**********1234>
*/
public static String bankCard(String cardNum) {
if (oConvertUtils.isEmpty(cardNum)) {
return "";
}
return formatBetween(cardNum, 6, 4);
}
/**
* [公司开户银行联号] 公司开户银行联行号,显示前两位,其他用星号隐藏,每位1个星号
* @param code 公司开户银行联号
* @return <例子:12********>
*/
public static String cnapsCode(String code) {
if (oConvertUtils.isEmpty(code)) {
return "";
}
return formatRight(code, 2);
}
/**
* 将右边的格式化成*
* @param str 字符串
* @param reservedLength 保留长度
* @return 格式化后的字符串
*/
public static String formatRight(String str, int reservedLength){
String name = str.substring(0, reservedLength);
String stars = String.join("", Collections.nCopies(str.length()-reservedLength, "*"));
return name + stars;
}
/**
* 将左边的格式化成*
* @param str 字符串
* @param reservedLength 保留长度
* @return 格式化后的字符串 | */
public static String formatLeft(String str, int reservedLength){
int len = str.length();
String show = str.substring(len-reservedLength);
String stars = String.join("", Collections.nCopies(len-reservedLength, "*"));
return stars + show;
}
/**
* 将中间的格式化成*
* @param str 字符串
* @param beginLen 开始保留长度
* @param endLen 结尾保留长度
* @return 格式化后的字符串
*/
public static String formatBetween(String str, int beginLen, int endLen){
int len = str.length();
String begin = str.substring(0, beginLen);
String end = str.substring(len-endLen);
String stars = String.join("", Collections.nCopies(len-beginLen-endLen, "*"));
return begin + stars + end;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\desensitization\util\SensitiveInfoUtil.java | 1 |
请完成以下Java代码 | public void setLoadOnStartup(int loadOnStartup) {
this.loadOnStartup = loadOnStartup;
}
/**
* Set the {@link MultipartConfigElement multi-part configuration}.
* @param multipartConfig the multipart configuration to set or {@code null}
*/
public void setMultipartConfig(@Nullable MultipartConfigElement multipartConfig) {
this.multipartConfig = multipartConfig;
}
/**
* Returns the {@link MultipartConfigElement multi-part configuration} to be applied
* or {@code null}.
* @return the multipart config
*/
public @Nullable MultipartConfigElement getMultipartConfig() {
return this.multipartConfig;
}
@Override
protected String getDescription() {
Assert.state(this.servlet != null, "Unable to return description for null servlet");
return "servlet " + getServletName();
}
@Override
protected ServletRegistration.Dynamic addRegistration(String description, ServletContext servletContext) {
String name = getServletName();
return servletContext.addServlet(name, this.servlet);
}
/**
* Configure registration settings. Subclasses can override this method to perform
* additional configuration if required.
* @param registration the registration
*/
@Override | protected void configure(ServletRegistration.Dynamic registration) {
super.configure(registration);
String[] urlMapping = StringUtils.toStringArray(this.urlMappings);
if (urlMapping.length == 0 && this.alwaysMapUrl) {
urlMapping = DEFAULT_MAPPINGS;
}
if (!ObjectUtils.isEmpty(urlMapping)) {
registration.addMapping(urlMapping);
}
registration.setLoadOnStartup(this.loadOnStartup);
if (this.multipartConfig != null) {
registration.setMultipartConfig(this.multipartConfig);
}
}
/**
* Returns the servlet name that will be registered.
* @return the servlet name
*/
public String getServletName() {
return getOrDeduceName(this.servlet);
}
@Override
public String toString() {
return getServletName() + " urls=" + getUrlMappings();
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\web\servlet\ServletRegistrationBean.java | 1 |
请完成以下Java代码 | void uncloseIt()
{
if (getStatus() != PPOrderRoutingActivityStatus.CLOSED)
{
logger.warn("Only Closed activities can be unclosed - {}", this);
return;
}
changeStatusTo(PPOrderRoutingActivityStatus.IN_PROGRESS);
}
void voidIt()
{
if (getStatus() == PPOrderRoutingActivityStatus.VOIDED)
{
logger.warn("Activity already voided - {}", this);
return;
}
changeStatusTo(PPOrderRoutingActivityStatus.VOIDED);
setQtyRequired(getQtyRequired().toZero()); | setSetupTimeRequired(Duration.ZERO);
setDurationRequired(Duration.ZERO);
}
public void completeIt()
{
changeStatusTo(PPOrderRoutingActivityStatus.COMPLETED);
if (getDateFinish() == null)
{
setDateFinish(SystemTime.asInstant());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\PPOrderRoutingActivity.java | 1 |
请完成以下Java代码 | public class AD_Role
{
public static final AD_Role instance = new AD_Role();
private AD_Role()
{
super();
}
@Init
public void init(final IModelValidationEngine engine)
{
CopyRecordFactory.enableForTableName(I_AD_Role.Table_Name);
final IModelCacheService cachingService = Services.get(IModelCacheService.class);
cachingService.createTableCacheConfigBuilder(I_AD_Role.class)
.setEnabled(true)
.setInitialCapacity(50)
.setMaxCapacity(50)
.setExpireMinutes(ITableCacheConfig.EXPIREMINUTES_Never)
.setCacheMapType(CacheMapType.LRU)
.setTrxLevel(TrxLevel.OutOfTransactionOnly)
.register();
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE })
public void beforeSave(final I_AD_Role role)
{
if (role.getAD_Client_ID() == Env.CTXVALUE_AD_Client_ID_System)
{
role.setUserLevel(X_AD_Role.USERLEVEL_System);
}
else if (role.getUserLevel().equals(X_AD_Role.USERLEVEL_System))
{
throw new AdempiereException("@AccessTableNoUpdate@ @UserLevel@");
}
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE })
public void afterSave(final I_AD_Role role, final ModelChangeType changeType)
{
// services:
final IRoleDAO roleDAO = Services.get(IRoleDAO.class);
final RoleId roleId = RoleId.ofRepoId(role.getAD_Role_ID());
//
// Automatically assign new role to SuperUser and to the user who created it.
if (changeType.isNew() && !InterfaceWrapperHelper.isCopying(role)) | {
// Add Role to SuperUser
roleDAO.createUserRoleAssignmentIfMissing(UserId.METASFRESH, roleId);
// Add Role to User which created this record
final UserId createdByUserId = UserId.ofRepoId(role.getCreatedBy());
if (!createdByUserId.equals(UserId.METASFRESH))
{
roleDAO.createUserRoleAssignmentIfMissing(createdByUserId, roleId);
}
}
//
// Update role access records
final boolean userLevelChange = InterfaceWrapperHelper.isValueChanged(role, I_AD_Role.COLUMNNAME_UserLevel);
final boolean notManual = !role.isManual();
if ((changeType.isNew() || userLevelChange) && notManual)
{
final UserId userId = UserId.ofRepoId(role.getUpdatedBy());
Services.get(IUserRolePermissionsDAO.class).updateAccessRecords(roleId, userId);
}
//
// Reset the cached role permissions after the transaction is commited.
// NOTE: not needed because it's performed automatically
// Services.get(IUserRolePermissionsDAO.class).resetCacheAfterTrxCommit();
} // afterSave
@ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE)
public void deleteAccessRecords(final I_AD_Role role)
{
final RoleId roleId = RoleId.ofRepoId(role.getAD_Role_ID());
Services.get(IUserRolePermissionsDAO.class).deleteAccessRecords(roleId);
} // afterDelete
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\model\interceptor\AD_Role.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public AthenaClient athenaClient() {
return AthenaClient.builder()
.credentialsProvider(constructCredentials())
.build();
}
@Bean
public QueryExecutionContext queryExecutionContext() {
final var database = awsConfigurationProperties.getAthena().getDatabase();
return QueryExecutionContext.builder()
.database(database)
.build();
}
@Bean | public ResultConfiguration resultConfiguration() {
final var outputLocation = awsConfigurationProperties.getAthena().getS3OutputLocation();
return ResultConfiguration.builder()
.outputLocation(outputLocation)
.build();
}
private StaticCredentialsProvider constructCredentials() {
final var accessKey = awsConfigurationProperties.getAccessKey();
final var secretKey = awsConfigurationProperties.getSecretKey();
final var awsCredentials = AwsBasicCredentials.create(accessKey, secretKey);
return StaticCredentialsProvider.create(awsCredentials);
}
} | repos\tutorials-master\aws-modules\amazon-athena\src\main\java\com\baeldung\athena\configuration\AmazonAthenaConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Map<String, Object> getMap() {
return map;
}
public void setMap(Map<String, Object> map) {
this.map = map;
}
public List<Object> getList() {
return list;
}
public void setList(List<Object> list) {
this.list = list;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder( "{\"Person\":{" ); | sb.append( "\"lastName\":\"" )
.append( lastName ).append( '\"' );
sb.append( ",\"age\":" )
.append( age );
sb.append( ",\"boss\":" )
.append( boss );
sb.append( ",\"birth\":\"" )
.append( birth ).append( '\"' );
sb.append( ",\"map\":" )
.append( map );
sb.append( ",\"list\":" )
.append( list );
sb.append( ",\"dog\":" )
.append( dog );
sb.append( "}}" );
return sb.toString();
}
} | repos\SpringBootLearning-master (1)\springboot-config\src\main\java\com\gf\entity\Person.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void start(StartContext context) throws StartException {
MscRuntimeContainerDelegate runtimeContainerDelegate = runtimeContainerDelegateSupplier.get();
runtimeContainerDelegate.processEngineStarted(processEngine);
createProcessEngineJndiBinding(context);
}
protected void createProcessEngineJndiBinding(StartContext context) {
final ProcessEngineManagedReferenceFactory managedReferenceFactory = new ProcessEngineManagedReferenceFactory(processEngine);
final ServiceName processEngineServiceBindingServiceName = ContextNames.GLOBAL_CONTEXT_SERVICE_NAME
.append(BpmPlatform.APP_JNDI_NAME)
.append(BpmPlatform.MODULE_JNDI_NAME)
.append(processEngine.getName());
final String jndiName = BpmPlatform.JNDI_NAME_PREFIX
+ "/" + BpmPlatform.APP_JNDI_NAME
+ "/" + BpmPlatform.MODULE_JNDI_NAME
+ "/" +processEngine.getName();
// bind process engine service | bindingService = BindingUtil.createJndiBindings(context.getChildTarget(), processEngineServiceBindingServiceName, jndiName, managedReferenceFactory);
// log info message
LOGG.info("jndi binding for process engine " + processEngine.getName() + " is " + jndiName);
}
protected void removeProcessEngineJndiBinding() {
bindingService.setMode(Mode.REMOVE);
}
@Override
public void stop(StopContext context) {
MscRuntimeContainerDelegate runtimeContainerDelegate = runtimeContainerDelegateSupplier.get();
runtimeContainerDelegate.processEngineStopped(processEngine);
}
public Supplier<MscRuntimeContainerDelegate> getRuntimeContainerDelegateSupplier() {
return runtimeContainerDelegateSupplier;
}
} | repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\MscManagedProcessEngine.java | 2 |
请完成以下Java代码 | public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Expense.
@param Expense Expense */
public void setExpense (BigDecimal Expense)
{
set_Value (COLUMNNAME_Expense, Expense);
}
/** Get Expense.
@return Expense */
public BigDecimal getExpense ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Expense);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Depreciate.
@param IsDepreciated
The asset will be depreciated
*/
public void setIsDepreciated (boolean IsDepreciated)
{
set_Value (COLUMNNAME_IsDepreciated, Boolean.valueOf(IsDepreciated));
}
/** Get Depreciate.
@return The asset will be depreciated
*/
public boolean isDepreciated ()
{
Object oo = get_Value(COLUMNNAME_IsDepreciated);
if (oo != null)
{ | if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set PostingType.
@param PostingType
The type of posted amount for the transaction
*/
public void setPostingType (String PostingType)
{
set_Value (COLUMNNAME_PostingType, PostingType);
}
/** Get PostingType.
@return The type of posted amount for the transaction
*/
public String getPostingType ()
{
return (String)get_Value(COLUMNNAME_PostingType);
}
/** 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;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Exp.java | 1 |
请完成以下Java代码 | public Duration getKeepAlive() {
return keepAlive;
}
public void setKeepAlive(Duration keepAlive) {
this.keepAlive = keepAlive;
}
public int getQueueSize() {
return queueSize;
}
public void setQueueSize(int queueSize) {
this.queueSize = queueSize;
}
public boolean isAllowCoreThreadTimeout() {
return allowCoreThreadTimeout;
}
public void setAllowCoreThreadTimeout(boolean allowCoreThreadTimeout) {
this.allowCoreThreadTimeout = allowCoreThreadTimeout;
} | public Duration getAwaitTerminationPeriod() {
return awaitTerminationPeriod;
}
public void setAwaitTerminationPeriod(Duration awaitTerminationPeriod) {
this.awaitTerminationPeriod = awaitTerminationPeriod;
}
public String getThreadPoolNamingPattern() {
return threadPoolNamingPattern;
}
public void setThreadPoolNamingPattern(String threadPoolNamingPattern) {
this.threadPoolNamingPattern = threadPoolNamingPattern;
}
public void setThreadNamePrefix(String prefix) {
if (prefix == null) {
this.threadPoolNamingPattern = "%d";
} else {
this.threadPoolNamingPattern = prefix + "%d";
}
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\async\AsyncTaskExecutorConfiguration.java | 1 |
请完成以下Java代码 | public class PricingUtil
{
@NonNull
public static IEditablePricingContext copyCtxOverridePriceListAndRefObject(
@NonNull final IPricingContext pricingCtx,
@NonNull final I_M_PriceList priceList)
{
final IEditablePricingContext newPricingContext = pricingCtx.copy();
newPricingContext.setReferencedObject(null);
newPricingContext.setPriceListId(PriceListId.ofRepoId(priceList.getM_PriceList_ID()));
newPricingContext.setPricingSystemId(PricingSystemId.ofRepoId(priceList.getM_PricingSystem_ID()));
newPricingContext.setPriceListVersionId(null);
final SOTrx soTrx = SOTrx.ofBoolean(priceList.isSOPriceList());
newPricingContext.setSOTrx(soTrx);
return newPricingContext;
} | @Nullable
public static I_M_PriceList retrievePriceListForConditionsAndCountry(
@NonNull final CountryId countryId,
@NonNull final PricingSystemId pricingSystemId,
@NonNull final SOTrx soTrx)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_M_PriceList.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_M_PriceList.COLUMN_C_Country_ID, countryId, null)
.addEqualsFilter(I_M_PriceList.COLUMN_M_PricingSystem_ID, pricingSystemId.getRepoId())
.addEqualsFilter(I_M_PriceList.COLUMN_IsSOPriceList, soTrx.toBoolean())
.orderBy()
.addColumnDescending(I_M_PriceList.COLUMNNAME_C_Country_ID)
.endOrderBy()
.create()
.first();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\pricing\PricingUtil.java | 1 |
请完成以下Java代码 | public abstract class BaseDataWithAdditionalInfo<I extends UUIDBased> extends BaseData<I> implements HasAdditionalInfo {
@NoXss
private transient JsonNode additionalInfo;
@JsonIgnore
private byte[] additionalInfoBytes;
public BaseDataWithAdditionalInfo() {
super();
}
public BaseDataWithAdditionalInfo(I id) {
super(id);
}
public BaseDataWithAdditionalInfo(BaseDataWithAdditionalInfo<I> baseData) {
super(baseData);
setAdditionalInfo(baseData.getAdditionalInfo());
}
@Override
public JsonNode getAdditionalInfo() {
return getJson(() -> additionalInfo, () -> additionalInfoBytes);
}
public void setAdditionalInfo(JsonNode addInfo) {
setJson(addInfo, json -> this.additionalInfo = json, bytes -> this.additionalInfoBytes = bytes);
}
public void setAdditionalInfoField(String field, JsonNode value) {
JsonNode additionalInfo = getAdditionalInfo();
if (!(additionalInfo instanceof ObjectNode)) {
additionalInfo = mapper.createObjectNode();
}
((ObjectNode) additionalInfo).set(field, value);
setAdditionalInfo(additionalInfo);
}
public <T> T getAdditionalInfoField(String field, Function<JsonNode, T> mapper, T defaultValue) {
JsonNode additionalInfo = getAdditionalInfo();
if (additionalInfo != null && additionalInfo.has(field)) {
return mapper.apply(additionalInfo.get(field));
}
return defaultValue;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
BaseDataWithAdditionalInfo<?> that = (BaseDataWithAdditionalInfo<?>) o;
return Arrays.equals(additionalInfoBytes, that.additionalInfoBytes);
}
@Override | public int hashCode() {
return Objects.hash(super.hashCode(), additionalInfoBytes);
}
public static JsonNode getJson(Supplier<JsonNode> jsonData, Supplier<byte[]> binaryData) {
JsonNode json = jsonData.get();
if (json != null) {
return json;
} else {
byte[] data = binaryData.get();
if (data != null) {
try {
return mapper.readTree(new ByteArrayInputStream(data));
} catch (IOException e) {
log.warn("Can't deserialize json data: ", e);
return null;
}
} else {
return null;
}
}
}
public static void setJson(JsonNode json, Consumer<JsonNode> jsonConsumer, Consumer<byte[]> bytesConsumer) {
jsonConsumer.accept(json);
try {
bytesConsumer.accept(mapper.writeValueAsBytes(json));
} catch (JsonProcessingException e) {
log.warn("Can't serialize json data: ", e);
}
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\BaseDataWithAdditionalInfo.java | 1 |
请完成以下Java代码 | public void windowOpened(final WindowEvent e)
{
//
// Disable frame (make new frame behave like a modal frame)
parentFrame.setFocusable(false);
parentFrame.setEnabled(false);
}
@Override
public void windowActivated(final WindowEvent e)
{
windowGainedFocus(e);
}
@Override
public void windowDeactivated(final WindowEvent e)
{
// nothing
}
@Override
public void windowGainedFocus(final WindowEvent e)
{
// nothing
}
@Override
public void windowLostFocus(final WindowEvent e)
{
// nothing
}
@Override
public void windowClosed(final WindowEvent e)
{
//
// Re-enable frame
parentFrame.setFocusable(true);
parentFrame.setEnabled(true);
modalFrame.removeWindowListener(this);
if (onCloseCallback != null)
{
onCloseCallback.run();
}
parentFrame.toFront();
}
});
parentFrame.addWindowListener(new WindowAdapter()
{
@Override
public void windowActivated(final WindowEvent e)
{
windowGainedFocus(e);
}
@Override
public void windowDeactivated(final WindowEvent e)
{
// nothing
}
@Override
public void windowGainedFocus(final WindowEvent e)
{
EventQueue.invokeLater(() -> {
if (modalFrame == null || !modalFrame.isVisible() || !modalFrame.isShowing()) | {
return;
}
modalFrame.toFront();
modalFrame.repaint();
});
}
@Override
public void windowLostFocus(final WindowEvent e)
{
// nothing
}
});
if (modalFrame instanceof CFrame)
{
addToWindowManager(modalFrame);
}
showCenterWindow(parentFrame, modalFrame);
}
/**
* Create a {@link FormFrame} for the given {@link I_AD_Form}.
*
* @return formFrame which was created or null
*/
public static FormFrame createForm(final I_AD_Form form)
{
final FormFrame formFrame = new FormFrame();
if (formFrame.openForm(form))
{
formFrame.pack();
return formFrame;
}
else
{
formFrame.dispose();
return null;
}
}
} // AEnv | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\AEnv.java | 1 |
请完成以下Java代码 | public final IHUProducerAllocationDestination setIsHUPlanningReceiptOwnerPM(boolean isHUPlanningReceiptOwnerPM)
{
this._isHUPlanningReceiptOwnerPM = isHUPlanningReceiptOwnerPM;
return this;
}
public final boolean isHUPlanningReceiptOwnerPM()
{
return _isHUPlanningReceiptOwnerPM;
}
/**
* Sets this producer in "non-configurable" state. No further configuration to this producer will be allowed after calling this method.
*/
protected final void setNotConfigurable()
{
_configurable = false;
}
/**
* Makes sure producer is in configurable state. If not, and exception will be thrown.
*/
protected final void assertConfigurable()
{
if (!_configurable)
{
throw new HUException("This producer is not configurable anymore: " + this);
}
}
@Override
public final IHUProducerAllocationDestination setHUClearanceStatusInfo(final ClearanceStatusInfo huClearanceStatusInfo)
{
assertConfigurable();
_huClearanceStatusInfo = huClearanceStatusInfo;
return this;
}
public final ClearanceStatusInfo getHUClearanceStatusInfo()
{
return _huClearanceStatusInfo;
}
private void destroyCurrentHU(final HUListCursor currentHUCursor, final IHUContext huContext)
{
final I_M_HU hu = currentHUCursor.current(); | if (hu == null)
{
return; // shall not happen
}
currentHUCursor.closeCurrent(); // close the current position of this cursor
// since _createdNonAggregateHUs is just a subset of _createdHUs, we don't know if 'hu' was in there to start with. All we care is that it's not in _createdNonAggregateHUs after this method.
_createdNonAggregateHUs.remove(hu);
final boolean removedFromCreatedHUs = _createdHUs.remove(hu);
Check.assume(removedFromCreatedHUs, "Cannot destroy {} because it wasn't created by us", hu);
// Delete only those HUs which were internally created by THIS producer
if (DYNATTR_Producer.getValue(hu) == this)
{
final Supplier<IAutoCloseable> getDontDestroyParentLUClosable = () -> {
final I_M_HU lu = handlingUnitsBL.getLoadingUnitHU(hu);
return lu != null
? huContext.temporarilyDontDestroyHU(HuId.ofRepoId(lu.getM_HU_ID()))
: () -> {
};
};
try (final IAutoCloseable ignored = getDontDestroyParentLUClosable.get())
{
handlingUnitsBL.destroyIfEmptyStorage(huContext, hu);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AbstractProducerDestination.java | 1 |
请完成以下Java代码 | public class Point {
private final double x;
private final double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
@Override
public String toString() { | return "Point{" +
"x=" + x +
", y=" + y +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Point point = (Point) o;
return Double.compare(point.x, x) == 0 &&
Double.compare(point.y, y) == 0;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
} | repos\tutorials-master\core-java-modules\core-java-lang-math-5\src\main\java\com\baeldung\storingXYcoordinates\Point.java | 1 |
请完成以下Java代码 | public java.lang.String getEntityType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** Set Kommentar/Hilfe.
@param Help
Comment or Hint
*/
@Override
public void setHelp (java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Kommentar/Hilfe.
@return Comment or Hint
*/
@Override
public java.lang.String getHelp ()
{
return (java.lang.String)get_Value(COLUMNNAME_Help);
}
/** Set Beta-Funktionalität.
@param IsBetaFunctionality
This functionality is considered Beta
*/
@Override
public void setIsBetaFunctionality (boolean IsBetaFunctionality)
{
set_Value (COLUMNNAME_IsBetaFunctionality, Boolean.valueOf(IsBetaFunctionality));
}
/** Get Beta-Funktionalität.
@return This functionality is considered Beta
*/
@Override
public boolean isBetaFunctionality ()
{
Object oo = get_Value(COLUMNNAME_IsBetaFunctionality);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set jsp-URL.
@param JSPURL
Web URL of the jsp function
*/
@Override
public void setJSPURL (java.lang.String JSPURL)
{
set_Value (COLUMNNAME_JSPURL, JSPURL);
}
/** Get jsp-URL.
@return Web URL of the jsp function
*/
@Override
public java.lang.String getJSPURL ()
{
return (java.lang.String)get_Value(COLUMNNAME_JSPURL);
}
/** Set Is Modal.
@param Modal Is Modal */
@Override | public void setModal (boolean Modal)
{
set_Value (COLUMNNAME_Modal, Boolean.valueOf(Modal));
}
/** Get Is Modal.
@return Is Modal */
@Override
public boolean isModal ()
{
Object oo = get_Value(COLUMNNAME_Modal);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Form.java | 1 |
请完成以下Java代码 | void deleteLast()
{
--_size;
}
/**
* 重设大小
* @param size 大小
*/
void resize(int size)
{
if (size > _capacity)
{
resizeBuf(size);
}
_size = size;
}
/**
* 重设大小,并且在末尾加一个值
* @param size 大小
* @param value 值
*/
void resize(int size, byte value)
{
if (size > _capacity)
{
resizeBuf(size);
}
while (_size < size)
{
_buf[_size++] = value;
}
}
/**
* 增加容量
* @param size 容量
*/
void reserve(int size)
{
if (size > _capacity)
{
resizeBuf(size);
}
}
/**
* 设置缓冲区大小
* @param size 大小
*/
private void resizeBuf(int size)
{
int capacity;
if (size >= _capacity * 2)
{
capacity = size; | }
else
{
capacity = 1;
while (capacity < size)
{
capacity <<= 1;
}
}
byte[] buf = new byte[capacity];
if (_size > 0)
{
System.arraycopy(_buf, 0, buf, 0, _size);
}
_buf = buf;
_capacity = capacity;
}
/**
* 缓冲区
*/
private byte[] _buf;
/**
* 大小
*/
private int _size;
/**
* 容量
*/
private int _capacity;
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\AutoBytePool.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EdgeDataValidator extends DataValidator<Edge> {
private final EdgeDao edgeDao;
private final TenantService tenantService;
private final CustomerDao customerDao;
@Override
protected void validateCreate(TenantId tenantId, Edge edge) {
validateNumberOfEntitiesPerTenant(tenantId, EntityType.EDGE);
}
@Override
protected Edge validateUpdate(TenantId tenantId, Edge edge) {
return edgeDao.findById(edge.getTenantId(), edge.getId().getId());
}
@Override
protected void validateDataImpl(TenantId tenantId, Edge edge) {
validateString("Edge name", edge.getName());
validateString("Edge type", edge.getType());
if (StringUtils.isEmpty(edge.getSecret())) {
throw new DataValidationException("Edge secret should be specified!");
}
if (StringUtils.isEmpty(edge.getRoutingKey())) { | throw new DataValidationException("Edge routing key should be specified!");
}
if (edge.getTenantId() == null) {
throw new DataValidationException("Edge should be assigned to tenant!");
} else {
if (!tenantService.tenantExists(edge.getTenantId())) {
throw new DataValidationException("Edge is referencing to non-existent tenant!");
}
}
if (edge.getCustomerId() == null) {
edge.setCustomerId(new CustomerId(NULL_UUID));
} else if (!edge.getCustomerId().getId().equals(NULL_UUID)) {
Customer customer = customerDao.findById(edge.getTenantId(), edge.getCustomerId().getId());
if (customer == null) {
throw new DataValidationException("Can't assign edge to non-existent customer!");
}
if (!customer.getTenantId().getId().equals(edge.getTenantId().getId())) {
throw new DataValidationException("Can't assign edge to customer from different tenant!");
}
}
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\EdgeDataValidator.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class CreditCard {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "credit_card_id_seq")
@SequenceGenerator(name = "credit_card_id_seq", sequenceName = "credit_card_id_seq", allocationSize = 1)
private Long id;
private String cardNumber;
private String expiryDate;
private Long customerId;
public Long getCustomerId() {
return customerId;
}
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
public String getExpiryDate() { | return expiryDate;
}
public void setExpiryDate(String expiryDate) {
this.expiryDate = expiryDate;
}
public CreditCard() {
}
@Override
public String toString() {
return "CreditCard{" + "id=" + id + ", cardNumber='" + cardNumber + '\'' + ", expiryDate='" + expiryDate + '\'' + ", customerId=" + customerId + '}';
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-query-2\src\main\java\com\baeldung\upsert\CreditCard.java | 2 |
请完成以下Java代码 | public String getA_Insurance_Co ()
{
return (String)get_Value(COLUMNNAME_A_Insurance_Co);
}
/** Set Insured Value.
@param A_Ins_Value Insured Value */
public void setA_Ins_Value (BigDecimal A_Ins_Value)
{
set_Value (COLUMNNAME_A_Ins_Value, A_Ins_Value);
}
/** Get Insured Value.
@return Insured Value */
public BigDecimal getA_Ins_Value ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Ins_Value);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Policy Number.
@param A_Policy_No Policy Number */
public void setA_Policy_No (String A_Policy_No)
{
set_Value (COLUMNNAME_A_Policy_No, A_Policy_No);
}
/** Get Policy Number.
@return Policy Number */
public String getA_Policy_No ()
{
return (String)get_Value(COLUMNNAME_A_Policy_No);
}
/** Set Policy Renewal Date.
@param A_Renewal_Date Policy Renewal Date */
public void setA_Renewal_Date (Timestamp A_Renewal_Date)
{
set_Value (COLUMNNAME_A_Renewal_Date, A_Renewal_Date);
}
/** Get Policy Renewal Date.
@return Policy Renewal Date */
public Timestamp getA_Renewal_Date ()
{
return (Timestamp)get_Value(COLUMNNAME_A_Renewal_Date); | }
/** Set Replacement Costs.
@param A_Replace_Cost Replacement Costs */
public void setA_Replace_Cost (BigDecimal A_Replace_Cost)
{
set_Value (COLUMNNAME_A_Replace_Cost, A_Replace_Cost);
}
/** Get Replacement Costs.
@return Replacement Costs */
public BigDecimal getA_Replace_Cost ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Replace_Cost);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Text.
@param Text Text */
public void setText (String Text)
{
set_Value (COLUMNNAME_Text, Text);
}
/** Get Text.
@return Text */
public String getText ()
{
return (String)get_Value(COLUMNNAME_Text);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Info_Ins.java | 1 |
请完成以下Java代码 | public void updateActivity(final I_C_OrderLine orderLine)
{
if (InterfaceWrapperHelper.isCopy(orderLine))
{
// let the activity be copied from the source.
return;
}
final ActivityId groupActivityId = getGroupActivityId(orderLine);
orderLine.setC_Activity_ID(ActivityId.toRepoId(groupActivityId));
if (orderLine.getC_Activity_ID() > 0)
{
return; // was already set, so don't try to auto-fill it
}
final ProductId productId = ProductId.ofRepoIdOrNull(orderLine.getM_Product_ID());
if (productId == null)
{
return;
}
// IsDiverse flag
orderLine.setIsDiverse(productBL.isDiverse(productId));
// Activity
final ActivityId productActivityId = productAcctDAO.retrieveActivityForAcct(
ClientId.ofRepoId(orderLine.getAD_Client_ID()),
OrgId.ofRepoId(orderLine.getAD_Org_ID()),
productId);
if (productActivityId == null)
{
return;
}
final Dimension orderLineDimension = dimensionService.getFromRecord(orderLine); | if (orderLineDimension == null)
{
//nothing to do
return;
}
dimensionService.updateRecord(orderLine, orderLineDimension.withActivityId(productActivityId));
}
private ActivityId getGroupActivityId(final I_C_OrderLine orderLine)
{
if (orderLine.getC_Order_CompensationGroup_ID() <= 0)
{
return null;
}
final GroupId groupId = OrderGroupRepository.extractGroupIdOrNull(orderLine);
if (groupId == null)
{
return null;
}
final Group group = orderGroupRepo.retrieveGroupIfExists(groupId);
if (group == null)
{
return null;
}
return group.getActivityId();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\activity\model\validator\C_OrderLine.java | 1 |
请完成以下Java代码 | public ExternalTaskRestService getExternalTaskRestService() {
return super.getExternalTaskRestService(null);
}
@Path(MigrationRestService.PATH)
public MigrationRestService getMigrationRestService() {
return super.getMigrationRestService(null);
}
@Path(ModificationRestService.PATH)
public ModificationRestService getModificationRestService() {
return super.getModificationRestService(null);
}
@Path(BatchRestService.PATH)
public BatchRestService getBatchRestService() {
return super.getBatchRestService(null);
}
@Path(TenantRestService.PATH)
public TenantRestService getTenantRestService() {
return super.getTenantRestService(null);
}
@Path(SignalRestService.PATH)
public SignalRestService getSignalRestService() {
return super.getSignalRestService(null);
}
@Path(ConditionRestService.PATH)
public ConditionRestService getConditionRestService() {
return super.getConditionRestService(null);
}
@Path(OptimizeRestService.PATH)
public OptimizeRestService getOptimizeRestService() {
return super.getOptimizeRestService(null);
} | @Path(VersionRestService.PATH)
public VersionRestService getVersionRestService() {
return super.getVersionRestService(null);
}
@Path(SchemaLogRestService.PATH)
public SchemaLogRestService getSchemaLogRestService() {
return super.getSchemaLogRestService(null);
}
@Path(EventSubscriptionRestService.PATH)
public EventSubscriptionRestService getEventSubscriptionRestService() {
return super.getEventSubscriptionRestService(null);
}
@Path(TelemetryRestService.PATH)
public TelemetryRestService getTelemetryRestService() {
return super.getTelemetryRestService(null);
}
@Override
protected URI getRelativeEngineUri(String engineName) {
// the default engine
return URI.create("/");
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\DefaultProcessEngineRestServiceImpl.java | 1 |
请完成以下Java代码 | public String getName() {
return this.name;
}
/**
* Return the return type.
* @return the return type
*/
public String getReturnType() {
return this.returnType;
}
/**
* Return the value.
* @return the value
*/
public Object getValue() {
return this.value;
}
/**
* Return whether this field is initialized.
* @return whether the field is initialized.
*/
public boolean isInitialized() {
return this.initialized;
}
/**
* Builder for creating a {@link JavaFieldDeclaration}.
*/
public static final class Builder {
private final String name;
private String returnType;
private int modifiers;
private Object value;
private boolean initialized;
private Builder(String name) {
this.name = name;
}
/**
* Sets the modifiers.
* @param modifiers the modifiers
* @return this for method chaining
*/ | public Builder modifiers(int modifiers) {
this.modifiers = modifiers;
return this;
}
/**
* Sets the value.
* @param value the value
* @return this for method chaining
*/
public Builder value(Object value) {
this.value = value;
this.initialized = true;
return this;
}
/**
* Sets the return type.
* @param returnType the return type
* @return this for method chaining
*/
public JavaFieldDeclaration returning(String returnType) {
this.returnType = returnType;
return new JavaFieldDeclaration(this);
}
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\java\JavaFieldDeclaration.java | 1 |
请完成以下Java代码 | public abstract class AbstractValueJasyptMojo extends AbstractJasyptMojo {
/**
* The decrypted property suffix
*/
@Parameter(property = "jasypt.plugin.value")
private String value = null;
@Override
void run(EncryptionService encryptionService, ConfigurableApplicationContext context, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix)
throws MojoExecutionException {
if (value == null) {
throw new MojoExecutionException("No jasypt.plugin.value property provided");
}
run(encryptionService, value, encryptPrefix, encryptSuffix, decryptPrefix, decryptSuffix); | }
/**
* Run the encryption task.
*
* @param encryptionService the service for encryption
* @param value the value to operate on
* @param encryptPrefix encryption prefix
* @param encryptSuffix encryption suffix
* @param decryptPrefix decryption prefix
* @param decryptSuffix decryption suffix
*/
abstract void run(EncryptionService encryptionService, String value, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix)
throws MojoExecutionException;
} | repos\jasypt-spring-boot-master\jasypt-maven-plugin\src\main\java\com\ulisesbocchio\jasyptmavenplugin\mojo\AbstractValueJasyptMojo.java | 1 |
请完成以下Spring Boot application配置 | #spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
#security.user.password=password
#security.oauth2.c | lient.client-id=client
#security.oauth2.client.client-secret=secret | repos\tutorials-master\spring-boot-modules\spring-boot-security\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public java.lang.String getTrxType ()
{
return (java.lang.String)get_Value(COLUMNNAME_TrxType);
}
/** Set Prüfziffer.
@param VoiceAuthCode
Voice Authorization Code from credit card company
*/
@Override
public void setVoiceAuthCode (java.lang.String VoiceAuthCode)
{
set_Value (COLUMNNAME_VoiceAuthCode, VoiceAuthCode);
}
/** Get Prüfziffer.
@return Voice Authorization Code from credit card company
*/
@Override
public java.lang.String getVoiceAuthCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_VoiceAuthCode);
}
/** Set Write-off Amount.
@param WriteOffAmt
Amount to write-off
*/
@Override
public void setWriteOffAmt (java.math.BigDecimal WriteOffAmt) | {
set_Value (COLUMNNAME_WriteOffAmt, WriteOffAmt);
}
/** Get Write-off Amount.
@return Amount to write-off
*/
@Override
public java.math.BigDecimal getWriteOffAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WriteOffAmt);
if (bd == null)
{
return Env.ZERO;
}
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Payment.java | 1 |
请完成以下Java代码 | public void setInOutLine (MInOutLine line)
{
setM_InOutLine_ID(line.getM_InOutLine_ID());
setTargetQty(line.getMovementQty()); // Confirmations in Storage UOM
setConfirmedQty (getTargetQty()); // suggestion
m_line = line;
} // setInOutLine
/**
* Get Shipment Line
* @return line
*/
public MInOutLine getLine()
{
if (m_line == null)
m_line = new MInOutLine (getCtx(), getM_InOutLine_ID(), get_TrxName());
return m_line;
} // getLine
/**
* Process Confirmation Line.
* - Update InOut Line
* @param isSOTrx sales order
* @param confirmType type
* @return success
*/
public boolean processLine (boolean isSOTrx, String confirmType)
{
MInOutLine line = getLine();
// Customer
if (MInOutConfirm.CONFIRMTYPE_CustomerConfirmation.equals(confirmType))
{
line.setConfirmedQty(getConfirmedQty());
}
// Drop Ship
else if (MInOutConfirm.CONFIRMTYPE_DropShipConfirm.equals(confirmType))
{
}
// Pick or QA
else if (MInOutConfirm.CONFIRMTYPE_PickQAConfirm.equals(confirmType))
{
line.setTargetQty(getTargetQty());
line.setMovementQty(getConfirmedQty()); // Entered NOT changed
line.setPickedQty(getConfirmedQty());
//
line.setScrappedQty(getScrappedQty());
}
// Ship or Receipt
else if (MInOutConfirm.CONFIRMTYPE_ShipReceiptConfirm.equals(confirmType))
{
line.setTargetQty(getTargetQty());
BigDecimal qty = getConfirmedQty();
if (!isSOTrx) // In PO, we have the responsibility for scapped
qty = qty.add(getScrappedQty());
line.setMovementQty(qty); // Entered NOT changed
//
line.setScrappedQty(getScrappedQty());
}
// Vendor
else if (MInOutConfirm.CONFIRMTYPE_VendorConfirmation.equals(confirmType)) | {
line.setConfirmedQty(getConfirmedQty());
}
return line.save(get_TrxName());
} // processConfirmation
/**
* Is Fully Confirmed
* @return true if Target = Confirmed qty
*/
public boolean isFullyConfirmed()
{
return getTargetQty().compareTo(getConfirmedQty()) == 0;
} // isFullyConfirmed
/**
* Before Delete - do not delete
* @return false
*/
@Override
protected boolean beforeDelete ()
{
throw new AdempiereException("@CannotDelete@");
} // beforeDelete
/**
* Before Save
* @param newRecord new
* @return true
*/
@Override
protected boolean beforeSave (boolean newRecord)
{
// Calculate Difference = Target - Confirmed - Scrapped
BigDecimal difference = getTargetQty();
difference = difference.subtract(getConfirmedQty());
difference = difference.subtract(getScrappedQty());
setDifferenceQty(difference);
//
return true;
} // beforeSave
} // MInOutLineConfirm | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MInOutLineConfirm.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void addToTheEnd() {
ShoppingCart cart = shoppingCartRepository.findByOwner("Mark Juno");
cart.getBooks().add("The last day");
}
@Transactional
public void addInTheMiddle() {
ShoppingCart cart = shoppingCartRepository.findByOwner("Mark Juno");
cart.getBooks().add(cart.getBooks().size() / 2, "Middle man");
}
@Transactional
public void removeFirst() {
ShoppingCart cart = shoppingCartRepository.findByOwner("Mark Juno");
cart.getBooks().remove(0);
} | @Transactional
public void removeLast() {
ShoppingCart cart = shoppingCartRepository.findByOwner("Mark Juno");
cart.getBooks().remove(cart.getBooks().size() - 1);
}
@Transactional
public void removeMiddle() {
ShoppingCart cart = shoppingCartRepository.findByOwner("Mark Juno");
cart.getBooks().remove(cart.getBooks().size() / 2);
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootElementCollectionNoOrderColumn\src\main\java\com\bookstore\service\ShoppingCartService.java | 2 |
请完成以下Java代码 | public TaxInformation4 getTaxRmt() {
return taxRmt;
}
/**
* Sets the value of the taxRmt property.
*
* @param value
* allowed object is
* {@link TaxInformation4 }
*
*/
public void setTaxRmt(TaxInformation4 value) {
this.taxRmt = value;
}
/**
* Gets the value of the grnshmtRmt property.
*
* @return
* possible object is
* {@link Garnishment1 }
*
*/
public Garnishment1 getGrnshmtRmt() {
return grnshmtRmt;
}
/**
* Sets the value of the grnshmtRmt property.
*
* @param value
* allowed object is
* {@link Garnishment1 }
*
*/ | public void setGrnshmtRmt(Garnishment1 value) {
this.grnshmtRmt = value;
}
/**
* Gets the value of the addtlRmtInf 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 addtlRmtInf property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAddtlRmtInf().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getAddtlRmtInf() {
if (addtlRmtInf == null) {
addtlRmtInf = new ArrayList<String>();
}
return this.addtlRmtInf;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\StructuredRemittanceInformation13.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Post {
@Id
@GeneratedValue
private Long id;
private String title;
private String content;
@ManyToOne(fetch = FetchType.LAZY)
private Person author;
public Post() {
}
public Post(String title, String content, Person author) {
this.title = title;
this.content = content;
this.author = author;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content; | }
public Person getAuthor() {
return author;
}
public void setAuthor(Person author) {
this.author = author;
}
@Override
public String toString() {
return "Post{" +
"id=" + id +
", title='" + title + '\'' +
", content='" + content + '\'' +
'}';
}
} | repos\tutorials-master\persistence-modules\blaze-persistence\src\main\java\com\baeldung\model\Post.java | 2 |
请完成以下Java代码 | public void onFailure(Throwable t) {
log.error("Failed to submit Housekeeper task", t);
}
};
}
@Override
public void submitTask(HousekeeperTask task) {
HousekeeperTaskType taskType = task.getTaskType();
if (config.getDisabledTaskTypes().contains(taskType)) {
log.trace("Task type {} is disabled, ignoring {}", taskType, task);
return;
}
log.debug("[{}][{}][{}] Submitting task: {}", task.getTenantId(), task.getEntityId().getEntityType(), task.getEntityId(), task);
/* | * using msg key as entity id so that msgs related to certain entity are pushed to same partition,
* e.g. on tenant deletion (entity id is tenant id), we need to clean up tenant entities in certain order
* */
try {
producer.send(submitTpi, new TbProtoQueueMsg<>(task.getEntityId().getId(), ToHousekeeperServiceMsg.newBuilder()
.setTask(TransportProtos.HousekeeperTaskProto.newBuilder()
.setValue(JacksonUtil.toString(task))
.setTs(task.getTs())
.setAttempt(0)
.build())
.build()), submitCallback);
} catch (Throwable t) {
log.error("Failed to submit Housekeeper task {}", task, t);
}
}
} | repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\housekeeper\DefaultHousekeeperClient.java | 1 |
请完成以下Java代码 | public String getEmail() {
return email;
}
public void setEmail(final String email) {
this.email = email;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public int getAge() {
return age;
}
public void setAge(final int age) {
this.age = age;
}
public LocalDate getCreationDate() {
return creationDate;
}
public LocalDate getLastLoginDate() {
return lastLoginDate;
}
public void setLastLoginDate(LocalDate lastLoginDate) {
this.lastLoginDate = lastLoginDate;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active; | }
@Override
public String toString() {
return "User [name=" + name + ", id=" + id + "]";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return id == user.id &&
age == user.age &&
Objects.equals(name, user.name) &&
Objects.equals(creationDate, user.creationDate) &&
Objects.equals(email, user.email) &&
Objects.equals(status, user.status);
}
@Override
public int hashCode() {
return Objects.hash(id, name, creationDate, age, email, status);
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-simple\src\main\java\com\baeldung\jpa\query\model\User.java | 1 |
请完成以下Java代码 | public List<TableRecordIdDescriptor> retrieveAllTableRecordIdReferences()
{
return retrieveTableRecordIdReferences(null);
}
private ImmutableList<TableRecordIdDescriptor> retrieveTableRecordIdReferences(@Nullable final String onlyTableName)
{
final POInfoMap poInfoMap = POInfo.getPOInfoMap();
final ImmutableCollection<POInfo> selectedPOInfos;
if (onlyTableName != null)
{
final POInfo poInfo = POInfo.getPOInfoIfPresent(onlyTableName).orElse(null);
if (poInfo == null)
{
return ImmutableList.of();
}
selectedPOInfos = ImmutableList.of(poInfo);
}
else
{
selectedPOInfos = poInfoMap.toCollection();
}
final ImmutableList.Builder<TableRecordIdDescriptor> result = ImmutableList.builder();
for (final POInfo poInfo : selectedPOInfos)
{
if (poInfo.isView())
{
continue;
}
final String tableName = poInfo.getTableName();
for (final TableAndColumnName tableAndRecordIdColumnName : poInfo.getTableAndRecordColumnNames())
{
for (final AdTableId referencedTableId : retrieveDistinctIds(tableName, tableAndRecordIdColumnName.getTableNameAsString()))
{
final POInfo referencedPOInfo = poInfoMap.getByTableIdOrNull(referencedTableId);
if (referencedPOInfo == null)
{
continue;
}
result.add(
TableRecordIdDescriptor.builder()
.originTableName(tableName)
.recordIdColumnName(tableAndRecordIdColumnName.getColumnNameAsString())
.targetTableName(referencedPOInfo.getTableName())
.build()
);
}
}
} | return result.build();
}
/**
* This method executes the equivalent of the following query:
* <p>
* {@code SELECT DISTINCT(<p_id_columnname>) FROM <p_tablename> WHERE COALESCE(<p_id_columnname>,0)!=0}
* <p>
* ...just faster.
* <p>
* See <a href="https://github.com/metasfresh/metasfresh/issues/3389">https://github.com/metasfresh/metasfresh/issues/3389</a>
*/
private ImmutableSet<AdTableId> retrieveDistinctIds(
@NonNull final String tableName,
@NonNull final String idColumnName)
{
final String sql = "SELECT " + DB_FUNCTION_RETRIEVE_DISTINCT_IDS + "(?,?)";
final Object[] sqlParams = new Object[] { tableName, idColumnName };
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None);
DB.setParameters(pstmt, ImmutableList.of(tableName, idColumnName));
rs = pstmt.executeQuery();
final ImmutableSet.Builder<AdTableId> result = ImmutableSet.builder();
while (rs.next())
{
final AdTableId adTableId = AdTableId.ofRepoIdOrNull(rs.getInt(1));
if (adTableId != null)
{
result.add(adTableId);
}
}
return result.build();
}
catch (final SQLException ex)
{
throw DBException.wrapIfNeeded(ex)
.appendParametersToMessage()
.setParameter("sql", sql)
.setParameter("sqlParams", sqlParams);
}
finally
{
DB.close(rs, pstmt);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\api\impl\TableRecordIdDAO.java | 1 |
请完成以下Java代码 | public String toString()
{
StringBuffer sb = new StringBuffer ("X_T_BoilerPlate_Spool[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Process Instance.
@param AD_PInstance_ID
Instance of the process
*/
@Override
public void setAD_PInstance_ID (int AD_PInstance_ID)
{
if (AD_PInstance_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_PInstance_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_PInstance_ID, Integer.valueOf(AD_PInstance_ID));
}
/** Get Process Instance.
@return Instance of the process
*/
@Override
public int getAD_PInstance_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_PInstance_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Message Text.
@param MsgText
Textual Informational, Menu or Error Message
*/
@Override
public void setMsgText (java.lang.String MsgText)
{
set_ValueNoCheck (COLUMNNAME_MsgText, MsgText);
}
/** Get Message Text.
@return Textual Informational, Menu or Error Message
*/
@Override
public java.lang.String getMsgText ()
{
return (java.lang.String)get_Value(COLUMNNAME_MsgText);
} | /** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
@Override
public void setSeqNo (int SeqNo)
{
set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\letters\model\X_T_BoilerPlate_Spool.java | 1 |
请完成以下Java代码 | public String getType() {
return TYPE;
}
public void execute(BatchMonitorJobConfiguration configuration, ExecutionEntity execution, CommandContext commandContext, String tenantId) {
String batchId = configuration.getBatchId();
BatchEntity batch = commandContext.getBatchManager().findBatchById(configuration.getBatchId());
ensureNotNull("Batch with id '" + batchId + "' cannot be found", "batch", batch);
boolean completed = batch.isCompleted();
if (!completed) {
batch.createMonitorJob(true);
}
else {
batch.delete(false, false);
}
}
@Override
public BatchMonitorJobConfiguration newConfiguration(String canonicalString) {
return new BatchMonitorJobConfiguration(canonicalString);
}
public static class BatchMonitorJobConfiguration implements JobHandlerConfiguration {
protected String batchId;
public BatchMonitorJobConfiguration(String batchId) {
this.batchId = batchId;
} | public String getBatchId() {
return batchId;
}
@Override
public String toCanonicalString() {
return batchId;
}
}
public void onDelete(BatchMonitorJobConfiguration configuration, JobEntity jobEntity) {
// do nothing
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\BatchMonitorJobHandler.java | 1 |
请完成以下Java代码 | public SslContext initSslContext() {
try {
SslContextBuilder builder = SslContextBuilder.forClient();
if (StringUtils.hasLength(caCert)) {
builder.trustManager(createAndInitTrustManagerFactory());
}
if (StringUtils.hasLength(cert) && StringUtils.hasLength(privateKey)) {
builder.keyManager(createAndInitKeyManagerFactory());
}
return builder.build();
} catch (Exception e) {
log.error("[{}:{}] Creating TLS factory failed!", caCert, cert, e);
throw new RuntimeException("Creating TLS factory failed!", e);
}
}
protected TrustManagerFactory createAndInitTrustManagerFactory() throws Exception {
List<X509Certificate> caCerts = SslUtil.readCertFile(caCert);
KeyStore caKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
caKeyStore.load(null, null);
for (X509Certificate caCert : caCerts) {
caKeyStore.setCertificateEntry(CA_CERT_CERT_ALIAS_PREFIX + caCert.getSubjectDN().getName(), caCert);
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(caKeyStore);
return trustManagerFactory;
}
private KeyManagerFactory createAndInitKeyManagerFactory() throws Exception {
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(loadKeyStore(), SslUtil.getPassword(password));
return kmf;
} | protected KeyStore loadKeyStore() throws Exception {
List<X509Certificate> certificates = SslUtil.readCertFile(this.cert);
PrivateKey privateKey = SslUtil.readPrivateKey(this.privateKey, password);
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null);
List<X509Certificate> unique = certificates.stream().distinct().collect(Collectors.toList());
for (X509Certificate cert : unique) {
keyStore.setCertificateEntry(CERT_ALIAS_PREFIX + cert.getSubjectDN().getName(), cert);
}
if (privateKey != null) {
CertificateFactory factory = CertificateFactory.getInstance(X_509);
CertPath certPath = factory.generateCertPath(certificates);
List<? extends Certificate> path = certPath.getCertificates();
Certificate[] x509Certificates = path.toArray(new Certificate[0]);
keyStore.setKeyEntry(PRIVATE_KEY_ALIAS, privateKey, SslUtil.getPassword(password), x509Certificates);
}
return keyStore;
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\credentials\CertPemCredentials.java | 1 |
请完成以下Java代码 | public void setXssProtectionValue(String xssProtectionValue) {
this.xssProtectionValue = xssProtectionValue;
}
public boolean isContentSecurityPolicyDisabled() {
return contentSecurityPolicyDisabled;
}
public void setContentSecurityPolicyDisabled(boolean contentSecurityPolicyDisabled) {
this.contentSecurityPolicyDisabled = contentSecurityPolicyDisabled;
}
public String getContentSecurityPolicyValue() {
return contentSecurityPolicyValue;
}
public void setContentSecurityPolicyValue(String contentSecurityPolicyValue) {
this.contentSecurityPolicyValue = contentSecurityPolicyValue;
}
public boolean isContentTypeOptionsDisabled() {
return contentTypeOptionsDisabled;
}
public void setContentTypeOptionsDisabled(boolean contentTypeOptionsDisabled) {
this.contentTypeOptionsDisabled = contentTypeOptionsDisabled;
}
public String getContentTypeOptionsValue() {
return contentTypeOptionsValue;
}
public void setContentTypeOptionsValue(String contentTypeOptionsValue) {
this.contentTypeOptionsValue = contentTypeOptionsValue;
}
public boolean isHstsDisabled() {
return hstsDisabled;
}
public void setHstsDisabled(boolean hstsDisabled) {
this.hstsDisabled = hstsDisabled;
}
public boolean isHstsIncludeSubdomainsDisabled() {
return hstsIncludeSubdomainsDisabled;
}
public void setHstsIncludeSubdomainsDisabled(boolean hstsIncludeSubdomainsDisabled) {
this.hstsIncludeSubdomainsDisabled = hstsIncludeSubdomainsDisabled;
}
public String getHstsValue() { | return hstsValue;
}
public void setHstsValue(String hstsValue) {
this.hstsValue = hstsValue;
}
public String getHstsMaxAge() {
return hstsMaxAge;
}
public void setHstsMaxAge(String hstsMaxAge) {
this.hstsMaxAge = hstsMaxAge;
}
@Override
public String toString() {
StringJoiner joinedString = joinOn(this.getClass())
.add("xssProtectionDisabled=" + xssProtectionDisabled)
.add("xssProtectionOption=" + xssProtectionOption)
.add("xssProtectionValue=" + xssProtectionValue)
.add("contentSecurityPolicyDisabled=" + contentSecurityPolicyDisabled)
.add("contentSecurityPolicyValue=" + contentSecurityPolicyValue)
.add("contentTypeOptionsDisabled=" + contentTypeOptionsDisabled)
.add("contentTypeOptionsValue=" + contentTypeOptionsValue)
.add("hstsDisabled=" + hstsDisabled)
.add("hstsMaxAge=" + hstsMaxAge)
.add("hstsIncludeSubdomainsDisabled=" + hstsIncludeSubdomainsDisabled)
.add("hstsValue=" + hstsValue);
return joinedString.toString();
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\HeaderSecurityProperties.java | 1 |
请完成以下Java代码 | private static ADProcessName retrieve(final ResultSet rs) throws SQLException
{
return ADProcessName.builder()
.value(rs.getString(PREFIX + "Value"))
.classname(rs.getString(PREFIX + "Classname"))
.build();
}
}
public static final class ADElementName_Loader
{
public static String retrieveColumnName(@NonNull final AdElementId adElementId)
{
return DB.getSQLValueStringEx(ITrx.TRXNAME_ThreadInherited,
"SELECT ColumnName FROM AD_Element WHERE AD_Element_ID=?", | adElementId);
}
}
public static final class ADMessageName_Loader
{
public static String retrieveValue(@NonNull final AdMessageId adMessageId)
{
return DB.getSQLValueStringEx(ITrx.TRXNAME_ThreadInherited,
"SELECT Value FROM AD_Message WHERE AD_Message_ID=?",
adMessageId);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\validator\sql_migration_context_info\names\Names.java | 1 |
请完成以下Spring Boot application配置 | spring.mvc.pathmatch.matching-strategy=ant_path_matcher
springdoc.swagger-ui.path=/swagger-ui.html
management.endpoints.enabled-by-default=false
management.endpoint.info.enabled=false
# Local app server port
server.port=8081
# Playground
# Obtain key and secret by logging into https://play.orkes.io/
# and navigating to applications menu, create an application and generate key/secret
conductor.server.url=https://play.orkes.io/api
conductor.security.client.key-id=<key>
conductor.security.client.secret=<secret>
# Task Domain
conductor.worker.all.domain=saga
conductor.worker.all.pollingInterval=22
# DB Setup
sp | ring.jpa.database-platform=com.springboot.sqlite.SQLDialect
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:sqlite:food_delivery.db
spring.datasource.driver-class-name = org.sqlite.JDBC
spring.datasource.username=admin
spring.datasource.password=admin | repos\tutorials-master\microservices-modules\saga-pattern\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
VersionRange other = (VersionRange) obj;
if (this.higherInclusive != other.higherInclusive) {
return false;
}
if (this.higherVersion == null) {
if (other.higherVersion != null) {
return false;
}
}
else if (!this.higherVersion.equals(other.higherVersion)) {
return false;
}
if (this.lowerInclusive != other.lowerInclusive) {
return false;
}
if (this.lowerVersion == null) {
if (other.lowerVersion != null) {
return false;
}
}
else if (!this.lowerVersion.equals(other.lowerVersion)) {
return false;
}
return true;
} | @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (this.higherInclusive ? 1231 : 1237);
result = prime * result + ((this.higherVersion == null) ? 0 : this.higherVersion.hashCode());
result = prime * result + (this.lowerInclusive ? 1231 : 1237);
result = prime * result + ((this.lowerVersion == null) ? 0 : this.lowerVersion.hashCode());
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (this.lowerVersion != null) {
sb.append(this.lowerInclusive ? ">=" : ">").append(this.lowerVersion);
}
if (this.higherVersion != null) {
sb.append(" and ").append(this.higherInclusive ? "<=" : "<").append(this.higherVersion);
}
return sb.toString();
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\version\VersionRange.java | 1 |
请完成以下Java代码 | public class DefaultAutoDeploymentStrategy extends AbstractAutoDeploymentStrategy {
/**
* The deployment mode this strategy handles.
*/
public static final String DEPLOYMENT_MODE = "default";
public DefaultAutoDeploymentStrategy(ApplicationUpgradeContextService applicationUpgradeContextService) {
super(applicationUpgradeContextService);
}
@Override
protected String getDeploymentMode() {
return DEPLOYMENT_MODE;
}
@Override
public void deployResources(
final String deploymentNameHint,
final Resource[] resources,
final RepositoryService repositoryService
) {
// Create a single deployment for all resources using the name hint as
// the
// literal name | DeploymentBuilder deploymentBuilder = repositoryService
.createDeployment()
.enableDuplicateFiltering()
.name(deploymentNameHint);
for (final Resource resource : resources) {
final String resourceName = determineResourceName(resource);
deploymentBuilder.addInputStream(resourceName, resource);
}
loadApplicationUpgradeContext(deploymentBuilder).deploy();
}
} | repos\Activiti-develop\activiti-core\activiti-spring\src\main\java\org\activiti\spring\autodeployment\DefaultAutoDeploymentStrategy.java | 1 |
请完成以下Java代码 | public class C_Invoice_Candidate_Assign_MaterialTracking extends JavaProcess implements IProcessPrecondition
{
private final MaterialTrackingInvoiceCandService invoiceCandService = SpringContextHolder.instance.getBean(MaterialTrackingInvoiceCandService.class);
private final IQueryBL queryBL = Services.get(IQueryBL.class);
@Param(parameterName = I_M_Material_Tracking.COLUMNNAME_M_Material_Tracking_ID, mandatory = true)
private int p_M_Material_Tracking_ID;
@Param(parameterName = "IsClearAggregationKeyOverride", mandatory = true)
private boolean p_isClearAggregationKeyOverride;
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final List<I_C_Invoice_Candidate> ics = getSelectedInvoiceCandidates();
final MaterialTrackingId materialTrackingId = MaterialTrackingId.ofRepoIdOrNull(p_M_Material_Tracking_ID);
if (materialTrackingId == null)
{ | invoiceCandService.unlinkMaterialTrackings(ics, p_isClearAggregationKeyOverride);
}
else
{
invoiceCandService.linkMaterialTrackings(ics, materialTrackingId);
}
return MSG_OK;
}
private List<I_C_Invoice_Candidate> getSelectedInvoiceCandidates()
{
final IQueryFilter<I_C_Invoice_Candidate> selectedPartners = getProcessInfo().getQueryFilterOrElseFalse();
return queryBL.createQueryBuilder(I_C_Invoice_Candidate.class, getCtx(), ITrx.TRXNAME_ThreadInherited)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_Processed, false)
.addFilter(selectedPartners)
.create()
.list();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\process\C_Invoice_Candidate_Assign_MaterialTracking.java | 1 |
请完成以下Java代码 | public String getValue() {
return this.value;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
WebServerNamespace other = (WebServerNamespace) obj;
return this.value.equals(other.value);
}
@Override
public int hashCode() {
return this.value.hashCode();
}
@Override
public String toString() {
return this.value;
}
/**
* Factory method to create a new {@link WebServerNamespace} from a value. If the
* context is {@code null} or not a web server context then {@link #SERVER} is
* returned.
* @param context the application context
* @return the web server namespace
* @since 4.0.1
*/
public static WebServerNamespace from(@Nullable ApplicationContext context) { | if (!ClassUtils.isPresent(WEB_SERVER_CONTEXT_CLASS, null)) {
return SERVER;
}
return from(WebServerApplicationContext.getServerNamespace(context));
}
/**
* Factory method to create a new {@link WebServerNamespace} from a value. If the
* value is empty or {@code null} then {@link #SERVER} is returned.
* @param value the namespace value or {@code null}
* @return the web server namespace
*/
public static WebServerNamespace from(@Nullable String value) {
if (StringUtils.hasText(value)) {
return new WebServerNamespace(value);
}
return SERVER;
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\web\WebServerNamespace.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(final Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(final String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(final String content) {
this.content = content;
}
public String getLanguage() {
return language;
}
public void setLanguage(final String language) {
this.language = language;
}
@Override
public String toString() {
return "News{" +
"id=" + id +
", title='" + title + '\'' +
", content='" + content + '\'' +
", language=" + language +
'}';
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) { | return false;
}
final Article article = (Article) o;
if (!Objects.equals(id, article.id)) {
return false;
}
if (!Objects.equals(title, article.title)) {
return false;
}
if (!Objects.equals(content, article.content)) {
return false;
}
return Objects.equals(language, article.language);
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (title != null ? title.hashCode() : 0);
result = 31 * result + (content != null ? content.hashCode() : 0);
result = 31 * result + (language != null ? language.hashCode() : 0);
return result;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-query-3\src\main\java\com\baeldung\spring\data\jpa\spel\entity\Article.java | 1 |
请完成以下Java代码 | final class RepositoryUtils {
private RepositoryUtils() {
}
@SuppressWarnings("unchecked")
static <T> Class<T> getDomainType(Object executor) {
return (Class<T>) getRepositoryMetadata(executor).getDomainType();
}
static RepositoryMetadata getRepositoryMetadata(Object executor) {
Assert.isInstanceOf(Repository.class, executor);
Type[] genericInterfaces = executor.getClass().getGenericInterfaces();
for (Type genericInterface : genericInterfaces) {
Class<?> rawClass = ResolvableType.forType(genericInterface).getRawClass();
if (rawClass == null || MergedAnnotations.from(rawClass).isPresent(NoRepositoryBean.class)) {
continue;
}
if (Repository.class.isAssignableFrom(rawClass)) {
return new DefaultRepositoryMetadata(rawClass);
}
}
throw new IllegalArgumentException(
String.format("Cannot resolve repository interface from %s", executor));
}
static @Nullable String getGraphQlTypeName(Object repository) {
GraphQlRepository annotation =
AnnotatedElementUtils.findMergedAnnotation(repository.getClass(), GraphQlRepository.class);
if (annotation == null) {
return null;
}
return (StringUtils.hasText(annotation.typeName()) ?
annotation.typeName() : RepositoryUtils.getDomainType(repository).getSimpleName());
} | static CursorStrategy<ScrollPosition> defaultCursorStrategy() {
return CursorStrategy.withEncoder(new ScrollPositionCursorStrategy(), CursorEncoder.base64());
}
static int defaultScrollCount() {
return 20;
}
static Function<Boolean, ScrollPosition> defaultScrollPosition() {
return (forward) -> ScrollPosition.offset();
}
static ScrollSubrange getScrollSubrange(
DataFetchingEnvironment env, CursorStrategy<ScrollPosition> cursorStrategy) {
boolean forward = true;
String cursor = env.getArgument("after");
Integer count = env.getArgument("first");
if (cursor == null && count == null) {
cursor = env.getArgument("before");
count = env.getArgument("last");
if (cursor != null || count != null) {
forward = false;
}
}
ScrollPosition pos = (cursor != null) ? cursorStrategy.fromCursor(cursor) : null;
return ScrollSubrange.create(pos, count, forward);
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\data\query\RepositoryUtils.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Map<String, String> resourceAttributes() {
Map<String, String> resourceAttributes = new LinkedHashMap<>();
new OpenTelemetryResourceAttributes(this.environment, this.openTelemetryProperties.getResourceAttributes())
.applyTo(resourceAttributes::put);
return Collections.unmodifiableMap(resourceAttributes);
}
@Override
public Map<String, String> headers() {
return obtain(OtlpMetricsProperties::getHeaders, OtlpConfig.super::headers);
}
@Override
public HistogramFlavor histogramFlavor() {
return obtain(OtlpMetricsProperties::getHistogramFlavor, OtlpConfig.super::histogramFlavor);
}
@Override
public Map<String, HistogramFlavor> histogramFlavorPerMeter() {
return obtain(perMeter(Meter::getHistogramFlavor), OtlpConfig.super::histogramFlavorPerMeter);
}
@Override
public Map<String, Integer> maxBucketsPerMeter() {
return obtain(perMeter(Meter::getMaxBucketCount), OtlpConfig.super::maxBucketsPerMeter);
}
@Override
public int maxScale() {
return obtain(OtlpMetricsProperties::getMaxScale, OtlpConfig.super::maxScale);
}
@Override
public int maxBucketCount() {
return obtain(OtlpMetricsProperties::getMaxBucketCount, OtlpConfig.super::maxBucketCount);
} | @Override
public TimeUnit baseTimeUnit() {
return obtain(OtlpMetricsProperties::getBaseTimeUnit, OtlpConfig.super::baseTimeUnit);
}
private <V> Getter<OtlpMetricsProperties, Map<String, V>> perMeter(Getter<Meter, V> getter) {
return (properties) -> {
if (CollectionUtils.isEmpty(properties.getMeter())) {
return null;
}
Map<String, V> perMeter = new LinkedHashMap<>();
properties.getMeter().forEach((key, meterProperties) -> {
V value = getter.get(meterProperties);
if (value != null) {
perMeter.put(key, value);
}
});
return (!perMeter.isEmpty()) ? perMeter : null;
};
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\otlp\OtlpMetricsPropertiesConfigAdapter.java | 2 |
请完成以下Java代码 | public final class GlobalQRCodeType
{
public static GlobalQRCodeType ofString(@NonNull final String code)
{
final String codeNorm = StringUtils.trimBlankToNull(code);
if (codeNorm == null)
{
throw Check.mkEx("Invalid global QR code type: `" + code + "`");
}
return interner.intern(new GlobalQRCodeType(codeNorm));
}
private static final Interner<GlobalQRCodeType> interner = Interners.newStrongInterner();
private final String code;
private GlobalQRCodeType(@NonNull final String code)
{
this.code = code;
}
@Override | @Deprecated
public String toString()
{
return toJson();
}
@JsonValue
public String toJson()
{
return code;
}
public static boolean equals(@Nullable final GlobalQRCodeType type1, @Nullable final GlobalQRCodeType type2)
{
return Objects.equals(type1, type2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.global_qrcode.api\src\main\java\de\metas\global_qrcodes\GlobalQRCodeType.java | 1 |
请完成以下Java代码 | public static void equalsOperator() {
Bson filter = eq("userName", "Jack");
FindIterable<Document> documents = collection.find(filter);
printResult(documents);
}
public static void notEqualOperator() {
Bson filter = ne("userName", "Jack");
FindIterable<Document> documents = collection.find(filter);
printResult(documents);
}
public static void greaterThanOperator() {
Bson filter = gt("age", 25);
FindIterable<Document> documents = collection.find(filter);
printResult(documents);
}
public static void lessThanOperator() {
Bson filter = lt("age", 25);
FindIterable<Document> documents = collection.find(filter);
printResult(documents);
}
public static void inOperator() {
Bson filter = in("userName", "Jack", "Lisa");
FindIterable<Document> documents = collection.find(filter);
printResult(documents);
}
public static void notInOperator() {
Bson filter = nin("userName", "Jack", "Lisa");
FindIterable<Document> documents = collection.find(filter);
printResult(documents);
}
public static void andOperator() {
Bson filter = and(gt("age", 25), eq("role", "Admin"));
FindIterable<Document> documents = collection.find(filter);
printResult(documents);
}
public static void orOperator() {
Bson filter = or(gt("age", 30), eq("role", "Admin"));
FindIterable<Document> documents = collection.find(filter);
printResult(documents);
}
public static void existsOperator() { | Bson filter = exists("type");
FindIterable<Document> documents = collection.find(filter);
printResult(documents);
}
public static void regexOperator() {
Bson filter = regex("userName", "a");
FindIterable<Document> documents = collection.find(filter);
printResult(documents);
}
private static void printResult(FindIterable<Document> documents) {
MongoCursor<Document> cursor = documents.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
}
public static void main(String args[]) {
setUp();
equalsOperator();
notEqualOperator();
greaterThanOperator();
lessThanOperator();
inOperator();
notInOperator();
andOperator();
orOperator();
existsOperator();
regexOperator();
}
} | repos\tutorials-master\persistence-modules\java-mongodb\src\main\java\com\baeldung\mongo\filter\FilterOperation.java | 1 |
请完成以下Java代码 | public int getAttempts() {
return attempts;
}
public void setAttempts(int attempts) {
this.attempts = attempts;
}
public void encryptPassword() {
if (newPassword != null) {
salt = generateSalt();
setDbPassword(encryptPassword(newPassword, salt));
}
}
protected String encryptPassword(String password, String salt) {
if (password == null) {
return null;
} else {
String saltedPassword = saltPassword(password, salt);
return Context.getProcessEngineConfiguration()
.getPasswordManager()
.encrypt(saltedPassword);
}
}
protected String generateSalt() {
return Context.getProcessEngineConfiguration()
.getSaltGenerator() | .generateSalt();
}
public boolean checkPasswordAgainstPolicy() {
PasswordPolicyResult result = Context.getProcessEngineConfiguration()
.getIdentityService()
.checkPasswordAgainstPolicy(newPassword, this);
return result.isValid();
}
public boolean hasNewPassword() {
return newPassword != null;
}
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", revision=" + revision
+ ", firstName=" + firstName
+ ", lastName=" + lastName
+ ", email=" + email
+ ", password=******" // sensitive for logging
+ ", salt=******" // sensitive for logging
+ ", lockExpirationTime=" + lockExpirationTime
+ ", attempts=" + attempts
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\UserEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean isRequireAuthentication() {
return this.requireAuthentication;
}
public void setRequireAuthentication(boolean requireAuthentication) {
this.requireAuthentication = requireAuthentication;
}
public String getTruststore() {
return this.truststore;
}
public void setTruststore(String truststore) {
this.truststore = truststore;
}
public KeyStoreProperties getTruststoreConfig() {
return this.truststoreConfig;
}
public boolean isWebRequireAuthentication() {
return this.webRequireAuthentication;
}
public void setWebRequireAuthentication(boolean webRequireAuthentication) {
this.webRequireAuthentication = webRequireAuthentication;
}
public static class KeyStoreProperties {
private String password;
private String type;
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
}
public static class SslCertificateProperties {
@NestedConfigurationProperty
private SslCertificateAliasProperties alias = new SslCertificateAliasProperties();
public SslCertificateAliasProperties getAlias() {
return this.alias;
}
}
public static class SslCertificateAliasProperties {
private String all;
private String cluster;
private String defaultAlias;
private String gateway;
private String jmx;
private String locator;
private String server;
private String web;
public String getAll() {
return this.all;
}
public void setAll(String all) {
this.all = all;
}
public String getCluster() { | return this.cluster;
}
public void setCluster(String cluster) {
this.cluster = cluster;
}
public String getDefaultAlias() {
return this.defaultAlias;
}
public void setDefaultAlias(String defaultAlias) {
this.defaultAlias = defaultAlias;
}
public String getGateway() {
return this.gateway;
}
public void setGateway(String gateway) {
this.gateway = gateway;
}
public String getJmx() {
return this.jmx;
}
public void setJmx(String jmx) {
this.jmx = jmx;
}
public String getLocator() {
return this.locator;
}
public void setLocator(String locator) {
this.locator = locator;
}
public String getServer() {
return this.server;
}
public void setServer(String server) {
this.server = server;
}
public String getWeb() {
return this.web;
}
public void setWeb(String web) {
this.web = web;
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\SslProperties.java | 2 |
请完成以下Java代码 | public static void findOneAndReplace() {
Document replaceDocument = new Document();
replaceDocument.append("student_id", 8764)
.append("student_name", "Paul Starc")
.append("address", "Hostel 4")
.append("age", 18)
.append("roll_no", 199406);
Document sort = new Document("roll_no", 1);
Document projection = new Document("_id", 0).append("student_id", 1)
.append("address", 1);
Document resultDocument = collection.findOneAndReplace(Filters.eq("student_id", 8764), replaceDocument, new FindOneAndReplaceOptions().upsert(true)
.sort(sort)
.projection(projection)
.returnDocument(ReturnDocument.AFTER));
System.out.println("resultDocument:- " + resultDocument);
}
public static void findOneAndUpdate() {
Document sort = new Document("roll_no", 1);
Document projection = new Document("_id", 0).append("student_id", 1)
.append("address", 1);
Document resultDocument = collection.findOneAndUpdate(Filters.eq("student_id", 8764), Updates.inc("roll_no", 5), new FindOneAndUpdateOptions().upsert(true)
.sort(sort)
.projection(projection)
.returnDocument(ReturnDocument.AFTER));
System.out.println("resultDocument:- " + resultDocument);
}
public static void setup() {
if (mongoClient == null) {
mongoClient = MongoClients.create("mongodb://localhost:27017");
database = mongoClient.getDatabase("baeldung");
collection = database.getCollection("student");
}
}
public static void main(String[] args) {
//
// Connect to cluster (default is localhost:27017)
// | setup();
//
// Update a document using updateOne method
//
updateOne();
//
// Update documents using updateMany method
//
updateMany();
//
// replace a document using replaceOne method
//
replaceOne();
//
// replace a document using findOneAndReplace method
//
findOneAndReplace();
//
// Update a document using findOneAndUpdate method
//
findOneAndUpdate();
}
} | repos\tutorials-master\persistence-modules\java-mongodb\src\main\java\com\baeldung\mongo\update\UpdateFields.java | 1 |
请完成以下Java代码 | public class ItemDefinitionImpl extends NamedElementImpl implements ItemDefinition {
protected static Attribute<String> typeLanguageAttribute;
protected static Attribute<Boolean> isCollectionAttribute;
protected static ChildElement<TypeRef> typeRefChild;
protected static ChildElement<AllowedValues> allowedValuesChild;
protected static ChildElementCollection<ItemComponent> itemComponentCollection;
public ItemDefinitionImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getTypeLanguage() {
return typeLanguageAttribute.getValue(this);
}
public void setTypeLanguage(String typeLanguage) {
typeLanguageAttribute.setValue(this, typeLanguage);
}
public boolean isCollection() {
return isCollectionAttribute.getValue(this);
}
public void setCollection(boolean isCollection) {
isCollectionAttribute.setValue(this, isCollection);
}
public TypeRef getTypeRef() {
return typeRefChild.getChild(this);
}
public void setTypeRef(TypeRef typeRef) {
typeRefChild.setChild(this, typeRef);
}
public AllowedValues getAllowedValues() {
return allowedValuesChild.getChild(this);
}
public void setAllowedValues(AllowedValues allowedValues) {
allowedValuesChild.setChild(this, allowedValues);
}
public Collection<ItemComponent> getItemComponents() {
return itemComponentCollection.get(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ItemDefinition.class, DMN_ELEMENT_ITEM_DEFINITION)
.namespaceUri(LATEST_DMN_NS)
.extendsType(NamedElement.class) | .instanceProvider(new ModelTypeInstanceProvider<ItemDefinition>() {
public ItemDefinition newInstance(ModelTypeInstanceContext instanceContext) {
return new ItemDefinitionImpl(instanceContext);
}
});
typeLanguageAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_TYPE_LANGUAGE)
.build();
isCollectionAttribute = typeBuilder.booleanAttribute(DMN_ATTRIBUTE_IS_COLLECTION)
.defaultValue(false)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
typeRefChild = sequenceBuilder.element(TypeRef.class)
.build();
allowedValuesChild = sequenceBuilder.element(AllowedValues.class)
.build();
itemComponentCollection = sequenceBuilder.elementCollection(ItemComponent.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\ItemDefinitionImpl.java | 1 |
请完成以下Java代码 | public String getImplementation() {
return implementation;
}
public void setImplementation(String implementation) {
this.implementation = implementation;
}
public String getImplementationType() {
return implementationType;
}
public void setImplementationType(String implementationType) {
this.implementationType = implementationType;
}
public String getResultVariableName() {
return resultVariableName;
}
public void setResultVariableName(String resultVariableName) {
this.resultVariableName = resultVariableName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isStoreResultVariableAsTransient() {
return storeResultVariableAsTransient;
}
public void setStoreResultVariableAsTransient(boolean storeResultVariableAsTransient) {
this.storeResultVariableAsTransient = storeResultVariableAsTransient;
}
@Override | public ServiceTask clone() {
ServiceTask clone = new ServiceTask();
clone.setValues(this);
return clone;
}
public void setValues(ServiceTask otherElement) {
super.setValues(otherElement);
setImplementation(otherElement.getImplementation());
setImplementationType(otherElement.getImplementationType());
setResultVariableName(otherElement.getResultVariableName());
setType(otherElement.getType());
setStoreResultVariableAsTransient(otherElement.isStoreResultVariableAsTransient());
fieldExtensions = new ArrayList<>();
if (otherElement.getFieldExtensions() != null && !otherElement.getFieldExtensions().isEmpty()) {
for (FieldExtension extension : otherElement.getFieldExtensions()) {
fieldExtensions.add(extension.clone());
}
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\ServiceTask.java | 1 |
请完成以下Java代码 | public Integer getSalary() {
return salary;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() { | return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-functions-azure\src\main\java\com\baeldung\azure\functions\entity\Employee.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static void validateMetaDataFieldsAndConnections(RuleChainMetaData ruleChainMetaData) {
ConstraintValidator.validateFields(ruleChainMetaData);
if (CollectionUtils.isNotEmpty(ruleChainMetaData.getConnections())) {
validateCircles(ruleChainMetaData.getConnections());
}
}
public static Throwable validateRuleNode(RuleNode ruleNode) {
String errorPrefix = "'" + ruleNode.getName() + "' node configuration is invalid: ";
ConstraintValidator.validateFields(ruleNode, errorPrefix);
Object nodeConfig;
try {
Class<Object> nodeConfigType = ReflectionUtils.getAnnotationProperty(ruleNode.getType(),
"org.thingsboard.rule.engine.api.RuleNode", "configClazz");
nodeConfig = JacksonUtil.treeToValue(ruleNode.getConfiguration(), nodeConfigType);
} catch (Throwable t) {
log.warn("Failed to validate node configuration: {}", ExceptionUtils.getRootCauseMessage(t));
return t;
}
ConstraintValidator.validateFields(nodeConfig, errorPrefix);
return null;
}
private static void validateCircles(List<NodeConnectionInfo> connectionInfos) {
Map<Integer, Set<Integer>> connectionsMap = new HashMap<>();
for (NodeConnectionInfo nodeConnection : connectionInfos) {
if (nodeConnection.getFromIndex() == nodeConnection.getToIndex()) { | throw new DataValidationException("Can't create the relation to yourself.");
}
connectionsMap
.computeIfAbsent(nodeConnection.getFromIndex(), from -> new HashSet<>())
.add(nodeConnection.getToIndex());
}
connectionsMap.keySet().forEach(key -> validateCircles(key, connectionsMap.get(key), connectionsMap));
}
private static void validateCircles(int from, Set<Integer> toList, Map<Integer, Set<Integer>> connectionsMap) {
if (toList == null) {
return;
}
for (Integer to : toList) {
if (from == to) {
throw new DataValidationException("Can't create circling relations in rule chain.");
}
validateCircles(from, connectionsMap.get(to), connectionsMap);
}
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\RuleChainDataValidator.java | 2 |
请完成以下Java代码 | public class PvmAtomicOperationDeleteCascade implements PvmAtomicOperation {
public boolean isAsync(PvmExecutionImpl execution) {
return false;
}
public boolean isAsyncCapable() {
return false;
}
public void execute(PvmExecutionImpl execution) {
PvmExecutionImpl nextLeaf;
do {
nextLeaf = findNextLeaf(execution);
// nextLeaf can already be removed, if it was the concurrent parent of the previous leaf.
// In that case, DELETE_CASCADE_FIRE_ACTIVITY_END on the previousLeaf already removed
// nextLeaf, so calling DELETE_CASCADE_FIRE_ACTIVITY_END again would incorrectly
// invoke execution listeners
if (nextLeaf.isDeleteRoot() && nextLeaf.isRemoved()) {
return;
}
// propagate properties
PvmExecutionImpl deleteRoot = getDeleteRoot(execution);
if (deleteRoot != null) {
nextLeaf.setSkipCustomListeners(deleteRoot.isSkipCustomListeners());
nextLeaf.setSkipIoMappings(deleteRoot.isSkipIoMappings());
nextLeaf.setExternallyTerminated(deleteRoot.isExternallyTerminated());
}
PvmExecutionImpl subProcessInstance = nextLeaf.getSubProcessInstance();
if (subProcessInstance != null) {
if (deleteRoot.isSkipSubprocesses()) {
subProcessInstance.setSuperExecution(null);
} else {
subProcessInstance.deleteCascade(execution.getDeleteReason(), nextLeaf.isSkipCustomListeners(), nextLeaf.isSkipIoMappings(),
nextLeaf.isExternallyTerminated(), nextLeaf.isSkipSubprocesses());
}
}
nextLeaf.performOperation(DELETE_CASCADE_FIRE_ACTIVITY_END); | } while (!nextLeaf.isDeleteRoot());
}
protected PvmExecutionImpl findNextLeaf(PvmExecutionImpl execution) {
if (execution.hasChildren()) {
return findNextLeaf(execution.getExecutions().get(0));
}
return execution;
}
protected PvmExecutionImpl getDeleteRoot(PvmExecutionImpl execution) {
if(execution == null) {
return null;
} else if(execution.isDeleteRoot()) {
return execution;
} else {
return getDeleteRoot(execution.getParent());
}
}
public String getCanonicalName() {
return "delete-cascade";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\PvmAtomicOperationDeleteCascade.java | 1 |
请完成以下Java代码 | public boolean hasError(ClientHttpResponse response) throws IOException {
return this.defaultErrorHandler.hasError(response);
}
@Override
public void handleError(URI url, HttpMethod method, ClientHttpResponse response) throws IOException {
if (HttpStatus.BAD_REQUEST.value() != response.getStatusCode().value()) {
this.defaultErrorHandler.handleError(url, method, response);
}
// A Bearer Token Error may be in the WWW-Authenticate response header
// See https://tools.ietf.org/html/rfc6750#section-3
OAuth2Error oauth2Error = this.readErrorFromWwwAuthenticate(response.getHeaders());
if (oauth2Error == null) {
oauth2Error = this.oauth2ErrorConverter.read(OAuth2Error.class, response);
}
throw new OAuth2AuthorizationException(oauth2Error);
}
private OAuth2Error readErrorFromWwwAuthenticate(HttpHeaders headers) {
String wwwAuthenticateHeader = headers.getFirst(HttpHeaders.WWW_AUTHENTICATE);
if (!StringUtils.hasText(wwwAuthenticateHeader)) {
return null;
}
BearerTokenError bearerTokenError = getBearerToken(wwwAuthenticateHeader);
if (bearerTokenError == null) {
return new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, null, null);
}
String errorCode = (bearerTokenError.getCode() != null) ? bearerTokenError.getCode()
: OAuth2ErrorCodes.SERVER_ERROR;
String errorDescription = bearerTokenError.getDescription();
String errorUri = (bearerTokenError.getURI() != null) ? bearerTokenError.getURI().toString() : null;
return new OAuth2Error(errorCode, errorDescription, errorUri);
}
private BearerTokenError getBearerToken(String wwwAuthenticateHeader) {
try { | return BearerTokenError.parse(wwwAuthenticateHeader);
}
catch (Exception ex) {
return null;
}
}
/**
* Sets the {@link HttpMessageConverter} for an OAuth 2.0 Error.
* @param oauth2ErrorConverter A {@link HttpMessageConverter} for an
* {@link OAuth2Error OAuth 2.0 Error}.
* @since 5.7
*/
public final void setErrorConverter(HttpMessageConverter<OAuth2Error> oauth2ErrorConverter) {
Assert.notNull(oauth2ErrorConverter, "oauth2ErrorConverter cannot be null");
this.oauth2ErrorConverter = oauth2ErrorConverter;
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\http\OAuth2ErrorResponseErrorHandler.java | 1 |
请完成以下Java代码 | public class C_Invoice_Candidate_BillBPartner_FacetCollector extends SingleFacetCategoryCollectorTemplate<I_C_Invoice_Candidate>
{
public C_Invoice_Candidate_BillBPartner_FacetCollector()
{
super(FacetCategory.builder()
.setDisplayNameAndTranslate(I_C_Invoice_Candidate.COLUMNNAME_Bill_BPartner_ID)
.setCollapsed(true) // 08755: default collapsed
.build());
}
@Override
protected List<IFacet<I_C_Invoice_Candidate>> collectFacets(final IQueryBuilder<I_C_Invoice_Candidate> queryBuilder)
{
// FRESH-560: Add default filter
final IQueryBuilder<I_C_Invoice_Candidate> queryBuilderWithDefaultFilters = Services.get(IInvoiceCandDAO.class).applyDefaultFilter(queryBuilder);
final List<Map<String, Object>> bpartners = queryBuilderWithDefaultFilters
.andCollect(I_C_Invoice_Candidate.COLUMNNAME_Bill_BPartner_ID, I_C_BPartner.class)
.create()
.listDistinct(I_C_BPartner.COLUMNNAME_C_BPartner_ID, I_C_BPartner.COLUMNNAME_Name, I_C_BPartner.COLUMNNAME_Value);
final List<IFacet<I_C_Invoice_Candidate>> facets = new ArrayList<>(bpartners.size());
for (final Map<String, Object> row : bpartners)
{
final IFacet<I_C_Invoice_Candidate> facet = createFacet(row);
facets.add(facet);
}
return facets;
} | private IFacet<I_C_Invoice_Candidate> createFacet(final Map<String, Object> row)
{
final IFacetCategory facetCategoryBPartners = getFacetCategory();
final int bpartnerId = (int)row.get(I_C_BPartner.COLUMNNAME_C_BPartner_ID);
final String bpartnerName = new StringBuilder()
.append(row.get(I_C_BPartner.COLUMNNAME_Value))
.append(" - ")
.append(row.get(I_C_BPartner.COLUMNNAME_Name))
.toString();
final Facet<I_C_Invoice_Candidate> facet = Facet.<I_C_Invoice_Candidate> builder()
.setFacetCategory(facetCategoryBPartners)
.setDisplayName(bpartnerName)
.setFilter(TypedSqlQueryFilter.of(I_C_Invoice_Candidate.COLUMNNAME_Bill_BPartner_ID + "=" + bpartnerId))
.build();
return facet;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\facet\impl\C_Invoice_Candidate_BillBPartner_FacetCollector.java | 1 |
请完成以下Java代码 | public class URIDemo {
private final Logger logger = LoggerFactory.getLogger(URIDemo.class);
String URISTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
// parsed locator
String URISCHEME = "https";
String URISCHEMESPECIFIC;
String URIHOST = "wordpress.org";
String URIAUTHORITY = "wordpress.org:443";
String URIPATH = "/support/topic/page-jumps-within-wordpress/";
int URIPORT = 443;
String URIQUERY = "replies=3";
String URIFRAGMENT = "post-2278484";
String URIUSERINFO;
String URICOMPOUND = URISCHEME + "://" + URIHOST + ":" + URIPORT + URIPATH + "?" + URIQUERY + "#" + URIFRAGMENT;
URI uri;
URL url;
BufferedReader in = null;
String URIContent = "";
private String getParsedPieces(URI uri) {
logger.info("*** List of parsed pieces ***");
URISCHEME = uri.getScheme();
logger.info("URISCHEME: " + URISCHEME);
URISCHEMESPECIFIC = uri.getSchemeSpecificPart();
logger.info("URISCHEMESPECIFIC: " + URISCHEMESPECIFIC);
URIHOST = uri.getHost();
URIAUTHORITY = uri.getAuthority();
logger.info("URIAUTHORITY: " + URIAUTHORITY);
logger.info("URIHOST: " + URIHOST);
URIPATH = uri.getPath();
logger.info("URIPATH: " + URIPATH);
URIPORT = uri.getPort();
logger.info("URIPORT: " + URIPORT);
URIQUERY = uri.getQuery();
logger.info("URIQUERY: " + URIQUERY);
URIFRAGMENT = uri.getFragment();
logger.info("URIFRAGMENT: " + URIFRAGMENT);
try {
url = uri.toURL();
} catch (MalformedURLException e) {
logger.info("MalformedURLException thrown: " + e.getMessage());
e.printStackTrace();
} catch (IllegalArgumentException e) {
logger.info("IllegalArgumentException thrown: " + e.getMessage());
e.printStackTrace();
}
return url.toString();
} | public String testURIAsNew(String URIString) {
// creating URI object
try {
uri = new URI(URIString);
} catch (URISyntaxException e) {
logger.info("URISyntaxException thrown: " + e.getMessage());
e.printStackTrace();
throw new IllegalArgumentException();
}
return getParsedPieces(uri);
}
public String testURIAsCreate(String URIString) {
// creating URI object
uri = URI.create(URIString);
return getParsedPieces(uri);
}
public static void main(String[] args) throws Exception {
URIDemo demo = new URIDemo();
String contentCreate = demo.testURIAsCreate(demo.URICOMPOUND);
demo.logger.info(contentCreate);
String contentNew = demo.testURIAsNew(demo.URICOMPOUND);
demo.logger.info(contentNew);
}
} | repos\tutorials-master\core-java-modules\core-java-networking-5\src\main\java\com\baeldung\networking\uriurl\URIDemo.java | 1 |
请完成以下Java代码 | public List<JobEntity> findExpiredJobs(Page page) {
Date now = getClock().getCurrentTime();
return getDbSqlSession().selectList("selectExpiredJobs", now, page);
}
@Override
@SuppressWarnings("unchecked")
public List<Job> findJobsByQueryCriteria(JobQueryImpl jobQuery, Page page) {
final String query = "selectJobByQueryCriteria";
return getDbSqlSession().selectList(query, jobQuery, page);
}
@Override
public long findJobCountByQueryCriteria(JobQueryImpl jobQuery) {
return (Long) getDbSqlSession().selectOne("selectJobCountByQueryCriteria", jobQuery);
} | @Override
public void updateJobTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().update("updateJobTenantIdForDeployment", params);
}
@Override
public void resetExpiredJob(String jobId) {
Map<String, Object> params = new HashMap<String, Object>(2);
params.put("id", jobId);
getDbSqlSession().update("resetExpiredJob", params);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisJobDataManager.java | 1 |
请完成以下Java代码 | public String getCode() {
return code;
}
/**
* Sets the value of the code property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCode(String value) {
this.code = value;
}
/**
* Gets the value of the text property.
*
* @return
* possible object is
* {@link String }
*
*/ | public String getText() {
return text;
}
/**
* Sets the value of the text property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setText(String value) {
this.text = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\NotificationType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int hashCode() {
return Objects.hash(_id, patientId, patientBirthday, orderId, prescriptionType, creationDate, deliveryDate, startDate, endDate, accountingMonths, doctorId, pharmacyId, therapyId, therapyTypeIds, prescriptedArticleLines, createdBy, annotation, archived, timestamp, updated);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PrescriptionRequest {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" patientId: ").append(toIndentedString(patientId)).append("\n");
sb.append(" patientBirthday: ").append(toIndentedString(patientBirthday)).append("\n");
sb.append(" orderId: ").append(toIndentedString(orderId)).append("\n");
sb.append(" prescriptionType: ").append(toIndentedString(prescriptionType)).append("\n");
sb.append(" creationDate: ").append(toIndentedString(creationDate)).append("\n");
sb.append(" deliveryDate: ").append(toIndentedString(deliveryDate)).append("\n");
sb.append(" startDate: ").append(toIndentedString(startDate)).append("\n");
sb.append(" endDate: ").append(toIndentedString(endDate)).append("\n");
sb.append(" accountingMonths: ").append(toIndentedString(accountingMonths)).append("\n");
sb.append(" doctorId: ").append(toIndentedString(doctorId)).append("\n");
sb.append(" pharmacyId: ").append(toIndentedString(pharmacyId)).append("\n");
sb.append(" therapyId: ").append(toIndentedString(therapyId)).append("\n");
sb.append(" therapyTypeIds: ").append(toIndentedString(therapyTypeIds)).append("\n");
sb.append(" prescriptedArticleLines: ").append(toIndentedString(prescriptedArticleLines)).append("\n");
sb.append(" createdBy: ").append(toIndentedString(createdBy)).append("\n"); | sb.append(" annotation: ").append(toIndentedString(annotation)).append("\n");
sb.append(" archived: ").append(toIndentedString(archived)).append("\n");
sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n");
sb.append(" updated: ").append(toIndentedString(updated)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\PrescriptionRequest.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public AlarmComment saveAlarmComment(Alarm alarm, AlarmComment alarmComment, User user) throws ThingsboardException {
ActionType actionType = alarmComment.getId() == null ? ActionType.ADDED_COMMENT : ActionType.UPDATED_COMMENT;
if (user != null) {
alarmComment.setUserId(user.getId());
}
try {
AlarmComment savedAlarmComment = checkNotNull(alarmCommentService.createOrUpdateAlarmComment(alarm.getTenantId(), alarmComment));
logEntityActionService.logEntityAction(alarm.getTenantId(), alarm.getId(), alarm, alarm.getCustomerId(), actionType, user, savedAlarmComment);
return savedAlarmComment;
} catch (Exception e) {
logEntityActionService.logEntityAction(alarm.getTenantId(), emptyId(EntityType.ALARM), alarm, actionType, user, e, alarmComment);
throw e;
}
}
@Override | public void deleteAlarmComment(Alarm alarm, AlarmComment alarmComment, User user) throws ThingsboardException {
if (alarmComment.getType() == AlarmCommentType.OTHER) {
alarmComment.setType(AlarmCommentType.SYSTEM);
alarmComment.setUserId(null);
alarmComment.setComment(JacksonUtil.newObjectNode()
.put("text", String.format(COMMENT_DELETED.getText(), user.getTitle()))
.put("subtype", COMMENT_DELETED.name())
.put("userName", user.getTitle()));
AlarmComment savedAlarmComment = checkNotNull(alarmCommentService.saveAlarmComment(alarm.getTenantId(), alarmComment));
logEntityActionService.logEntityAction(alarm.getTenantId(), alarm.getId(), alarm, alarm.getCustomerId(), ActionType.DELETED_COMMENT, user, savedAlarmComment);
} else {
throw new ThingsboardException("System comment could not be deleted", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\alarm\DefaultTbAlarmCommentService.java | 2 |
请完成以下Java代码 | public EntityType getEntityType() {
return EntityType.ASSET_PROFILE;
}
@Override
public List<EntityInfo> findAssetProfileNamesByTenantId(TenantId tenantId, boolean activeOnly) {
log.trace("Executing findAssetProfileNamesByTenantId, tenantId [{}]", tenantId);
validateId(tenantId, id -> INCORRECT_TENANT_ID + id);
return assetProfileDao.findTenantAssetProfileNames(tenantId.getId(), activeOnly)
.stream().sorted(Comparator.comparing(EntityInfo::getName))
.collect(Collectors.toList());
}
@Override
public List<AssetProfileInfo> findAssetProfilesByIds(TenantId tenantId, List<AssetProfileId> assetProfileIds) {
log.trace("Executing findAssetProfilesByIds, tenantId [{}], assetProfileIds [{}]", tenantId, assetProfileIds);
return assetProfileDao.findAssetProfilesByTenantIdAndIds(tenantId.getId(), toUUIDs(assetProfileIds));
}
private final PaginatedRemover<TenantId, AssetProfile> tenantAssetProfilesRemover =
new PaginatedRemover<>() { | @Override
protected PageData<AssetProfile> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) {
return assetProfileDao.findAssetProfiles(id, pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, AssetProfile entity) {
removeAssetProfile(tenantId, entity);
}
};
private AssetProfileInfo toAssetProfileInfo(AssetProfile profile) {
return profile == null ? null : new AssetProfileInfo(profile.getId(), profile.getTenantId(), profile.getName(), profile.getImage(),
profile.getDefaultDashboardId());
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\asset\AssetProfileServiceImpl.java | 1 |
请完成以下Java代码 | public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CaseFileItem.class, CMMN_ELEMENT_CASE_FILE_ITEM)
.namespaceUri(CMMN11_NS)
.extendsType(CmmnElement.class)
.instanceProvider(new ModelTypeInstanceProvider<CaseFileItem>() {
public CaseFileItem newInstance(ModelTypeInstanceContext instanceContext) {
return new CaseFileItemImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME)
.build();
multiplicityAttribute = typeBuilder.enumAttribute(CMMN_ATTRIBUTE_MULTIPLICITY, MultiplicityEnum.class)
.defaultValue(MultiplicityEnum.Unspecified)
.build();
definitionRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_DEFINITION_REF)
.qNameAttributeReference(CaseFileItemDefinition.class)
.build();
sourceRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REF) | .namespace(CMMN10_NS)
.idAttributeReference(CaseFileItem.class)
.build();
sourceRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REFS)
.idAttributeReferenceCollection(CaseFileItem.class, CmmnAttributeElementReferenceCollection.class)
.build();
targetRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_TARGET_REFS)
.idAttributeReferenceCollection(CaseFileItem.class, CmmnAttributeElementReferenceCollection.class)
.build();
SequenceBuilder sequence = typeBuilder.sequence();
childrenChild = sequence.element(Children.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CaseFileItemImpl.java | 1 |
请完成以下Java代码 | public ETag getETag()
{
return etag;
}
public String getImageName()
{
return adImage.getFilename();
}
public String getContentType()
{
return adImage.getContentType();
}
public byte[] getImageData()
{
return adImage.getScaledImageData(maxWidth, maxHeight);
}
public ClientId getAdClientId()
{
return adImage.getClientAndOrgId().getClientId();
} | public OrgId getAdOrgId()
{
return adImage.getClientAndOrgId().getOrgId();
}
public AdImageId getAdImageId()
{
return adImage.getId();
}
public ResponseEntity<byte[]> toResponseEntity()
{
return toResponseEntity(ResponseEntity.status(HttpStatus.OK));
}
public ResponseEntity<byte[]> toResponseEntity(@NonNull final ResponseEntity.BodyBuilder responseBuilder)
{
return responseBuilder
.contentType(MediaType.parseMediaType(getContentType()))
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + getImageName() + "\"")
.body(getImageData());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\upload\WebuiImage.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable String getDatabasePlatform() {
return this.databasePlatform;
}
public void setDatabasePlatform(@Nullable String databasePlatform) {
this.databasePlatform = databasePlatform;
}
public @Nullable Database getDatabase() {
return this.database;
}
public void setDatabase(@Nullable Database database) {
this.database = database;
}
public boolean isGenerateDdl() {
return this.generateDdl;
} | public void setGenerateDdl(boolean generateDdl) {
this.generateDdl = generateDdl;
}
public boolean isShowSql() {
return this.showSql;
}
public void setShowSql(boolean showSql) {
this.showSql = showSql;
}
public @Nullable Boolean getOpenInView() {
return this.openInView;
}
public void setOpenInView(@Nullable Boolean openInView) {
this.openInView = openInView;
}
} | repos\spring-boot-4.0.1\module\spring-boot-jpa\src\main\java\org\springframework\boot\jpa\autoconfigure\JpaProperties.java | 2 |
请完成以下Java代码 | public void setQtyInternalUse(final BigDecimal QtyInternalUse)
{
super.setQtyInternalUse(adjustQtyToUOMPrecision(QtyInternalUse));
} // setQtyInternalUse
/**
* String Representation
*
* @return info
*/
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder("MInventoryLine[");
sb.append(get_ID())
.append("-M_Product_ID=").append(getM_Product_ID())
.append(",QtyCount=").append(getQtyCount())
.append(",QtyInternalUse=").append(getQtyInternalUse())
.append(",QtyBook=").append(getQtyBook())
.append(",M_AttributeSetInstance_ID=").append(getM_AttributeSetInstance_ID())
.append("]");
return sb.toString();
} // toString
@Override
protected boolean beforeSave(final boolean newRecord)
{
final IInventoryBL inventoryBL = Services.get(IInventoryBL.class);
if (newRecord && Services.get(IInventoryBL.class).isComplete(getM_Inventory()))
{
throw new AdempiereException("@ParentComplete@ @M_Inventory_ID@");
}
if (newRecord && is_ManualUserAction())
{
// Product requires ASI
if (getM_AttributeSetInstance_ID() <= 0)
{
final ProductId productId = ProductId.ofRepoId(getM_Product_ID());
if(Services.get(IProductBL.class).isASIMandatory(productId, isSOTrx()))
{
throw new FillMandatoryException(COLUMNNAME_M_AttributeSetInstance_ID);
}
} // No ASI
} // new or manual
// Set Line No
if (getLine() <= 0)
{
final String sql = "SELECT COALESCE(MAX(Line),0)+10 AS DefaultValue FROM M_InventoryLine WHERE M_Inventory_ID=?";
final int lineNo = DB.getSQLValueEx(get_TrxName(), sql, getM_Inventory_ID());
setLine(lineNo);
}
// Enforce Qty UOM
if (newRecord || is_ValueChanged(COLUMNNAME_QtyCount))
{
setQtyCount(getQtyCount());
}
if (newRecord || is_ValueChanged(COLUMNNAME_QtyInternalUse))
{
setQtyInternalUse(getQtyInternalUse());
}
// InternalUse Inventory
if (isInternalUseInventory())
{
if (!INVENTORYTYPE_ChargeAccount.equals(getInventoryType()))
{
setInventoryType(INVENTORYTYPE_ChargeAccount);
}
// | if (getC_Charge_ID() <= 0)
{
inventoryBL.setDefaultInternalChargeId(this);
}
}
else if (INVENTORYTYPE_ChargeAccount.equals(getInventoryType()))
{
if (getC_Charge_ID() <= 0)
{
throw new FillMandatoryException(COLUMNNAME_C_Charge_ID);
}
}
else if (getC_Charge_ID() > 0)
{
setC_Charge_ID(0);
}
// Set AD_Org to parent if not charge
if (getC_Charge_ID() <= 0)
{
setAD_Org_ID(getM_Inventory().getAD_Org_ID());
}
return true;
}
@Deprecated
private boolean isInternalUseInventory()
{
return Services.get(IInventoryBL.class).isInternalUseInventory(this);
}
/**
* @return true if is an outgoing transaction
*/
@Deprecated
private boolean isSOTrx()
{
return Services.get(IInventoryBL.class).isSOTrx(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MInventoryLine.java | 1 |
请完成以下Java代码 | public Notification findNotificationById(TenantId tenantId, NotificationId notificationId) {
return notificationDao.findById(tenantId, notificationId.getId());
}
@Override
public boolean markNotificationAsRead(TenantId tenantId, UserId recipientId, NotificationId notificationId) {
return notificationDao.updateStatusByIdAndRecipientId(tenantId, recipientId, notificationId, NotificationStatus.READ);
}
@Override
public int markAllNotificationsAsRead(TenantId tenantId, NotificationDeliveryMethod deliveryMethod, UserId recipientId) {
return notificationDao.updateStatusByDeliveryMethodAndRecipientId(tenantId, deliveryMethod, recipientId, NotificationStatus.READ);
}
@Override
public PageData<Notification> findNotificationsByRecipientIdAndReadStatus(TenantId tenantId, NotificationDeliveryMethod deliveryMethod, UserId recipientId, boolean unreadOnly, PageLink pageLink) {
if (unreadOnly) {
return notificationDao.findUnreadByDeliveryMethodAndRecipientIdAndPageLink(tenantId, deliveryMethod, recipientId, pageLink);
} else {
return notificationDao.findByDeliveryMethodAndRecipientIdAndPageLink(tenantId, deliveryMethod, recipientId, pageLink);
}
}
@Override
public PageData<Notification> findLatestUnreadNotificationsByRecipientIdAndNotificationTypes(TenantId tenantId, NotificationDeliveryMethod deliveryMethod, UserId recipientId, Set<NotificationType> types, int limit) {
SortOrder sortOrder = new SortOrder(EntityKeyMapping.CREATED_TIME, SortOrder.Direction.DESC);
PageLink pageLink = new PageLink(limit, 0, null, sortOrder);
return notificationDao.findUnreadByDeliveryMethodAndRecipientIdAndNotificationTypesAndPageLink(tenantId, deliveryMethod, recipientId, types, pageLink);
} | @Override
public int countUnreadNotificationsByRecipientId(TenantId tenantId, NotificationDeliveryMethod deliveryMethod, UserId recipientId) {
return notificationDao.countUnreadByDeliveryMethodAndRecipientId(tenantId, deliveryMethod, recipientId);
}
@Override
public boolean deleteNotification(TenantId tenantId, UserId recipientId, NotificationId notificationId) {
return notificationDao.deleteByIdAndRecipientId(tenantId, recipientId, notificationId);
}
@Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findNotificationById(tenantId, new NotificationId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(notificationDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\notification\DefaultNotificationService.java | 1 |
请完成以下Java代码 | public void setInvoicableQtyBasedOn (final java.lang.String InvoicableQtyBasedOn)
{
set_Value (COLUMNNAME_InvoicableQtyBasedOn, InvoicableQtyBasedOn);
}
@Override
public java.lang.String getInvoicableQtyBasedOn()
{
return get_ValueAsString(COLUMNNAME_InvoicableQtyBasedOn);
}
@Override
public void setM_PricingSystem_ID (final int M_PricingSystem_ID)
{
if (M_PricingSystem_ID < 1)
set_Value (COLUMNNAME_M_PricingSystem_ID, null);
else
set_Value (COLUMNNAME_M_PricingSystem_ID, M_PricingSystem_ID);
}
@Override
public int getM_PricingSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PricingSystem_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 setPriceList (final @Nullable BigDecimal PriceList)
{
set_Value (COLUMNNAME_PriceList, PriceList); | }
@Override
public BigDecimal getPriceList()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceList);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPriceStd (final BigDecimal PriceStd)
{
set_Value (COLUMNNAME_PriceStd, PriceStd);
}
@Override
public BigDecimal getPriceStd()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceStd);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Campaign_Price.java | 1 |
请完成以下Java代码 | public java.lang.String getI_ErrorMsg ()
{
return (java.lang.String)get_Value(COLUMNNAME_I_ErrorMsg);
}
/**
* I_IsImported AD_Reference_ID=540745
* Reference name: I_IsImported
*/
public static final int I_ISIMPORTED_AD_Reference_ID=540745;
/** NotImported = N */
public static final String I_ISIMPORTED_NotImported = "N";
/** Imported = Y */
public static final String I_ISIMPORTED_Imported = "Y";
/** ImportFailed = E */
public static final String I_ISIMPORTED_ImportFailed = "E";
/** Set Importiert.
@param I_IsImported
Ist dieser Import verarbeitet worden?
*/
@Override
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代码 | public CommandExecutor getCommandExecutor() {
return commandExecutor;
}
public CommandContext getCommandContext() {
return commandContext;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public List<AbstractProcessInstanceModificationCommand> getModificationOperations() {
return operations;
}
public void setModificationOperations(List<AbstractProcessInstanceModificationCommand> operations) {
this.operations = operations;
}
public boolean isSkipCustomListeners() {
return skipCustomListeners;
}
public boolean isSkipIoMappings() {
return skipIoMappings;
}
public boolean isExternallyTerminated() {
return externallyTerminated;
}
public void setSkipCustomListeners(boolean skipCustomListeners) {
this.skipCustomListeners = skipCustomListeners;
}
public void setSkipIoMappings(boolean skipIoMappings) {
this.skipIoMappings = skipIoMappings;
}
public VariableMap getProcessVariables() {
return processVariables; | }
public String getModificationReason() {
return modificationReason;
}
public void setModificationReason(String modificationReason) {
this.modificationReason = modificationReason;
}
public String getAnnotation() {
return annotation;
}
public void setAnnotationInternal(String annotation) {
this.annotation = annotation;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessInstanceModificationBuilderImpl.java | 1 |
请完成以下Java代码 | public boolean hasInactiveValues()
{
return this.hasInactiveValues;
}
@Override
public boolean isAllLoaded()
{
return allLoaded;
}
@Override
public boolean isDirty()
{
return wasInterrupted;
}
private final String normalizeKey(final Object key)
{
return key == null ? null : key.toString();
}
@Override
public boolean containsKey(Object key) | {
final String keyStr = normalizeKey(key);
return values.containsKey(keyStr);
}
@Override
public NamePair getByKey(Object key)
{
final String keyStr = normalizeKey(key);
return values.get(keyStr);
}
@Override
public Collection<NamePair> getValues()
{
return values.values();
}
@Override
public int size()
{
return values.size();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\MLookupLoader.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getType() {
return type;
}
/**
* 操作员类型
*
* @return
*/
public void setType(String type) {
this.type = type;
}
/**
* 盐
*
* @return
*/
public String getsalt() {
return salt;
}
/**
* 盐
*
* @param salt
*/
public void setsalt(String salt) {
this.salt = salt; | }
/**
* 认证加密的盐
*
* @return
*/
public String getCredentialsSalt() {
return loginName + salt;
}
public PmsOperator() {
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\entity\PmsOperator.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private OAuth2AuthorizedClientProvider getTokenExchangeAuthorizedClientProvider(
Collection<OAuth2AuthorizedClientProvider> authorizedClientProviders) {
TokenExchangeOAuth2AuthorizedClientProvider authorizedClientProvider = getAuthorizedClientProviderByType(
authorizedClientProviders, TokenExchangeOAuth2AuthorizedClientProvider.class);
OAuth2AccessTokenResponseClient<TokenExchangeGrantRequest> accessTokenResponseClient = getBeanOfType(
ResolvableType.forClassWithGenerics(OAuth2AccessTokenResponseClient.class,
TokenExchangeGrantRequest.class));
if (accessTokenResponseClient != null) {
if (authorizedClientProvider == null) {
authorizedClientProvider = new TokenExchangeOAuth2AuthorizedClientProvider();
}
authorizedClientProvider.setAccessTokenResponseClient(accessTokenResponseClient);
}
return authorizedClientProvider;
}
private List<OAuth2AuthorizedClientProvider> getAdditionalAuthorizedClientProviders(
Collection<OAuth2AuthorizedClientProvider> authorizedClientProviders) {
List<OAuth2AuthorizedClientProvider> additionalAuthorizedClientProviders = new ArrayList<>(
authorizedClientProviders);
additionalAuthorizedClientProviders
.removeIf((provider) -> KNOWN_AUTHORIZED_CLIENT_PROVIDERS.contains(provider.getClass()));
return additionalAuthorizedClientProviders;
}
private <T extends OAuth2AuthorizedClientProvider> T getAuthorizedClientProviderByType(
Collection<OAuth2AuthorizedClientProvider> authorizedClientProviders, Class<T> providerClass) {
T authorizedClientProvider = null;
for (OAuth2AuthorizedClientProvider current : authorizedClientProviders) {
if (providerClass.isInstance(current)) {
assertAuthorizedClientProviderIsNull(authorizedClientProvider); | authorizedClientProvider = providerClass.cast(current);
}
}
return authorizedClientProvider;
}
private static void assertAuthorizedClientProviderIsNull(OAuth2AuthorizedClientProvider authorizedClientProvider) {
if (authorizedClientProvider != null) {
// @formatter:off
throw new BeanInitializationException(String.format(
"Unable to create an %s bean. Expected one bean of type %s, but found multiple. " +
"Please consider defining only a single bean of this type, or define an %s bean yourself.",
OAuth2AuthorizedClientManager.class.getName(),
authorizedClientProvider.getClass().getName(),
OAuth2AuthorizedClientManager.class.getName()));
// @formatter:on
}
}
private <T> String[] getBeanNamesForType(Class<T> beanClass) {
return BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, beanClass, false, false);
}
private <T> T getBeanOfType(ResolvableType resolvableType) {
ObjectProvider<T> objectProvider = this.beanFactory.getBeanProvider(resolvableType, true);
return objectProvider.getIfAvailable();
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\OAuth2AuthorizedClientManagerRegistrar.java | 2 |
请完成以下Java代码 | public List<EncryptionPropertyType> getEncryptionProperty() {
if (encryptionProperty == null) {
encryptionProperty = new ArrayList<EncryptionPropertyType>();
}
return this.encryptionProperty;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() { | return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\EncryptionPropertiesType.java | 1 |
请完成以下Java代码 | public double getColWidth ()
{
return m_width;
} // getColWidth
/**
* @param width The column width in pixels.
*/
public void setColWidth (double width)
{
m_width = width;
} // getColWidth
/**
* @return Returns the height in pixels.
*/
public double getColHeight()
{
return m_height;
} // getHeight
/**
* @param height The height in pixels.
*/
public void setColHeight (double height)
{
m_height = height;
} // setHeight
public MQuery getMQuery(MGoal mGoal)
{
MQuery query = null;
if (getAchievement() != null) // Single Achievement
{
MAchievement a = getAchievement();
query = MQuery.getEqualQuery("PA_Measure_ID", a.getPA_Measure_ID());
}
else if (getGoal() != null) // Multiple Achievements | {
MGoal goal = getGoal();
query = MQuery.getEqualQuery("PA_Measure_ID", goal.getPA_Measure_ID());
}
else if (getMeasureCalc() != null) // Document
{
MMeasureCalc mc = getMeasureCalc();
query = mc.getQuery(mGoal.getRestrictions(false),
getMeasureDisplay(), getDate(),
Env.getUserRolePermissions()); // logged in role
}
else if (getProjectType() != null) // Document
{
ProjectType pt = getProjectType();
query = MMeasure.getQuery(pt, mGoal.getRestrictions(false),
getMeasureDisplay(), getDate(), getID(),
Env.getUserRolePermissions()); // logged in role
}
else if (getRequestType() != null) // Document
{
MRequestType rt = getRequestType();
query = rt.getQuery(mGoal.getRestrictions(false),
getMeasureDisplay(), getDate(), getID(),
Env.getUserRolePermissions()); // logged in role
}
return query;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\adempiere\apps\graph\GraphColumn.java | 1 |
请完成以下Java代码 | protected String resolveJobHandlerType(S context) {
return jobHandlerType;
}
protected abstract JobHandlerConfiguration resolveJobHandlerConfiguration(S context);
protected boolean resolveExclusive(S context) {
return exclusive;
}
protected int resolveRetries(S context) {
return Context.getProcessEngineConfiguration().getDefaultNumberOfRetries();
}
public Date resolveDueDate(S context) {
ProcessEngineConfiguration processEngineConfiguration = Context.getProcessEngineConfiguration();
if (processEngineConfiguration != null && (processEngineConfiguration.isJobExecutorAcquireByDueDate() || processEngineConfiguration.isEnsureJobDueDateNotNull())) {
return ClockUtil.getCurrentTime();
}
else {
return null;
}
}
public boolean isExclusive() {
return exclusive;
}
public void setExclusive(boolean exclusive) {
this.exclusive = exclusive;
}
public String getActivityId() {
if (activity != null) {
return activity.getId();
}
else {
return null;
}
}
public ActivityImpl getActivity() {
return activity;
} | public void setActivity(ActivityImpl activity) {
this.activity = activity;
}
public ProcessDefinitionImpl getProcessDefinition() {
if (activity != null) {
return activity.getProcessDefinition();
}
else {
return null;
}
}
public String getJobConfiguration() {
return jobConfiguration;
}
public void setJobConfiguration(String jobConfiguration) {
this.jobConfiguration = jobConfiguration;
}
public ParameterValueProvider getJobPriorityProvider() {
return jobPriorityProvider;
}
public void setJobPriorityProvider(ParameterValueProvider jobPriorityProvider) {
this.jobPriorityProvider = jobPriorityProvider;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\JobDeclaration.java | 1 |
请完成以下Java代码 | public Flux<ServerSentEvent<Instance>> instanceStream(@PathVariable String id) {
return Flux.from(eventStore)
.filter((event) -> event.getInstance().equals(InstanceId.of(id)))
.flatMap((event) -> registry.getInstance(event.getInstance()))
.map((event) -> ServerSentEvent.builder(event).build())
.mergeWith(ping());
}
/**
* Returns a periodic Server-Sent Event (SSE) comment-only ping every 10 seconds.
* <p>
* This method is used to keep SSE connections alive for all event stream endpoints in
* Spring Boot Admin. The ping event is sent as a comment (": ping") and does not
* contain any data payload. <br>
* <b>Why?</b> Many proxies, firewalls, and browsers may close idle HTTP connections.
* The ping event provides regular activity on the stream, ensuring the connection
* remains open even when no instance events are emitted. <br>
* <b>Technical details:</b> | * <ul>
* <li>Interval: 10 seconds</li>
* <li>Format: SSE comment-only event</li>
* <li>Applies to: All event stream endpoints (e.g., /instances/events,
* /instances/{id} with Accept: text/event-stream)</li>
* </ul>
* </p>
* @param <T> the type of event data (unused for ping)
* @return flux of ServerSentEvent representing periodic ping comments
*/
@SuppressWarnings("unchecked")
private static <T> Flux<ServerSentEvent<T>> ping() {
return (Flux<ServerSentEvent<T>>) (Flux) PING_FLUX;
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\web\InstancesController.java | 1 |
请完成以下Java代码 | public boolean isEnum() {
return getParent().isEnum();
}
@Override
public Object getField(String fieldName) {
return getParent().getField(fieldName);
}
@Override
public List<String> getFieldNames() {
return getParent().getFieldNames();
}
@Override
public boolean isIdentityField(String fieldName) {
return getParent().isIdentityField(fieldName);
}
@Override
public Object getObject() {
return getParent().getObject();
}
@Override
public WritablePdxInstance createWriter() {
return this;
}
@Override | public boolean hasField(String fieldName) {
return getParent().hasField(fieldName);
}
};
}
/**
* Determines whether the given {@link String field name} is a {@link PropertyDescriptor property}
* on the underlying, target {@link Object}.
*
* @param fieldName {@link String} containing the name of the field to match against
* a {@link PropertyDescriptor property} from the underlying, target {@link Object}.
* @return a boolean value that determines whether the given {@link String field name}
* is a {@link PropertyDescriptor property} on the underlying, target {@link Object}.
* @see #getFieldNames()
*/
@Override
public boolean hasField(String fieldName) {
return getFieldNames().contains(fieldName);
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\pdx\ObjectPdxInstanceAdapter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void configureCaseDefinitionQuery(CaseDefinitionQueryImpl query) {
getTenantManager().configureQuery(query);
}
protected ListQueryParameterObject configureParameterizedQuery(Object parameter) {
return getTenantManager().configureQuery(parameter);
}
@Override
public CaseDefinitionEntity findLatestDefinitionByKey(String key) {
return findLatestCaseDefinitionByKey(key);
}
@Override
public CaseDefinitionEntity findLatestDefinitionById(String id) {
return findCaseDefinitionById(id);
}
@Override
public CaseDefinitionEntity getCachedResourceDefinitionEntity(String definitionId) {
return getDbEntityManager().getCachedEntity(CaseDefinitionEntity.class, definitionId);
}
@Override
public CaseDefinitionEntity findLatestDefinitionByKeyAndTenantId(String definitionKey, String tenantId) {
return findLatestCaseDefinitionByKeyAndTenantId(definitionKey, tenantId);
} | @Override
public CaseDefinitionEntity findDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId) {
throw new UnsupportedOperationException("Currently finding case definition by version tag and tenant is not implemented.");
}
@Override
public CaseDefinitionEntity findDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId) {
return findCaseDefinitionByKeyVersionAndTenantId(definitionKey, definitionVersion, tenantId);
}
@Override
public CaseDefinitionEntity findDefinitionByDeploymentAndKey(String deploymentId, String definitionKey) {
return findCaseDefinitionByDeploymentAndKey(deploymentId, definitionKey);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\repository\CaseDefinitionManager.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager, @Qualifier("rcCaptchaValidateFilter") RcCaptchaValidateFilter rcCaptchaValidateFilter) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
shiroFilterFactoryBean.setLoginUrl("/login");
shiroFilterFactoryBean.setUnauthorizedUrl("/system/unauthorized.jsp");
Map<String, Filter> filters = new LinkedMap();
filters.put("authc", rcFormAuthenticationFilter());
filters.put("rcCaptchaValidate", rcCaptchaValidateFilter);
shiroFilterFactoryBean.setFilters(filters);
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/rcCaptcha*", "anon");
filterChainDefinitionMap.put("/system/unauthorized.jsp", "anon");
filterChainDefinitionMap.put("/common/**", "anon");
filterChainDefinitionMap.put("/dwz/**", "anon");
filterChainDefinitionMap.put("/favicon.ico", "anon");
filterChainDefinitionMap.put("/login", "rcCaptchaValidate,authc");
filterChainDefinitionMap.put("/logout", "logout");
filterChainDefinitionMap.put("/**", "authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
@Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
@Bean | public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(defaultWebSecurityManager);
return authorizationAttributeSourceAdvisor;
}
@Bean
@ConditionalOnMissingBean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
DefaultAdvisorAutoProxyCreator app=new DefaultAdvisorAutoProxyCreator();
app.setProxyTargetClass(true);
return app;
}
} | repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\config\ShiroConfig.java | 2 |
请完成以下Java代码 | public void processWithManualCommit() {
Properties props = new Properties();
props.put("bootstrap.servers", bootstrapServers);
props.put("group.id", "manual-commit-group");
props.put("enable.auto.commit", "false");
props.put("max.poll.records", "10");
props.put("key.deserializer", StringDeserializer.class.getName());
props.put("value.deserializer", StringDeserializer.class.getName());
props.put("auto.offset.reset", "earliest");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Arrays.asList("orders"));
int totalProcessed = 0;
while (totalProcessed < 10) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
for (ConsumerRecord<String, String> record : records) {
try {
processOrder(record);
totalProcessed++;
} catch (Exception e) {
logger.error("Processing failed for offset: {}", record.offset(), e);
break;
}
} | if (!records.isEmpty()) {
consumer.commitSync();
logger.info("Committed {} records", records.count());
}
}
consumer.close();
}
private void processOrder(ConsumerRecord<String, String> record) {
// simulate order processing
logger.info("Processing order: {}", record.value());
// this section is mostly your part of implementation, which is out of bounds of the article topic coverage
}
} | repos\tutorials-master\apache-kafka-3\src\main\java\com\baeldung\kafka\partitions\KafkaMultiplePartitionsDemo.java | 1 |
请完成以下Java代码 | public void setResult(String result) {
this.result = result;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getSourceProcessDefinitionId() {
return sourceProcessDefinitionId;
}
public void setSourceProcessDefinitionId(String sourceProcessDefinitionId) {
this.sourceProcessDefinitionId = sourceProcessDefinitionId;
}
public String getTargetProcessDefinitionId() {
return targetProcessDefinitionId;
}
public void setTargetProcessDefinitionId(String targetProcessDefinitionId) {
this.targetProcessDefinitionId = targetProcessDefinitionId; | }
public String getMigrationMessage() {
return migrationMessage;
}
public void setMigrationMessage(String migrationMessage) {
this.migrationMessage = migrationMessage;
}
public String getMigrationStacktrace() {
return migrationStacktrace;
}
public void setMigrationStacktrace(String migrationStacktrace) {
this.migrationStacktrace = migrationStacktrace;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\migration\ProcessInstanceBatchMigrationPartResult.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() { | return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-mvc\src\main\java\com\baeldung\springvalidation\domain\UserAccount.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.