instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public JobExecutionObservationProvider getJobExecutionObservationProvider() {
return jobExecutionObservationProvider;
}
public void setJobExecutionObservationProvider(JobExecutionObservationProvider jobExecutionObservationProvider) {
this.jobExecutionObservationProvider = jobExecutionObservationProvider;
}
public AcquireTimerJobsRunnable getTimerJobRunnable() {
return timerJobRunnable;
}
public AcquireAsyncJobsDueRunnable getAsyncJobsDueRunnable() {
return asyncJobsDueRunnable;
}
public ResetExpiredJobsRunnable getResetExpiredJobsRunnable() {
return resetExpiredJobsRunnable;
}
public String getTenantId() {
return configuration.getTenantId();
}
public void setTenantId(String tenantId) {
configuration.setTenantId(tenantId);
}
public AsyncJobExecutorConfiguration getConfiguration() {
return configuration;
}
public void setConfiguration(AsyncJobExecutorConfiguration configuration) {
this.configuration = configuration;
}
public class AcquireTimerRunnableConfiguration implements AcquireJobsRunnableConfiguration {
@Override
public boolean isGlobalAcquireLockEnabled() {
return configuration.isGlobalAcquireLockEnabled();
}
@Override
public String getGlobalAcquireLockPrefix() {
return configuration.getGlobalAcquireLockPrefix();
}
@Override
public Duration getLockWaitTime() {
return configuration.getTimerLockWaitTime();
}
@Override
public Duration getLockPollRate() {
return configuration.getTimerLockPollRate();
}
@Override
public Duration getLockForceAcquireAfter() {
return configuration.getTimerLockForceAcquireAfter();
}
}
|
public class AcquireAsyncJobsDueRunnableConfiguration implements AcquireJobsRunnableConfiguration {
@Override
public boolean isGlobalAcquireLockEnabled() {
return configuration.isGlobalAcquireLockEnabled();
}
@Override
public String getGlobalAcquireLockPrefix() {
return configuration.getGlobalAcquireLockPrefix();
}
@Override
public Duration getLockWaitTime() {
return configuration.getAsyncJobsGlobalLockWaitTime();
}
@Override
public Duration getLockPollRate() {
return configuration.getAsyncJobsGlobalLockPollRate();
}
@Override
public Duration getLockForceAcquireAfter() {
return configuration.getAsyncJobsGlobalLockForceAcquireAfter();
}
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\AbstractAsyncExecutor.java
| 2
|
请完成以下Java代码
|
protected boolean matchesNonNull(String rawPassword, String encodedPassword) {
if (!this.BCRYPT_PATTERN.matcher(encodedPassword).matches()) {
this.logger.warn("Encoded password does not look like BCrypt");
return false;
}
return BCrypt.checkpw(rawPassword.toString(), encodedPassword);
}
@Override
protected boolean upgradeEncodingNonNull(String encodedPassword) {
Matcher matcher = this.BCRYPT_PATTERN.matcher(encodedPassword);
if (!matcher.matches()) {
throw new IllegalArgumentException("Encoded password does not look like BCrypt: " + encodedPassword);
}
int strength = Integer.parseInt(matcher.group(2));
return strength < this.strength;
}
/**
* Stores the default bcrypt version for use in configuration.
*
* @author Lin Feng
*/
public enum BCryptVersion {
|
$2A("$2a"),
$2Y("$2y"),
$2B("$2b");
private final String version;
BCryptVersion(String version) {
this.version = version;
}
public String getVersion() {
return this.version;
}
}
}
|
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\bcrypt\BCryptPasswordEncoder.java
| 1
|
请完成以下Java代码
|
private IQueryBuilder<I_Fact_Acct_UserChange> queryByDocRecordRef(final @NonNull TableRecordReference docRecordRef)
{
final IQueryBuilder<I_Fact_Acct_UserChange> queryBuilder = queryBL.createQueryBuilder(I_Fact_Acct_UserChange.class)
.orderBy(I_Fact_Acct_UserChange.COLUMNNAME_Fact_Acct_UserChange_ID)
.addOnlyActiveRecordsFilter();
if (I_C_Invoice.Table_Name.equals(docRecordRef.getTableName()))
{
queryBuilder.addEqualsFilter(I_Fact_Acct_UserChange.COLUMNNAME_C_Invoice_ID, docRecordRef.getRecord_ID());
}
else
{
return null;
}
return queryBuilder;
}
private static FactAcctChanges fromRecord(@NonNull final I_Fact_Acct_UserChange record)
{
return FactAcctChanges.builder()
.type(FactAcctChangesType.ofCode(record.getChangeType()))
.matchKey(FactLineMatchKey.ofNullableString(record.getMatchKey()))
.acctSchemaId(AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID()))
.postingSign(PostingSign.ofCode(record.getPostingSign()))
.accountId(ElementValueId.ofRepoId(record.getAccount_ID()))
.amount_DC(Money.of(record.getAmount_DC(), CurrencyId.ofRepoId(record.getLocal_Currency_ID())))
.amount_LC(Money.of(record.getAmount_LC(), CurrencyId.ofRepoId(record.getDocument_Currency_ID())))
.taxId(TaxId.ofRepoIdOrNull(record.getC_Tax_ID()))
.description(StringUtils.trimBlankToNull(record.getDescription()))
.productId(ProductId.ofRepoIdOrNull(record.getM_Product_ID()))
.userElementString1(StringUtils.trimBlankToNull(record.getUserElementString1()))
.salesOrderId(OrderId.ofRepoIdOrNull(record.getC_OrderSO_ID()))
.activityId(ActivityId.ofRepoIdOrNull(record.getC_Activity_ID()))
.build();
|
}
private static void updateRecord(final I_Fact_Acct_UserChange record, final FactAcctChanges from)
{
record.setChangeType(from.getType().getCode());
record.setMatchKey(from.getMatchKey() != null ? from.getMatchKey().getAsString() : null);
record.setC_AcctSchema_ID(from.getAcctSchemaId().getRepoId());
record.setPostingSign(from.getPostingSign().getCode());
record.setAccount_ID(ElementValueId.toRepoId(from.getAccountId()));
record.setDocument_Currency_ID(from.getAmount_DC().getCurrencyId().getRepoId());
record.setAmount_DC(from.getAmount_DC().toBigDecimal());
record.setLocal_Currency_ID(from.getAmount_LC().getCurrencyId().getRepoId());
record.setAmount_LC(from.getAmount_LC().toBigDecimal());
record.setC_Tax_ID(TaxId.toRepoId(from.getTaxId()));
record.setDescription(StringUtils.trimBlankToNull(from.getDescription()));
record.setM_Product_ID(ProductId.toRepoId(from.getProductId()));
record.setUserElementString1(StringUtils.trimBlankToNull(from.getUserElementString1()));
record.setC_OrderSO_ID(OrderId.toRepoId(from.getSalesOrderId()));
record.setC_Activity_ID(ActivityId.toRepoId(from.getActivityId()));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\factacct_userchanges\FactAcctUserChangesRepository.java
| 1
|
请完成以下Java代码
|
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (id == null ? 0 : id.hashCode());
result = prime * result + (name == null ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Role other = (Role) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
|
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Role [id=").append(id).append(", name=").append(name).append("]");
return builder.toString();
}
}
|
repos\tutorials-master\spring-katharsis\src\main\java\com\baeldung\persistence\model\Role.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MainApplication {
private final BookstoreService bookstoreService;
public MainApplication(BookstoreService bookstoreService) {
this.bookstoreService = bookstoreService;
}
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
@Bean
public OptimisticConcurrencyControlAspect
optimisticConcurrencyControlAspect() {
return new OptimisticConcurrencyControlAspect();
}
@Bean
public ApplicationRunner init() {
|
return args -> {
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(bookstoreService);
// Thread.sleep(2000); -> adding a sleep here will break the transactions concurrency
executor.execute(bookstoreService);
executor.shutdown();
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
};
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootRetryVersionedOptimisticLocking\src\main\java\com\bookstore\MainApplication.java
| 2
|
请完成以下Java代码
|
public int getC_Flatrate_RefundConfig_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Flatrate_RefundConfig_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Vertrag-Rechnungskandidat.
@param C_Invoice_Candidate_Term_ID Vertrag-Rechnungskandidat */
@Override
public void setC_Invoice_Candidate_Term_ID (int C_Invoice_Candidate_Term_ID)
{
if (C_Invoice_Candidate_Term_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Term_ID, null);
|
else
set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Term_ID, Integer.valueOf(C_Invoice_Candidate_Term_ID));
}
/** Get Vertrag-Rechnungskandidat.
@return Vertrag-Rechnungskandidat */
@Override
public int getC_Invoice_Candidate_Term_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_Candidate_Term_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Invoice_Candidate_Assignment_Aggregate_V.java
| 1
|
请完成以下Java代码
|
public List<String> getCandidateGroups() {
return candidateGroups;
}
public void setCandidateGroups(List<String> candidateGroups) {
this.candidateGroups = candidateGroups;
}
@Override
public CasePageTask clone() {
CasePageTask clone = new CasePageTask();
clone.setValues(this);
return clone;
}
public void setValues(CasePageTask otherElement) {
|
super.setValues(otherElement);
setType(otherElement.getType());
setFormKey(otherElement.getFormKey());
setSameDeployment(otherElement.isSameDeployment());
setLabel(otherElement.getLabel());
setIcon(otherElement.getIcon());
setAssignee(otherElement.getAssignee());
setOwner(otherElement.getOwner());
setCandidateGroups(new ArrayList<>(otherElement.getCandidateGroups()));
setCandidateUsers(new ArrayList<>(otherElement.getCandidateUsers()));
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\CasePageTask.java
| 1
|
请完成以下Java代码
|
public void setColumnValue(Object value)
{
final String columnType = getColumnType();
if (MHRConcept.COLUMNTYPE_Quantity.equals(columnType))
{
BigDecimal qty = new BigDecimal(value.toString());
setQty(qty);
setAmount(Env.ZERO);
}
else if(MHRConcept.COLUMNTYPE_Amount.equals(columnType))
{
BigDecimal amount = new BigDecimal(value.toString());
setAmount(amount);
setQty(Env.ZERO);
}
else if(MHRConcept.COLUMNTYPE_Text.equals(columnType))
{
setTextMsg(value.toString().trim());
}
else if(MHRConcept.COLUMNTYPE_Date.equals(columnType))
{
if (value instanceof Timestamp)
|
{
setServiceDate((Timestamp)value);
}
else
{
setServiceDate(Timestamp.valueOf(value.toString().trim().substring(0, 10)+ " 00:00:00.0"));
}
}
else
{
throw new AdempiereException("@NotSupported@ @ColumnType@ - "+columnType);
}
}
} // HRMovement
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.libero.liberoHR\src\main\java\org\eevolution\model\MHRMovement.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static Map<String, Object> extractProperties(ConfigurableEnvironment environment) {
return Collections.unmodifiableMap(doExtraProperties(environment));
}
// /**
// * Gets {@link PropertySource} Map , the {@link PropertySource#getName()} as key
// *
// * @param environment {@link ConfigurableEnvironment}
// * @return Read-only Map
// */
// public static Map<String, PropertySource<?>> getPropertySources(ConfigurableEnvironment environment) {
// return Collections.unmodifiableMap(doGetPropertySources(environment));
// }
private static Map<String, Object> doExtraProperties(ConfigurableEnvironment environment) {
Map<String, Object> properties = new LinkedHashMap<>(); // orderly
Map<String, PropertySource<?>> map = doGetPropertySources(environment);
for (PropertySource<?> source : map.values()) {
if (source instanceof EnumerablePropertySource) {
EnumerablePropertySource propertySource = (EnumerablePropertySource) source;
String[] propertyNames = propertySource.getPropertyNames();
if (ObjectUtils.isEmpty(propertyNames)) {
continue;
}
for (String propertyName : propertyNames) {
if (!properties.containsKey(propertyName)) { // put If absent
properties.put(propertyName, propertySource.getProperty(propertyName));
|
}
}
}
}
return properties;
}
private static Map<String, PropertySource<?>> doGetPropertySources(ConfigurableEnvironment environment) {
Map<String, PropertySource<?>> map = new LinkedHashMap<String, PropertySource<?>>();
MutablePropertySources sources = environment.getPropertySources();
for (PropertySource<?> source : sources) {
extract("", map, source);
}
return map;
}
private static void extract(String root, Map<String, PropertySource<?>> map,
PropertySource<?> source) {
if (source instanceof CompositePropertySource) {
for (PropertySource<?> nest : ((CompositePropertySource) source)
.getPropertySources()) {
extract(source.getName() + ":", map, nest);
}
} else {
map.put(root + source.getName(), source);
}
}
}
|
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\autoconfigure\src\main\java\org\apache\dubbo\spring\boot\util\EnvironmentUtils.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class ManyTag {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
@ManyToMany(mappedBy = "manyTags")
private Set<ManyStudent> students = new HashSet<>();
public ManyTag() {
}
public ManyTag(String name) {
this.name = name;
}
|
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<ManyStudent> getStudents() {
return students;
}
public void setStudents(Set<ManyStudent> students) {
this.students.addAll(students);
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-filtering\src\main\java\com\baeldung\inmemory\persistence\model\ManyTag.java
| 2
|
请完成以下Java代码
|
public List<ProcessInstanceQueryImpl> getOrQueryObjects() {
return orQueryObjects;
}
/**
* Methods needed for ibatis because of re-use of query-xml for executions. ExecutionQuery contains a parentId property.
*/
public String getParentId() {
return null;
}
public boolean isOnlyChildExecutions() {
return onlyChildExecutions;
}
public boolean isOnlyProcessInstanceExecutions() {
return onlyProcessInstanceExecutions;
}
public boolean isOnlySubProcessExecutions() {
return onlySubProcessExecutions;
}
public Date getStartedBefore() {
return startedBefore;
}
public void setStartedBefore(Date startedBefore) {
this.startedBefore = startedBefore;
}
public Date getStartedAfter() {
return startedAfter;
}
public void setStartedAfter(Date startedAfter) {
this.startedAfter = startedAfter;
}
|
public String getStartedBy() {
return startedBy;
}
public void setStartedBy(String startedBy) {
this.startedBy = startedBy;
}
public List<String> getInvolvedGroups() {
return involvedGroups;
}
public ProcessInstanceQuery involvedGroupsIn(List<String> involvedGroups) {
if (involvedGroups == null || involvedGroups.isEmpty()) {
throw new ActivitiIllegalArgumentException("Involved groups list is null or empty.");
}
if (inOrStatement) {
this.currentOrQueryObject.involvedGroups = involvedGroups;
} else {
this.involvedGroups = involvedGroups;
}
return this;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ProcessInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
public static HttpHeaders parseFromString(String headersString) {
HttpHeaders headers = new HttpHeaders(headersString);
if (StringUtils.isNotEmpty(headersString)) {
try (BufferedReader reader = new BufferedReader(new StringReader(headersString))) {
String line = reader.readLine();
while (line != null) {
int colonIndex = line.indexOf(':');
if (colonIndex > 0) {
String headerName = line.substring(0, colonIndex);
if (line.length() > colonIndex + 2) {
headers.add(headerName, StringUtils.strip(line.substring(colonIndex + 1)));
} else {
headers.add(headerName, "");
}
|
line = reader.readLine();
} else {
throw new FlowableIllegalArgumentException("Header line '" + line + "' is invalid");
}
}
} catch (IOException ex) {
throw new FlowableException("IO exception occurred", ex);
}
}
return headers;
}
}
|
repos\flowable-engine-main\modules\flowable-http-common\src\main\java\org\flowable\http\common\api\HttpHeaders.java
| 1
|
请完成以下Java代码
|
public class TbMsgPushToCloudNode extends AbstractTbMsgPushNode<TbMsgPushToCloudNodeConfiguration, Object, Object> {
// Implementation of this node is done on the Edge
@Override
Object buildEvent(TenantId tenantId, EdgeEventActionType eventAction, UUID entityId, Object eventType, JsonNode entityBody) {
return null;
}
@Override
Object getEventTypeByEntityType(EntityType entityType) {
return null;
}
@Override
Object getAlarmEventType() {
return null;
|
}
@Override
String getIgnoredMessageSource() {
return null;
}
@Override
protected Class<TbMsgPushToCloudNodeConfiguration> getConfigClazz() {
return TbMsgPushToCloudNodeConfiguration.class;
}
@Override
void processMsg(TbContext ctx, TbMsg msg) {}
}
|
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\edge\TbMsgPushToCloudNode.java
| 1
|
请完成以下Java代码
|
protected String createEndTag()
{
StringBuffer out = new StringBuffer();
setStartTagChar(' ');
setEndStartModifier(' ');
out.append(getStartTagChar());
if (getEndStartModifierDefined())
{
out.append(getEndStartModifier());
}
|
out.append(getElementType());
if (getEndEndModifierDefined())
{
out.append(getEndEndModifier());
}
out.append(getEndTagChar());
setStartTagChar('<'); // put back the tag start character
return (out.toString());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\comment.java
| 1
|
请完成以下Java代码
|
protected CommandContext getCommandContext() {
return Context.getCommandContext();
}
protected <T> T getSession(Class<T> sessionClass) {
return getCommandContext().getSession(sessionClass);
}
protected DbSqlSession getDbSqlSession() {
return getSession(DbSqlSession.class);
}
protected AppResourceEntityManager getAppResourceEntityManager() {
return appEngineConfiguration.getAppResourceEntityManager();
}
protected AppDeploymentEntityManager getAppDeploymentEntityManager() {
return appEngineConfiguration.getAppDeploymentEntityManager();
}
protected AppDefinitionEntityManager getAppDefinitionEntityManager() {
|
return appEngineConfiguration.getAppDefinitionEntityManager();
}
protected VariableInstanceEntityManager getVariableInstanceEntityManager() {
return appEngineConfiguration.getVariableServiceConfiguration().getVariableInstanceEntityManager();
}
protected IdentityLinkEntityManager getIdentityLinkEntityManager() {
return appEngineConfiguration.getIdentityLinkServiceConfiguration().getIdentityLinkEntityManager();
}
protected AppEngineConfiguration getappEngineConfiguration() {
return appEngineConfiguration;
}
}
|
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\AbstractCmmnManager.java
| 1
|
请完成以下Java代码
|
public class KotlinJpaGradleBuildCustomizer implements BuildCustomizer<GradleBuild> {
private final BuildMetadataResolver buildMetadataResolver;
private final KotlinProjectSettings settings;
private final char quote;
public KotlinJpaGradleBuildCustomizer(InitializrMetadata metadata, KotlinProjectSettings settings,
ProjectDescription projectDescription, char quote) {
this.buildMetadataResolver = new BuildMetadataResolver(metadata, projectDescription.getPlatformVersion());
this.settings = settings;
this.quote = quote;
}
@Override
public void customize(GradleBuild build) {
|
if (this.buildMetadataResolver.hasFacet(build, "jpa")) {
build.plugins()
.add("org.jetbrains.kotlin.plugin.jpa", (plugin) -> plugin.setVersion(this.settings.getVersion()));
build.extensions().customize("allOpen", (allOpen) -> {
allOpen.invoke("annotation", quote("jakarta.persistence.Entity"));
allOpen.invoke("annotation", quote("jakarta.persistence.MappedSuperclass"));
allOpen.invoke("annotation", quote("jakarta.persistence.Embeddable"));
});
}
}
private String quote(String element) {
return this.quote + element + this.quote;
}
}
|
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\code\kotlin\KotlinJpaGradleBuildCustomizer.java
| 1
|
请完成以下Java代码
|
public void onChangePaymentDate(I_ESR_ImportLine esrImportLine)
{
if (!InterfaceWrapperHelper.isUIAction(esrImportLine))
{
// do nothing if the modification was triggered from the application, not by the user
return;
}
esrImportLine.setIsManual(true);
final Timestamp paymentDate = esrImportLine.getPaymentDate();
if (paymentDate == null)
{
// nothing to do.
}
else
{
esrImportLine.setAccountingDate(paymentDate);
}
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE,
ifColumnsChanged = I_ESR_ImportLine.COLUMNNAME_C_Payment_ID)
public void onChangePayment(I_ESR_ImportLine esrImportLine)
{
if (InterfaceWrapperHelper.isUIAction(esrImportLine))
|
{
// do nothing if the modification was triggered by the user
return;
}
// if invoice is not set, do nothing
if (esrImportLine.getC_Invoice_ID() <= 0)
{
return;
}
// note that setInvoice doesn't actually save the given esrImportLine, so we are fine to call it from here
Services.get(IESRImportBL.class).setInvoice(esrImportLine, esrImportLine.getC_Invoice());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\model\validator\ESR_ImportLine.java
| 1
|
请完成以下Java代码
|
public LinkedHashMap<String, ?> getSender() {
return sender;
}
public void setSender(LinkedHashMap<String, ?> sender) {
this.sender = sender;
}
public List<String> getTopics() {
return topics;
}
public void setTopics(List<String> topics) {
this.topics = topics;
}
public int getPort() {
return port;
}
|
public void setPort(int port) {
this.port = port;
}
public boolean isResend() {
return resend;
}
public void setResend(boolean resend) {
this.resend = resend;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-properties-3\src\main\java\com\baeldung\properties\json\JsonProperties.java
| 1
|
请完成以下Java代码
|
public java.math.BigDecimal getAssignedQuantity ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_AssignedQuantity);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
@Override
public de.metas.contracts.model.I_C_Flatrate_RefundConfig getC_Flatrate_RefundConfig() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_Flatrate_RefundConfig_ID, de.metas.contracts.model.I_C_Flatrate_RefundConfig.class);
}
@Override
public void setC_Flatrate_RefundConfig(de.metas.contracts.model.I_C_Flatrate_RefundConfig C_Flatrate_RefundConfig)
{
set_ValueFromPO(COLUMNNAME_C_Flatrate_RefundConfig_ID, de.metas.contracts.model.I_C_Flatrate_RefundConfig.class, C_Flatrate_RefundConfig);
}
/** Set C_Flatrate_RefundConfig.
@param C_Flatrate_RefundConfig_ID C_Flatrate_RefundConfig */
@Override
public void setC_Flatrate_RefundConfig_ID (int C_Flatrate_RefundConfig_ID)
{
if (C_Flatrate_RefundConfig_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Flatrate_RefundConfig_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Flatrate_RefundConfig_ID, Integer.valueOf(C_Flatrate_RefundConfig_ID));
}
/** Get C_Flatrate_RefundConfig.
@return C_Flatrate_RefundConfig */
@Override
public int getC_Flatrate_RefundConfig_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Flatrate_RefundConfig_ID);
|
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Vertrag-Rechnungskandidat.
@param C_Invoice_Candidate_Term_ID Vertrag-Rechnungskandidat */
@Override
public void setC_Invoice_Candidate_Term_ID (int C_Invoice_Candidate_Term_ID)
{
if (C_Invoice_Candidate_Term_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Term_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Term_ID, Integer.valueOf(C_Invoice_Candidate_Term_ID));
}
/** Get Vertrag-Rechnungskandidat.
@return Vertrag-Rechnungskandidat */
@Override
public int getC_Invoice_Candidate_Term_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_Candidate_Term_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Invoice_Candidate_Assignment_Aggregate_V.java
| 1
|
请完成以下Java代码
|
public String getUpcCode() {
return upcCode;
}
public void setUpcCode(String upcCode) {
this.upcCode = upcCode;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((backCoverArtUrl == null) ? 0 : backCoverArtUrl.hashCode());
result = prime * result + ((frontCoverArtUrl == null) ? 0 : frontCoverArtUrl.hashCode());
result = prime * result + ((upcCode == null) ? 0 : upcCode.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CoverArt other = (CoverArt) obj;
if (backCoverArtUrl == null) {
if (other.backCoverArtUrl != null)
return false;
|
} else if (!backCoverArtUrl.equals(other.backCoverArtUrl))
return false;
if (frontCoverArtUrl == null) {
if (other.frontCoverArtUrl != null)
return false;
} else if (!frontCoverArtUrl.equals(other.frontCoverArtUrl))
return false;
if (upcCode == null) {
if (other.upcCode != null)
return false;
} else if (!upcCode.equals(other.upcCode))
return false;
return true;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-libraries\src\main\java\com\baeldung\hibernate\types\CoverArt.java
| 1
|
请完成以下Java代码
|
protected TbPair<Boolean, JsonNode> upgradeRuleNodesWithOldPropertyToUseFetchTo(
JsonNode oldConfiguration,
String oldProperty,
String ifTrue,
String ifFalse
) throws TbNodeException {
var newConfig = (ObjectNode) oldConfiguration;
if (!newConfig.has(oldProperty)) {
throw new TbNodeException("property to update: '" + oldProperty + "' doesn't exists in configuration!");
}
return upgradeConfigurationToUseFetchTo(oldProperty, ifTrue, ifFalse, newConfig);
}
protected TbPair<Boolean, JsonNode> upgradeConfigurationToUseFetchTo(
String oldProperty, String ifTrue,
String ifFalse, ObjectNode newConfig
) throws TbNodeException {
|
var value = newConfig.get(oldProperty).asText();
if ("true".equals(value)) {
newConfig.remove(oldProperty);
newConfig.put(FETCH_TO_PROPERTY_NAME, ifTrue);
return new TbPair<>(true, newConfig);
} else if ("false".equals(value)) {
newConfig.remove(oldProperty);
newConfig.put(FETCH_TO_PROPERTY_NAME, ifFalse);
return new TbPair<>(true, newConfig);
} else {
throw new TbNodeException("property to update: '" + oldProperty + "' has unexpected value: "
+ value + ". Allowed values: true or false!");
}
}
}
|
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\metadata\TbAbstractNodeWithFetchTo.java
| 1
|
请完成以下Java代码
|
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代码
|
public int getM_Locator_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Locator_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_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 setMovementDate (final java.sql.Timestamp MovementDate)
{
set_Value (COLUMNNAME_MovementDate, MovementDate);
}
@Override
public java.sql.Timestamp getMovementDate()
{
return get_ValueAsTimestamp(COLUMNNAME_MovementDate);
}
@Override
public void setMovementQty (final BigDecimal MovementQty)
{
set_Value (COLUMNNAME_MovementQty, MovementQty);
}
@Override
public BigDecimal getMovementQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MovementQty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPosted (final boolean Posted)
{
set_Value (COLUMNNAME_Posted, Posted);
}
@Override
public boolean isPosted()
{
return get_ValueAsBoolean(COLUMNNAME_Posted);
}
@Override
public void setPostingError_Issue_ID (final int PostingError_Issue_ID)
{
if (PostingError_Issue_ID < 1)
set_Value (COLUMNNAME_PostingError_Issue_ID, null);
else
set_Value (COLUMNNAME_PostingError_Issue_ID, PostingError_Issue_ID);
}
@Override
public int getPostingError_Issue_ID()
{
return get_ValueAsInt(COLUMNNAME_PostingError_Issue_ID);
}
@Override
public void setProcessed (final boolean Processed)
{
|
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public org.compiere.model.I_S_TimeExpenseLine getS_TimeExpenseLine()
{
return get_ValueAsPO(COLUMNNAME_S_TimeExpenseLine_ID, org.compiere.model.I_S_TimeExpenseLine.class);
}
@Override
public void setS_TimeExpenseLine(final org.compiere.model.I_S_TimeExpenseLine S_TimeExpenseLine)
{
set_ValueFromPO(COLUMNNAME_S_TimeExpenseLine_ID, org.compiere.model.I_S_TimeExpenseLine.class, S_TimeExpenseLine);
}
@Override
public void setS_TimeExpenseLine_ID (final int S_TimeExpenseLine_ID)
{
if (S_TimeExpenseLine_ID < 1)
set_Value (COLUMNNAME_S_TimeExpenseLine_ID, null);
else
set_Value (COLUMNNAME_S_TimeExpenseLine_ID, S_TimeExpenseLine_ID);
}
@Override
public int getS_TimeExpenseLine_ID()
{
return get_ValueAsInt(COLUMNNAME_S_TimeExpenseLine_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ProjectIssue.java
| 1
|
请完成以下Java代码
|
void processOrder(Order order){
log.info("Processing order: id={}, symbol={}, qty={}, price={}",
order.getId(),
order.getSymbol(),
order.getQuantity(),
order.getPrice());
BigDecimal orderTotal = order.getQuantity().multiply(order.getPrice());
if ( order.getOrderType() == OrderType.SELL) {
orderTotal = orderTotal.negate();
}
BigDecimal sum = orderSummary.get(order.getSymbol());
if ( sum == null) {
sum = orderTotal;
}
else {
sum = sum.add(orderTotal);
}
|
orderSummary.put(order.getSymbol(), sum);
orderSemaphore.release();
}
public BigDecimal getTotalBySymbol(String symbol) {
return orderSummary.get(symbol);
}
public boolean awaitNextMessage(long time, TimeUnit unit) throws InterruptedException {
return orderSemaphore.tryAcquire(time, unit);
}
}
|
repos\tutorials-master\spring-integration\src\main\java\com\baeldung\subflows\postgresqlnotify\PostgresqlPubSubExample.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class RestartJobBatchApp {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(RestartJobBatchApp.class);
app.setAdditionalProfiles("restart");
app.run(args);
}
@Bean
@ConditionalOnProperty(prefix = "job.autorun", name = "enabled", havingValue = "true", matchIfMissing = true)
CommandLineRunner run(JobLauncher jobLauncher, Job job, JobExplorer jobExplorer,
JobOperator jobOperator, BatchConfig.RestartItemProcessor itemProcessor) {
return args -> {
JobParameters jobParameters = new JobParametersBuilder()
.addString("jobId", "test-job-" + System.currentTimeMillis())
.toJobParameters();
List<JobInstance> instances = jobExplorer.getJobInstances("simpleJob", 0, 1);
if (!instances.isEmpty()) {
JobInstance lastInstance = instances.get(0);
List<JobExecution> executions = jobExplorer.getJobExecutions(lastInstance);
if (!executions.isEmpty()) {
JobExecution lastExecution = executions.get(0);
|
if (lastExecution.getStatus() == BatchStatus.FAILED) {
System.out.println("Restarting failed job execution with ID: " + lastExecution.getId());
itemProcessor.setFailOnItem3(false);
JobExecution restartedExecution = jobLauncher.run(job, jobParameters);
// final Long restartId = jobOperator.restart(lastExecution.getId());
// final JobExecution restartedExecution = jobExplorer.getJobExecution(restartedExecution);
System.out.println("Restarted job status: " + restartedExecution.getStatus());
return;
}
}
}
System.out.println("Starting new job execution...");
JobExecution jobExecution = jobLauncher.run(job, jobParameters);
System.out.println("Job started with status: " + jobExecution.getStatus());
};
}
}
|
repos\tutorials-master\spring-batch-2\src\main\java\com\baeldung\restartjob\RestartJobBatchApp.java
| 2
|
请完成以下Java代码
|
public class MigratingCompensationEventSubscriptionInstance extends MigratingProcessElementInstance implements RemovingInstance {
public static final MigrationLogger MIGRATION_LOGGER = ProcessEngineLogger.MIGRATION_LOGGER;
protected EventSubscriptionEntity eventSubscription;
public MigratingCompensationEventSubscriptionInstance(
MigrationInstruction migrationInstruction,
ScopeImpl sourceScope,
ScopeImpl targetScope,
EventSubscriptionEntity eventSubscription) {
this.migrationInstruction = migrationInstruction;
this.eventSubscription = eventSubscription;
this.sourceScope = sourceScope;
this.targetScope = targetScope;
this.currentScope = sourceScope;
}
@Override
public boolean isDetached() {
return eventSubscription.getExecutionId() == null;
}
@Override
public void detachState() {
eventSubscription.setExecution(null);
}
@Override
public void attachState(MigratingTransitionInstance targetTransitionInstance) {
throw MIGRATION_LOGGER.cannotAttachToTransitionInstance(this);
}
@Override
public void migrateState() {
eventSubscription.setActivity((ActivityImpl) targetScope);
currentScope = targetScope;
}
@Override
public void migrateDependentEntities() {
}
@Override
public void addMigratingDependentInstance(MigratingInstance migratingInstance) {
}
@Override
public ExecutionEntity resolveRepresentativeExecution() {
return null;
}
|
@Override
public void attachState(MigratingScopeInstance targetActivityInstance) {
setParent(targetActivityInstance);
ExecutionEntity representativeExecution = targetActivityInstance.resolveRepresentativeExecution();
eventSubscription.setExecution(representativeExecution);
}
@Override
public void setParent(MigratingScopeInstance parentInstance) {
if (this.parentInstance != null) {
this.parentInstance.removeChild(this);
}
this.parentInstance = parentInstance;
if (parentInstance != null) {
parentInstance.addChild(this);
}
}
public void remove() {
eventSubscription.delete();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingCompensationEventSubscriptionInstance.java
| 1
|
请完成以下Java代码
|
public int getAD_ReplicationStrategy_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_ReplicationStrategy_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** EntityType AD_Reference_ID=389 */
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entity Type.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
public void setEntityType (String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entity Type.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
public org.compiere.model.I_EXP_Processor getEXP_Processor() throws RuntimeException
{
return (org.compiere.model.I_EXP_Processor)MTable.get(getCtx(), org.compiere.model.I_EXP_Processor.Table_Name)
.getPO(getEXP_Processor_ID(), get_TrxName()); }
/** Set Export Processor.
@param EXP_Processor_ID Export Processor */
public void setEXP_Processor_ID (int EXP_Processor_ID)
{
if (EXP_Processor_ID < 1)
set_Value (COLUMNNAME_EXP_Processor_ID, null);
else
set_Value (COLUMNNAME_EXP_Processor_ID, Integer.valueOf(EXP_Processor_ID));
}
/** Get Export Processor.
@return Export Processor */
public int getEXP_Processor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_EXP_Processor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
|
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ReplicationStrategy.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public HUPIItemProduct getPackingInfo(@NonNull final HUPIItemProductId huPIItemProductId)
{
return huService.getPackingInfo(huPIItemProductId);
}
@Override
public String getPICaption(@NonNull final HuPackingInstructionsId piId)
{
return huService.getPI(piId).getName();
}
@Override
public String getLocatorName(@NonNull final LocatorId locatorId)
{
return locatorNamesCache.computeIfAbsent(locatorId, warehouseService::getLocatorNameById);
}
@Override
public HUQRCode getQRCodeByHUId(final HuId huId)
{
return huService.getQRCodeByHuId(huId);
}
|
@Override
public ScheduledPackageableLocks getLocks(final ShipmentScheduleAndJobScheduleIdSet scheduleIds)
{
return pickingJobLockService.getLocks(scheduleIds);
}
@Override
public int getSalesOrderLineSeqNo(@NonNull final OrderAndLineId orderAndLineId)
{
return orderService.getSalesOrderLineSeqNo(orderAndLineId);
}
//
//
//
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\repository\DefaultPickingJobLoaderSupportingServices.java
| 2
|
请完成以下Java代码
|
public Builder addExploded(final IValidationRule rule)
{
add(rule, true);
return this;
}
private Builder add(final IValidationRule rule, final boolean explodeComposite)
{
// Don't add null rules
if (NullValidationRule.isNull(rule))
{
return this;
}
// Don't add if already exists
if (rules.contains(rule))
{
return this;
}
if (explodeComposite && rule instanceof CompositeValidationRule)
{
final CompositeValidationRule compositeRule = (CompositeValidationRule)rule;
addAll(compositeRule.getValidationRules(), true);
|
}
else
{
rules.add(rule);
}
return this;
}
private Builder addAll(final Collection<IValidationRule> rules)
{
return addAll(rules, false);
}
private Builder addAll(final Collection<IValidationRule> rules, final boolean explodeComposite)
{
rules.forEach(includedRule -> add(includedRule, explodeComposite));
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\validationRule\impl\CompositeValidationRule.java
| 1
|
请完成以下Java代码
|
public ClusterServerModifyRequest setIp(String ip) {
this.ip = ip;
return this;
}
@Override
public Integer getPort() {
return port;
}
public ClusterServerModifyRequest setPort(Integer port) {
this.port = port;
return this;
}
@Override
public Integer getMode() {
return mode;
}
public ClusterServerModifyRequest setMode(Integer mode) {
this.mode = mode;
return this;
}
public ServerFlowConfig getFlowConfig() {
return flowConfig;
}
public ClusterServerModifyRequest setFlowConfig(
ServerFlowConfig flowConfig) {
this.flowConfig = flowConfig;
return this;
}
public ServerTransportConfig getTransportConfig() {
return transportConfig;
}
public ClusterServerModifyRequest setTransportConfig(
ServerTransportConfig transportConfig) {
this.transportConfig = transportConfig;
return this;
}
|
public Set<String> getNamespaceSet() {
return namespaceSet;
}
public ClusterServerModifyRequest setNamespaceSet(Set<String> namespaceSet) {
this.namespaceSet = namespaceSet;
return this;
}
@Override
public String toString() {
return "ClusterServerModifyRequest{" +
"app='" + app + '\'' +
", ip='" + ip + '\'' +
", port=" + port +
", mode=" + mode +
", flowConfig=" + flowConfig +
", transportConfig=" + transportConfig +
", namespaceSet=" + namespaceSet +
'}';
}
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\request\ClusterServerModifyRequest.java
| 1
|
请完成以下Java代码
|
class WebServerStartStopLifecycle implements SmartLifecycle {
private final ServletWebServerApplicationContext applicationContext;
private final WebServer webServer;
private volatile boolean running;
WebServerStartStopLifecycle(ServletWebServerApplicationContext applicationContext, WebServer webServer) {
this.applicationContext = applicationContext;
this.webServer = webServer;
}
@Override
public void start() {
this.webServer.start();
this.running = true;
this.applicationContext
.publishEvent(new ServletWebServerInitializedEvent(this.webServer, this.applicationContext));
}
@Override
public void stop() {
|
this.running = false;
this.webServer.stop();
}
@Override
public boolean isRunning() {
return this.running;
}
@Override
public int getPhase() {
return WebServerApplicationContext.START_STOP_LIFECYCLE_PHASE;
}
@Override
public boolean isPauseable() {
return false;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\context\WebServerStartStopLifecycle.java
| 1
|
请完成以下Java代码
|
/* package */class HandlingUnitHUDocument extends AbstractHUDocument
{
private final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class);
private final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class);
// private final I_M_HU hu;
private final I_M_HU innerHU;
private final String displayName;
private final List<IHUDocumentLine> documentLines;
private final List<IHUDocumentLine> documentLinesRO;
public HandlingUnitHUDocument(final I_M_HU hu, final I_M_HU innerHU, final List<IHUDocumentLine> documentLines)
{
super();
Check.assumeNotNull(hu, "hu not null");
// this.hu = hu;
this.innerHU = hu;
displayName = createDisplayName(hu);
Check.assumeNotNull(documentLines, "documentLines not null");
// Check.assume(!documentLines.isEmpty(), "documentLines not empty");
this.documentLines = new ArrayList<IHUDocumentLine>(documentLines);
documentLinesRO = Collections.unmodifiableList(this.documentLines);
}
private final String createDisplayName(final I_M_HU hu)
{
final StringBuilder sb = new StringBuilder();
final String huDisplayName = handlingUnitsBL.getDisplayName(hu);
sb.append(huDisplayName);
final I_M_HU parentHU = handlingUnitsDAO.retrieveParent(hu);
if (parentHU != null)
{
final String parentHUDisplayName = handlingUnitsBL.getDisplayName(parentHU);
sb.append(" - ");
sb.append(parentHUDisplayName);
}
return sb.toString();
}
@Override
public String getDisplayName()
{
return displayName;
|
}
@Override
public List<IHUDocumentLine> getLines()
{
return documentLinesRO;
}
@Override
public IHUDocument getReversal()
{
// Always null, there is no reversal
return null;
}
@Override
public I_M_HU getInnerHandlingUnit()
{
return innerHU;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\document\impl\HandlingUnitHUDocument.java
| 1
|
请完成以下Java代码
|
public ImmutableSet<WarehouseId> getAllActiveIds()
{
return getWarehouseMap().allActive.stream()
.map(Warehouse::getWarehouseId)
.collect(ImmutableSet.toImmutableSet());
}
//
//
//
//
//
private static final class WarehouseMap
{
@Getter private final ImmutableList<Warehouse> allActive;
private final ImmutableMap<WarehouseId, Warehouse> byId;
WarehouseMap(final List<Warehouse> list)
|
{
this.allActive = list.stream().filter(Warehouse::isActive).collect(ImmutableList.toImmutableList());
this.byId = Maps.uniqueIndex(list, Warehouse::getWarehouseId);
}
@NonNull
public Warehouse getById(@NonNull final WarehouseId id)
{
final Warehouse warehouse = byId.get(id);
if (warehouse == null)
{
throw new AdempiereException("Warehouse not found by ID: " + id);
}
return warehouse;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\WarehouseRepository.java
| 1
|
请完成以下Java代码
|
public class DeleteHistoricTaskInstanceCmd implements Command<Object>, Serializable {
private static final long serialVersionUID = 1L;
protected String taskId;
public DeleteHistoricTaskInstanceCmd(String taskId) {
this.taskId = taskId;
}
public Object execute(CommandContext commandContext) {
ensureNotNull("taskId", taskId);
HistoricTaskInstanceEntity task = commandContext.getHistoricTaskInstanceManager().findHistoricTaskInstanceById(taskId);
for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkDeleteHistoricTaskInstance(task);
}
writeUserOperationLog(commandContext, task);
commandContext
.getHistoricTaskInstanceManager()
.deleteHistoricTaskInstanceById(taskId);
|
return null;
}
protected void writeUserOperationLog(CommandContext commandContext, HistoricTaskInstanceEntity historicTask) {
List<PropertyChange> propertyChanges = new ArrayList<>();
propertyChanges.add(new PropertyChange("nrOfInstances", null, 1));
propertyChanges.add(new PropertyChange("async", null, false));
commandContext.getOperationLogManager()
.logTaskOperations(UserOperationLogEntry.OPERATION_TYPE_DELETE_HISTORY,
historicTask,
propertyChanges);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeleteHistoricTaskInstanceCmd.java
| 1
|
请完成以下Java代码
|
private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws Exception {
OutputStream outputStream=null;
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
outputStream = response.getOutputStream();
workbook.write(outputStream);
} catch (IOException e) {
throw new Exception(e.getMessage());
}finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws Exception {
Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
if (workbook != null);
downLoadExcel(fileName, response, workbook);
}
public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass) throws Exception {
if (StringUtils.isBlank(filePath)){
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
|
try {
list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
}catch (NoSuchElementException e){
throw new Exception("template not null");
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
return list;
}
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws Exception {
if (file == null){
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
}catch (NoSuchElementException e){
throw new Exception("excel file not null");
} catch (Exception e) {
throw new Exception(e.getMessage());
}
return list;
}
}
|
repos\springboot-demo-master\eaypoi\src\main\java\com\et\easypoi\Util\FileUtil.java
| 1
|
请完成以下Java代码
|
public void setCamundaDelegateExpression(String camundaExpression) {
camundaDelegateExpressionAttribute.setValue(this, camundaExpression);
}
public String getCamundaExpression() {
return camundaExpressionAttribute.getValue(this);
}
public void setCamundaExpression(String camundaExpression) {
camundaExpressionAttribute.setValue(this, camundaExpression);
}
public String getCamundaResultVariable() {
return camundaResultVariableAttribute.getValue(this);
}
public void setCamundaResultVariable(String camundaResultVariable) {
camundaResultVariableAttribute.setValue(this, camundaResultVariable);
}
public String getCamundaTopic() {
return camundaTopicAttribute.getValue(this);
}
public void setCamundaTopic(String camundaTopic) {
camundaTopicAttribute.setValue(this, camundaTopic);
}
public String getCamundaType() {
return camundaTypeAttribute.getValue(this);
}
public void setCamundaType(String camundaType) {
camundaTypeAttribute.setValue(this, camundaType);
}
public String getCamundaDecisionRef() {
return camundaDecisionRefAttribute.getValue(this);
}
public void setCamundaDecisionRef(String camundaDecisionRef) {
camundaDecisionRefAttribute.setValue(this, camundaDecisionRef);
}
public String getCamundaDecisionRefBinding() {
return camundaDecisionRefBindingAttribute.getValue(this);
}
public void setCamundaDecisionRefBinding(String camundaDecisionRefBinding) {
camundaDecisionRefBindingAttribute.setValue(this, camundaDecisionRefBinding);
}
public String getCamundaDecisionRefVersion() {
return camundaDecisionRefVersionAttribute.getValue(this);
}
public void setCamundaDecisionRefVersion(String camundaDecisionRefVersion) {
camundaDecisionRefVersionAttribute.setValue(this, camundaDecisionRefVersion);
}
|
public String getCamundaDecisionRefVersionTag() {
return camundaDecisionRefVersionTagAttribute.getValue(this);
}
public void setCamundaDecisionRefVersionTag(String camundaDecisionRefVersionTag) {
camundaDecisionRefVersionTagAttribute.setValue(this, camundaDecisionRefVersionTag);
}
@Override
public String getCamundaMapDecisionResult() {
return camundaMapDecisionResultAttribute.getValue(this);
}
@Override
public void setCamundaMapDecisionResult(String camundaMapDecisionResult) {
camundaMapDecisionResultAttribute.setValue(this, camundaMapDecisionResult);
}
public String getCamundaDecisionRefTenantId() {
return camundaDecisionRefTenantIdAttribute.getValue(this);
}
public void setCamundaDecisionRefTenantId(String tenantId) {
camundaDecisionRefTenantIdAttribute.setValue(this, tenantId);
}
@Override
public String getCamundaTaskPriority() {
return camundaTaskPriorityAttribute.getValue(this);
}
@Override
public void setCamundaTaskPriority(String taskPriority) {
camundaTaskPriorityAttribute.setValue(this, taskPriority);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\BusinessRuleTaskImpl.java
| 1
|
请完成以下Java代码
|
public I_M_HU getHUById(final @NotNull HuId huId)
{
return husById.computeIfAbsent(huId, huService::getById);
}
@NonNull
public Set<ProductId> getProductIds(final I_M_HU hu)
{
return getProductStorages(hu).getProductIds();
}
@NonNull
public Quantity getQty(final I_M_HU hu, final ProductId productId)
{
return getProductStorages(hu).getQty(productId);
}
private HUProductStorages getProductStorages(final I_M_HU hu)
{
return productStoragesByHUId.computeIfAbsent(HuId.ofRepoId(hu.getM_HU_ID()), huId -> huService.getProductStorages(hu));
}
public Attributes getAttributes(final I_M_HU hu)
{
|
return attributesByHUId.computeIfAbsent(HuId.ofRepoId(hu.getM_HU_ID()), huId -> huService.getImmutableAttributeSet(hu));
}
public LocatorId getLocatorId(@NonNull final I_M_HU hu)
{
return huLocatorsByHUId.computeIfAbsent(HuId.ofRepoId(hu.getM_HU_ID()), huId -> IHandlingUnitsBL.extractLocatorId(hu));
}
public String getDisplayName(@NonNull final HuId huId)
{
return displayNamesByHUId.computeIfAbsent(huId, this::retrieveDisplayName);
}
private String retrieveDisplayName(final HuId huId)
{
return huService.getDisplayName(getHUById(huId));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\deps\handlingunits\HULoadingCache.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public R<RoleVO> detail(Role role) {
Role detail = roleService.getOne(Condition.getQueryWrapper(role));
return R.data(RoleWrapper.build().entityVO(detail));
}
/**
* 列表
*/
@GetMapping("/list")
@Parameters({
@Parameter(name = "roleName", description = "参数名称", in = ParameterIn.QUERY, schema = @Schema(type = "string")),
@Parameter(name = "roleAlias", description = "角色别名", in = ParameterIn.QUERY, schema = @Schema(type = "string"))
})
@ApiOperationSupport(order = 2)
@Operation(summary = "列表", description = "传入role")
public R<List<RoleVO>> list(@Parameter(hidden = true) @RequestParam Map<String, Object> role, BladeUser bladeUser) {
QueryWrapper<Role> queryWrapper = Condition.getQueryWrapper(role, Role.class);
List<Role> list = roleService.list((!bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) ? queryWrapper.lambda().eq(Role::getTenantId, bladeUser.getTenantId()) : queryWrapper);
return R.data(RoleWrapper.build().listNodeVO(list));
}
/**
* 获取角色树形结构
*/
@GetMapping("/tree")
@ApiOperationSupport(order = 3)
@Operation(summary = "树形结构", description = "树形结构")
public R<List<RoleVO>> tree(String tenantId, BladeUser bladeUser) {
List<RoleVO> tree = roleService.tree(Func.toStr(tenantId, bladeUser.getTenantId()));
return R.data(tree);
}
/**
* 获取指定角色树形结构
*/
@GetMapping("/tree-by-id")
@ApiOperationSupport(order = 4)
@Operation(summary = "树形结构", description = "树形结构")
public R<List<RoleVO>> treeById(Long roleId, BladeUser bladeUser) {
Role role = roleService.getById(roleId);
List<RoleVO> tree = roleService.tree(Func.notNull(role) ? role.getTenantId() : bladeUser.getTenantId());
return R.data(tree);
|
}
/**
* 新增或修改
*/
@PostMapping("/submit")
@ApiOperationSupport(order = 5)
@Operation(summary = "新增或修改", description = "传入role")
public R submit(@Valid @RequestBody Role role, BladeUser user) {
CacheUtil.clear(SYS_CACHE);
if (Func.isEmpty(role.getId())) {
role.setTenantId(user.getTenantId());
}
return R.status(roleService.saveOrUpdate(role));
}
/**
* 删除
*/
@PostMapping("/remove")
@ApiOperationSupport(order = 6)
@Operation(summary = "删除", description = "传入ids")
public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
CacheUtil.clear(SYS_CACHE);
return R.status(roleService.removeByIds(Func.toLongList(ids)));
}
/**
* 设置菜单权限
*/
@PostMapping("/grant")
@ApiOperationSupport(order = 7)
@Operation(summary = "权限设置", description = "传入roleId集合以及menuId集合")
public R grant(@RequestBody GrantVO grantVO) {
CacheUtil.clear(SYS_CACHE);
boolean temp = roleService.grant(grantVO.getRoleIds(), grantVO.getMenuIds(), grantVO.getDataScopeIds());
return R.status(temp);
}
}
|
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\RoleController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Account {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false, length = 100)
private String name;
@Column(name = "email_address")
private String emailAddress;
@OneToMany(mappedBy = "account", cascade = CascadeType.ALL)
private List<AccountSetting> accountSettings = new ArrayList<>();
public Account() {
}
public Account(String name, String emailAddress) {
this.name = name;
this.emailAddress = emailAddress;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
|
}
public void setName(String name) {
this.name = name;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public List<AccountSetting> getAccountSettings() {
return accountSettings;
}
public void setAccountSettings(List<AccountSetting> accountSettings) {
this.accountSettings = accountSettings;
}
public void addAccountSetting(AccountSetting setting) {
this.accountSettings.add(setting);
setting.setAccount(this);
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-simple\src\main\java\com\baeldung\jpa\schemageneration\model\Account.java
| 2
|
请完成以下Java代码
|
public void setParentProcessDefinitionId(String parentProcessDefinitionId) {
this.parentProcessDefinitionId = parentProcessDefinitionId;
}
public String getSuperProcessDefinitionId() {
return superProcessDefinitionId;
}
@CamundaQueryParam(value="superProcessDefinitionId")
public void setSuperProcessDefinitionId(String superProcessDefinitionId) {
this.superProcessDefinitionId = superProcessDefinitionId;
}
public String[] getActivityIdIn() {
return activityIdIn;
}
@CamundaQueryParam(value="activityIdIn", converter = StringArrayConverter.class)
public void setActivityIdIn(String[] activityIdIn) {
this.activityIdIn = activityIdIn;
}
public String getBusinessKey() {
return businessKey;
}
@CamundaQueryParam(value="businessKey")
public void setBusinessKey(String businessKey) {
this.businessKey = businessKey;
}
@CamundaQueryParam(value = "variables", converter = VariableListConverter.class)
public void setVariables(List<VariableQueryParameterDto> variables) {
this.variables = variables;
}
public List<QueryVariableValue> getQueryVariableValues() {
return queryVariableValues;
}
public void initQueryVariableValues(VariableSerializers variableTypes, String dbType) {
queryVariableValues = createQueryVariableValues(variableTypes, variables, dbType);
}
|
@Override
protected String getOrderByValue(String sortBy) {
return super.getOrderBy();
}
@Override
protected boolean isValidSortByValue(String value) {
return false;
}
private List<QueryVariableValue> createQueryVariableValues(VariableSerializers variableTypes, List<VariableQueryParameterDto> variables, String dbType) {
List<QueryVariableValue> values = new ArrayList<QueryVariableValue>();
if (variables == null) {
return values;
}
for (VariableQueryParameterDto variable : variables) {
QueryVariableValue value = new QueryVariableValue(
variable.getName(),
resolveVariableValue(variable.getValue()),
ConditionQueryParameterDto.getQueryOperator(variable.getOperator()),
false);
value.initialize(variableTypes, dbType);
values.add(value);
}
return values;
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\query\ProcessDefinitionQueryDto.java
| 1
|
请完成以下Java代码
|
protected String getManagementPath(ServiceInstance instance) {
String managementPath = getMetadataValue(instance, KEYS_MANAGEMENT_PATH);
if (hasText(managementPath)) {
return managementPath;
}
return this.managementContextPath;
}
protected URI getServiceUrl(ServiceInstance instance) {
return instance.getUri();
}
protected Map<String, String> getMetadata(ServiceInstance instance) {
return (instance.getMetadata() != null) ? instance.getMetadata()
.entrySet()
.stream()
.filter((e) -> e.getKey() != null && e.getValue() != null)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) : emptyMap();
}
public String getManagementContextPath() {
|
return this.managementContextPath;
}
public void setManagementContextPath(String managementContextPath) {
this.managementContextPath = managementContextPath;
}
public String getHealthEndpointPath() {
return this.healthEndpointPath;
}
public void setHealthEndpointPath(String healthEndpointPath) {
this.healthEndpointPath = healthEndpointPath;
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server-cloud\src\main\java\de\codecentric\boot\admin\server\cloud\discovery\DefaultServiceInstanceConverter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AuthTokenFilter extends OncePerRequestFilter {
@Autowired
private JwtUtils jwtUtils;
@Autowired
private UserDetailsServiceImpl userDetailsService;
private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try {
String jwt = parseJwt(request);
if (jwt != null && jwtUtils.validateJwtToken(jwt)) {
String username = jwtUtils.getUserNameFromJwtToken(jwt);
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
SecurityContextHolder.getContext()
.setAuthentication(authentication);
}
} catch (Exception e) {
logger.error("Cannot set user authentication: {}", e);
}
filterChain.doFilter(request, response);
}
private String parseJwt(HttpServletRequest request) {
String headerAuth = request.getHeader("Authorization");
if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer ")) {
return headerAuth.substring(7, headerAuth.length());
}
return null;
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\jwtsignkey\jwtconfig\AuthTokenFilter.java
| 2
|
请完成以下Java代码
|
public IdGenerator getIdGenerator() {
return idGenerator;
}
public void setIdGenerator(IdGenerator idGenerator) {
this.idGenerator = idGenerator;
}
public ParsedDeploymentBuilderFactory getExParsedDeploymentBuilderFactory() {
return parsedDeploymentBuilderFactory;
}
public void setParsedDeploymentBuilderFactory(ParsedDeploymentBuilderFactory parsedDeploymentBuilderFactory) {
this.parsedDeploymentBuilderFactory = parsedDeploymentBuilderFactory;
}
public EventDefinitionDeploymentHelper getEventDeploymentHelper() {
return eventDeploymentHelper;
}
public void setEventDeploymentHelper(EventDefinitionDeploymentHelper eventDeploymentHelper) {
this.eventDeploymentHelper = eventDeploymentHelper;
}
|
public ChannelDefinitionDeploymentHelper getChannelDeploymentHelper() {
return channelDeploymentHelper;
}
public void setChannelDeploymentHelper(ChannelDefinitionDeploymentHelper channelDeploymentHelper) {
this.channelDeploymentHelper = channelDeploymentHelper;
}
public CachingAndArtifactsManager getCachingAndArtifcatsManager() {
return cachingAndArtifactsManager;
}
public void setCachingAndArtifactsManager(CachingAndArtifactsManager manager) {
this.cachingAndArtifactsManager = manager;
}
public boolean isUsePrefixId() {
return usePrefixId;
}
public void setUsePrefixId(boolean usePrefixId) {
this.usePrefixId = usePrefixId;
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\deployer\EventDefinitionDeployer.java
| 1
|
请完成以下Java代码
|
private static final String normalizeString(final String str)
{
if (str == null)
{
return null;
}
final String strNorm = str.trim();
if (strNorm.isEmpty())
{
return null;
}
return strNorm;
}
private NamePattern()
{
this.any = true;
this.pattern = null;
}
@Override
public String toString()
{
if (any)
{
return MoreObjects.toStringHelper(this).addValue("ANY").toString();
}
else
{
return MoreObjects.toStringHelper(this).add("pattern", pattern).toString();
}
}
public boolean isMatching(@NonNull final DataEntryTab tab)
{
return isMatching(tab.getInternalName())
|| isMatching(tab.getCaption());
}
public boolean isMatching(@NonNull final DataEntrySubTab subTab)
{
return isMatching(subTab.getInternalName())
|| isMatching(subTab.getCaption());
}
public boolean isMatching(@NonNull final DataEntrySection section)
{
return isMatching(section.getInternalName())
|| isMatching(section.getCaption());
}
public boolean isMatching(@NonNull final DataEntryLine line)
{
return isMatching(String.valueOf(line.getSeqNo()));
}
public boolean isMatching(@NonNull final DataEntryField field)
{
return isAny()
|| isMatching(field.getCaption());
|
}
private boolean isMatching(final ITranslatableString trl)
{
if (isAny())
{
return true;
}
if (isMatching(trl.getDefaultValue()))
{
return true;
}
for (final String adLanguage : trl.getAD_Languages())
{
if (isMatching(trl.translate(adLanguage)))
{
return true;
}
}
return false;
}
@VisibleForTesting
boolean isMatching(final String name)
{
if (isAny())
{
return true;
}
final String nameNorm = normalizeString(name);
if (nameNorm == null)
{
return false;
}
return pattern.equalsIgnoreCase(nameNorm);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\data\impexp\NamePattern.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public UserDetailsService myUserDetailsService() {
InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
String[][] usersGroupsAndRoles = {
{ "system", "password", "ROLE_ACTIVITI_USER" },
{ "reviewer", "password", "ROLE_ACTIVITI_USER" },
{ "admin", "password", "ROLE_ACTIVITI_ADMIN" },
};
for (String[] user : usersGroupsAndRoles) {
List<String> authoritiesStrings = asList(Arrays.copyOfRange(user, 2, user.length));
logger.info(
"> Registering new user: " + user[0] + " with the following Authorities[" + authoritiesStrings + "]"
);
inMemoryUserDetailsManager.createUser(
new User(
user[0],
passwordEncoder().encode(user[1]),
|
authoritiesStrings
.stream()
.map(s -> new SimpleGrantedAuthority(s))
.collect(Collectors.toList())
)
);
}
return inMemoryUserDetailsManager;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
|
repos\Activiti-develop\activiti-examples\activiti-api-basic-connector-example\src\main\java\org\activiti\examples\DemoApplicationConfiguration.java
| 2
|
请完成以下Java代码
|
public de.metas.printing.model.I_AD_Printer_Config getAD_Printer_Config()
{
return get_ValueAsPO(COLUMNNAME_AD_Printer_Config_ID, de.metas.printing.model.I_AD_Printer_Config.class);
}
@Override
public void setAD_Printer_Config(de.metas.printing.model.I_AD_Printer_Config AD_Printer_Config)
{
set_ValueFromPO(COLUMNNAME_AD_Printer_Config_ID, de.metas.printing.model.I_AD_Printer_Config.class, AD_Printer_Config);
}
@Override
public void setAD_Printer_Config_ID (int AD_Printer_Config_ID)
{
if (AD_Printer_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Printer_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Printer_Config_ID, Integer.valueOf(AD_Printer_Config_ID));
}
@Override
public int getAD_Printer_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Printer_Config_ID);
}
@Override
public de.metas.printing.model.I_AD_PrinterHW getAD_PrinterHW()
{
return get_ValueAsPO(COLUMNNAME_AD_PrinterHW_ID, de.metas.printing.model.I_AD_PrinterHW.class);
}
@Override
public void setAD_PrinterHW(de.metas.printing.model.I_AD_PrinterHW AD_PrinterHW)
{
set_ValueFromPO(COLUMNNAME_AD_PrinterHW_ID, de.metas.printing.model.I_AD_PrinterHW.class, AD_PrinterHW);
}
@Override
public void setAD_PrinterHW_ID (int AD_PrinterHW_ID)
{
if (AD_PrinterHW_ID < 1)
set_Value (COLUMNNAME_AD_PrinterHW_ID, null);
else
set_Value (COLUMNNAME_AD_PrinterHW_ID, Integer.valueOf(AD_PrinterHW_ID));
}
@Override
public int getAD_PrinterHW_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_PrinterHW_ID);
}
@Override
public void setAD_Printer_ID (int AD_Printer_ID)
{
if (AD_Printer_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Printer_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Printer_ID, Integer.valueOf(AD_Printer_ID));
}
@Override
public int getAD_Printer_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Printer_ID);
|
}
@Override
public void setAD_Printer_Matching_ID (int AD_Printer_Matching_ID)
{
if (AD_Printer_Matching_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Printer_Matching_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Printer_Matching_ID, Integer.valueOf(AD_Printer_Matching_ID));
}
@Override
public int getAD_Printer_Matching_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Printer_Matching_ID);
}
@Override
public void setAD_Tray_Matching_IncludedTab (java.lang.String AD_Tray_Matching_IncludedTab)
{
set_Value (COLUMNNAME_AD_Tray_Matching_IncludedTab, AD_Tray_Matching_IncludedTab);
}
@Override
public java.lang.String getAD_Tray_Matching_IncludedTab()
{
return (java.lang.String)get_Value(COLUMNNAME_AD_Tray_Matching_IncludedTab);
}
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_Printer_Matching.java
| 1
|
请完成以下Java代码
|
public java.lang.String getM_HU_PI_Item_Product()
{
return get_ValueAsString(COLUMNNAME_M_HU_PI_Item_Product);
}
@Override
public void setM_Product_Category_ID (final int M_Product_Category_ID)
{
if (M_Product_Category_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_ID, null);
else
set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID);
}
@Override
public int getM_Product_Category_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Category_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 setProductName (final @Nullable java.lang.String ProductName)
{
set_Value (COLUMNNAME_ProductName, ProductName);
}
@Override
public java.lang.String getProductName()
{
return get_ValueAsString(COLUMNNAME_ProductName);
}
@Override
public void setProductValue (final @Nullable java.lang.String ProductValue)
{
set_Value (COLUMNNAME_ProductValue, ProductValue);
}
@Override
public java.lang.String getProductValue()
{
return get_ValueAsString(COLUMNNAME_ProductValue);
}
@Override
public void setQtyAvailable (final @Nullable BigDecimal QtyAvailable)
{
set_Value (COLUMNNAME_QtyAvailable, QtyAvailable);
}
@Override
public BigDecimal getQtyAvailable()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyAvailable);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyOnHand (final @Nullable BigDecimal QtyOnHand)
{
|
set_Value (COLUMNNAME_QtyOnHand, QtyOnHand);
}
@Override
public BigDecimal getQtyOnHand()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHand);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyOrdered (final @Nullable BigDecimal QtyOrdered)
{
set_Value (COLUMNNAME_QtyOrdered, QtyOrdered);
}
@Override
public BigDecimal getQtyOrdered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyReserved (final @Nullable BigDecimal QtyReserved)
{
set_Value (COLUMNNAME_QtyReserved, QtyReserved);
}
@Override
public BigDecimal getQtyReserved()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_RV_HU_Quantities.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isLwcEnabled() {
return this.lwcEnabled;
}
public void setLwcEnabled(boolean lwcEnabled) {
this.lwcEnabled = lwcEnabled;
}
public Duration getLwcStep() {
return this.lwcStep;
}
public void setLwcStep(Duration lwcStep) {
this.lwcStep = lwcStep;
}
public boolean isLwcIgnorePublishStep() {
return this.lwcIgnorePublishStep;
}
public void setLwcIgnorePublishStep(boolean lwcIgnorePublishStep) {
this.lwcIgnorePublishStep = lwcIgnorePublishStep;
}
public Duration getConfigRefreshFrequency() {
return this.configRefreshFrequency;
}
public void setConfigRefreshFrequency(Duration configRefreshFrequency) {
this.configRefreshFrequency = configRefreshFrequency;
}
|
public Duration getConfigTimeToLive() {
return this.configTimeToLive;
}
public void setConfigTimeToLive(Duration configTimeToLive) {
this.configTimeToLive = configTimeToLive;
}
public String getConfigUri() {
return this.configUri;
}
public void setConfigUri(String configUri) {
this.configUri = configUri;
}
public String getEvalUri() {
return this.evalUri;
}
public void setEvalUri(String evalUri) {
this.evalUri = evalUri;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\atlas\AtlasProperties.java
| 2
|
请完成以下Java代码
|
private XmlRejected createXmlRejected(@NonNull final RejectedType rejected)
{
final XmlRejectedBuilder rejectedBuilder = XmlRejected.builder();
rejectedBuilder.explanation(rejected.getExplanation())
.statusIn(rejected.getStatusIn())
.statusOut(rejected.getStatusOut());
if (rejected.getError() != null && !rejected.getError().isEmpty())
{
rejectedBuilder.errors(createXmlErrors(rejected.getError()));
}
return rejectedBuilder.build();
}
private List<XmlError> createXmlErrors(@NonNull final List<ErrorType> error)
{
|
final ImmutableList.Builder<XmlError> errorsBuilder = ImmutableList.builder();
for (final ErrorType errorType : error)
{
final XmlError xmlError = XmlError
.builder()
.code(errorType.getCode())
.errorValue(errorType.getErrorValue())
.recordId(errorType.getRecordId())
.text(errorType.getText())
.validValue(errorType.getValidValue())
.build();
errorsBuilder.add(xmlError);
}
return errorsBuilder.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\Invoice440ToCrossVersionModelTool.java
| 1
|
请完成以下Java代码
|
class SelectionColumnCellEditor extends AbstractCellEditor implements TableCellEditor
{
private static final long serialVersionUID = 1L;
public SelectionColumnCellEditor()
{
checkbox.setMargin(new Insets(0, 0, 0, 0));
checkbox.setHorizontalAlignment(SwingConstants.CENTER);
checkbox.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
fireEditingStopped();
}
});
}
private final JCheckBox checkbox = new CCheckBox();
/**
* Return Selection Status as IDColumn
*
* @return value
*/
@Override
public Object getCellEditorValue()
{
return checkbox.isSelected();
}
/**
* Get visual Component
*
* @param table
* @param value
* @param isSelected
* @param row
* @param column
* @return Component
|
*/
@Override
public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int row, final int column)
{
final boolean selected = DisplayType.toBooleanNonNull(value, false);
checkbox.setSelected(selected);
return checkbox;
}
@Override
public boolean isCellEditable(final EventObject anEvent)
{
return true;
}
@Override
public boolean shouldSelectCell(final EventObject anEvent)
{
return true;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\SelectionColumnCellEditor.java
| 1
|
请完成以下Java代码
|
public XMLGregorianCalendar getTxDtTm() {
return txDtTm;
}
/**
* Sets the value of the txDtTm property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setTxDtTm(XMLGregorianCalendar value) {
this.txDtTm = value;
}
/**
* Gets the value of the txRef property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTxRef() {
return txRef;
|
}
/**
* Sets the value of the txRef property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTxRef(String value) {
this.txRef = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\TransactionIdentifier1.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 8888
spring:
config:
name: configserver
cloud:
config:
server:
git:
uri: file://${user.home}/tmp/config-data
#uri: https://github.com/spring-cloud-samples/config-repo
default-label: main
bas
|
edir: build/config
force-pull: true
logging:
level:
root: INFO
org.springframework.cloud: 'DEBUG'
|
repos\spring-examples-java-17\spring-cloud-config\cloud-config-server\src\main\resources\application.yml
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public int hashCode() {
return this.replacements.hashCode();
}
/**
* Loads the relocations from the classpath. Relocations are stored in files named
* {@code META-INF/spring/full-qualified-annotation-name.replacements} on the
* classpath. The file is loaded using {@link Properties#load(java.io.InputStream)}
* with each entry containing an auto-configuration class name as the key and the
* replacement class name as the value.
* @param annotation annotation to load
* @param classLoader class loader to use for loading
* @return list of names of annotated classes
*/
static AutoConfigurationReplacements load(Class<?> annotation, @Nullable ClassLoader classLoader) {
Assert.notNull(annotation, "'annotation' must not be null");
ClassLoader classLoaderToUse = decideClassloader(classLoader);
String location = String.format(LOCATION, annotation.getName());
Enumeration<URL> urls = findUrlsInClasspath(classLoaderToUse, location);
Map<String, String> replacements = new HashMap<>();
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
replacements.putAll(readReplacements(url));
}
return new AutoConfigurationReplacements(replacements);
}
private static ClassLoader decideClassloader(@Nullable ClassLoader classLoader) {
if (classLoader == null) {
|
return ImportCandidates.class.getClassLoader();
}
return classLoader;
}
private static Enumeration<URL> findUrlsInClasspath(ClassLoader classLoader, String location) {
try {
return classLoader.getResources(location);
}
catch (IOException ex) {
throw new IllegalArgumentException("Failed to load configurations from location [" + location + "]", ex);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private static Map<String, String> readReplacements(URL url) {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(new UrlResource(url).getInputStream(), StandardCharsets.UTF_8))) {
Properties properties = new Properties();
properties.load(reader);
return (Map) properties;
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load replacements from location [" + url + "]", ex);
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\AutoConfigurationReplacements.java
| 2
|
请完成以下Java代码
|
protected static List<Artifact> gatherAllArtifacts(BpmnModel bpmnModel) {
List<Artifact> artifacts = new ArrayList<Artifact>();
for (Process process : bpmnModel.getProcesses()) {
artifacts.addAll(process.getArtifacts());
}
return artifacts;
}
protected static List<FlowNode> gatherAllFlowNodes(BpmnModel bpmnModel) {
List<FlowNode> flowNodes = new ArrayList<FlowNode>();
for (Process process : bpmnModel.getProcesses()) {
flowNodes.addAll(gatherAllFlowNodes(process));
}
return flowNodes;
}
protected static List<FlowNode> gatherAllFlowNodes(FlowElementsContainer flowElementsContainer) {
List<FlowNode> flowNodes = new ArrayList<FlowNode>();
for (FlowElement flowElement : flowElementsContainer.getFlowElements()) {
if (flowElement instanceof FlowNode) {
flowNodes.add((FlowNode) flowElement);
}
if (flowElement instanceof FlowElementsContainer) {
flowNodes.addAll(gatherAllFlowNodes((FlowElementsContainer) flowElement));
}
}
return flowNodes;
}
public Map<Class<? extends BaseElement>, ActivityDrawInstruction> getActivityDrawInstructions() {
return activityDrawInstructions;
}
public void setActivityDrawInstructions(
Map<Class<? extends BaseElement>, ActivityDrawInstruction> activityDrawInstructions
) {
|
this.activityDrawInstructions = activityDrawInstructions;
}
public Map<Class<? extends BaseElement>, ArtifactDrawInstruction> getArtifactDrawInstructions() {
return artifactDrawInstructions;
}
public void setArtifactDrawInstructions(
Map<Class<? extends BaseElement>, ArtifactDrawInstruction> artifactDrawInstructions
) {
this.artifactDrawInstructions = artifactDrawInstructions;
}
protected interface ActivityDrawInstruction {
void draw(DefaultProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, FlowNode flowNode);
}
protected interface ArtifactDrawInstruction {
void draw(DefaultProcessDiagramCanvas processDiagramCanvas, BpmnModel bpmnModel, Artifact artifact);
}
}
|
repos\Activiti-develop\activiti-core\activiti-image-generator\src\main\java\org\activiti\image\impl\DefaultProcessDiagramGenerator.java
| 1
|
请完成以下Java代码
|
public int getSAP_GLJournal_ID()
{
return get_ValueAsInt(COLUMNNAME_SAP_GLJournal_ID);
}
@Override
public void setSAP_GLJournalLine_ID (final int SAP_GLJournalLine_ID)
{
if (SAP_GLJournalLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_SAP_GLJournalLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SAP_GLJournalLine_ID, SAP_GLJournalLine_ID);
}
@Override
public int getSAP_GLJournalLine_ID()
{
return get_ValueAsInt(COLUMNNAME_SAP_GLJournalLine_ID);
}
@Override
public void setUserElementString1 (final @Nullable java.lang.String UserElementString1)
{
set_Value (COLUMNNAME_UserElementString1, UserElementString1);
}
@Override
public java.lang.String getUserElementString1()
{
return get_ValueAsString(COLUMNNAME_UserElementString1);
}
@Override
public void setUserElementString2 (final @Nullable java.lang.String UserElementString2)
{
set_Value (COLUMNNAME_UserElementString2, UserElementString2);
}
@Override
public java.lang.String getUserElementString2()
{
return get_ValueAsString(COLUMNNAME_UserElementString2);
}
@Override
public void setUserElementString3 (final @Nullable java.lang.String UserElementString3)
{
set_Value (COLUMNNAME_UserElementString3, UserElementString3);
}
@Override
public java.lang.String getUserElementString3()
{
return get_ValueAsString(COLUMNNAME_UserElementString3);
}
@Override
public void setUserElementString4 (final @Nullable java.lang.String UserElementString4)
{
set_Value (COLUMNNAME_UserElementString4, UserElementString4);
}
@Override
public java.lang.String getUserElementString4()
{
|
return get_ValueAsString(COLUMNNAME_UserElementString4);
}
@Override
public void setUserElementString5 (final @Nullable java.lang.String UserElementString5)
{
set_Value (COLUMNNAME_UserElementString5, UserElementString5);
}
@Override
public java.lang.String getUserElementString5()
{
return get_ValueAsString(COLUMNNAME_UserElementString5);
}
@Override
public void setUserElementString6 (final @Nullable java.lang.String UserElementString6)
{
set_Value (COLUMNNAME_UserElementString6, UserElementString6);
}
@Override
public java.lang.String getUserElementString6()
{
return get_ValueAsString(COLUMNNAME_UserElementString6);
}
@Override
public void setUserElementString7 (final @Nullable java.lang.String UserElementString7)
{
set_Value (COLUMNNAME_UserElementString7, UserElementString7);
}
@Override
public java.lang.String getUserElementString7()
{
return get_ValueAsString(COLUMNNAME_UserElementString7);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_SAP_GLJournalLine.java
| 1
|
请完成以下Java代码
|
private void searchByUsername(String username, boolean exact) {
logger.info("Searching by username: {} (exact {})", username, exact);
List<UserRepresentation> users = keycloak.realm(REALM_NAME)
.users()
.searchByUsername(username, exact);
logger.info("Users found by username {}", users.stream()
.map(user -> user.getUsername())
.collect(Collectors.toList()));
}
private void searchByEmail(String email, boolean exact) {
logger.info("Searching by email: {} (exact {})", email, exact);
List<UserRepresentation> users = keycloak.realm(REALM_NAME)
.users()
.searchByEmail(email, exact);
logger.info("Users found by email {}", users.stream()
.map(user -> user.getEmail())
.collect(Collectors.toList()));
}
private void searchByAttributes(String query) {
logger.info("Searching by attributes: {}", query);
List<UserRepresentation> users = keycloak.realm(REALM_NAME)
.users()
.searchByAttributes(query);
logger.info("Users found by attributes {}", users.stream()
.map(user -> user.getUsername() + " " + user.getAttributes())
.collect(Collectors.toList()));
}
private void searchByGroup(String groupId) {
logger.info("Searching by group: {}", groupId);
List<UserRepresentation> users = keycloak.realm(REALM_NAME)
.groups()
|
.group(groupId)
.members();
logger.info("Users found by group {}", users.stream()
.map(user -> user.getUsername())
.collect(Collectors.toList()));
}
private void searchByRole(String roleName) {
logger.info("Searching by role: {}", roleName);
List<UserRepresentation> users = keycloak.realm(REALM_NAME)
.roles()
.get(roleName)
.getUserMembers();
logger.info("Users found by role {}", users.stream()
.map(user -> user.getUsername())
.collect(Collectors.toList()));
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-keycloak-2\src\main\java\com\baeldung\keycloak\adminclient\AdminClientService.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 8080
servlet:
context-path: /demo
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/spring-boot-demo?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.zaxxer.hikari.HikariDataSource
hikari:
minimum-idle: 5
connection-test-query: SELECT 1 FROM DUAL
maximum-pool-size: 20
auto-commit: true
idle-timeout: 30000
pool-name: SpringBootDemoHikariCP
max-lifetime: 60000
connection-timeout: 30000
quartz:
# 参见 org.springframework.boot.autoconfigure.quartz.QuartzProperties
job-store-type: jdbc
wait-for-jobs-to-complete-on-shutdown: true
scheduler-name: SpringBootDemoScheduler
properties:
org.quartz.threadPool.threadCount: 5
org.quartz.threadPool.threadPriority: 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true
org.quartz.jobStore.misfireThreshold: 5000
org.quartz.jobStore.class: org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
# 在调度流程的第一步,也就是拉取待即将触发的triggers时,是上锁的状态,即不会同时存在多个线程拉取到相同的trigger的情况,也就避免的重复调度的危险。参考:https://segmentfault.com/a/1190000015492260
|
org.quartz.jobStore.acquireTriggersWithinLock: true
logging:
level:
com.xkcoding: debug
com.xkcoding.task.quartz.mapper: trace
mybatis:
configuration:
# 下划线转驼峰
map-underscore-to-camel-case: true
mapper-locations: classpath:mappers/*.xml
type-aliases-package: com.xkcoding.task.quartz.entity
mapper:
mappers:
- tk.mybatis.mapper.common.Mapper
not-empty: true
style: camelhump
wrap-keyword: "`{0}`"
safe-delete: true
safe-update: true
identity: MYSQL
pagehelper:
auto-dialect: true
helper-dialect: mysql
reasonable: true
params: count=countSql
|
repos\spring-boot-demo-master\demo-task-quartz\src\main\resources\application.yml
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class MustacheResourceTemplateLoader implements TemplateLoader, ResourceLoaderAware {
private String prefix = "";
private String suffix = "";
private Charset charset = StandardCharsets.UTF_8;
private ResourceLoader resourceLoader = new DefaultResourceLoader(null);
public MustacheResourceTemplateLoader() {
}
public MustacheResourceTemplateLoader(String prefix, String suffix) {
this.prefix = prefix;
this.suffix = suffix;
}
/**
* Set the {@link Charset} to use.
* @param charset the charset
* @since 4.1.0
*/
public void setCharset(Charset charset) {
this.charset = charset;
}
/**
* Set the name of the charset to use.
* @param charset the charset
* @deprecated since 4.1.0 for removal in 4.3.0 in favor of
* {@link #setCharset(Charset)}
*/
@Deprecated(since = "4.1.0", forRemoval = true)
public void setCharset(String charset) {
|
this.charset = Charset.forName(charset);
}
/**
* Set the resource loader.
* @param resourceLoader the resource loader
*/
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@Override
public Reader getTemplate(String name) throws Exception {
return new InputStreamReader(this.resourceLoader.getResource(this.prefix + name + this.suffix).getInputStream(),
this.charset);
}
}
|
repos\spring-boot-main\module\spring-boot-mustache\src\main\java\org\springframework\boot\mustache\autoconfigure\MustacheResourceTemplateLoader.java
| 2
|
请完成以下Java代码
|
public static final <T> POJOInSelectionQueryFilter<T> notInSelection(final PInstanceId selectionId)
{
final boolean include = false;
return new POJOInSelectionQueryFilter<>(selectionId, include);
}
private final PInstanceId selectionId;
private final boolean include;
private POJOInSelectionQueryFilter(@NonNull final PInstanceId selectionId, final boolean include)
{
this.selectionId = selectionId;
this.include = include;
}
@Override
public String toString()
{
return (include ? "InSelection-" : "NotInSelection-") + selectionId.getRepoId();
}
@Override
public boolean accept(final T model)
{
if (model == null)
|
{
return false;
}
final int id = InterfaceWrapperHelper.getId(model);
final boolean isInSelection = POJOLookupMap.get().isInSelection(selectionId, id);
if (include)
{
return isInSelection;
}
else // exclude
{
return !isInSelection;
}
}
public PInstanceId getSelectionId()
{
return selectionId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\POJOInSelectionQueryFilter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getAuthMethod() {
return authMethod;
}
public void setAuthMethod(String authMethod) {
this.authMethod = authMethod;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
@NotBlank
private String hostName;
@Min(1025)
@Max(65536)
private int port;
@Pattern(regexp = "^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,6}$")
private String from;
private Credentials credentials;
private List<String> defaultRecipients;
private Map<String, String> additionalHeaders;
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public int getPort() {
|
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public Credentials getCredentials() {
return credentials;
}
public void setCredentials(Credentials credentials) {
this.credentials = credentials;
}
public List<String> getDefaultRecipients() {
return defaultRecipients;
}
public void setDefaultRecipients(List<String> defaultRecipients) {
this.defaultRecipients = defaultRecipients;
}
public Map<String, String> getAdditionalHeaders() {
return additionalHeaders;
}
public void setAdditionalHeaders(Map<String, String> additionalHeaders) {
this.additionalHeaders = additionalHeaders;
}
@Bean
@ConfigurationProperties(prefix = "item")
public Item item(){
return new Item();
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-core\src\main\java\com\baeldung\configurationproperties\ConfigProperties.java
| 2
|
请完成以下Java代码
|
public static <T> HttpResult<T> failure(int code, String msg) {
HttpResult result = new HttpResult<T>();
result.setStatus(false);
result.setMessage(msg);
result.setCode(code);
return result;
}
public static <T> HttpResult<T> success(T obj) {
SuccessResult result = new SuccessResult<T>();
result.setStatus(true);
result.setEntry(obj);
result.setCode(200);
return result;
}
public static <T> HttpResult<T> success(T obj, int code) {
SuccessResult<T> result = new SuccessResult<T>();
result.setStatus(true);
result.setCode(200);
result.setEntry(obj);
return result;
}
public static <T> HttpResult<List<T>> success(List<T> list) {
SuccessResult<List<T>> result = new SuccessResult<List<T>>();
result.setStatus(true);
result.setCode(200);
if (null == list) {
result.setEntry(new ArrayList<T>(0));
} else {
result.setEntry(list);
}
return result;
}
public static HttpResult<Boolean> success() {
SuccessResult<Boolean> result = new SuccessResult<Boolean>();
result.setStatus(true);
result.setEntry(true);
result.setCode(200);
return result;
}
public static <T> HttpResult<T> success(T entry, String message) {
SuccessResult<T> result = new SuccessResult<T>();
result.setStatus(true);
result.setEntry(entry);
result.setMessage(message);
|
result.setCode(200);
return result;
}
/**
* Result set data with paging information
*/
public static class PageSuccessResult<T> extends HttpResult<T> {
@Override
public String getMessage() {
return null != message ? message : HttpResult.MESSAGE_SUCCESS;
}
@Override
public int getCode() {
return HttpResult.RESPONSE_SUCCESS;
}
}
public static class SuccessResult<T> extends HttpResult<T> {
@Override
public String getMessage() {
return null != message ? message : HttpResult.MESSAGE_SUCCESS;
}
@Override
public int getCode() {
return code != 0 ? code : HttpResult.RESPONSE_SUCCESS;
}
}
public static class FailureResult<T> extends HttpResult<T> {
@Override
public String getMessage() {
return null != message ? message : HttpResult.MESSAGE_FAILURE;
}
@Override
public int getCode() {
return code != 0 ? code : HttpResult.RESPONSE_FAILURE;
}
}
}
|
repos\springboot-demo-master\Aviator\src\main\java\com\et\exception\HttpResult.java
| 1
|
请完成以下Java代码
|
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
|
return "Y".equals(oo);
}
return false;
}
public I_AD_User getSupervisor() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getSupervisor_ID(), get_TrxName()); }
/** Set Supervisor.
@param Supervisor_ID
Supervisor for this user/organization - used for escalation and approval
*/
public void setSupervisor_ID (int Supervisor_ID)
{
if (Supervisor_ID < 1)
set_Value (COLUMNNAME_Supervisor_ID, null);
else
set_Value (COLUMNNAME_Supervisor_ID, Integer.valueOf(Supervisor_ID));
}
/** Get Supervisor.
@return Supervisor for this user/organization - used for escalation and approval
*/
public int getSupervisor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Supervisor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AlertProcessor.java
| 1
|
请完成以下Java代码
|
public String getType() {
return Batch.TYPE_PROCESS_INSTANCE_MODIFICATION;
}
@Override
protected void postProcessJob(ModificationBatchConfiguration configuration, JobEntity job, ModificationBatchConfiguration jobConfiguration) {
if (job.getDeploymentId() == null) {
CommandContext commandContext = Context.getCommandContext();
ProcessDefinitionEntity processDefinitionEntity = commandContext.getProcessEngineConfiguration().getDeploymentCache()
.findDeployedProcessDefinitionById(configuration.getProcessDefinitionId());
job.setDeploymentId(processDefinitionEntity.getDeploymentId());
}
}
@Override
public void executeHandler(ModificationBatchConfiguration batchConfiguration,
ExecutionEntity execution,
CommandContext commandContext,
String tenantId) {
ModificationBuilderImpl executionBuilder = (ModificationBuilderImpl) commandContext.getProcessEngineConfiguration()
.getRuntimeService()
.createModification(batchConfiguration.getProcessDefinitionId())
.processInstanceIds(batchConfiguration.getIds());
executionBuilder.setInstructions(batchConfiguration.getInstructions());
if (batchConfiguration.isSkipCustomListeners()) {
executionBuilder.skipCustomListeners();
}
if (batchConfiguration.isSkipIoMappings()) {
executionBuilder.skipIoMappings();
}
executionBuilder.execute(false);
}
@Override
public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() {
return JOB_DECLARATION;
|
}
@Override
protected ModificationBatchConfiguration createJobConfiguration(ModificationBatchConfiguration configuration, List<String> processIdsForJob) {
return new ModificationBatchConfiguration(
processIdsForJob,
configuration.getProcessDefinitionId(),
configuration.getInstructions(),
configuration.isSkipCustomListeners(),
configuration.isSkipIoMappings()
);
}
@Override
protected ModificationBatchConfigurationJsonConverter getJsonConverterInstance() {
return ModificationBatchConfigurationJsonConverter.INSTANCE;
}
protected ProcessDefinitionEntity getProcessDefinition(CommandContext commandContext, String processDefinitionId) {
return commandContext.getProcessEngineConfiguration()
.getDeploymentCache()
.findDeployedProcessDefinitionById(processDefinitionId);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ModificationBatchJobHandler.java
| 1
|
请完成以下Java代码
|
public ReactorClientHttpRequestFactoryBuilder withHttpClientCustomizer(
UnaryOperator<HttpClient> httpClientCustomizer) {
Assert.notNull(httpClientCustomizer, "'httpClientCustomizer' must not be null");
return new ReactorClientHttpRequestFactoryBuilder(getCustomizers(),
this.httpClientBuilder.withHttpClientCustomizer(httpClientCustomizer));
}
/**
* Return a new {@link ReactorClientHttpRequestFactoryBuilder} that applies the given
* customizer. This can be useful for applying pre-packaged customizations.
* @param customizer the customizer to apply
* @return a new {@link ReactorClientHttpRequestFactoryBuilder}
* @since 4.0.0
*/
public ReactorClientHttpRequestFactoryBuilder with(
UnaryOperator<ReactorClientHttpRequestFactoryBuilder> customizer) {
return customizer.apply(this);
}
@Override
protected ReactorClientHttpRequestFactory createClientHttpRequestFactory(HttpClientSettings settings) {
HttpClient httpClient = this.httpClientBuilder.build(settings.withTimeouts(null, null));
ReactorClientHttpRequestFactory requestFactory = new ReactorClientHttpRequestFactory(httpClient);
PropertyMapper map = PropertyMapper.get();
map.from(settings::connectTimeout).asInt(Duration::toMillis).to(requestFactory::setConnectTimeout);
|
map.from(settings::readTimeout).asInt(Duration::toMillis).to(requestFactory::setReadTimeout);
return requestFactory;
}
static class Classes {
static final String HTTP_CLIENT = "reactor.netty.http.client.HttpClient";
static boolean present(@Nullable ClassLoader classLoader) {
return ClassUtils.isPresent(HTTP_CLIENT, classLoader);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\ReactorClientHttpRequestFactoryBuilder.java
| 1
|
请完成以下Java代码
|
public static List<Document> loadCorpus(String path)
{
return (List<Document>) IOUtil.readObjectFrom(path);
}
public static boolean saveCorpus(List<Document> documentList, String path)
{
return IOUtil.saveObjectTo(documentList, path);
}
public static List<List<IWord>> loadSentenceList(String path)
{
return (List<List<IWord>>) IOUtil.readObjectFrom(path);
}
public static boolean saveSentenceList(List<List<IWord>> sentenceList, String path)
{
return IOUtil.saveObjectTo(sentenceList, path);
}
public static List<List<IWord>> convert2SentenceList(String path)
{
List<Document> documentList = CorpusLoader.convert2DocumentList(path);
List<List<IWord>> simpleList = new LinkedList<List<IWord>>();
for (Document document : documentList)
{
for (Sentence sentence : document.sentenceList)
{
simpleList.add(sentence.wordList);
}
}
return simpleList;
}
public static List<List<Word>> convert2SimpleSentenceList(String path)
{
List<Document> documentList = CorpusLoader.convert2DocumentList(path);
List<List<Word>> simpleList = new LinkedList<List<Word>>();
for (Document document : documentList)
{
simpleList.addAll(document.getSimpleSentenceList());
}
return simpleList;
}
public static Document convert2Document(File file)
{
// try
// {
Document document = Document.create(file);
if (document != null)
{
return document;
}
else
{
throw new IllegalArgumentException(file.getPath() + "读取失败");
}
// }
// catch (IOException e)
// {
// e.printStackTrace();
// }
// return null;
}
public static interface Handler
{
void handle(Document document);
|
}
/**
* 多线程任务
*/
public static abstract class HandlerThread extends Thread implements Handler
{
/**
* 这个线程负责处理这些事情
*/
public List<File> fileList;
public HandlerThread(String name)
{
super(name);
}
@Override
public void run()
{
long start = System.currentTimeMillis();
System.out.printf("线程#%s 开始运行\n", getName());
int i = 0;
for (File file : fileList)
{
System.out.print(file);
Document document = convert2Document(file);
System.out.println(" " + ++i + " / " + fileList.size());
handle(document);
}
System.out.printf("线程#%s 运行完毕,耗时%dms\n", getName(), System.currentTimeMillis() - start);
}
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\document\CorpusLoader.java
| 1
|
请完成以下Java代码
|
protected void prepare()
{
if (I_C_Print_Job.Table_Name.equals(getTableName()) && getRecord_ID() > 0)
{
printJobID = getRecord_ID();
}
}
@Override
protected String doIt() throws IOException, DocumentException
{
final Properties ctx = Env.getCtx();
final String trxName = ITrx.TRXNAME_None;
final String outputDir = Services.get(ISysConfigBL.class).getValue(SYSCONFIG_PdfDownloadPath);
final String fileName = "printjobs_" + getPinstanceId().getRepoId();
final I_C_Print_Job job = InterfaceWrapperHelper.create(ctx, printJobID, I_C_Print_Job.class, trxName);
final Iterator<I_C_Print_Job_Line> jobLines = Services.get(IPrintingDAO.class).retrievePrintJobLines(job);
if (!jobLines.hasNext())
{
return "No print job lines found. Pdf not generated.";
}
final File file;
if (Check.isEmpty(outputDir, true))
{
file = File.createTempFile(fileName, ".pdf");
}
else
{
file = new File(outputDir, fileName + ".pdf");
}
final Document document = new Document();
final FileOutputStream fos = new FileOutputStream(file, false);
|
final PdfCopy copy = new PdfCopy(document, fos);
document.open();
for (final I_C_Print_Job_Line jobLine : IteratorUtils.asIterable(jobLines))
{
final I_C_Printing_Queue queue = jobLine.getC_Printing_Queue();
Check.assume(queue != null, jobLine + " references a C_Printing_Queue");
final I_AD_Archive archive = queue.getAD_Archive();
Check.assume(archive != null, queue + " references an AD_Archive record");
final byte[] data = Services.get(IArchiveBL.class).getBinaryData(archive);
final PdfReader reader = new PdfReader(data);
for (int page = 0; page < reader.getNumberOfPages();)
{
copy.addPage(copy.getImportedPage(reader, ++page));
}
copy.freeReader(reader);
reader.close();
}
document.close();
fos.close();
outputFile = new File(outputDir);
return "@Created@ " + fileName + ".pdf" + " in " + outputDir;
}
public File getOutputFile()
{
return outputFile;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\process\ConcatenatePdfs.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public abstract class AttributesRecordAdapter<T, PARENT_ID>
{
protected final IQueryBL queryBL = Services.get(IQueryBL.class);
protected abstract IQuery<T> queryRecords(final @NonNull PARENT_ID parentId);
protected abstract BPartnerAttribute extractAttribute(final @NonNull T record);
protected abstract T createNewRecord(final @NonNull PARENT_ID parentId, final BPartnerAttribute attribute);
private void deleteRecords(final Collection<T> records)
{
InterfaceWrapperHelper.deleteAll(records);
}
public ImmutableSet<BPartnerAttribute> getAttributes(final @NonNull PARENT_ID parentId)
{
return queryRecords(parentId)
.stream()
.map(this::extractAttribute)
.distinct()
.collect(ImmutableSet.toImmutableSet());
}
// see also: de.metas.ui.web.window.model.sql.SqlDocumentsRepository.saveLabels
public void saveAttributes(
@NonNull final ImmutableSet<BPartnerAttribute> attributesSet,
|
@NonNull final PARENT_ID parentId)
{
final HashMap<BPartnerAttribute, T> existingRecords = queryRecords(parentId)
.stream()
.collect(GuavaCollectors.toHashMapByKey(this::extractAttribute));
for (final BPartnerAttribute attribute : attributesSet)
{
final T existingRecord = existingRecords.remove(attribute);
if (existingRecord == null)
{
createNewRecord(parentId, attribute);
}
}
deleteRecords(existingRecords.values());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\attributes\service\attributes_record_adapter\AttributesRecordAdapter.java
| 2
|
请完成以下Java代码
|
public void setQtyAllocated (final @Nullable BigDecimal QtyAllocated)
{
set_ValueNoCheck (COLUMNNAME_QtyAllocated, QtyAllocated);
}
@Override
public BigDecimal getQtyAllocated()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyAllocated);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyAllocatedInCatchUOM (final @Nullable BigDecimal QtyAllocatedInCatchUOM)
{
set_Value (COLUMNNAME_QtyAllocatedInCatchUOM, QtyAllocatedInCatchUOM);
}
@Override
public BigDecimal getQtyAllocatedInCatchUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyAllocatedInCatchUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyWithIssues (final BigDecimal QtyWithIssues)
{
set_ValueNoCheck (COLUMNNAME_QtyWithIssues, QtyWithIssues);
}
@Override
public BigDecimal getQtyWithIssues()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyWithIssues);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyWithIssuesInCatchUOM (final @Nullable BigDecimal QtyWithIssuesInCatchUOM)
{
set_Value (COLUMNNAME_QtyWithIssuesInCatchUOM, QtyWithIssuesInCatchUOM);
}
@Override
public BigDecimal getQtyWithIssuesInCatchUOM()
|
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyWithIssuesInCatchUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQualityDiscountPercent (final @Nullable BigDecimal QualityDiscountPercent)
{
throw new IllegalArgumentException ("QualityDiscountPercent is virtual column"); }
@Override
public BigDecimal getQualityDiscountPercent()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QualityDiscountPercent);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQualityNote (final @Nullable java.lang.String QualityNote)
{
throw new IllegalArgumentException ("QualityNote is virtual column"); }
@Override
public java.lang.String getQualityNote()
{
return get_ValueAsString(COLUMNNAME_QualityNote);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ReceiptSchedule_Alloc.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MessageController {
@Autowired
private MessageEventHandler messageHandler;
@PostMapping("/broadcast")
public Dict broadcast(@RequestBody BroadcastMessageRequest message) {
if (isBlank(message)) {
return Dict.create().set("flag", false).set("code", 400).set("message", "参数为空");
}
messageHandler.sendToBroadcast(message);
return Dict.create().set("flag", true).set("code", 200).set("message", "发送成功");
}
/**
* 判断Bean是否为空对象或者空白字符串,空对象表示本身为<code>null</code>或者所有属性都为<code>null</code>
*
* @param bean Bean对象
* @return 是否为空,<code>true</code> - 空 / <code>false</code> - 非空
*/
|
private boolean isBlank(Object bean) {
if (null != bean) {
for (Field field : ReflectUtil.getFields(bean.getClass())) {
Object fieldValue = ReflectUtil.getFieldValue(bean, field);
if (null != fieldValue) {
if (fieldValue instanceof String && StrUtil.isNotBlank((String) fieldValue)) {
return false;
} else if (!(fieldValue instanceof String)) {
return false;
}
}
}
}
return true;
}
}
|
repos\spring-boot-demo-master\demo-websocket-socketio\src\main\java\com\xkcoding\websocket\socketio\controller\MessageController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
protected String getDeploymentMode() {
return DEPLOYMENT_MODE;
}
@Override
protected void deployResourcesInternal(String deploymentNameHint, Resource[] resources, ProcessEngine engine) {
RepositoryService repositoryService = engine.getRepositoryService();
// Create a deployment for each distinct parent folder using the namehint as a prefix
final Map<String, Set<Resource>> resourcesMap = createMap(resources);
for (final Entry<String, Set<Resource>> group : resourcesMap.entrySet()) {
final String deploymentName = determineDeploymentName(deploymentNameHint, group.getKey());
final DeploymentBuilder deploymentBuilder = repositoryService.createDeployment().enableDuplicateFiltering().name(deploymentName);
for (final Resource resource : group.getValue()) {
addResource(resource, deploymentBuilder);
}
try {
deploymentBuilder.deploy();
} catch (Exception e) {
if (isThrowExceptionOnDeploymentFailure()) {
throw e;
} else {
LOGGER.warn("Exception while autodeploying process definitions. "
+ "This exception can be ignored if the root cause indicates a unique constraint violation, "
+ "which is typically caused by two (or more) servers booting up at the exact same time and deploying the same definitions. ", e);
}
}
}
}
private Map<String, Set<Resource>> createMap(final Resource[] resources) {
final Map<String, Set<Resource>> resourcesMap = new HashMap<>();
for (final Resource resource : resources) {
final String parentFolderName = determineGroupName(resource);
if (resourcesMap.get(parentFolderName) == null) {
resourcesMap.put(parentFolderName, new HashSet<>());
}
resourcesMap.get(parentFolderName).add(resource);
|
}
return resourcesMap;
}
private String determineGroupName(final Resource resource) {
String result = determineResourceName(resource);
try {
if (resourceParentIsDirectory(resource)) {
result = resource.getFile().getParentFile().getName();
}
} catch (IOException e) {
// no-op, fallback to resource name
}
return result;
}
private boolean resourceParentIsDirectory(final Resource resource) throws IOException {
return resource.getFile() != null && resource.getFile().getParentFile() != null && resource.getFile().getParentFile().isDirectory();
}
private String determineDeploymentName(final String deploymentNameHint, final String groupName) {
return String.format(DEPLOYMENT_NAME_PATTERN, deploymentNameHint, groupName);
}
}
|
repos\flowable-engine-main\modules\flowable-spring\src\main\java\org\flowable\spring\configurator\ResourceParentFolderAutoDeploymentStrategy.java
| 2
|
请完成以下Java代码
|
public void setEnableCommand (final @Nullable java.lang.String EnableCommand)
{
set_Value (COLUMNNAME_EnableCommand, EnableCommand);
}
@Override
public java.lang.String getEnableCommand()
{
return get_ValueAsString(COLUMNNAME_EnableCommand);
}
@Override
public de.metas.externalsystem.model.I_ExternalSystem getExternalSystem()
{
return get_ValueAsPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class);
}
@Override
public void setExternalSystem(final de.metas.externalsystem.model.I_ExternalSystem ExternalSystem)
{
set_ValueFromPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class, ExternalSystem);
}
@Override
public void setExternalSystem_ID (final int ExternalSystem_ID)
{
if (ExternalSystem_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID);
}
@Override
public int getExternalSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID);
}
@Override
public void setExternalSystem_Service_ID (final int ExternalSystem_Service_ID)
{
if (ExternalSystem_Service_ID < 1)
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Service_ID, null);
else
|
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Service_ID, ExternalSystem_Service_ID);
}
@Override
public int getExternalSystem_Service_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Service_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Service.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void update(App resources) {
// 验证应用名称是否存在恶意攻击payload,https://github.com/elunez/eladmin/issues/873
String appName = resources.getName();
if (appName.contains(";") || appName.contains("|") || appName.contains("&")) {
throw new IllegalArgumentException("非法的应用名称,请勿包含[; | &]等特殊字符");
}
verification(resources);
App app = appRepository.findById(resources.getId()).orElseGet(App::new);
ValidationUtil.isNull(app.getId(),"App","id",resources.getId());
app.copy(resources);
appRepository.save(app);
}
private void verification(App resources){
String opt = "/opt";
String home = "/home";
if (!(resources.getUploadPath().startsWith(opt) || resources.getUploadPath().startsWith(home))) {
throw new BadRequestException("文件只能上传在opt目录或者home目录 ");
}
if (!(resources.getDeployPath().startsWith(opt) || resources.getDeployPath().startsWith(home))) {
throw new BadRequestException("文件只能部署在opt目录或者home目录 ");
}
if (!(resources.getBackupPath().startsWith(opt) || resources.getBackupPath().startsWith(home))) {
throw new BadRequestException("文件只能备份在opt目录或者home目录 ");
}
}
|
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Set<Long> ids) {
for (Long id : ids) {
appRepository.deleteById(id);
}
}
@Override
public void download(List<AppDto> queryAll, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (AppDto appDto : queryAll) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("应用名称", appDto.getName());
map.put("端口", appDto.getPort());
map.put("上传目录", appDto.getUploadPath());
map.put("部署目录", appDto.getDeployPath());
map.put("备份目录", appDto.getBackupPath());
map.put("启动脚本", appDto.getStartScript());
map.put("部署脚本", appDto.getDeployScript());
map.put("创建日期", appDto.getCreateTime());
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\service\impl\AppServiceImpl.java
| 2
|
请完成以下Java代码
|
public org.compiere.model.I_AD_Reference getAD_Reference()
{
return get_ValueAsPO(COLUMNNAME_AD_Reference_ID, org.compiere.model.I_AD_Reference.class);
}
@Override
public void setAD_Reference(final org.compiere.model.I_AD_Reference AD_Reference)
{
set_ValueFromPO(COLUMNNAME_AD_Reference_ID, org.compiere.model.I_AD_Reference.class, AD_Reference);
}
@Override
public void setAD_Reference_ID (final int AD_Reference_ID)
{
if (AD_Reference_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Reference_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Reference_ID, AD_Reference_ID);
}
@Override
public int getAD_Reference_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Reference_ID);
}
@Override
public void setAD_Ref_List_ID (final int AD_Ref_List_ID)
{
if (AD_Ref_List_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Ref_List_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Ref_List_ID, AD_Ref_List_ID);
}
@Override
public int getAD_Ref_List_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Ref_List_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
@Override
public void setEntityType (final java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
@Override
public java.lang.String getEntityType()
{
return get_ValueAsString(COLUMNNAME_EntityType);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setValidFrom (final @Nullable 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 @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setValueName (final @Nullable java.lang.String ValueName)
{
set_ValueNoCheck (COLUMNNAME_ValueName, ValueName);
}
@Override
public java.lang.String getValueName()
{
return get_ValueAsString(COLUMNNAME_ValueName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Ref_List.java
| 1
|
请完成以下Java代码
|
Mono<User> retrieveOneUserWithExchangeAndManipulate(@PathVariable int id) {
return client.get()
.uri("/{id}", id)
.exchangeToMono(res -> res.bodyToMono(User.class))
.map(user -> {
user.setName(user.getName()
.toUpperCase());
user.setId(user.getId() + 100);
return user;
});
}
@GetMapping("/user/exchange-mono/{id}")
Mono<User> retrieveUsersWithExchangeAndError(@PathVariable int id) {
return client.get()
.uri("/{id}", id)
.exchangeToMono(res -> {
if (res.statusCode()
.is2xxSuccessful()) {
return res.bodyToMono(User.class);
} else if (res.statusCode()
.is4xxClientError()) {
return Mono.error(new RuntimeException("Client Error: can't fetch user"));
} else if (res.statusCode()
.is5xxServerError()) {
return Mono.error(new RuntimeException("Server Error: can't fetch user"));
} else {
return res.createError();
}
});
}
@GetMapping("/user/exchange-header/{id}")
Mono<User> retrieveUsersWithExchangeAndHeader(@PathVariable int id) {
return client.get()
.uri("/{id}", id)
.exchangeToMono(res -> {
if (res.statusCode()
.is2xxSuccessful()) {
logger.info("Status code: " + res.headers()
.asHttpHeaders());
logger.info("Content-type" + res.headers()
.contentType());
|
return res.bodyToMono(User.class);
} else if (res.statusCode()
.is4xxClientError()) {
return Mono.error(new RuntimeException("Client Error: can't fetch user"));
} else if (res.statusCode()
.is5xxServerError()) {
return Mono.error(new RuntimeException("Server Error: can't fetch user"));
} else {
return res.createError();
}
});
}
@GetMapping("/user-exchange")
Flux<User> retrieveAllUserWithExchange(@PathVariable int id) {
return client.get()
.exchangeToFlux(res -> res.bodyToFlux(User.class))
.onErrorResume(Flux::error);
}
@GetMapping("/user-exchange-flux")
Flux<User> retrieveUsersWithExchange() {
return client.get()
.exchangeToFlux(res -> {
if (res.statusCode()
.is2xxSuccessful()) {
return res.bodyToFlux(User.class);
} else {
return Flux.error(new RuntimeException("Error while fetching users"));
}
});
}
}
|
repos\tutorials-master\spring-reactive-modules\spring-reactive-client-2\src\main\java\com\baeldung\webclientretrievevsexchange\RetrieveAndExchangeController.java
| 1
|
请完成以下Java代码
|
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_AD_Attribute_Value[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set System Attribute.
@param AD_Attribute_ID System Attribute */
public void setAD_Attribute_ID (int AD_Attribute_ID)
{
if (AD_Attribute_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Attribute_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Attribute_ID, Integer.valueOf(AD_Attribute_ID));
}
/** Get System Attribute.
@return System Attribute */
public int getAD_Attribute_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Attribute_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Record ID.
@param Record_ID
Direct internal record ID
*/
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 Record ID.
@return Direct internal record ID
*/
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set V_Date.
@param V_Date V_Date */
public void setV_Date (Timestamp V_Date)
{
set_Value (COLUMNNAME_V_Date, V_Date);
}
|
/** Get V_Date.
@return V_Date */
public Timestamp getV_Date ()
{
return (Timestamp)get_Value(COLUMNNAME_V_Date);
}
/** Set V_Number.
@param V_Number V_Number */
public void setV_Number (String V_Number)
{
set_Value (COLUMNNAME_V_Number, V_Number);
}
/** Get V_Number.
@return V_Number */
public String getV_Number ()
{
return (String)get_Value(COLUMNNAME_V_Number);
}
/** Set V_String.
@param V_String V_String */
public void setV_String (String V_String)
{
set_Value (COLUMNNAME_V_String, V_String);
}
/** Get V_String.
@return V_String */
public String getV_String ()
{
return (String)get_Value(COLUMNNAME_V_String);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attribute_Value.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UserRepository {
@GetMapping
public List<User> getUsers() {
return Arrays.asList(
new User("Sam", 2000L),
new User("Peter", 1000L)
);
}
@GetMapping("/{userName}")
public User getUser(@PathVariable("userName") final String userName)
{
return new User(userName, 1000L);
}
private class User {
@ApiModelProperty(notes = "name of the User")
private String userName;
@ApiModelProperty(notes = "salary of the user")
private Long salary;
public User(String userName, Long salary) {
this.userName = userName;
|
this.salary = salary;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Long getSalary() {
return salary;
}
public void setSalary(Long salary) {
this.salary = salary;
}
}
}
|
repos\SpringBoot-Projects-FullStack-master\Part-4 Spring Boot REST API\SpringSwaggerProjectAgain\src\main\java\spring\swagger\resource\UserRepository.java
| 2
|
请完成以下Java代码
|
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public int getMgr() {
return mgr;
}
public void setMgr(int mgr) {
this.mgr = mgr;
}
public Date getHiredate() {
return hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
public int getSal() {
return sal;
}
public void setSal(int sal) {
this.sal = sal;
}
|
public int getComm() {
return comm;
}
public void setComm(int comm) {
this.comm = comm;
}
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
@Override
public String toString() {
return String.format("Employee [empNo=%d, ename=%s, job=%s, mgr=%d, hiredate=%s, sal=%d, comm=%d, deptno=%d]", empNo, ename, job, mgr, hiredate, sal, comm, deptno);
}
}
|
repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\flexypool\Employee.java
| 1
|
请完成以下Java代码
|
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
// simple auth api purpose
.antMatchers("/", "index", "/css/*", "/js/*").permitAll()
.antMatchers("/api/**").hasRole(ADMIN.name()) // managing role here based on enum categories.
// management api
.antMatchers("/management/api/**").hasAnyRole(ADMIN.name(), ADMINTRAINEE.name())
.antMatchers(HttpMethod.DELETE, "/management/api/**").hasAuthority(COURSE_WRITE.name())
.antMatchers(HttpMethod.POST, "/management/api/**").hasAuthority(COURSE_WRITE.name())
.antMatchers(HttpMethod.PUT, "/management/api/**").hasAuthority(COURSE_WRITE.name())
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
@Override
@Bean
protected UserDetailsService userDetailsService() {
// Permission User(s)
UserDetails urunovUser = User.builder()
.username("urunov")
.password(passwordEncoder.encode("urunov1987"))
//.roles(ADMIN.name()) // ROLE_STUDENT
.authorities(STUDENT.getGrantedAuthorities())
.build();
UserDetails lindaUser = User.builder()
.username("linda")
.password(passwordEncoder.encode("linda333"))
.authorities(STUDENT.name())
//.roles(STUDENT.name()) // ROLE_ADMIN
.authorities(ADMIN.getGrantedAuthorities())
.build();
UserDetails tomUser = User.builder()
.username("tom")
|
.password(passwordEncoder.encode("tom555"))
.authorities(ADMINTRAINEE.name())
.authorities(ADMINTRAINEE.getGrantedAuthorities())
// .roles(ADMINTRAINEE.name()) // ROLE ADMINTRAINEE
.build();
UserDetails tolik = User.builder()
.username("tolik")
.password(passwordEncoder.encode("tolik1"))
.authorities(STUDENT.name())
.authorities(ADMIN.getGrantedAuthorities())
.build();
UserDetails hotamboyUser = User.builder()
.username("hotam")
.password(passwordEncoder.encode("hotamboy"))
.authorities(ADMIN.name())
.authorities(ADMIN.getGrantedAuthorities())
// .roles(ADMIN.name()) // ROLE ADMIN
.build();
return new InMemoryUserDetailsManager(
urunovUser,
lindaUser,
tomUser,
hotamboyUser,
tolik
);
}
}
|
repos\SpringBoot-Projects-FullStack-master\Advanced-SpringSecure\spring-management-api\spring-management-api\src\main\java\uz\bepro\springmanagementapi\security\ApplicationSecurityConfig.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
public String getSubScopeId() {
return subScopeId;
}
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public Date getFrom() {
return from;
}
public void setFrom(Date from) {
this.from = from;
}
public Date getTo() {
return to;
}
public void setTo(Date to) {
this.to = to;
}
public String getTenantId() {
return tenantId;
|
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public Long getFromLogNumber() {
return fromLogNumber;
}
public void setFromLogNumber(Long fromLogNumber) {
this.fromLogNumber = fromLogNumber;
}
public Long getToLogNumber() {
return toLogNumber;
}
public void setToLogNumber(Long toLogNumber) {
this.toLogNumber = toLogNumber;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskLogEntryQueryRequest.java
| 2
|
请完成以下Java代码
|
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
|
}
/** Set Total Ratio.
@param RatioTotal
Total of relative weight in a distribution
*/
public void setRatioTotal (BigDecimal RatioTotal)
{
set_Value (COLUMNNAME_RatioTotal, RatioTotal);
}
/** Get Total Ratio.
@return Total of relative weight in a distribution
*/
public BigDecimal getRatioTotal ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RatioTotal);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DistributionList.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class School {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String name;
@OneToMany(mappedBy = "school")
private List<Student> students;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
|
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-crud\src\main\java\com\baeldung\batchinserts\model\School.java
| 2
|
请完成以下Java代码
|
private IncotermsMap getIncotermsMap()
{
return cache.getOrLoadNonNull(0, this::retrieveIncotermsMap);
}
@NotNull
private IncotermsMap retrieveIncotermsMap()
{
final ImmutableList<Incoterms> incoterms = queryBL.createQueryBuilder(I_C_Incoterms.class)
.addOnlyActiveRecordsFilter()
.create()
.stream()
.map(IncotermsRepository::ofRecord)
.collect(ImmutableList.toImmutableList());
return new IncotermsRepository.IncotermsMap(incoterms);
}
private static Incoterms ofRecord(@NotNull final I_C_Incoterms record)
{
return Incoterms.builder()
.id(IncotermsId.ofRepoId(record.getC_Incoterms_ID()))
.name(record.getName())
.value(record.getValue())
.isDefault(record.isDefault())
.defaultLocation(record.getDefaultLocation())
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.build();
}
private static final class IncotermsMap
{
private final ImmutableMap<IncotermsId, Incoterms> byId;
private final ImmutableMap<OrgId, Incoterms> defaultByOrgId;
private final ImmutableMap<ValueAndOrgId, Incoterms> byValueAndOrgId;
IncotermsMap(final List<Incoterms> list)
{
this.byId = Maps.uniqueIndex(list, Incoterms::getId);
this.defaultByOrgId = list.stream().filter(Incoterms::isDefault)
.collect(ImmutableMap.toImmutableMap(Incoterms::getOrgId, incoterms->incoterms));
this.byValueAndOrgId = Maps.uniqueIndex(list, incoterm -> ValueAndOrgId.builder().value(incoterm.getValue()).orgId(incoterm.getOrgId()).build());
}
@NonNull
public Incoterms getById(@NonNull final IncotermsId id)
{
final Incoterms incoterms = byId.get(id);
if (incoterms == null)
{
throw new AdempiereException("Incoterms not found by ID: " + id);
}
return incoterms;
}
|
@Nullable
public Incoterms getDefaultByOrgId(@NonNull final OrgId orgId)
{
return CoalesceUtil.coalesce(defaultByOrgId.get(orgId), defaultByOrgId.get(OrgId.ANY));
}
@NonNull Incoterms getByValue(@NonNull final String value, @NonNull final OrgId orgId)
{
final Incoterms incoterms = CoalesceUtil.coalesce(byValueAndOrgId.get(ValueAndOrgId.builder().value(value).orgId(orgId).build()),
byValueAndOrgId.get(ValueAndOrgId.builder().value(value).orgId(OrgId.ANY).build()));
if (incoterms == null)
{
throw new AdempiereException("Incoterms not found by value: " + value + " and orgIds: " + orgId + " or " + OrgId.ANY);
}
return incoterms;
}
@Builder
@Value
private static class ValueAndOrgId
{
@NonNull String value;
@NonNull OrgId orgId;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\incoterms\IncotermsRepository.java
| 1
|
请完成以下Java代码
|
public void keyPressed(final KeyEvent e)
{
}
@Override
public void keyTyped(final KeyEvent e)
{
}
/**
* Key Released. if Escape Restore old Text
*
* @param e event
* @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
*/
@Override
public void keyReleased(final KeyEvent e)
{
if (LogManager.isLevelFinest())
{
log.trace("Key=" + e.getKeyCode() + " - " + e.getKeyChar() + " -> " + m_text.getText());
}
// ESC
if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
{
m_text.setText(m_initialText);
}
else if (e.getKeyChar() == KeyEvent.CHAR_UNDEFINED)
{
return;
}
|
m_setting = true;
try
{
String clear = m_text.getText();
if (clear.length() > m_fieldLength)
{
clear = clear.substring(0, m_fieldLength);
}
fireVetoableChange(m_columnName, m_oldText, clear);
}
catch (final PropertyVetoException pve)
{
}
m_setting = false;
}
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport();
}
} // VFile
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VFile.java
| 1
|
请完成以下Java代码
|
public class EAAsyncExample {
static {
Async.init();
}
public static void main(String[] args) throws Exception {
usingCompletableFuture();
usingAsyncAwait();
}
public static void usingCompletableFuture() throws InterruptedException, ExecutionException, Exception {
CompletableFuture<Void> completableFuture = hello()
.thenComposeAsync(hello -> mergeWorld(hello))
.thenAcceptAsync(helloWorld -> print(helloWorld))
.exceptionally( throwable -> {
System.out.println(throwable.getCause());
return null;
});
completableFuture.get();
}
public static CompletableFuture<String> hello() {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
return completableFuture;
}
|
public static CompletableFuture<String> mergeWorld(String s) {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
return s + " World!";
});
return completableFuture;
}
public static void print(String str) {
CompletableFuture.runAsync(() -> System.out.println(str));
}
private static void usingAsyncAwait() {
try {
String hello = await(hello());
String helloWorld = await(mergeWorld(hello));
await(CompletableFuture.runAsync(() -> print(helloWorld)));
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced\src\main\java\com\baeldung\async\EAAsyncExample.java
| 1
|
请完成以下Java代码
|
private byte[] toByteArray()
{
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (final PrintingDataToPDFWriter pdfWriter = new PrintingDataToPDFWriter(baos))
{
for (PrintingDataAndSegment printingDataAndSegment : segments)
{
pdfWriter.addArchivePartToPDF(printingDataAndSegment.getPrintingData(), printingDataAndSegment.getSegment());
}
}
return baos.toByteArray();
}
private String suggestFilename()
{
final ImmutableSet<String> filenames = segments.stream()
.map(PrintingDataAndSegment::getDocumentFileName)
.collect(ImmutableSet.toImmutableSet());
|
return filenames.size() == 1 ? filenames.iterator().next() : "report.pdf";
}
}
@Value(staticConstructor = "of")
private static class PrintingDataAndSegment
{
@NonNull PrintingData printingData;
@NonNull PrintingSegment segment;
public String getDocumentFileName()
{
return printingData.getDocumentFileName();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\frontend\FrontendPrinter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class RpPayGateWayPageShowVo {
/** 订单金额 **/
private BigDecimal orderAmount;
/** 产品名称 **/
private String productName;
/** 商户名称 **/
private String merchantName;
/** 商户订单号 **/
private String merchantOrderNo;
/** 商户支付key **/
private String payKey;
/** 支付方式列表 **/
private Map<String , PayTypeEnum> payTypeEnumMap;
public BigDecimal getOrderAmount() {
return orderAmount;
}
public void setOrderAmount(BigDecimal orderAmount) {
this.orderAmount = orderAmount;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getMerchantName() {
|
return merchantName;
}
public void setMerchantName(String merchantName) {
this.merchantName = merchantName;
}
public String getMerchantOrderNo() {
return merchantOrderNo;
}
public void setMerchantOrderNo(String merchantOrderNo) {
this.merchantOrderNo = merchantOrderNo;
}
public String getPayKey() {
return payKey;
}
public void setPayKey(String payKey) {
this.payKey = payKey;
}
public Map<String, PayTypeEnum> getPayTypeEnumMap() {
return payTypeEnumMap;
}
public void setPayTypeEnumMap(Map<String, PayTypeEnum> payTypeEnumMap) {
this.payTypeEnumMap = payTypeEnumMap;
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\RpPayGateWayPageShowVo.java
| 2
|
请完成以下Java代码
|
public class UserInputApplication extends SimpleApplication {
private boolean rotationEnabled = false;
public static void main(String[] args) {
UserInputApplication app = new UserInputApplication();
app.start();
}
public UserInputApplication() {
super(new StatsAppState());
}
@Override
public void simpleInitApp() {
Box mesh = new Box(1, 2, 3);
Geometry geometry = new Geometry("Box", mesh);
Material material = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
material.setColor("Color", ColorRGBA.Red);
geometry.setMaterial(material);
Node rotation = new Node("rotation");
rotation.attachChild(geometry);
rootNode.attachChild(rotation);
inputManager.addMapping("Rotate", new KeyTrigger(KeyInput.KEY_SPACE));
inputManager.addMapping("Left", new KeyTrigger(KeyInput.KEY_J));
inputManager.addMapping("Right", new KeyTrigger(KeyInput.KEY_K));
ActionListener actionListener = new ActionListener() {
@Override
public void onAction(String name, boolean isPressed, float tpf) {
if (name.equals("Rotate") && !isPressed) {
rotationEnabled = !rotationEnabled;
}
}
};
AnalogListener analogListener = new AnalogListener() {
|
@Override
public void onAnalog(String name, float value, float tpf) {
if (name.equals("Left")) {
rotation.rotate(0, -tpf, 0);
} else if (name.equals("Right")) {
rotation.rotate(0, tpf, 0);
}
}
};
inputManager.addListener(actionListener, "Rotate");
inputManager.addListener(analogListener, "Left", "Right");
}
@Override
public void simpleUpdate(float tpf) {
if (rotationEnabled) {
Spatial rotation = rootNode.getChild("rotation");
rotation.rotate(0, 0, tpf);
}
}
}
|
repos\tutorials-master\jmonkeyengine\src\main\java\com\baeldung\jmonkeyengine\UserInputApplication.java
| 1
|
请完成以下Java代码
|
private static AddToResultGroupRequest createAddToResultGroupRequest(final I_MD_Available_For_Sales_QueryResult result)
{
return AddToResultGroupRequest.builder()
.productId(ProductId.ofRepoId(result.getM_Product_ID()))
.storageAttributesKey(AttributesKey.ofString(result.getStorageAttributesKey()))
.qtyToBeShipped(result.getQtyToBeShipped())
.qtyOnHandStock(result.getQtyOnHandStock())
.queryNo(result.getQueryNo())
.warehouseId(WarehouseId.ofRepoId(result.getM_Warehouse_ID()))
.build();
}
public Set<AttributesKeyPattern> getPredefinedStorageAttributeKeys()
{
final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
final int clientId = Env.getAD_Client_ID(Env.getCtx());
final int orgId = Env.getAD_Org_ID(Env.getCtx());
final String storageAttributesKeys = sysConfigBL.getValue(
|
SYSCONFIG_AVAILABILITY_INFO_ATTRIBUTES_KEYS,
AttributesKey.ALL.getAsString(),
clientId, orgId);
return AttributesKeyPatternsUtil.parseCommaSeparatedString(storageAttributesKeys);
}
private static void validateResultUOM(@NonNull final I_MD_Available_For_Sales_QueryResult result, @NonNull final UomId stockUOMId)
{
if (result.getC_UOM_ID() != stockUOMId.getRepoId())
{
throw new AdempiereException("MD_Available_For_Sales_QueryResult is not in stock uom!")
.appendParametersToMessage()
.setParameter("Result.C_UOM_ID", result.getC_UOM_ID())
.setParameter("stockUOMId", stockUOMId.getRepoId());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\availableforsales\AvailableForSalesRepository.java
| 1
|
请完成以下Java代码
|
public class FullTextSearchLookupDescriptorProvider implements LookupDescriptorProvider
{
// services
private final Client elasticsearchClient;
private final LookupDataSourceFactory lookupDataSourceFactory;
private final String modelTableName;
private final String esIndexName;
private final ImmutableSet<String> esSearchFieldNames;
private final LookupDescriptorProvider databaseLookupDescriptorProvider;
private final transient Function<LookupScope, Optional<LookupDescriptor>> lookupDescriptorsByScope = Functions.memoizing(this::createLookupDescriptor);
@Builder
private FullTextSearchLookupDescriptorProvider(
@NonNull final LookupDataSourceFactory lookupDataSourceFactory,
@NonNull final Client elasticsearchClient,
@NonNull final String modelTableName,
@NonNull final String esIndexName,
@NonNull final Set<String> esSearchFieldNames,
@NonNull final LookupDescriptorProvider databaseLookupDescriptorProvider)
{
this.lookupDataSourceFactory = lookupDataSourceFactory;
this.elasticsearchClient = elasticsearchClient;
this.modelTableName = modelTableName;
this.esIndexName = esIndexName;
this.esSearchFieldNames = ImmutableSet.copyOf(esSearchFieldNames);
this.databaseLookupDescriptorProvider = databaseLookupDescriptorProvider;
}
@Override
public Optional<LookupDescriptor> provideForScope(final LookupScope scope)
{
return lookupDescriptorsByScope.apply(scope);
|
}
private Optional<LookupDescriptor> createLookupDescriptor(final LookupScope scope)
{
final LookupDescriptor databaseLookupDescriptor = databaseLookupDescriptorProvider.provideForScope(scope).orElse(null);
if (databaseLookupDescriptor == null)
{
return Optional.empty();
}
final LookupDataSource databaseLookup = lookupDataSourceFactory.createLookupDataSource(databaseLookupDescriptor);
final FullTextSearchLookupDescriptor lookupDescriptor = FullTextSearchLookupDescriptor.builder()
.elasticsearchClient(elasticsearchClient)
.modelTableName(modelTableName)
.esIndexName(esIndexName)
.esSearchFieldNames(esSearchFieldNames)
.sqlLookupDescriptor(databaseLookupDescriptor.castOrNull(ISqlLookupDescriptor.class))
.databaseLookup(databaseLookup)
.build();
return Optional.of(lookupDescriptor);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\FullTextSearchLookupDescriptorProvider.java
| 1
|
请完成以下Java代码
|
public boolean accept(I_C_Period pojo)
{
if (!pojo.getC_Year().equals(year))
{
return false;
}
if (!pojo.isActive())
{
return false;
}
if (pojo.getAD_Client_ID() != 0 && pojo.getAD_Client_ID() != Env.getAD_Client_ID(ctx))
{
return false;
}
return true;
}
});
|
Collections.sort(periods, new AccessorComparator<I_C_Period, Timestamp>(
new ComparableComparator<Timestamp>(),
new TypedAccessor<Timestamp>()
{
@Override
public Timestamp getValue(Object o)
{
return ((I_C_Period)o).getStartDate();
}
}));
return periods;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\calendar\impl\PlainCalendarDAO.java
| 1
|
请完成以下Java代码
|
protected List<IAttributeValue> loadAttributeValues()
{
final IAttributeSetInstanceBL asiBL = Services.get(IAttributeSetInstanceBL.class);
final ImmutableList.Builder<IAttributeValue> result = ImmutableList.builder();
final List<I_M_AttributeInstance> attributeInstances = asiBL.getAttributeInstances(asi);
for (final I_M_AttributeInstance attributeInstance : attributeInstances)
{
final IAttributeValue attributeValue = new AIAttributeValue(this, attributeInstance);
result.add(attributeValue);
}
return result.build();
}
@Override
protected List<IAttributeValue> generateAndGetInitialAttributes(final IAttributeValueContext attributesCtx, final Map<AttributeId, Object> defaultAttributesValue)
{
throw new UnsupportedOperationException("Generating initial attributes not supported for " + this);
}
@Override
public void updateHUTrxAttribute(final MutableHUTransactionAttribute huTrxAttribute, final IAttributeValue fromAttributeValue)
{
huTrxAttribute.setReferencedObject(asi);
}
/**
* Method not supported.
*
* @throws UnsupportedOperationException
*/
@Override
protected void addChildAttributeStorage(final IAttributeStorage childAttributeStorage)
{
throw new UnsupportedOperationException("Child attribute storages are not supported for " + this);
}
/**
* Method not supported.
*
|
* @throws UnsupportedOperationException
*/
@Override
protected IAttributeStorage removeChildAttributeStorage(final IAttributeStorage childAttributeStorage)
{
throw new UnsupportedOperationException("Child attribute storages are not supported for " + this);
}
@Override
public void saveChangesIfNeeded()
{
throw new UnsupportedOperationException();
}
@Override
public void setSaveOnChange(boolean saveOnChange)
{
throw new UnsupportedOperationException();
}
@Override
public UOMType getQtyUOMTypeOrNull()
{
// ASI attribute storages does not support Qty Storage
return null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\ASIAttributeStorage.java
| 1
|
请完成以下Java代码
|
private static String appendZeros(String a, int zeros) {
StringBuilder sb = new StringBuilder(a);
for (int i = 0; i < zeros; i++) {
sb.append('0');
}
return sb.toString();
}
private static String unsignedDivide(String a, String b) {
validateUnsignedBinaryString(a);
validateUnsignedBinaryString(b);
if (compareBinaryStrings(b, a) > 0) {
return "0";
}
// Remove leading zeros
a = a.replaceFirst("^0+(?!$)", "");
b = b.replaceFirst("^0+(?!$)", "");
if (b.equals("0")) {
throw new ArithmeticException("Division by zero is not allowed");
}
StringBuilder result = new StringBuilder(a.length());
String remainder = "";
// Iterate through each bit of the dividend "a" from MSB to LSB
for (int i = 0; i < a.length(); i++) {
if (result.length() == 0) {
// Initialize result and remainder if not yet done
if (compareBinaryStrings(a.substring(0, i + 1), b) >= 0) {
result.append('1');
remainder = unsignedSubtract(a.substring(0, i + 1), b);
}
} else {
// Concatenate the current bit of "a" to the remainder
remainder += a.charAt(i);
// Compare the current remainder with the divisor "b"
if (compareBinaryStrings(remainder, b) >= 0) {
// If remainder is greater than or equal to divisor, append '1' to result
|
result.append('1');
// Subtract divisor "b" from remainder
remainder = unsignedSubtract(remainder, b);
} else {
// If remainder is less than divisor, append '0' to result
result.append('0');
}
}
}
return result.toString();
}
private static String removePlusMinus(String s) {
if (s == null || s.isEmpty()) {
throw new IllegalArgumentException("The string cannot be null or empty");
}
if (s.startsWith("+") || s.startsWith("-")) {
return s.substring(1);
}
return s;
}
private static boolean isPositive(String s) {
if (s == null || s.isEmpty()) {
throw new IllegalArgumentException("String cannot be null or empty");
}
char firstChar = s.charAt(0);
if (firstChar == '+' || firstChar == '0' || firstChar == '1') {
return true;
} else if (firstChar == '-') {
return false;
} else {
throw new IllegalArgumentException("String does not start with a valid character");
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-numbers-8\src\main\java\com\baeldung\arbitrarylengthbinaryintegers\BinaryStringOperations.java
| 1
|
请完成以下Java代码
|
public Map<String, Command> getCommands() {
return commands;
}
public void setCommands(Map<String, Command> commands) {
this.commands = commands;
}
public void putCommand(String commandName, int count) {
if (commands == null) {
commands = new HashMap<>();
}
commands.put(commandName, new CommandImpl(count));
}
@Override
public Map<String, Metric> getMetrics() {
return metrics;
}
public void setMetrics(Map<String, Metric> metrics) {
this.metrics = metrics;
}
public void putMetric(String metricName, int count) {
if (metrics == null) {
metrics = new HashMap<>();
}
metrics.put(metricName, new MetricImpl(count));
}
public void mergeDynamicData(InternalsImpl other) {
this.commands = other.commands;
this.metrics = other.metrics;
}
@Override
public JdkImpl getJdk() {
return jdk;
}
public void setJdk(JdkImpl jdk) {
this.jdk = jdk;
}
@Override
public Set<String> getCamundaIntegration() {
return camundaIntegration;
}
|
public void setCamundaIntegration(Set<String> camundaIntegration) {
this.camundaIntegration = camundaIntegration;
}
@Override
public LicenseKeyDataImpl getLicenseKey() {
return licenseKey;
}
public void setLicenseKey(LicenseKeyDataImpl licenseKey) {
this.licenseKey = licenseKey;
}
@Override
public Set<String> getWebapps() {
return webapps;
}
public void setWebapps(Set<String> webapps) {
this.webapps = webapps;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\telemetry\dto\InternalsImpl.java
| 1
|
请完成以下Java代码
|
public String getPermissionName() {
return permissionName;
}
public void setPermissionName(String permissionName) {
this.permissionName = permissionName;
}
public Boolean isAuthorized() {
return isAuthorized;
}
public void setAuthorized(Boolean isAuthorized) {
this.isAuthorized = isAuthorized;
}
|
public String getResourceName() {
return resourceName;
}
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
public String getResourceId() {
return resourceId;
}
public void setResourceId(String resourceId) {
this.resourceId = resourceId;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\authorization\AuthorizationCheckResultDto.java
| 1
|
请完成以下Java代码
|
public List<Customer> findAll() {
String sql = "SELECT * FROM CUSTOMER";
List<Customer> customers = new ArrayList<>();
List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);
for (Map row : rows) {
Customer obj = new Customer();
obj.setID(((Integer) row.get("ID")).longValue());
//obj.setID(((Long) row.get("ID"))); no, ClassCastException
obj.setName((String) row.get("NAME"));
obj.setAge(((BigDecimal) row.get("AGE")).intValue()); // Spring returns BigDecimal, need convert
obj.setCreatedDate(((Timestamp) row.get("CREATED_DATE")).toLocalDateTime());
customers.add(obj);
}
return customers;
}
public List<Customer> findAll2() {
String sql = "SELECT * FROM CUSTOMER";
List<Customer> customers = jdbcTemplate.query(
sql,
new CustomerRowMapper());
return customers;
}
public List<Customer> findAll3() {
String sql = "SELECT * FROM CUSTOMER";
List<Customer> customers = jdbcTemplate.query(
sql,
new BeanPropertyRowMapper(Customer.class));
return customers;
}
public List<Customer> findAll4() {
String sql = "SELECT * FROM CUSTOMER";
|
return jdbcTemplate.query(
sql,
(rs, rowNum) ->
new Customer(
rs.getLong("id"),
rs.getString("name"),
rs.getInt("age"),
rs.getTimestamp("created_date").toLocalDateTime()
)
);
}
public String findCustomerNameById(Long id) {
String sql = "SELECT NAME FROM CUSTOMER WHERE ID = ?";
return jdbcTemplate.queryForObject(
sql, new Object[]{id}, String.class);
}
public int count() {
String sql = "SELECT COUNT(*) FROM CUSTOMER";
// queryForInt() is Deprecated
// https://www.mkyong.com/spring/jdbctemplate-queryforint-is-deprecated/
//int total = jdbcTemplate.queryForInt(sql);
return jdbcTemplate.queryForObject(sql, Integer.class);
}
}
|
repos\spring-boot-master\spring-jdbc\src\main\java\com\mkyong\customer\CustomerRepository.java
| 1
|
请完成以下Java代码
|
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 C_Aggregation_Builder end()
{
return parentBuilder;
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
public C_AggregationItem_Builder setC_Aggregation(final I_C_Aggregation aggregation)
{
this.aggregation = aggregation;
return this;
}
private I_C_Aggregation getC_Aggregation()
{
Check.assumeNotNull(aggregation, "aggregation not null");
return aggregation;
}
public C_AggregationItem_Builder setType(final String type)
{
this.type = type;
return this;
}
private String getType()
{
Check.assumeNotEmpty(type, "type not empty");
return type;
}
public C_AggregationItem_Builder setAD_Column(@Nullable final String columnName)
{
if (isBlank(columnName))
{
this.adColumnId = null;
}
else
{
this.adColumnId = Services.get(IADTableDAO.class).retrieveColumnId(adTableId, columnName);
}
return this;
}
private AdColumnId getAD_Column_ID()
{
return adColumnId;
}
|
public C_AggregationItem_Builder setIncluded_Aggregation(final I_C_Aggregation includedAggregation)
{
this.includedAggregation = includedAggregation;
return this;
}
private I_C_Aggregation getIncluded_Aggregation()
{
return includedAggregation;
}
public C_AggregationItem_Builder setIncludeLogic(final String includeLogic)
{
this.includeLogic = includeLogic;
return this;
}
private String getIncludeLogic()
{
return includeLogic;
}
public C_AggregationItem_Builder setC_Aggregation_Attribute(I_C_Aggregation_Attribute attribute)
{
this.attribute = attribute;
return this;
}
private I_C_Aggregation_Attribute getC_Aggregation_Attribute()
{
return this.attribute;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\model\C_AggregationItem_Builder.java
| 1
|
请完成以下Java代码
|
public void setOptOutDate (Timestamp OptOutDate)
{
set_ValueNoCheck (COLUMNNAME_OptOutDate, OptOutDate);
}
/** Get Opt-out Date.
@return Date the contact opted out
*/
public Timestamp getOptOutDate ()
{
return (Timestamp)get_Value(COLUMNNAME_OptOutDate);
}
public I_R_InterestArea getR_InterestArea() throws RuntimeException
{
return (I_R_InterestArea)MTable.get(getCtx(), I_R_InterestArea.Table_Name)
.getPO(getR_InterestArea_ID(), get_TrxName()); }
/** Set Interest Area.
@param R_InterestArea_ID
Interest Area or Topic
*/
public void setR_InterestArea_ID (int R_InterestArea_ID)
{
if (R_InterestArea_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_InterestArea_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_InterestArea_ID, Integer.valueOf(R_InterestArea_ID));
}
/** Get Interest Area.
@return Interest Area or Topic
*/
|
public int getR_InterestArea_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_InterestArea_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Subscribe Date.
@param SubscribeDate
Date the contact actively subscribed
*/
public void setSubscribeDate (Timestamp SubscribeDate)
{
set_ValueNoCheck (COLUMNNAME_SubscribeDate, SubscribeDate);
}
/** Get Subscribe Date.
@return Date the contact actively subscribed
*/
public Timestamp getSubscribeDate ()
{
return (Timestamp)get_Value(COLUMNNAME_SubscribeDate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_ContactInterest.java
| 1
|
请完成以下Java代码
|
public void schemaCreate() {
if (isUpdateNeeded()) {
String dbVersion = getSchemaVersion();
if (!FlowableVersions.CURRENT_VERSION.equals(dbVersion)) {
throw new FlowableWrongDbException(FlowableVersions.CURRENT_VERSION, dbVersion);
}
} else {
internalDbSchemaCreate();
}
}
protected void internalDbSchemaCreate() {
executeMandatorySchemaResource("create", schemaComponent);
}
@Override
public void schemaDrop() {
try {
executeMandatorySchemaResource("drop", schemaComponent);
} catch (Exception e) {
logger.info("Error dropping {} tables", schemaComponent, e);
}
}
@Override
public String schemaUpdate() {
return schemaUpdate(null);
}
@Override
public String schemaUpdate(String engineDbVersion) {
String feedback = null;
if (isUpdateNeeded()) {
String dbVersion = getSchemaVersion();
String compareWithVersion = null;
if (dbVersion == null) {
compareWithVersion = "6.1.2.0"; // last version before services were separated. Start upgrading from this point.
} else {
compareWithVersion = dbVersion;
}
int matchingVersionIndex = FlowableVersions.getFlowableVersionIndexForDbVersion(compareWithVersion);
boolean isUpgradeNeeded = (matchingVersionIndex != (FlowableVersions.FLOWABLE_VERSIONS.size() - 1));
if (isUpgradeNeeded) {
dbSchemaUpgrade(schemaComponent, matchingVersionIndex, engineDbVersion);
}
feedback = "upgraded from " + compareWithVersion + " to " + FlowableVersions.CURRENT_VERSION;
} else {
schemaCreate();
|
}
return feedback;
}
@Override
public void schemaCheckVersion() {
String dbVersion = getSchemaVersion();
if (!FlowableVersions.CURRENT_VERSION.equals(dbVersion)) {
throw new FlowableWrongDbException(FlowableVersions.CURRENT_VERSION, dbVersion);
}
}
protected boolean isUpdateNeeded() {
return isTablePresent(table);
}
protected String getSchemaVersion() {
if (schemaVersionProperty == null) {
throw new FlowableException("Schema version property is not set");
}
String dbVersion = getProperty(schemaVersionProperty);
if (dbVersion == null) {
return getUpgradeStartVersion();
}
return dbVersion;
}
protected String getUpgradeStartVersion() {
return "6.1.2.0"; // last version before most services were separated. Start upgrading from this point.
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\db\ServiceSqlScriptBasedDbSchemaManager.java
| 1
|
请完成以下Java代码
|
default boolean isAllowNonTransactional() {
return false;
}
/**
* Return true if the template is currently running in a transaction on the calling
* thread.
* @return true if a transaction is running.
* @since 2.5
*/
default boolean inTransaction() {
return false;
}
/**
* Return the producer factory used by this template.
* @return the factory.
* @since 2.5
*/
default ProducerFactory<K, V> getProducerFactory() {
throw new UnsupportedOperationException("This implementation does not support this operation");
}
/**
* Receive a single record with the default poll timeout (5 seconds).
* @param topic the topic.
* @param partition the partition.
* @param offset the offset.
* @return the record or null.
* @since 2.8
* @see #DEFAULT_POLL_TIMEOUT
*/
@Nullable
default ConsumerRecord<K, V> receive(String topic, int partition, long offset) {
return receive(topic, partition, offset, DEFAULT_POLL_TIMEOUT);
}
/**
* Receive a single record.
* @param topic the topic.
* @param partition the partition.
* @param offset the offset.
* @param pollTimeout the timeout.
* @return the record or null.
* @since 2.8
*/
@Nullable
ConsumerRecord<K, V> receive(String topic, int partition, long offset, Duration pollTimeout);
/**
* Receive a multiple records with the default poll timeout (5 seconds). Only
* absolute, positive offsets are supported.
* @param requested a collection of record requests (topic/partition/offset).
* @return the records
* @since 2.8
* @see #DEFAULT_POLL_TIMEOUT
|
*/
default ConsumerRecords<K, V> receive(Collection<TopicPartitionOffset> requested) {
return receive(requested, DEFAULT_POLL_TIMEOUT);
}
/**
* Receive multiple records. Only absolute, positive offsets are supported.
* @param requested a collection of record requests (topic/partition/offset).
* @param pollTimeout the timeout.
* @return the record or null.
* @since 2.8
*/
ConsumerRecords<K, V> receive(Collection<TopicPartitionOffset> requested, Duration pollTimeout);
/**
* A callback for executing arbitrary operations on the {@link Producer}.
* @param <K> the key type.
* @param <V> the value type.
* @param <T> the return type.
* @since 1.3
*/
interface ProducerCallback<K, V, T> {
T doInKafka(Producer<K, V> producer);
}
/**
* A callback for executing arbitrary operations on the {@link KafkaOperations}.
* @param <K> the key type.
* @param <V> the value type.
* @param <T> the return type.
* @since 1.3
*/
interface OperationsCallback<K, V, T> {
@Nullable
T doInOperations(KafkaOperations<K, V> operations);
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\core\KafkaOperations.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.