instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Spring Boot application配置 | server:
http2:
enabled: false
port: 8443
ssl:
enabled: true
key-store: classpath:keystore.p12
key-store-password: ab | cd1234
key-store-type: PKCS12
key-alias: http2-alias | repos\tutorials-master\spring-boot-modules\spring-boot-http2\src\main\resources\application-config-class.yml | 2 |
请在Spring Boot框架中完成以下Java代码 | public Builder relayState(String relayState) {
this.parameters.put(Saml2ParameterNames.RELAY_STATE, relayState);
return this;
}
/**
* This is the unique id used in the {@link #samlRequest}
* @param id the Logout Request id
* @return the {@link Builder} for further configurations
*/
public Builder id(String id) {
this.id = id;
return this;
}
/**
* Use this {@link Consumer} to modify the set of query parameters
*
* No parameter should be URL-encoded as this will be done when the request is
* sent
* @param parametersConsumer the {@link Consumer}
* @return the {@link Builder} for further configurations
*/
public Builder parameters(Consumer<Map<String, String>> parametersConsumer) {
parametersConsumer.accept(this.parameters);
return this;
}
/**
* Use this strategy for converting parameters into an encoded query string. The
* resulting query does not contain a leading question mark. | *
* In the event that you already have an encoded version that you want to use, you
* can call this by doing {@code parameterEncoder((params) -> encodedValue)}.
* @param encoder the strategy to use
* @return the {@link Builder} for further configurations
* @since 5.8
*/
public Builder parametersQuery(Function<Map<String, String>, String> encoder) {
this.encoder = encoder;
return this;
}
/**
* Build the {@link Saml2LogoutRequest}
* @return a constructed {@link Saml2LogoutRequest}
*/
public Saml2LogoutRequest build() {
return new Saml2LogoutRequest(this.location, this.binding, this.parameters, this.id,
this.registration.getRegistrationId(), this.encoder);
}
}
} | repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\logout\Saml2LogoutRequest.java | 2 |
请完成以下Java代码 | public final class Sql
{
@NonNull private final Instant timestamp = SystemTime.asInstant();
@Nullable private final String sqlCommand2;
@NonNull private final SqlParams sqlParams;
@Nullable private final String comment;
private transient String _sqlWithInlinedParams = null; // lazy
private static final SqlParamsInliner sqlParamsInliner = SqlParamsInliner.builder().failOnError(true).build();
public static Sql ofSql(@NonNull final String sql)
{
return new Sql(sql, null, null);
}
public static Sql ofSql(@NonNull final String sql, @Nullable Map<Integer, Object> sqlParamsMap)
{
return new Sql(sql, SqlParams.ofMap(sqlParamsMap), null);
}
public static Sql ofSql(@NonNull final String sql, @Nullable SqlParams sqlParamsMap)
{
return new Sql(sql, sqlParamsMap, null);
}
public static Sql ofComment(@NonNull final String comment) {return new Sql(null, null, comment);}
private Sql(
@Nullable final String sqlCommand,
@Nullable final SqlParams sqlParams,
@Nullable final String comment)
{
this.sqlCommand2 = StringUtils.trimBlankToNull(sqlCommand);
this.sqlParams = sqlParams != null ? sqlParams : SqlParams.EMPTY;
this.comment = StringUtils.trimBlankToNull(comment);
}
@Override
@Deprecated
public String toString() {return toSql();}
public boolean isEmpty() {return sqlCommand2 == null && comment == null;}
public String getSqlCommand() {return sqlCommand2 != null ? sqlCommand2 : "";} | public String toSql()
{
String sqlWithInlinedParams = this._sqlWithInlinedParams;
if (sqlWithInlinedParams == null)
{
sqlWithInlinedParams = this._sqlWithInlinedParams = buildFinalSql();
}
return sqlWithInlinedParams;
}
private String buildFinalSql()
{
final StringBuilder finalSql = new StringBuilder();
final String sqlComment = toSqlCommentLine(comment);
if (sqlComment != null)
{
finalSql.append(sqlComment);
}
if (sqlCommand2 != null && !sqlCommand2.isEmpty())
{
finalSql.append(toSqlCommentLine(timestamp.toString()));
final String sqlWithParams = !sqlParams.isEmpty()
? sqlParamsInliner.inline(sqlCommand2, sqlParams.toList())
: sqlCommand2;
finalSql.append(sqlWithParams).append("\n;\n\n");
}
return finalSql.toString();
}
private static String toSqlCommentLine(@Nullable final String comment)
{
final String commentNorm = StringUtils.trimBlankToNull(comment);
if (commentNorm == null)
{
return null;
}
return "-- "
+ commentNorm
.replace("\r\n", "\n")
.replace("\n", "\n-- ")
+ "\n";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\logger\Sql.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DefaultDeploymentHandler implements DeploymentHandler {
protected ProcessEngine processEngine;
protected RepositoryService repositoryService;
public DefaultDeploymentHandler(ProcessEngine processEngine) {
this.processEngine = processEngine;
this.repositoryService = processEngine.getRepositoryService();
}
@Override
public boolean shouldDeployResource(Resource newResource, Resource existingResource) {
return resourcesDiffer(newResource, existingResource);
}
@Override
public String determineDuplicateDeployment(CandidateDeployment candidateDeployment) {
return Context.getCommandContext()
.getDeploymentManager()
.findLatestDeploymentByName(candidateDeployment.getName())
.getId();
}
@Override
public Set<String> determineDeploymentsToResumeByProcessDefinitionKey(
String[] processDefinitionKeys) {
Set<String> deploymentIds = new HashSet<>();
List<ProcessDefinition> processDefinitions = Context.getCommandContext().getProcessDefinitionManager()
.findProcessDefinitionsByKeyIn(processDefinitionKeys);
for (ProcessDefinition processDefinition : processDefinitions) {
deploymentIds.add(processDefinition.getDeploymentId());
}
return deploymentIds;
}
@Override
public Set<String> determineDeploymentsToResumeByDeploymentName(CandidateDeployment candidateDeployment) {
List<Deployment> previousDeployments = processEngine.getRepositoryService() | .createDeploymentQuery()
.deploymentName(candidateDeployment.getName())
.list();
Set<String> deploymentIds = new HashSet<>();
for (Deployment deployment : previousDeployments) {
deploymentIds.add(deployment.getId());
}
return deploymentIds;
}
protected boolean resourcesDiffer(Resource resource, Resource existing) {
byte[] bytes = resource.getBytes();
byte[] savedBytes = existing.getBytes();
return !Arrays.equals(bytes, savedBytes);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\repository\DefaultDeploymentHandler.java | 2 |
请完成以下Java代码 | public LUTUAssignBuilder setDocumentLine(final IHUDocumentLine documentLine)
{
assertConfigurable();
_documentLine = documentLine;
return this;
}
private IHUDocumentLine getDocumentLine()
{
return _documentLine; // null is ok
}
public LUTUAssignBuilder setC_BPartner(final I_C_BPartner bpartner)
{
assertConfigurable();
this._bpartnerId = bpartner != null ? BPartnerId.ofRepoId(bpartner.getC_BPartner_ID()) : null;
return this;
}
private final BPartnerId getBPartnerId()
{
return _bpartnerId;
}
public LUTUAssignBuilder setC_BPartner_Location_ID(final int bpartnerLocationId)
{
assertConfigurable();
_bpLocationId = bpartnerLocationId;
return this;
} | private final int getC_BPartner_Location_ID()
{
return _bpLocationId;
}
public LUTUAssignBuilder setM_Locator(final I_M_Locator locator)
{
assertConfigurable();
_locatorId = LocatorId.ofRecordOrNull(locator);
return this;
}
private LocatorId getLocatorId()
{
Check.assumeNotNull(_locatorId, "_locatorId not null");
return _locatorId;
}
public LUTUAssignBuilder setHUStatus(final String huStatus)
{
assertConfigurable();
_huStatus = huStatus;
return this;
}
private String getHUStatus()
{
Check.assumeNotEmpty(_huStatus, "_huStatus not empty");
return _huStatus;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\impl\LUTUAssignBuilder.java | 1 |
请完成以下Java代码 | protected Function<List<Val>, Val> transformFunction(CustomFunction function) {
return args -> {
List<Object> unpackedArgs = unpackVals(args);
Function<List<Object>, Object> functionHandler = function.getFunction();
Object result = functionHandler.apply(unpackedArgs);
return toVal(result);
};
}
protected List<Object> unpackVals(List<Val> args) {
return args.stream()
.map(this::unpackVal)
.collect(Collectors.toList());
}
protected Val toVal(Object rawResult) {
return valueMapper.toVal(rawResult);
} | protected Object unpackVal(Val arg) {
return valueMapper.unpackVal(arg);
}
@Override
public Optional<JavaFunction> resolveFunction(String functionName) {
return Optional.ofNullable(functions.get(functionName));
}
@Override
public Collection<String> getFunctionNames() {
return functions.keySet();
}
} | repos\camunda-bpm-platform-master\engine-dmn\feel-scala\src\main\java\org\camunda\bpm\dmn\feel\impl\scala\function\CustomFunctionTransformer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | org.apache.commons.dbcp2.BasicDataSource dataSource(DataSourceProperties properties,
JdbcConnectionDetails connectionDetails) {
Class<? extends DataSource> dataSourceType = org.apache.commons.dbcp2.BasicDataSource.class;
return createDataSource(connectionDetails, dataSourceType, properties.getClassLoader());
}
}
/**
* Oracle UCP DataSource configuration.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ PoolDataSourceImpl.class, OracleConnection.class })
@ConditionalOnMissingBean(DataSource.class)
@ConditionalOnProperty(name = "spring.datasource.type", havingValue = "oracle.ucp.jdbc.PoolDataSource",
matchIfMissing = true)
static class OracleUcp {
@Bean
static OracleUcpJdbcConnectionDetailsBeanPostProcessor oracleUcpJdbcConnectionDetailsBeanPostProcessor(
ObjectProvider<JdbcConnectionDetails> connectionDetailsProvider) {
return new OracleUcpJdbcConnectionDetailsBeanPostProcessor(connectionDetailsProvider);
}
@Bean
@ConfigurationProperties("spring.datasource.oracleucp")
PoolDataSourceImpl dataSource(DataSourceProperties properties, JdbcConnectionDetails connectionDetails) | throws SQLException {
PoolDataSourceImpl dataSource = createDataSource(connectionDetails, PoolDataSourceImpl.class,
properties.getClassLoader());
if (StringUtils.hasText(properties.getName())) {
dataSource.setConnectionPoolName(properties.getName());
}
return dataSource;
}
}
/**
* Generic DataSource configuration.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(DataSource.class)
@ConditionalOnProperty(name = "spring.datasource.type")
static class Generic {
@Bean
DataSource dataSource(DataSourceProperties properties, JdbcConnectionDetails connectionDetails) {
return createDataSource(connectionDetails, properties.getType(), properties.getClassLoader());
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\DataSourceConfiguration.java | 2 |
请完成以下Java代码 | public class PrimitiveClass {
private boolean primitiveBoolean;
private int primitiveInt;
public PrimitiveClass(boolean primitiveBoolean, int primitiveInt) {
super();
this.primitiveBoolean = primitiveBoolean;
this.primitiveInt = primitiveInt;
}
protected boolean isPrimitiveBoolean() {
return primitiveBoolean;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (primitiveBoolean ? 1231 : 1237);
result = prime * result + primitiveInt;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null) | return false;
if (getClass() != obj.getClass())
return false;
PrimitiveClass other = (PrimitiveClass) obj;
if (primitiveBoolean != other.primitiveBoolean)
return false;
if (primitiveInt != other.primitiveInt)
return false;
return true;
}
protected void setPrimitiveBoolean(boolean primitiveBoolean) {
this.primitiveBoolean = primitiveBoolean;
}
protected int getPrimitiveInt() {
return primitiveInt;
}
protected void setPrimitiveInt(int primitiveInt) {
this.primitiveInt = primitiveInt;
}
} | repos\tutorials-master\core-java-modules\core-java-lang-8\src\main\java\com\baeldung\equalshashcode\entities\PrimitiveClass.java | 1 |
请完成以下Java代码 | public String hello(String name) {
// 获得服务 `demo-provider` 的一个实例
ServiceInstance instance = loadBalancerClient.choose("demo-provider");
// 发起调用
String targetUrl = instance.getUri() + "/echo?name=" + name;
String response = restTemplate.getForObject(targetUrl, String.class);
// 返回结果
return "consumer:" + response;
}
@GetMapping("/hello02")
public String hello02(String name) {
// 直接使用 RestTemplate 调用服务 `demo-provider`
String targetUrl = "http://demo-provider/echo?name=" + name;
String response = restTemplate.getForObject(targetUrl, String.class); | // 返回结果
return "consumer:" + response;
}
// @GetMapping("/hello03")
// public String hello03(String name) {
// // 直接使用 RestTemplate 调用服务 `demo-provider`
// String targetUrl = "http://demo-provider-2/echo?name=" + name;
// String response = restTemplate.getForObject(targetUrl, String.class);
// // 返回结果
// return "consumer:" + response;
// }
}
} | repos\SpringBoot-Labs-master\labx-02-spring-cloud-netflix-ribbon\labx-02-scn-ribbon-demo02B-consumer\src\main\java\cn\iocoder\springcloudnetflix\labx02\ribbondemo\consumer\DemoConsumerApplication.java | 1 |
请完成以下Java代码 | private LocalDate computeNextTwiceMonthlyInvoiceDate(@NonNull final LocalDate deliveryDate)
{
final LocalDate dateToInvoice;
final LocalDate middleDayOfMonth = deliveryDate.withDayOfMonth(15);
// tasks 08484, 08869
if (deliveryDate.isAfter(middleDayOfMonth))
{
dateToInvoice = deliveryDate.with(lastDayOfMonth());
}
else
{
dateToInvoice = middleDayOfMonth;
}
return dateToInvoice;
}
private LocalDate computeNextMonthlyInvoiceDate( | @NonNull final LocalDate deliveryDate,
final int offset)
{
final LocalDate dateToInvoice;
final int invoiceDayOfMonthToUse = Integer.min(deliveryDate.lengthOfMonth(), getInvoiceDayOfMonth());
final LocalDate deliveryDateWithDayOfMonth = deliveryDate.withDayOfMonth(invoiceDayOfMonthToUse);
if (!deliveryDateWithDayOfMonth.isAfter(deliveryDate))
{
dateToInvoice = deliveryDateWithDayOfMonth.plus(1 + offset, ChronoUnit.MONTHS);
}
else
{
dateToInvoice = deliveryDateWithDayOfMonth.plus(offset, ChronoUnit.MONTHS);
}
return dateToInvoice;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\InvoiceSchedule.java | 1 |
请完成以下Java代码 | protected List<ActivityInstance> getActivityInstancesForActivity(ActivityInstance tree, Set<String> parentScopeIds) {
// prune all search paths that are not in the scope hierarchy of the activity in question
if (!parentScopeIds.contains(tree.getActivityId())) {
return Collections.emptyList();
}
List<ActivityInstance> instances = new ArrayList<ActivityInstance>();
if (activityId.equals(tree.getActivityId())) {
instances.add(tree);
}
for (ActivityInstance child : tree.getChildActivityInstances()) {
instances.addAll(getActivityInstancesForActivity(child, parentScopeIds));
}
return instances;
}
public ActivityInstance getActivityInstanceTree(final CommandContext commandContext) {
return commandContext.runWithoutAuthorization(new GetActivityInstanceCmd(processInstanceId));
}
public String getActivityId() {
return activityId;
}
public void setActivityInstanceTreeToCancel(ActivityInstance activityInstanceTreeToCancel) {
this.activityInstanceTree = activityInstanceTreeToCancel;
}
@Override
protected String describe() {
return "Cancel all instances of activity '" + activityId + "'";
}
public List<AbstractInstanceCancellationCmd> createActivityInstanceCancellations(ActivityInstance activityInstanceTree, CommandContext commandContext) {
List<AbstractInstanceCancellationCmd> commands = new ArrayList<AbstractInstanceCancellationCmd>();
ExecutionEntity processInstance = commandContext.getExecutionManager().findExecutionById(processInstanceId);
ProcessDefinitionImpl processDefinition = processInstance.getProcessDefinition(); | Set<String> parentScopeIds = collectParentScopeIdsForActivity(processDefinition, activityId);
List<ActivityInstance> childrenForActivity = getActivityInstancesForActivity(activityInstanceTree, parentScopeIds);
for (ActivityInstance instance : childrenForActivity) {
commands.add(new ActivityInstanceCancellationCmd(processInstanceId, instance.getId()));
}
List<TransitionInstance> transitionInstancesForActivity = getTransitionInstancesForActivity(activityInstanceTree, parentScopeIds);
for (TransitionInstance instance : transitionInstancesForActivity) {
commands.add(new TransitionInstanceCancellationCmd(processInstanceId, instance.getId()));
}
return commands;
}
public boolean isCancelCurrentActiveActivityInstances() {
return cancelCurrentActiveActivityInstances;
}
public void setCancelCurrentActiveActivityInstances(boolean cancelCurrentActiveActivityInstances) {
this.cancelCurrentActiveActivityInstances = cancelCurrentActiveActivityInstances;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\ActivityCancellationCmd.java | 1 |
请完成以下Java代码 | public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "Passenger{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + '}'; | }
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Passenger passenger = (Passenger) o;
return Objects.equals(firstName, passenger.firstName) && Objects.equals(lastName, passenger.lastName);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName);
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-repo-2\src\main\java\com\baeldung\jpa\domain\Passenger.java | 1 |
请完成以下Java代码 | default String getSubject() {
return this.getClaimAsString(JwtClaimNames.SUB);
}
/**
* Returns the Audience {@code (aud)} claim which identifies the recipient(s) that the
* JWT is intended for.
* @return the Audience(s) that this JWT intended for
*/
default List<String> getAudience() {
return this.getClaimAsStringList(JwtClaimNames.AUD);
}
/**
* Returns the Expiration time {@code (exp)} claim which identifies the expiration
* time on or after which the JWT MUST NOT be accepted for processing.
* @return the Expiration time on or after which the JWT MUST NOT be accepted for
* processing
*/
default Instant getExpiresAt() {
return this.getClaimAsInstant(JwtClaimNames.EXP);
}
/**
* Returns the Not Before {@code (nbf)} claim which identifies the time before which
* the JWT MUST NOT be accepted for processing.
* @return the Not Before time before which the JWT MUST NOT be accepted for
* processing
*/
default Instant getNotBefore() {
return this.getClaimAsInstant(JwtClaimNames.NBF);
}
/**
* Returns the Issued at {@code (iat)} claim which identifies the time at which the | * JWT was issued.
* @return the Issued at claim which identifies the time at which the JWT was issued
*/
default Instant getIssuedAt() {
return this.getClaimAsInstant(JwtClaimNames.IAT);
}
/**
* Returns the JWT ID {@code (jti)} claim which provides a unique identifier for the
* JWT.
* @return the JWT ID claim which provides a unique identifier for the JWT
*/
default String getId() {
return this.getClaimAsString(JwtClaimNames.JTI);
}
} | repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JwtClaimAccessor.java | 1 |
请完成以下Java代码 | public LocalDate getDateAcct()
{
if (dateAcctSet)
{
return dateAcct;
}
else if (defaults != null)
{
return defaults.getDateAcct();
}
else
{
return null;
}
}
public void setDateAcct(final LocalDate dateAcct)
{
this.dateAcct = dateAcct;
dateAcctSet = true;
}
@Nullable
@Override
public String getPOReference()
{
if (poReferenceSet)
{
return poReference;
}
else if (defaults != null)
{
return defaults.getPOReference();
}
else
{
return null;
}
}
public void setPOReference(@Nullable final String poReference)
{
this.poReference = poReference;
poReferenceSet = true;
}
@Nullable
@Override
public BigDecimal getCheck_NetAmtToInvoice()
{
if (check_NetAmtToInvoice != null)
{
return check_NetAmtToInvoice;
}
else if (defaults != null)
{
return defaults.getCheck_NetAmtToInvoice();
}
return null;
}
@Override
public boolean isStoreInvoicesInResult()
{
if (storeInvoicesInResult != null)
{
return storeInvoicesInResult;
}
else if (defaults != null)
{
return defaults.isStoreInvoicesInResult();
}
else
{ | return false;
}
}
public PlainInvoicingParams setStoreInvoicesInResult(final boolean storeInvoicesInResult)
{
this.storeInvoicesInResult = storeInvoicesInResult;
return this;
}
@Override
public boolean isAssumeOneInvoice()
{
if (assumeOneInvoice != null)
{
return assumeOneInvoice;
}
else if (defaults != null)
{
return defaults.isAssumeOneInvoice();
}
else
{
return false;
}
}
public PlainInvoicingParams setAssumeOneInvoice(final boolean assumeOneInvoice)
{
this.assumeOneInvoice = assumeOneInvoice;
return this;
}
public boolean isUpdateLocationAndContactForInvoice()
{
return updateLocationAndContactForInvoice;
}
public void setUpdateLocationAndContactForInvoice(boolean updateLocationAndContactForInvoice)
{
this.updateLocationAndContactForInvoice = updateLocationAndContactForInvoice;
}
public PlainInvoicingParams setCompleteInvoices(final boolean completeInvoices)
{
this.completeInvoices = completeInvoices;
return this;
}
@Override
public boolean isCompleteInvoices()
{
return completeInvoices;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\PlainInvoicingParams.java | 1 |
请完成以下Java代码 | public Iterator<TermFrequency> iterator()
{
return termFrequencyMap.values().iterator();
}
@Override
public Object[] toArray()
{
return termFrequencyMap.values().toArray();
}
@Override
public <T> T[] toArray(T[] a)
{
return termFrequencyMap.values().toArray(a);
}
@Override
public boolean add(TermFrequency termFrequency)
{
TermFrequency tf = termFrequencyMap.get(termFrequency.getTerm());
if (tf == null)
{
termFrequencyMap.put(termFrequency.getKey(), termFrequency);
return true;
}
tf.increase(termFrequency.getFrequency());
return false;
}
@Override
public boolean remove(Object o)
{
return termFrequencyMap.remove(o) != null;
}
@Override
public boolean containsAll(Collection<?> c)
{
for (Object o : c)
{
if (!contains(o))
return false;
}
return true;
}
@Override
public boolean addAll(Collection<? extends TermFrequency> c)
{
for (TermFrequency termFrequency : c)
{
add(termFrequency);
}
return !c.isEmpty();
}
@Override
public boolean removeAll(Collection<?> c)
{
for (Object o : c)
{
if (!remove(o))
return false;
}
return true;
}
@Override
public boolean retainAll(Collection<?> c)
{
return termFrequencyMap.values().retainAll(c);
}
@Override
public void clear()
{ | termFrequencyMap.clear();
}
/**
* 提取关键词(非线程安全)
*
* @param termList
* @param size
* @return
*/
@Override
public List<String> getKeywords(List<Term> termList, int size)
{
clear();
add(termList);
Collection<TermFrequency> topN = top(size);
List<String> r = new ArrayList<String>(topN.size());
for (TermFrequency termFrequency : topN)
{
r.add(termFrequency.getTerm());
}
return r;
}
/**
* 提取关键词(线程安全)
*
* @param document 文档内容
* @param size 希望提取几个关键词
* @return 一个列表
*/
public static List<String> getKeywordList(String document, int size)
{
return new TermFrequencyCounter().getKeywords(document, size);
}
@Override
public String toString()
{
final int max = 100;
return top(Math.min(max, size())).toString();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word\TermFrequencyCounter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class C_Queue_WorkPackage
{
private static final Logger logger = LogManager.getLogger(C_Queue_WorkPackage.class);
private final AsyncBatchService asyncBatchService;
private final ITrxManager trxManager = Services.get(ITrxManager.class);
private final IWorkpackageParamDAO workpackageParamDAO = Services.get(IWorkpackageParamDAO.class);
public C_Queue_WorkPackage(@NonNull final AsyncBatchService asyncBatchService)
{
this.asyncBatchService = asyncBatchService;
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE)
public void deleteElements(@NonNull final I_C_Queue_WorkPackage wp)
{
final int deleteCount = Services.get(IQueryBL.class).createQueryBuilder(I_C_Queue_Element.class, wp)
.addEqualsFilter(I_C_Queue_Element.COLUMN_C_Queue_WorkPackage_ID, wp.getC_Queue_WorkPackage_ID())
.create()
.delete();
logger.info("Deleted {} {} that referenced the to-be-deleted {} ", deleteCount, I_C_Queue_Element.Table_Name, wp);
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE)
public void deleteParams(@NonNull final I_C_Queue_WorkPackage wp)
{
final QueueWorkPackageId workpackageId = QueueWorkPackageId.ofRepoId(wp.getC_Queue_WorkPackage_ID());
workpackageParamDAO.deleteWorkpackageParams(workpackageId);
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE) | public void deleteLogs(@NonNull final I_C_Queue_WorkPackage wp)
{
final IWorkpackageLogsRepository logsRepository = SpringContextHolder.instance.getBean(IWorkpackageLogsRepository.class);
final QueueWorkPackageId workpackageId = QueueWorkPackageId.ofRepoId(wp.getC_Queue_WorkPackage_ID());
logsRepository.deleteLogsInTrx(workpackageId);
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = {
I_C_Queue_WorkPackage.COLUMNNAME_Processed,
I_C_Queue_WorkPackage.COLUMNNAME_IsError
})
public void processBatchFromWP(@NonNull final I_C_Queue_WorkPackage wp)
{
if (wp.getC_Async_Batch_ID() <= 0)
{
return;
}
final String trxName = InterfaceWrapperHelper.getTrxName(wp);
final AsyncBatchId asyncBatchId = AsyncBatchId.ofRepoId(wp.getC_Async_Batch_ID());
trxManager
.getTrxListenerManager(trxName)
.runAfterCommit(() -> processBatchInOwnTrx(asyncBatchId));
}
private void processBatchInOwnTrx(@NonNull final AsyncBatchId asyncBatchId)
{
trxManager.runInNewTrx(() -> asyncBatchService.checkProcessed(asyncBatchId, ITrx.TRXNAME_ThreadInherited));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\model\validator\C_Queue_WorkPackage.java | 2 |
请完成以下Java代码 | public void init()
{
if (m_AD_Client_ID > 0)
{
final I_AD_Client client = clientDAO.getById(m_AD_Client_ID);
modelValidationEngine.addModelValidator(this, client);
}
else
{
// register for all clients
modelValidationEngine.addModelValidator(this);
}
}
// NOTE: keep in sync with initialize method
public void destroy()
{
// Unregister from model validation engine
final String tableName = getTableName();
modelValidationEngine.removeModelChange(tableName, this);
modelValidationEngine.removeDocValidate(tableName, this);
}
@Override
public int getAD_Client_ID()
{
return m_AD_Client_ID;
}
@Override
public String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID)
{
return null; // nothing
}
@Nullable
@Override
public String modelChange(final PO po, final int type) throws Exception
{
return null; // nothing
}
@Nullable
@Override
public String docValidate(final PO po, final int timing) throws Exception
{
Check.assume(isDocument(), "PO '{}' is a document", po);
if (timing == ModelValidator.TIMING_AFTER_COMPLETE
&& !documentBL.isReversalDocument(po))
{
externalSystemScriptedExportConversionService
.retrieveBestMatchingConfig(AdTableAndClientId.of(AdTableId.ofRepoId(po.get_Table_ID()),
ClientId.ofRepoId(getAD_Client_ID())), po.get_ID())
.ifPresent(config -> executeInvokeScriptedExportConversionAction(config, po.get_ID()));
}
return null;
}
@NonNull
public AdTableId getTableId()
{
return adTableId;
} | private void executeInvokeScriptedExportConversionAction(
@NonNull final ExternalSystemScriptedExportConversionConfig config,
final int recordId)
{
final int configTableId = tableDAO.retrieveTableId(I_ExternalSystem_Config_ScriptedExportConversion.Table_Name);
try
{
trxManager.runAfterCommit(() -> {
ProcessInfo.builder()
.setCtx(getCtx())
.setRecord(configTableId, config.getId().getRepoId())
.setAD_ProcessByClassname(InvokeScriptedExportConversionAction.class.getName())
.addParameter(PARAM_EXTERNAL_REQUEST, COMMAND_CONVERT_MESSAGE_FROM_METASFRESH)
.addParameter(PARAM_CHILD_CONFIG_ID, config.getId().getRepoId())
.addParameter(PARAM_Record_ID, recordId)
.buildAndPrepareExecution()
.executeSync();
});
}
catch (final Exception e)
{
log.warn(InvokeScriptedExportConversionAction.class.getName() + " process failed for Config ID {}, Record ID: {}",
config.getId(), recordId, e);
}
}
private String getTableName()
{
return tableName;
}
private boolean isDocument()
{
return isDocument;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\scriptedexportconversion\interceptor\ExternalSystemScriptedExportConversionInterceptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String determineDuplicateDeployment(CandidateDeployment candidateDeployment) {
return Context.getCommandContext()
.getDeploymentManager()
.findLatestDeploymentByName(candidateDeployment.getName())
.getId();
}
@Override
public Set<String> determineDeploymentsToResumeByProcessDefinitionKey(
String[] processDefinitionKeys) {
Set<String> deploymentIds = new HashSet<>();
List<ProcessDefinition> processDefinitions = Context.getCommandContext().getProcessDefinitionManager()
.findProcessDefinitionsByKeyIn(processDefinitionKeys);
for (ProcessDefinition processDefinition : processDefinitions) {
deploymentIds.add(processDefinition.getDeploymentId());
}
return deploymentIds;
}
@Override | public Set<String> determineDeploymentsToResumeByDeploymentName(CandidateDeployment candidateDeployment) {
List<Deployment> previousDeployments = processEngine.getRepositoryService()
.createDeploymentQuery()
.deploymentName(candidateDeployment.getName())
.list();
Set<String> deploymentIds = new HashSet<>();
for (Deployment deployment : previousDeployments) {
deploymentIds.add(deployment.getId());
}
return deploymentIds;
}
protected boolean resourcesDiffer(Resource resource, Resource existing) {
byte[] bytes = resource.getBytes();
byte[] savedBytes = existing.getBytes();
return !Arrays.equals(bytes, savedBytes);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\repository\DefaultDeploymentHandler.java | 2 |
请完成以下Java代码 | public static void main(String[] args) throws Exception {
// 本地模式
Configuration conf = new Configuration();
// 指定端口
conf.setString(RestOptions.BIND_PORT, "7777");
// 创建执行环境
StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(conf);
// 全局指定并行度,默认是电脑的线程数
env.setParallelism(2);
// 读取socket文本流
DataStreamSource<String> socketDS = env.socketTextStream("172.24.4.193", 8888);
// 处理数据: 切割、转换、分组、聚合 得到统计结果
SingleOutputStreamOperator<Tuple2<String, Integer>> sum = socketDS
.flatMap(
(String value, Collector<Tuple2<String, Integer>> out) -> {
String[] words = value.split(" ");
for (String word : words) {
out.collect(Tuple2.of(word, 1));
} | }
)
// 局部设置算子并行度
.setParallelism(3)
.returns(Types.TUPLE(Types.STRING, Types.INT))
.keyBy(value -> value.f0)
.sum(1)
// 局部设置算子并行度
.setParallelism(4);
// 输出
sum.print();
// 执行
env.execute();
}
} | repos\springboot-demo-master\flink\src\main\java\com\et\flink\job\FlinkWebUI.java | 1 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper("composite")
.addValue(predicates)
.toString();
}
@Override
public ImmutableSet<String> getParameters(@Nullable final String contextTableName)
{
return predicates.stream()
.flatMap(predicate -> predicate.getParameters(contextTableName).stream())
.collect(ImmutableSet.toImmutableSet());
}
@Override
public boolean accept(final IValidationContext evalCtx, final NamePair item)
{
for (final INamePairPredicate predicate : predicates)
{
if (predicate.accept(evalCtx, item))
{
return true;
}
}
return false;
}
}
public static class Composer
{
private Set<INamePairPredicate> collectedPredicates = null;
private Composer()
{
super();
} | public INamePairPredicate build()
{
if (collectedPredicates == null || collectedPredicates.isEmpty())
{
return ACCEPT_ALL;
}
else if (collectedPredicates.size() == 1)
{
return collectedPredicates.iterator().next();
}
else
{
return new ComposedNamePairPredicate(collectedPredicates);
}
}
public Composer add(@Nullable final INamePairPredicate predicate)
{
if (predicate == null || predicate == ACCEPT_ALL)
{
return this;
}
if (collectedPredicates == null)
{
collectedPredicates = new LinkedHashSet<>();
}
if (collectedPredicates.contains(predicate))
{
return this;
}
collectedPredicates.add(predicate);
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\validationRule\NamePairPredicates.java | 1 |
请完成以下Java代码 | public Action getAction()
{
return action;
}
public void setAction(Action action)
{
this.action = action;
}
public I_AD_MigrationStep getMigrationStep()
{
return migrationStep;
}
@Override
protected String doIt() throws Exception
{
if (migrationStep == null || migrationStep.getAD_MigrationStep_ID() <= 0)
{
throw new AdempiereException("@NotFound@ AD_MigrationStep_ID@");
}
final IMigrationExecutorProvider executorProvider = Services.get(IMigrationExecutorProvider.class);
final IMigrationExecutorContext migrationCtx = executorProvider.createInitialContext(getCtx());
final IMigrationExecutor executor = executorProvider.newMigrationExecutor(migrationCtx, migrationStep.getAD_Migration_ID());
executor.setMigrationSteps(Arrays.asList(migrationStep));
if (action == null)
{
action = getAction(migrationStep);
} | executor.execute(action);
return "Executed: " + action;
}
protected Action getAction(I_AD_MigrationStep step)
{
if (X_AD_MigrationStep.STATUSCODE_Applied.equals(migrationStep.getStatusCode()))
{
return IMigrationExecutor.Action.Rollback;
}
else
{
return IMigrationExecutor.Action.Apply;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\MigrationStepApply.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Signal getSignal() {
return signal;
}
@Override
public String getExecutionId() {
return executionId;
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
@Override
public String getProcessDefinitionId() {
return processDefinitionId;
}
@Override
public String getActivityId() {
return activityId;
}
@Override
public String getSubScopeId() {
return subScopeId;
}
@Override
public String getScopeId() {
return scopeId;
}
@Override
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
@Override | public String getScopeDefinitionKey() {
return scopeDefinitionKey;
}
@Override
public String getScopeType() {
return scopeType;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public String getConfiguration() {
return configuration;
}
} | repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\EventSubscriptionBuilderImpl.java | 2 |
请完成以下Java代码 | public ImmutableList<InventoryLineHU> getLineHUs()
{
return streamLineHUs().collect(ImmutableList.toImmutableList());
}
private Stream<InventoryLineHU> streamLineHUs()
{
return lines.stream().flatMap(line -> line.getInventoryLineHUs().stream());
}
public ImmutableSet<HuId> getHuIds()
{
return InventoryLineHU.extractHuIds(streamLineHUs());
}
public Inventory assigningTo(@NonNull final UserId newResponsibleId)
{
return assigningTo(newResponsibleId, false);
}
public Inventory reassigningTo(@NonNull final UserId newResponsibleId)
{
return assigningTo(newResponsibleId, true);
}
private Inventory assigningTo(@NonNull final UserId newResponsibleId, boolean allowReassignment)
{
// no responsible change
if (UserId.equals(responsibleId, newResponsibleId))
{
return this;
}
if (!newResponsibleId.isRegularUser())
{
throw new AdempiereException("Only regular users can be assigned to an inventory");
}
if (!allowReassignment && responsibleId != null)
{
throw new AdempiereException("Inventory is already assigned");
}
return toBuilder().responsibleId(newResponsibleId).build();
}
public Inventory unassign()
{
return responsibleId == null ? this : toBuilder().responsibleId(null).build();
}
public void assertHasAccess(@NonNull final UserId calledId)
{ | if (!UserId.equals(responsibleId, calledId))
{
throw new AdempiereException("No access");
}
}
public Stream<InventoryLine> streamLines(@Nullable final InventoryLineId onlyLineId)
{
return onlyLineId != null
? Stream.of(getLineById(onlyLineId))
: lines.stream();
}
public Set<LocatorId> getLocatorIdsEligibleForCounting(@Nullable final InventoryLineId onlyLineId)
{
return streamLines(onlyLineId)
.filter(InventoryLine::isEligibleForCounting)
.map(InventoryLine::getLocatorId)
.collect(ImmutableSet.toImmutableSet());
}
public Inventory updatingLineById(@NonNull final InventoryLineId lineId, @NonNull UnaryOperator<InventoryLine> updater)
{
final ImmutableList<InventoryLine> newLines = CollectionUtils.map(
this.lines,
line -> InventoryLineId.equals(line.getId(), lineId) ? updater.apply(line) : line
);
return this.lines == newLines
? this
: toBuilder().lines(newLines).build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\Inventory.java | 1 |
请完成以下Java代码 | public String getDecisionKey() {
return decisionKey;
}
public String getInstanceId() {
return instanceId;
}
public String getExecutionId() {
return executionId;
}
public String getActivityId() {
return activityId;
}
public String getScopeType() {
return scopeType;
}
public boolean isWithoutScopeType() {
return withoutScopeType;
}
public String getProcessInstanceIdWithChildren() {
return processInstanceIdWithChildren;
} | public String getCaseInstanceIdWithChildren() {
return caseInstanceIdWithChildren;
}
public Boolean getFailed() {
return failed;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\HistoricDecisionExecutionQueryImpl.java | 1 |
请完成以下Java代码 | public IHUAssignmentBuilder setM_TU_HU(final I_M_HU tuHU)
{
this.tuHU = tuHU;
return this;
}
@Override
public IHUAssignmentBuilder setVHU(final I_M_HU vhu)
{
this.vhu = vhu;
return this;
}
@Override
public IHUAssignmentBuilder setQty(final BigDecimal qty)
{
this.qty = qty;
return this;
}
@Override
public IHUAssignmentBuilder setIsTransferPackingMaterials(final boolean isTransferPackingMaterials)
{
this.isTransferPackingMaterials = isTransferPackingMaterials;
return this;
}
@Override
public IHUAssignmentBuilder setIsActive(final boolean isActive)
{
this.isActive = isActive;
return this;
}
@Override
public boolean isActive()
{
return isActive;
}
@Override
public I_M_HU_Assignment getM_HU_Assignment()
{
return assignment;
}
@Override
public boolean isNewAssignment()
{
return InterfaceWrapperHelper.isNew(assignment);
}
@Override
public IHUAssignmentBuilder initializeAssignment(final Properties ctx, final String trxName)
{
final I_M_HU_Assignment assignment = InterfaceWrapperHelper.create(ctx, I_M_HU_Assignment.class, trxName);
setAssignmentRecordToUpdate(assignment);
return this;
}
@Override
public IHUAssignmentBuilder setTemplateForNewRecord(final I_M_HU_Assignment assignmentRecord)
{
this.assignment = newInstance(I_M_HU_Assignment.class);
return updateFromRecord(assignmentRecord);
} | @Override
public IHUAssignmentBuilder setAssignmentRecordToUpdate(@NonNull final I_M_HU_Assignment assignmentRecord)
{
this.assignment = assignmentRecord;
return updateFromRecord(assignmentRecord);
}
private IHUAssignmentBuilder updateFromRecord(final I_M_HU_Assignment assignmentRecord)
{
setTopLevelHU(assignmentRecord.getM_HU());
setM_LU_HU(assignmentRecord.getM_LU_HU());
setM_TU_HU(assignmentRecord.getM_TU_HU());
setVHU(assignmentRecord.getVHU());
setQty(assignmentRecord.getQty());
setIsTransferPackingMaterials(assignmentRecord.isTransferPackingMaterials());
setIsActive(assignmentRecord.isActive());
return this;
}
@Override
public I_M_HU_Assignment build()
{
Check.assumeNotNull(model, "model not null");
Check.assumeNotNull(topLevelHU, "topLevelHU not null");
Check.assumeNotNull(assignment, "assignment not null");
TableRecordCacheLocal.setReferencedValue(assignment, model);
assignment.setM_HU(topLevelHU);
assignment.setM_LU_HU(luHU);
assignment.setM_TU_HU(tuHU);
assignment.setVHU(vhu);
assignment.setQty(qty);
assignment.setIsTransferPackingMaterials(isTransferPackingMaterials);
assignment.setIsActive(isActive);
InterfaceWrapperHelper.save(assignment);
return assignment;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUAssignmentBuilder.java | 1 |
请完成以下Java代码 | public final class InvoiceCandidateIdsSelection
{
private static final InvoiceCandidateIdsSelection EMPTY = new InvoiceCandidateIdsSelection(null, ImmutableSet.of());
public static InvoiceCandidateIdsSelection ofSelectionId(@NonNull final PInstanceId selectionId)
{
return new InvoiceCandidateIdsSelection(selectionId, null);
}
public static InvoiceCandidateIdsSelection ofIdsSet(@NonNull final Set<InvoiceCandidateId> ids)
{
return !ids.isEmpty()
? new InvoiceCandidateIdsSelection(null, ImmutableSet.copyOf(ids))
: EMPTY;
}
public static InvoiceCandidateIdsSelection extractFixedIdsSet(@NonNull final Iterable<? extends I_C_Invoice_Candidate> invoiceCandidates)
{
final ImmutableSet.Builder<InvoiceCandidateId> ids = ImmutableSet.builder();
for (final I_C_Invoice_Candidate ic : invoiceCandidates)
{
final InvoiceCandidateId id = InvoiceCandidateId.ofRepoIdOrNull(ic.getC_Invoice_Candidate_ID());
if (id != null)
{
ids.add(id);
}
}
return ofIdsSet(ids.build());
}
@Nullable private final PInstanceId selectionId;
@Nullable private final ImmutableSet<InvoiceCandidateId> ids;
private InvoiceCandidateIdsSelection(
@Nullable final PInstanceId selectionId,
@Nullable final ImmutableSet<InvoiceCandidateId> ids)
{
if (CoalesceUtil.countNotNulls(selectionId, ids) != 1)
{
throw new AdempiereException("Only `selectionId` or only `ids` can be set, but not both")
.appendParametersToMessage()
.setParameter("selectionId", selectionId)
.setParameter("ids", ids); | }
this.selectionId = selectionId;
this.ids = ids;
}
public boolean isEmpty() {return selectionId == null && (ids == null || ids.isEmpty());}
public boolean isDatabaseSelection()
{
return selectionId != null;
}
public interface CaseMapper
{
void empty();
void fixedSet(@NonNull ImmutableSet<InvoiceCandidateId> ids);
void selectionId(@NonNull PInstanceId selectionId);
}
public void apply(@NonNull final CaseMapper mapper)
{
if (selectionId != null)
{
mapper.selectionId(selectionId);
}
else if (ids != null && !ids.isEmpty())
{
mapper.fixedSet(ids);
}
else
{
mapper.empty();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\InvoiceCandidateIdsSelection.java | 1 |
请完成以下Java代码 | public SpinDataFormatException unrecognizableDataFormatException() {
return new SpinDataFormatException(exceptionMessage("004", "No matching data format detected"));
}
public SpinScriptException noScriptEnvFoundForLanguage(String scriptLanguage, String path) {
return new SpinScriptException(exceptionMessage("006", "No script script env found for script language '{}' at path '{}'", scriptLanguage, path));
}
public IOException unableToRewindReader() {
return new IOException(exceptionMessage("007", "Unable to rewind input stream: rewind buffering limit exceeded"));
}
public SpinDataFormatException multipleProvidersForDataformat(String dataFormatName) {
return new SpinDataFormatException(exceptionMessage("008", "Multiple providers found for dataformat '{}'", dataFormatName));
}
public void logDataFormats(Collection<DataFormat<?>> formats) {
if (isInfoEnabled()) {
for (DataFormat<?> format : formats) {
logDataFormat(format);
}
}
}
protected void logDataFormat(DataFormat<?> dataFormat) {
logInfo("009", "Discovered Spin data format: {}[name = {}]", dataFormat.getClass().getName(), dataFormat.getName()); | }
public void logDataFormatProvider(DataFormatProvider provider) {
if (isInfoEnabled()) {
logInfo("010", "Discovered Spin data format provider: {}[name = {}]",
provider.getClass().getName(), provider.getDataFormatName());
}
}
@SuppressWarnings("rawtypes")
public void logDataFormatConfigurator(DataFormatConfigurator configurator) {
if (isInfoEnabled()) {
logInfo("011", "Discovered Spin data format configurator: {}[dataformat = {}]",
configurator.getClass(), configurator.getDataFormatClass().getName());
}
}
public SpinDataFormatException classNotFound(String classname, ClassNotFoundException cause) {
return new SpinDataFormatException(exceptionMessage("012", "Class {} not found ", classname), cause);
}
public void tryLoadingClass(String classname, ClassLoader cl) {
logDebug("013", "Try loading class '{}' using classloader '{}'.", classname, cl);
}
} | repos\camunda-bpm-platform-master\spin\core\src\main\java\org\camunda\spin\impl\logging\SpinCoreLogger.java | 1 |
请完成以下Java代码 | public void setK_Source_ID (int K_Source_ID)
{
if (K_Source_ID < 1)
set_Value (COLUMNNAME_K_Source_ID, null);
else
set_Value (COLUMNNAME_K_Source_ID, Integer.valueOf(K_Source_ID));
}
/** Get Knowledge Source.
@return Source of a Knowledge Entry
*/
public int getK_Source_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_Source_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_K_Topic getK_Topic() throws RuntimeException
{
return (I_K_Topic)MTable.get(getCtx(), I_K_Topic.Table_Name)
.getPO(getK_Topic_ID(), get_TrxName()); }
/** Set Knowledge Topic.
@param K_Topic_ID
Knowledge Topic
*/
public void setK_Topic_ID (int K_Topic_ID)
{
if (K_Topic_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_Topic_ID, null);
else
set_ValueNoCheck (COLUMNNAME_K_Topic_ID, Integer.valueOf(K_Topic_ID));
}
/** Get Knowledge Topic.
@return Knowledge Topic
*/
public int getK_Topic_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_Topic_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** 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 Rating.
@param Rating
Classification or Importance
*/
public void setRating (int Rating)
{
set_Value (COLUMNNAME_Rating, Integer.valueOf(Rating));
} | /** Get Rating.
@return Classification or Importance
*/
public int getRating ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Rating);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Entry.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void doProgramAuth(@PathVariable(value = "payKey") String payKey, @PathVariable(value = "orderNo") String orderNo, HttpServletResponse response) {
logger.info("鉴权,payKey:[{}],订单号:[{}]", payKey, orderNo);
String payResultJson;
try {
RpUserPayConfig rpUserPayConfig = userPayConfigService.getByPayKey(payKey);
if (rpUserPayConfig == null) {
throw new UserBizException(UserBizException.USER_PAY_CONFIG_ERRPR, "用户支付配置有误");
}
String merchantNo = rpUserPayConfig.getUserNo();// 商户编号
AuthResultVo resultVo = tradePaymentManagerService.userAuth(merchantNo, orderNo);
payResultJson = JSONObject.toJSONString(resultVo);
} catch (Exception e) {
JSONObject resultJson = new JSONObject();
resultJson.put("errCode", "NO");
resultJson.put("bankReturnMsg", e.getMessage());
payResultJson = resultJson.toJSONString();
}
logger.debug("小程序--支付结果==>{}", payResultJson);
response.setContentType(CONTENT_TYPE);
response.setStatus(200);
write(response, payResultJson);
}
@RequestMapping("/orderQuery")
@ResponseBody
public String orderQuery(String payKey, String orderNo) {
logger.info("鉴权记录查询,payKey:[{}],订单号:[{}]", payKey, orderNo);
RpUserPayConfig rpUserPayConfig = userPayConfigService.getByPayKey(payKey);
if (rpUserPayConfig == null) {
throw new UserBizException(UserBizException.USER_PAY_CONFIG_ERRPR, "用户支付配置有误");
}
String merchantNo = rpUserPayConfig.getUserNo();// 商户编号
RpUserBankAuth userBankAuth = userBankAuthService.findByMerchantNoAndPayOrderNo(merchantNo, orderNo);
JSONObject resultJson = new JSONObject();
if (userBankAuth == null) { | resultJson.put("status", "NO");
} else {
resultJson.put("status", "YES");
resultJson.put("returnUrl", AuthConfigUtil.AUTH_ORDER_QUERY_URL + userBankAuth.getMerchantNo() + "/" + userBankAuth.getPayOrderNo());
}
return resultJson.toJSONString();
}
/**
* 获取错误返回信息
*
* @param bindingResult
* @return
*/
public String getErrorMsg(BindingResult bindingResult) {
StringBuffer sb = new StringBuffer();
for (ObjectError objectError : bindingResult.getAllErrors()) {
sb.append(objectError.getDefaultMessage()).append(",");
}
sb.delete(sb.length() - 1, sb.length());
return sb.toString();
}
} | repos\roncoo-pay-master\roncoo-pay-web-gateway\src\main\java\com\roncoo\pay\controller\auth\AuthController.java | 2 |
请完成以下Java代码 | public void setPP_Weighting_Spec_ID (final int PP_Weighting_Spec_ID)
{
if (PP_Weighting_Spec_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Weighting_Spec_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Weighting_Spec_ID, PP_Weighting_Spec_ID);
}
@Override
public int getPP_Weighting_Spec_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Weighting_Spec_ID);
}
@Override
public void setTolerance_Perc (final BigDecimal Tolerance_Perc)
{
set_Value (COLUMNNAME_Tolerance_Perc, Tolerance_Perc);
} | @Override
public BigDecimal getTolerance_Perc()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Tolerance_Perc);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setWeightChecksRequired (final int WeightChecksRequired)
{
set_Value (COLUMNNAME_WeightChecksRequired, WeightChecksRequired);
}
@Override
public int getWeightChecksRequired()
{
return get_ValueAsInt(COLUMNNAME_WeightChecksRequired);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Weighting_Spec.java | 1 |
请完成以下Java代码 | public ActiveOrHistoricCurrencyAndAmount getAmt() {
return amt;
}
/**
* Sets the value of the amt property.
*
* @param value
* allowed object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public void setAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.amt = value;
}
/**
* Gets the value of the inf property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the inf property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getInf().add(newItem);
* </pre> | *
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getInf() {
if (inf == null) {
inf = new ArrayList<String>();
}
return this.inf;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\StructuredRegulatoryReporting3.java | 1 |
请完成以下Java代码 | private static void loggContextSwitchDetails(ExecutionEntity execution) {
final CoreExecutionContext<? extends CoreExecution> executionContext = Context.getCoreExecutionContext();
// only log for first atomic op:
if(executionContext == null ||( executionContext.getExecution() != execution) ) {
ProcessApplicationManager processApplicationManager = Context.getProcessEngineConfiguration().getProcessApplicationManager();
LOG.debugNoTargetProcessApplicationFound(execution, processApplicationManager);
}
}
private static void loggContextSwitchDetails(CaseExecutionEntity execution) {
final CoreExecutionContext<? extends CoreExecution> executionContext = Context.getCoreExecutionContext();
// only log for first atomic op:
if(executionContext == null ||( executionContext.getExecution() != execution) ) {
ProcessApplicationManager processApplicationManager = Context.getProcessEngineConfiguration().getProcessApplicationManager();
LOG.debugNoTargetProcessApplicationFoundForCaseExecution(execution, processApplicationManager);
}
}
public static boolean requiresContextSwitch(ProcessApplicationReference processApplicationReference) {
final ProcessApplicationReference currentProcessApplication = Context.getCurrentProcessApplication();
if(processApplicationReference == null) {
return false;
}
if(currentProcessApplication == null) {
return true;
}
else {
if(!processApplicationReference.getName().equals(currentProcessApplication.getName())) {
return true;
}
else {
// check whether the thread context has been manipulated since last context switch. This can happen as a result of
// an operation causing the container to switch to a different application.
// Example: JavaDelegate implementation (inside PA) invokes an EJB from different application which in turn interacts with the Process engine.
ClassLoader processApplicationClassLoader = ProcessApplicationClassloaderInterceptor.getProcessApplicationClassLoader();
ClassLoader currentClassloader = ClassLoaderUtil.getContextClassloader();
return currentClassloader != processApplicationClassLoader;
} | }
}
public static void doContextSwitch(final Runnable runnable, ProcessDefinitionEntity contextDefinition) {
ProcessApplicationReference processApplication = getTargetProcessApplication(contextDefinition);
if (requiresContextSwitch(processApplication)) {
Context.executeWithinProcessApplication(new Callable<Void>() {
@Override
public Void call() throws Exception {
runnable.run();
return null;
}
}, processApplication);
}
else {
runnable.run();
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\context\ProcessApplicationContextUtil.java | 1 |
请完成以下Java代码 | protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_HR_Department[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_C_Activity getC_Activity() throws RuntimeException
{
return (I_C_Activity)MTable.get(getCtx(), I_C_Activity.Table_Name)
.getPO(getC_Activity_ID(), get_TrxName()); }
/** Set Activity.
@param C_Activity_ID
Business Activity
*/
public void setC_Activity_ID (int C_Activity_ID)
{
if (C_Activity_ID < 1)
set_Value (COLUMNNAME_C_Activity_ID, null);
else
set_Value (COLUMNNAME_C_Activity_ID, Integer.valueOf(C_Activity_ID));
}
/** Get Activity.
@return Business Activity
*/
public int getC_Activity_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Activity_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);
}
/** Set Payroll Department.
@param HR_Department_ID Payroll Department */
public void setHR_Department_ID (int HR_Department_ID)
{
if (HR_Department_ID < 1)
set_ValueNoCheck (COLUMNNAME_HR_Department_ID, null);
else | set_ValueNoCheck (COLUMNNAME_HR_Department_ID, Integer.valueOf(HR_Department_ID));
}
/** Get Payroll Department.
@return Payroll Department */
public int getHR_Department_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_Department_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** 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\eevolution\model\X_HR_Department.java | 1 |
请完成以下Java代码 | public void deleteVariable(String variableName) {
try {
removeVariableEntity(variableName);
} catch (AuthorizationException e) {
throw e;
} catch (ProcessEngineException e) {
String errorMessage = String.format("Cannot delete %s variable %s: %s", getResourceTypeName(), variableName, e.getMessage());
throw new RestException(Status.INTERNAL_SERVER_ERROR, e, errorMessage);
}
}
@Override
public void modifyVariables(PatchVariablesDto patch) {
VariableMap variableModifications = null;
try {
variableModifications = VariableValueDto.toMap(patch.getModifications(), engine, objectMapper);
} catch (RestException e) {
String errorMessage = String.format("Cannot modify variables for %s: %s", getResourceTypeName(), e.getMessage());
throw new InvalidRequestException(e.getStatus(), e, errorMessage);
}
List<String> variableDeletions = patch.getDeletions();
try {
updateVariableEntities(variableModifications, variableDeletions);
} catch (AuthorizationException e) {
throw e;
} catch (ProcessEngineException e) { | String errorMessage = String.format("Cannot modify variables for %s %s: %s", getResourceTypeName(), resourceId, e.getMessage());
throw new RestException(Status.INTERNAL_SERVER_ERROR, e, errorMessage);
}
}
protected abstract VariableMap getVariableEntities(boolean deserializeValues);
protected abstract void updateVariableEntities(VariableMap variables, List<String> deletions);
protected abstract TypedValue getVariableEntity(String variableKey, boolean deserializeValue);
protected abstract void setVariableEntity(String variableKey, TypedValue variableValue);
protected abstract void removeVariableEntity(String variableKey);
protected abstract String getResourceTypeName();
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\impl\AbstractVariablesResource.java | 1 |
请完成以下Java代码 | public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
synchronized (JreCompat.isGraalAvailable() ? this : getClassLoadingLock(name)) {
Class<?> result = findExistingLoadedClass(name);
result = (result != null) ? result : doLoadClass(name);
if (result == null) {
throw new ClassNotFoundException(name);
}
return resolveIfNecessary(result, resolve);
}
}
private @Nullable Class<?> findExistingLoadedClass(String name) {
Class<?> resultClass = findLoadedClass0(name);
resultClass = (resultClass != null || JreCompat.isGraalAvailable()) ? resultClass : findLoadedClass(name);
return resultClass;
}
private @Nullable Class<?> doLoadClass(String name) {
if ((this.delegate || filter(name, true))) {
Class<?> result = loadFromParent(name);
return (result != null) ? result : findClassIgnoringNotFound(name);
}
Class<?> result = findClassIgnoringNotFound(name);
return (result != null) ? result : loadFromParent(name);
}
private Class<?> resolveIfNecessary(Class<?> resultClass, boolean resolve) {
if (resolve) {
resolveClass(resultClass);
}
return (resultClass); | }
@Override
protected void addURL(URL url) {
// Ignore URLs added by the Tomcat 8 implementation (see gh-919)
if (logger.isTraceEnabled()) {
logger.trace("Ignoring request to add " + url + " to the tomcat classloader");
}
}
private @Nullable Class<?> loadFromParent(String name) {
if (this.parent == null) {
return null;
}
try {
return Class.forName(name, false, this.parent);
}
catch (ClassNotFoundException ex) {
return null;
}
}
private @Nullable Class<?> findClassIgnoringNotFound(String name) {
try {
return findClass(name);
}
catch (ClassNotFoundException ex) {
return null;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\TomcatEmbeddedWebappClassLoader.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected Publisher<Void> handle(Flux<InstanceEvent> publisher) {
return publisher
.filter((event) -> event instanceof InstanceRegisteredEvent
|| event instanceof InstanceRegistrationUpdatedEvent)
.flatMap((event) -> updateStatus(event.getInstance()));
}
protected Mono<Void> updateStatus(InstanceId instanceId) {
return this.statusUpdater.timeout(this.intervalCheck.getInterval())
.updateStatus(instanceId)
.onErrorResume((e) -> {
log.warn("Unexpected error while updating status for {}", instanceId, e);
return Mono.empty();
})
.doFinally((s) -> this.intervalCheck.markAsChecked(instanceId));
}
@Override
public void start() {
super.start();
this.intervalCheck.start();
} | @Override
public void stop() {
super.stop();
this.intervalCheck.stop();
}
public void setInterval(Duration updateInterval) {
this.intervalCheck.setInterval(updateInterval);
}
public void setLifetime(Duration statusLifetime) {
this.intervalCheck.setMinRetention(statusLifetime);
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\services\StatusUpdateTrigger.java | 2 |
请完成以下Java代码 | private ProjectManifest read(InputStream inputStream) throws IOException {
return objectMapper.readValue(inputStream, ProjectManifest.class);
}
public boolean isRollbackDeployment() {
return isRollbackDeployment;
}
public ProjectManifest loadProjectManifest() throws IOException {
Optional<Resource> resourceOptional = retrieveResource();
return read(
resourceOptional
.orElseThrow(() -> new FileNotFoundException("'" + projectManifestFilePath + "' manifest not found."))
.getInputStream() | );
}
public boolean hasProjectManifest() {
return retrieveResource().isPresent();
}
public boolean hasEnforcedAppVersion() {
return this.enforcedAppVersion > 0;
}
public Integer getEnforcedAppVersion() {
return this.enforcedAppVersion;
}
} | repos\Activiti-develop\activiti-core-common\activiti-spring-project\src\main\java\org\activiti\core\common\spring\project\ApplicationUpgradeContextService.java | 1 |
请完成以下Java代码 | public int hashCode()
{
if (_hashcode == null)
{
_hashcode = Objects.hash(isParameter1, operand1, operator, isParameter2, operand2);
}
return _hashcode;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final LogicTuple other = (LogicTuple)obj;
return isParameter1 == other.isParameter1
&& Objects.equals(operand1, other.operand1)
//
&& Objects.equals(operator, other.operator)
//
&& isParameter2 == other.isParameter2
&& Objects.equals(operand2, other.operand2)
&& Objects.equals(constantValue, other.constantValue);
}
public boolean isParameter1()
{
return isParameter1;
}
public boolean isParameter2()
{
return isParameter2;
}
@Override
public boolean isConstant()
{
return constantValue != null;
}
@Override
public boolean constantValue()
{
if (constantValue == null)
{
throw ExpressionEvaluationException.newWithTranslatableMessage("Not a constant expression: " + this);
}
return constantValue;
}
@Override
public ILogicExpression toConstantExpression(final boolean constantValue)
{
if (this.constantValue != null && this.constantValue == constantValue)
{
return this;
}
return new LogicTuple(constantValue, this);
}
@Override
public String getExpressionString()
{
return expressionStr;
}
@Override
public Set<CtxName> getParameters()
{
if (_parameters == null)
{
if (isConstant())
{
_parameters = ImmutableSet.of();
}
else | {
final Set<CtxName> result = new LinkedHashSet<>();
if (operand1 instanceof CtxName)
{
result.add((CtxName)operand1);
}
if (operand2 instanceof CtxName)
{
result.add((CtxName)operand2);
}
_parameters = ImmutableSet.copyOf(result);
}
}
return _parameters;
}
/**
* @return {@link CtxName} or {@link String}; never returns null
*/
public Object getOperand1()
{
return operand1;
}
/**
* @return {@link CtxName} or {@link String}; never returns null
*/
public Object getOperand2()
{
return operand2;
}
/**
* @return operator; never returns null
*/
public String getOperator()
{
return operator;
}
@Override
public String toString()
{
return getExpressionString();
}
@Override
public String getFormatedExpressionString()
{
return getExpressionString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\LogicTuple.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Page<UserDTO> getAllManagedUsers(Pageable pageable) {
return userRepository.findAllByLoginNot(pageable, Constants.ANONYMOUS_USER).map(UserDTO::new);
}
@Transactional(readOnly = true)
public Optional<User> getUserWithAuthoritiesByLogin(String login) {
return userRepository.findOneWithAuthoritiesByLogin(login);
}
@Transactional(readOnly = true)
public Optional<User> getUserWithAuthorities(Long id) {
return userRepository.findOneWithAuthoritiesById(id);
}
@Transactional(readOnly = true)
public Optional<User> getUserWithAuthorities() {
return SecurityUtils.getCurrentUserLogin().flatMap(userRepository::findOneWithAuthoritiesByLogin);
}
/**
* Not activated users should be automatically deleted after 3 days. | * <p>
* This is scheduled to get fired everyday, at 01:00 (am).
*/
@Scheduled(cron = "0 0 1 * * ?")
public void removeNotActivatedUsers() {
userRepository
.findAllByActivatedIsFalseAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS))
.forEach(user -> {
log.debug("Deleting not activated user {}", user.getLogin());
userRepository.delete(user);
});
}
/**
* @return a list of all the authorities
*/
public List<String> getAuthorities() {
return authorityRepository.findAll().stream().map(Authority::getName).collect(Collectors.toList());
}
} | repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\service\UserService.java | 2 |
请完成以下Java代码 | public void searchArrayLoop() {
for (int i = 0; i < SearchData.count; i++) {
searchLoop(SearchData.strings, "T");
}
}
@Benchmark
public void searchArrayAllocNewList() {
for (int i = 0; i < SearchData.count; i++) {
searchList(SearchData.strings, "T");
}
}
@Benchmark
public void searchArrayAllocNewSet() {
for (int i = 0; i < SearchData.count; i++) {
searchSet(SearchData.strings, "T");
}
}
@Benchmark
public void searchArrayReuseList() {
List<String> asList = Arrays.asList(SearchData.strings);
for (int i = 0; i < SearchData.count; i++) {
asList.contains("T");
}
}
@Benchmark
public void searchArrayReuseSet() {
Set<String> asSet = new HashSet<>(Arrays.asList(SearchData.strings));
for (int i = 0; i < SearchData.count; i++) {
asSet.contains("T");
}
}
@Benchmark
public void searchArrayBinarySearch() {
Arrays.sort(SearchData.strings);
for (int i = 0; i < SearchData.count; i++) {
Arrays.binarySearch(SearchData.strings, "T"); | }
}
private boolean searchList(String[] strings, String searchString) {
return Arrays.asList(strings).contains(searchString);
}
private boolean searchSet(String[] strings, String searchString) {
Set<String> set = new HashSet<>(Arrays.asList(strings));
return set.contains(searchString);
}
private boolean searchLoop(String[] strings, String searchString) {
for (String s : strings) {
if (s.equals(searchString))
return true;
}
return false;
}
private static String[] seedArray(int length) {
String[] strings = new String[length];
Random random = new Random();
for (int i = 0; i < length; i++)
{
strings[i] = String.valueOf(random.nextInt());
}
return strings;
}
} | repos\tutorials-master\core-java-modules\core-java-arrays-operations-basic-3\src\main\java\com\baeldung\array\SearchArrayBenchmark.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 Other SQL Clause.
@param OtherClause
Other SQL Clause
*/
public void setOtherClause (String OtherClause)
{
set_Value (COLUMNNAME_OtherClause, OtherClause);
}
/** Get Other SQL Clause.
@return Other SQL Clause
*/
public String getOtherClause ()
{
return (String)get_Value(COLUMNNAME_OtherClause);
} | /** Set Sql WHERE.
@param WhereClause
Fully qualified SQL WHERE clause
*/
public void setWhereClause (String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
public String getWhereClause ()
{
return (String)get_Value(COLUMNNAME_WhereClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_TemplateTable.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void publishConfigDeleted(final int MSV3_Customer_Config_ID)
{
final MSV3MetasfreshUserId userId = MSV3MetasfreshUserId.of(MSV3_Customer_Config_ID);
final MSV3UserChangedEvent deletedEvent = MSV3UserChangedEvent.deletedEvent(userId);
msv3ServerPeerService.publishUserChangedEvent(deletedEvent);
}
public void publishAllConfig()
{
final List<MSV3UserChangedEvent> events = Services.get(IQueryBL.class)
.createQueryBuilder(I_MSV3_Customer_Config.class)
// .addOnlyActiveRecordsFilter() // ALL, even if is not active. For those inactive we will generate delete events
.orderBy(I_MSV3_Customer_Config.COLUMN_MSV3_Customer_Config_ID)
.create()
.stream(I_MSV3_Customer_Config.class)
.map(configRecord -> toMSV3UserChangedEvent(configRecord))
.collect(ImmutableList.toImmutableList());
msv3ServerPeerService.publishUserChangedEvent(MSV3UserChangedBatchEvent.builder()
.events(events)
.deleteAllOtherUsers(true)
.build());
} | private static MSV3UserChangedEvent toMSV3UserChangedEvent(final I_MSV3_Customer_Config configRecord)
{
final MSV3MetasfreshUserId externalId = MSV3MetasfreshUserId.of(configRecord.getMSV3_Customer_Config_ID());
if (configRecord.isActive())
{
return MSV3UserChangedEvent.prepareCreatedOrUpdatedEvent(externalId)
.username(configRecord.getUserID())
.password(configRecord.getPassword())
.bpartnerId(configRecord.getC_BPartner_ID())
.bpartnerLocationId(configRecord.getC_BPartner_Location_ID())
.build();
}
else
{
return MSV3UserChangedEvent.deletedEvent(externalId);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java\de\metas\vertical\pharma\msv3\server\peer\metasfresh\services\MSV3CustomerConfigService.java | 2 |
请完成以下Java代码 | public class AccessFilter extends ZuulFilter {
private static Logger log = LoggerFactory.getLogger(AccessFilter.class);
@Override
public String filterType() {
return "pre";
}
@Override
public int filterOrder() {
return 0;
}
@Override
public boolean shouldFilter() {
return true;
} | @Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
log.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString()));
Object accessToken = request.getParameter("accessToken");
if(accessToken == null) {
log.warn("access token is empty");
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(401);
return null;
}
log.info("access token ok");
return null;
}
} | repos\SpringBoot-Learning-master\1.x\Chapter9-1-5\api-gateway\src\main\java\com\didispace\filter\AccessFilter.java | 1 |
请完成以下Java代码 | public String getDepartName() {
return departName;
}
public void setDepartName(String departName) {
this.departName = departName;
}
public String getDepartNameEn() {
return departNameEn;
}
public void setDepartNameEn(String departNameEn) {
this.departNameEn = departNameEn;
}
public String getDepartNameAbbr() {
return departNameAbbr;
}
public void setDepartNameAbbr(String departNameAbbr) {
this.departNameAbbr = departNameAbbr;
}
public Integer getDepartOrder() {
return departOrder;
}
public void setDepartOrder(Integer departOrder) {
this.departOrder = departOrder;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getOrgCategory() {
return orgCategory;
}
public void setOrgCategory(String orgCategory) {
this.orgCategory = orgCategory;
}
public String getOrgType() {
return orgType;
}
public void setOrgType(String orgType) {
this.orgType = orgType;
}
public String getOrgCode() {
return orgCode;
} | public void setOrgCode(String orgCode) {
this.orgCode = orgCode;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\vo\SysDepartModel.java | 1 |
请完成以下Java代码 | public final class NativeImageArgFile {
/**
* Location of the argfile.
*/
public static final String LOCATION = "META-INF/native-image/argfile";
private final List<String> excludes;
/**
* Constructs a new instance with the given excludes.
* @param excludes dependencies for which the reachability metadata should be excluded
*/
public NativeImageArgFile(Collection<String> excludes) {
this.excludes = List.copyOf(excludes);
}
/**
* Write the arguments file if it is necessary.
* @param writer consumer that should write the contents
*/ | public void writeIfNecessary(ThrowingConsumer<List<String>> writer) {
if (this.excludes.isEmpty()) {
return;
}
List<String> lines = new ArrayList<>();
for (String exclude : this.excludes) {
int lastSlash = exclude.lastIndexOf('/');
String jar = (lastSlash != -1) ? exclude.substring(lastSlash + 1) : exclude;
lines.add("--exclude-config");
lines.add(Pattern.quote(jar));
lines.add("^/META-INF/native-image/.*");
}
writer.accept(lines);
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\NativeImageArgFile.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<User> getUserList() {
List<User> users = new ArrayList<User>(usersMap.values());
return users;
}
@Operation(summary = "新增用户", description = "根据User对象新增用户")
@PostMapping("/users")
public String postUser(@RequestBody User user) {
usersMap.put(user.getId(), user);
return "新增成功";
}
@Operation(summary = "获取用户详细信息", description = "根据id来获取用户详细信息")
@GetMapping("/users/{id}")
public User getUser(@PathVariable Integer id) {
return usersMap.get(id);
}
@Operation(summary = "更新用户详细信息", description = "") | @PutMapping("/users/{id}")
public String putUser(@PathVariable Integer id, @RequestBody User user) {
User tempUser = usersMap.get(id);
tempUser.setName(user.getName());
tempUser.setPassword(user.getPassword());
usersMap.put(id, tempUser);
return "更新成功";
}
@Operation(summary = "删除用户", description = "根据id删除对象")
@DeleteMapping("/users/{id}")
public String deleteUser(@PathVariable Integer id) {
usersMap.remove(id);
return "删除成功";
}
} | repos\spring-boot-projects-main\玩转SpringBoot系列案例源码\spring-boot-swagger\src\main\java\cn\lanqiao\springboot3\controller\UserModuleController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class PPRoutingActivityTemplateId implements RepoIdAware
{
@JsonCreator
public static PPRoutingActivityTemplateId ofRepoId(final int repoId)
{
return new PPRoutingActivityTemplateId(repoId);
}
@Nullable
public static PPRoutingActivityTemplateId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static int toRepoId(@Nullable final PPRoutingActivityTemplateId id)
{
return id != null ? id.getRepoId() : -1; | }
int repoId;
private PPRoutingActivityTemplateId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "AD_WF_Node_Template_ID");
}
@JsonValue
public int toJson()
{
return getRepoId();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\PPRoutingActivityTemplateId.java | 2 |
请完成以下Java代码 | public boolean isMandatoryOnPicking(@NonNull final ProductId productId, @NonNull final AttributeId attributeId)
{
final AttributeSetId attributeSetId = productsService.getAttributeSetId(productId);
final Boolean mandatoryOnPicking = attributesRepo.getAttributeSetDescriptorById(attributeSetId)
.getMandatoryOnPicking(attributeId)
.toBooleanOrNull();
if (mandatoryOnPicking != null)
{
return mandatoryOnPicking;
}
return attributesRepo.getAttributeRecordById(attributeId).isMandatory();
}
@Override
public MathContext getMathContext(final org.compiere.model.I_M_Attribute attribute)
{
Check.assumeNotNull(attribute, "attribute not null");
final I_C_UOM uom = uomDAO.getByIdOrNull(attribute.getC_UOM_ID());
final MathContext mc;
if (uom != null)
{
mc = new MathContext(uom.getStdPrecision(), RoundingMode.HALF_UP);
}
else
{
mc = AttributesBL.DEFAULT_MATHCONTEXT;
}
return mc;
}
@Override
public Date calculateBestBeforeDate(
final Properties ctx,
final ProductId productId,
final BPartnerId vendorBPartnerId,
@NonNull final Date dateReceipt)
{
final I_M_Product product = productsService.getById(productId);
final OrgId orgId = OrgId.ofRepoId(product.getAD_Org_ID());
//
// Get Best-Before days
final I_C_BPartner_Product bpartnerProduct = bpartnerProductDAO.retrieveBPartnerProductAssociation(ctx, vendorBPartnerId, productId, orgId);
if (bpartnerProduct == null)
{ | // no BPartner-Product association defined, so we cannot fetch the bestBeforeDays
return null;
}
final int bestBeforeDays = bpartnerProduct.getShelfLifeMinDays(); // TODO: i think we shall introduce BestBeforeDays
if (bestBeforeDays <= 0)
{
// BestBeforeDays was not configured
return null;
}
//
// Calculate the Best-Before date
return TimeUtil.addDays(dateReceipt, bestBeforeDays);
}
@Override
public int getNumberDisplayType(@NonNull final I_M_Attribute attribute)
{
return isInteger(UomId.ofRepoIdOrNull(attribute.getC_UOM_ID()))
? DisplayType.Integer
: DisplayType.Number;
}
public static boolean isInteger(@Nullable final UomId uomId)
{
return uomId != null && UomId.equals(uomId, UomId.EACH);
}
@Override
public boolean isStorageRelevant(@NonNull final AttributeId attributeId)
{
final I_M_Attribute attribute = getAttributeById(attributeId);
return attribute.isStorageRelevant();
}
@Override
public AttributeListValue retrieveAttributeValueOrNull(@NonNull final AttributeId attributeId, @Nullable final String value)
{
return attributesRepo.retrieveAttributeValueOrNull(attributeId, value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\AttributesBL.java | 1 |
请完成以下Java代码 | private void setM_HU_PI_Item_Product(final I_M_HU sourceHU, final ProductId productId, final List<I_M_HU> husToConfigure)
{
final I_M_HU_PI_Item_Product piip = getM_HU_PI_Item_ProductToUse(sourceHU, productId);
if (piip == null)
{
return;
}
for (final I_M_HU hu : husToConfigure)
{
if (handlingUnitsBL.isLoadingUnit(hu))
{
setM_HU_PI_Item_Product(sourceHU, productId, handlingUnitsDAO.retrieveIncludedHUs(hu));
continue;
}
else if (handlingUnitsBL.isTransportUnit(hu))
{
setM_HU_PI_Item_Product(sourceHU, productId, handlingUnitsDAO.retrieveIncludedHUs(hu));
}
if (hu.getM_HU_PI_Item_Product_ID() > 0)
{
continue;
}
hu.setM_HU_PI_Item_Product_ID(piip.getM_HU_PI_Item_Product_ID());
handlingUnitsDAO.saveHU(hu);
}
}
private I_M_HU_PI_Item_Product getM_HU_PI_Item_ProductToUse(final I_M_HU hu, final ProductId productId)
{
if (tuPIItem == null)
{
return null;
}
final I_M_HU_PI_Item_Product piip = piipDAO.retrievePIMaterialItemProduct(
tuPIItem,
BPartnerId.ofRepoIdOrNull(hu.getC_BPartner_ID()),
productId,
SystemTime.asZonedDateTime());
return piip; | }
private void destroyIfEmptyStorage(@NonNull final IHUContext localHuContextCopy)
{
if (Adempiere.isUnitTestMode())
{
handlingUnitsBL.destroyIfEmptyStorage(localHuContextCopy, huToSplit); // in unit test mode, there won't be a commit
return;
}
// Destroy empty HUs from huToSplit
trxManager.getCurrentTrxListenerManagerOrAutoCommit()
.runAfterCommit(() -> trxManager
.runInNewTrx(() -> handlingUnitsBL
.destroyIfEmptyStorage(localHuContextCopy, huToSplit)));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\impl\HUSplitBuilderCoreEngine.java | 1 |
请完成以下Java代码 | public void exportStatusMassUpdate(
@NonNull final Set<ReceiptScheduleId> receiptScheduleIds,
@NonNull final APIExportStatus exportStatus)
{
if (receiptScheduleIds.isEmpty())
{
return;
}
final ICompositeQueryUpdater<I_M_ReceiptSchedule> updater = queryBL.createCompositeQueryUpdater(I_M_ReceiptSchedule.class)
.addSetColumnValue(COLUMNNAME_ExportStatus, exportStatus.getCode());
queryBL.createQueryBuilder(I_M_ReceiptSchedule.class)
.addInArrayFilter(COLUMNNAME_M_ReceiptSchedule_ID, receiptScheduleIds)
.create()
.updateDirectly(updater);
cacheInvalidationService.invalidate(
CacheInvalidateMultiRequest.fromTableNameAndRepoIdAwares(I_M_ReceiptSchedule.Table_Name, receiptScheduleIds),
ModelCacheInvalidationTiming.AFTER_CHANGE);
}
public void saveAll(@NonNull final ImmutableCollection<ReceiptSchedule> receiptSchedules)
{
for (final ReceiptSchedule receiptSchedule : receiptSchedules)
{
save(receiptSchedule);
}
}
private void save(@NonNull final ReceiptSchedule receiptSchedule)
{
final I_M_ReceiptSchedule record = load(receiptSchedule.getId(), I_M_ReceiptSchedule.class);
record.setExportStatus(receiptSchedule.getExportStatus().getCode());
saveRecord(record);
} | public ImmutableMap<ReceiptScheduleId, ReceiptSchedule> getByIds(@NonNull final ImmutableSet<ReceiptScheduleId> receiptScheduleIds)
{
final List<I_M_ReceiptSchedule> records = loadByRepoIdAwares(receiptScheduleIds, I_M_ReceiptSchedule.class);
final ImmutableMap.Builder<ReceiptScheduleId, ReceiptSchedule> result = ImmutableMap.builder();
for (final I_M_ReceiptSchedule record : records)
{
result.put(ReceiptScheduleId.ofRepoId(record.getM_ReceiptSchedule_ID()), ofRecord(record));
}
return result.build();
}
@Value
@Builder
public static class ReceiptScheduleQuery
{
@NonNull
@Builder.Default
QueryLimit limit = QueryLimit.NO_LIMIT;
Instant canBeExportedFrom;
APIExportStatus exportStatus;
@Builder.Default
boolean includeWithQtyToDeliverZero = false;
@Builder.Default
boolean includeProcessed = false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\ReceiptScheduleRepository.java | 1 |
请完成以下Spring Boot application配置 | server.port=8500
spring.application.name=sentinel-demo
# 日志配置
logging.level.root=info
#application.properties\u4E2D\u7684\u914D\u7F6E\u9879\u4F18\u5148\u7EA7\u9AD8\u4E8Elogback.xml\u6587\u4EF6\u4E2D\u7684\u914D\u7F6E\u9879
logging.file=e:/ssb | -student-log.log
logging.level.com.xiaolyuh=debug
logging.level.org.springframework.web=info
debug=false | repos\spring-boot-student-master\spring-boot-student-sentinel\src\main\resources\application.properties | 2 |
请完成以下Java代码 | final class CompositeRfQResponseProducerFactory implements IRfQResponseProducerFactory
{
private static final Logger logger = LogManager.getLogger(CompositeRfQResponseProducerFactory.class);
private final CopyOnWriteArrayList<IRfQResponseProducerFactory> factories = new CopyOnWriteArrayList<>();
@Override
public IRfQResponseProducer newRfQResponsesProducerFor(final I_C_RfQ rfq)
{
for (final IRfQResponseProducerFactory factory : factories)
{
final IRfQResponseProducer producer = factory.newRfQResponsesProducerFor(rfq);
if (producer != null)
{
return producer;
}
} | // No producer was created
return null;
}
public void addRfQResponsesProducerFactory(final IRfQResponseProducerFactory factory)
{
Check.assumeNotNull(factory, "factory not null");
final boolean added = factories.addIfAbsent(factory);
if (!added)
{
logger.warn("Factory {} was already registered: {}", factory, factories);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\impl\CompositeRfQResponseProducerFactory.java | 1 |
请完成以下Java代码 | public long iterateUsingIteratorAndValues() {
return mapIteration.iterateUsingIteratorAndValues(map);
}
@Benchmark
public long iterateUsingEnhancedForLoopAndEntrySet() {
return mapIteration.iterateUsingEnhancedForLoopAndEntrySet(map);
}
@Benchmark
public long iterateByKeysUsingLambdaAndForEach() {
return mapIteration.iterateByKeysUsingLambdaAndForEach(map);
}
@Benchmark
public long iterateValuesUsingLambdaAndForEach() {
return mapIteration.iterateValuesUsingLambdaAndForEach(map);
}
@Benchmark
public long iterateUsingIteratorAndKeySet() {
return mapIteration.iterateUsingIteratorAndKeySet(map);
}
@Benchmark
public long iterateUsingIteratorAndEntrySet() {
return mapIteration.iterateUsingIteratorAndEntrySet(map);
}
@Benchmark
public long iterateUsingKeySetAndEnhanceForLoop() {
return mapIteration.iterateUsingKeySetAndEnhanceForLoop(map);
}
@Benchmark | public long iterateUsingStreamAPIAndEntrySet() {
return mapIteration.iterateUsingStreamAPIAndEntrySet(map);
}
@Benchmark
public long iterateUsingStreamAPIAndKeySet() {
return mapIteration.iterateUsingStreamAPIAndKeySet(map);
}
@Benchmark
public long iterateKeysUsingKeySetAndEnhanceForLoop() {
return mapIteration.iterateKeysUsingKeySetAndEnhanceForLoop(map);
}
@Benchmark
public long iterateUsingMapIteratorApacheCollection() {
return mapIteration.iterateUsingMapIteratorApacheCollection(iterableMap);
}
@Benchmark
public long iterateEclipseMap() throws IOException {
return mapIteration.iterateEclipseMap(mutableMap);
}
@Benchmark
public long iterateMapUsingParallelStreamApi() throws IOException {
return mapIteration.iterateMapUsingParallelStreamApi(map);
}
} | repos\tutorials-master\core-java-modules\core-java-collections-maps\src\main\java\com\baeldung\map\iteration\MapIterationBenchmark.java | 1 |
请完成以下Java代码 | public void setM_HazardSymbol(final org.compiere.model.I_M_HazardSymbol M_HazardSymbol)
{
set_ValueFromPO(COLUMNNAME_M_HazardSymbol_ID, org.compiere.model.I_M_HazardSymbol.class, M_HazardSymbol);
}
@Override
public void setM_HazardSymbol_ID (final int M_HazardSymbol_ID)
{
if (M_HazardSymbol_ID < 1)
set_Value (COLUMNNAME_M_HazardSymbol_ID, null);
else
set_Value (COLUMNNAME_M_HazardSymbol_ID, M_HazardSymbol_ID);
}
@Override
public int getM_HazardSymbol_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HazardSymbol_ID);
}
@Override
public void setM_Product_HazardSymbol_ID (final int M_Product_HazardSymbol_ID)
{
if (M_Product_HazardSymbol_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_HazardSymbol_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_HazardSymbol_ID, M_Product_HazardSymbol_ID);
}
@Override
public int getM_Product_HazardSymbol_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_HazardSymbol_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);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_HazardSymbol.java | 1 |
请完成以下Java代码 | public mxGraph getGraph() {
return graph;
}
public void setGraph(mxGraph graph) {
this.graph = graph;
}
public int getEventSize() {
return eventSize;
}
public void setEventSize(int eventSize) {
this.eventSize = eventSize;
}
public int getGatewaySize() {
return gatewaySize;
}
public void setGatewaySize(int gatewaySize) {
this.gatewaySize = gatewaySize;
}
public int getTaskWidth() {
return taskWidth;
}
public void setTaskWidth(int taskWidth) {
this.taskWidth = taskWidth;
}
public int getTaskHeight() {
return taskHeight;
}
public void setTaskHeight(int taskHeight) {
this.taskHeight = taskHeight;
}
public int getSubProcessMargin() { | return subProcessMargin;
}
public void setSubProcessMargin(int subProcessMargin) {
this.subProcessMargin = subProcessMargin;
}
// Due to a bug (see
// http://forum.jgraph.com/questions/5952/mxhierarchicallayout-not-correct-when-using-child-vertex)
// We must extend the default hierarchical layout to tweak it a bit (see url
// link) otherwise the layouting crashes.
//
// Verify again with a later release if fixed (ie the mxHierarchicalLayout
// can be used directly)
static class CustomLayout extends mxHierarchicalLayout {
public CustomLayout(mxGraph graph, int orientation) {
super(graph, orientation);
this.traverseAncestors = false;
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-layout\src\main\java\org\activiti\bpmn\BpmnAutoLayout.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public PriceListBasicInfo getTargetPriceListInfo(@NonNull final JsonExternalSystemRequest request)
{
final String targetPriceListIdStr = request.getParameters().get(ExternalSystemConstants.PARAM_TARGET_PRICE_LIST_ID);
if (Check.isBlank(targetPriceListIdStr))
{
return null;
}
final JsonMetasfreshId priceListId = JsonMetasfreshId.of(Integer.parseInt(targetPriceListIdStr));
final PriceListBasicInfo.PriceListBasicInfoBuilder targetPriceListInfoBuilder = PriceListBasicInfo.builder();
targetPriceListInfoBuilder.priceListId(priceListId);
final String isTaxIncluded = request.getParameters().get(ExternalSystemConstants.PARAM_IS_TAX_INCLUDED);
if (isTaxIncluded == null)
{ | throw new RuntimeCamelException("isTaxIncluded is missing although priceListId is specified, targetPriceListId: " + priceListId);
}
targetPriceListInfoBuilder.isTaxIncluded(Boolean.parseBoolean(isTaxIncluded));
final String targetCurrencyCode = request.getParameters().get(ExternalSystemConstants.PARAM_PRICE_LIST_CURRENCY_CODE);
if (targetCurrencyCode == null)
{
throw new RuntimeCamelException("targetCurrencyCode param is missing although priceListId is specified, targetPriceListId: " + priceListId);
}
targetPriceListInfoBuilder.currencyCode(targetCurrencyCode);
return targetPriceListInfoBuilder.build();
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\product\GetProductsRouteHelper.java | 2 |
请完成以下Spring Boot application配置 | server.port=8080
logging.level.root=info
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.initial-size=1
spring.datasource.druid.min-idle=1
spring. | datasource.druid.max-active=20
spring.datasource.druid.test-on-borrow=true
spring.datasource.druid.stat-view-servlet.allow=true | repos\MyBatis-Spring-Boot-master\src\main\resources\application-production.properties | 2 |
请完成以下Java代码 | public PaymentTermId getPaymentTermId(@NonNull final SOTrx soTrx)
{
return soTrx.isSales() ? paymentTermId : poPaymentTermId;
}
@Nullable
public PricingSystemId getPricingSystemId(@NonNull final SOTrx soTrx)
{
return soTrx.isSales() ? pricingSystemId : poPricingSystemId;
}
@NonNull
public PaymentRule getPaymentRule(@NonNull final SOTrx soTrx)
{
return soTrx.isSales() ? paymentRule : poPaymentRule;
}
@NonNull
public InvoiceRule getInvoiceRule(@NonNull final SOTrx soTrx) | {
return soTrx.isSales() ? invoiceRule : poInvoiceRule;
}
public boolean isAutoInvoice(@NonNull final SOTrx soTrx)
{
return soTrx.isSales() && isAutoInvoice;
}
@Nullable
public Incoterms getIncoterms(@NonNull final SOTrx soTrx)
{
return soTrx.isSales() ? incoterms : poIncoterms;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\effective\BPartnerEffective.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void customize(GsonBuilder builder) {
GsonProperties properties = this.properties;
PropertyMapper map = PropertyMapper.get();
map.from(properties::getGenerateNonExecutableJson).whenTrue().toCall(builder::generateNonExecutableJson);
map.from(properties::getExcludeFieldsWithoutExposeAnnotation)
.whenTrue()
.toCall(builder::excludeFieldsWithoutExposeAnnotation);
map.from(properties::getSerializeNulls).whenTrue().toCall(builder::serializeNulls);
map.from(properties::getEnableComplexMapKeySerialization)
.whenTrue()
.toCall(builder::enableComplexMapKeySerialization);
map.from(properties::getDisableInnerClassSerialization)
.whenTrue()
.toCall(builder::disableInnerClassSerialization);
map.from(properties::getLongSerializationPolicy).to(builder::setLongSerializationPolicy);
map.from(properties::getFieldNamingPolicy).to(builder::setFieldNamingPolicy);
map.from(properties::getPrettyPrinting).whenTrue().toCall(builder::setPrettyPrinting);
map.from(properties::getStrictness).to(strictnessOrLeniency(builder));
map.from(properties::getDisableHtmlEscaping).whenTrue().toCall(builder::disableHtmlEscaping);
map.from(properties::getDateFormat).to(builder::setDateFormat);
} | @SuppressWarnings("deprecation")
private Consumer<GsonProperties.Strictness> strictnessOrLeniency(GsonBuilder builder) {
if (ClassUtils.isPresent("com.google.gson.Strictness", getClass().getClassLoader())) {
return (strictness) -> builder.setStrictness(Strictness.valueOf(strictness.name()));
}
return (strictness) -> {
if (strictness == GsonProperties.Strictness.LENIENT) {
builder.setLenient();
}
};
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-gson\src\main\java\org\springframework\boot\gson\autoconfigure\GsonAutoConfiguration.java | 2 |
请完成以下Java代码 | public void setLoginUsername (final @Nullable String LoginUsername)
{
set_Value (COLUMNNAME_LoginUsername, LoginUsername);
}
@Override
public String getLoginUsername()
{
return get_ValueAsString(COLUMNNAME_LoginUsername);
}
@Override
public void setOutboundHttpEP (final String OutboundHttpEP)
{
set_Value (COLUMNNAME_OutboundHttpEP, OutboundHttpEP);
}
@Override
public String getOutboundHttpEP()
{
return get_ValueAsString(COLUMNNAME_OutboundHttpEP);
}
@Override
public void setOutboundHttpMethod (final String OutboundHttpMethod)
{
set_Value (COLUMNNAME_OutboundHttpMethod, OutboundHttpMethod);
}
@Override
public String getOutboundHttpMethod()
{
return get_ValueAsString(COLUMNNAME_OutboundHttpMethod);
}
@Override
public void setPassword (final @Nullable String Password)
{
set_Value (COLUMNNAME_Password, Password);
}
@Override
public String getPassword()
{
return get_ValueAsString(COLUMNNAME_Password);
}
@Override
public void setSasSignature (final @Nullable String SasSignature) | {
set_Value (COLUMNNAME_SasSignature, SasSignature);
}
@Override
public String getSasSignature()
{
return get_ValueAsString(COLUMNNAME_SasSignature);
}
/**
* Type AD_Reference_ID=542016
* Reference name: ExternalSystem_Outbound_Endpoint_EndpointType
*/
public static final int TYPE_AD_Reference_ID=542016;
/** HTTP = HTTP */
public static final String TYPE_HTTP = "HTTP";
/** SFTP = SFTP */
public static final String TYPE_SFTP = "SFTP";
/** FILE = FILE */
public static final String TYPE_FILE = "FILE";
/** EMAIL = EMAIL */
public static final String TYPE_EMAIL = "EMAIL";
/** TCP = TCP */
public static final String TYPE_TCP = "TCP";
@Override
public void setType (final String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
@Override
public void setValue (final String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public 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_Outbound_Endpoint.java | 1 |
请完成以下Java代码 | private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addPackage("com.baeldung.hibernate.pojo");
metadataSources.addAnnotatedClass(Employee.class);
metadataSources.addAnnotatedClass(Phone.class);
metadataSources.addAnnotatedClass(EntityDescription.class);
metadataSources.addAnnotatedClass(DeptEmployee.class);
metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class);
Metadata metadata = metadataSources.getMetadataBuilder()
.build();
return metadata.getSessionFactoryBuilder()
.build();
}
private static ServiceRegistry configureServiceRegistry() throws IOException {
Properties properties = getProperties(); | return new StandardServiceRegistryBuilder().applySettings(properties)
.build();
}
private static Properties getProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties"));
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
} | repos\tutorials-master\persistence-modules\hibernate-mapping-2\src\main\java\com\baeldung\hibernate\HibernateUtil.java | 1 |
请完成以下Java代码 | public boolean canUpdate(final I_AD_BoilerPlate textTemplate)
{
if (textTemplate == null)
{
return false;
}
final Properties ctx = InterfaceWrapperHelper.getCtx(textTemplate);
final ClientId adClientId = ClientId.ofRepoId(textTemplate.getAD_Client_ID());
final OrgId adOrgId = OrgId.ofRepoId(textTemplate.getAD_Org_ID());
final int tableId = InterfaceWrapperHelper.getTableId(I_AD_BoilerPlate.class);
final int recordId = textTemplate.getAD_BoilerPlate_ID();
final boolean createError = false;
final boolean rw = Env.getUserRolePermissions(ctx).canUpdate(adClientId, adOrgId, tableId, recordId, createError);
return rw;
}
@Override
public <T> void createLetters(Iterator<T> source, ILetterProducer<T> producer)
{
while (source.hasNext())
{
final T item = source.next();
createLetter(item, producer);
}
}
@Override
public <T> I_C_Letter createLetter(final T item, final ILetterProducer<T> producer)
{
DB.saveConstraints();
DB.getConstraints().addAllowedTrxNamePrefix("POSave");
try
{
final Properties ctx = InterfaceWrapperHelper.getCtx(item);
// NOTE: we are working out of trx because we want to produce the letters one by one and build a huge transaction
final String trxName = ITrx.TRXNAME_None;
final I_C_Letter letter = InterfaceWrapperHelper.create(ctx, I_C_Letter.class, trxName);
if (!producer.createLetter(letter, item))
{
return null;
}
setLocationContactAndOrg(letter);
final int boilerPlateID = producer.getBoilerplateID(item);
if (boilerPlateID <= 0)
{
logger.warn("No default text template for org {}", letter.getAD_Org_ID());
return null;
}
final I_AD_BoilerPlate textTemplate = InterfaceWrapperHelper.create(ctx, boilerPlateID, I_AD_BoilerPlate.class, trxName); | setAD_BoilerPlate(letter, textTemplate);
final BoilerPlateContext attributes = producer.createAttributes(item);
setLetterBodyParsed(letter, attributes);
// 04238 : We need to flag the letter for enqueue.
letter.setIsMembershipBadgeToPrint(true);
// mo73_05916 : Add record and table ID
letter.setAD_Table_ID(InterfaceWrapperHelper.getModelTableId(item));
letter.setRecord_ID(InterfaceWrapperHelper.getId(item));
InterfaceWrapperHelper.save(letter);
return letter;
}
finally
{
DB.restoreConstraints();
}
}
@Override
public I_AD_BoilerPlate getById(int boilerPlateId)
{
return loadOutOfTrx(boilerPlateId, I_AD_BoilerPlate.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\letters\api\impl\TextTemplateBL.java | 1 |
请完成以下Java代码 | public class RabbitMqConsumer {
@RabbitListener(queues = {"${rabbit.mq.queue0}"}, containerFactory = "jmsQueue4TalentIdContainer0")
public void firstMq0(String msg) {
log.info("dev0 receive msg: {}", msg);
}
@RabbitListener(queues = {"${rabbit.mq.queue1}"}, containerFactory = "jmsQueue4TalentIdContainer1")
public void firstMq1(String msg) {
log.info("dev1 receive msg: {}", msg);
}
@RabbitListener(queues = {"${rabbit.mq.queue2}"}, containerFactory = "jmsQueue4TalentIdContainer2")
public void firstMq2(String msg) {
log.info("dev2 receive msg: {}", msg);
}
@RabbitListener(queues = {"${rabbit.mq.queue3}"}, containerFactory = "jmsQueue4TalentIdContainer3")
public void firstMq3(String msg) {
log.info("dev3 receive msg: {}", msg);
} | @RabbitListener(queues = {"${rabbit.mq.queue4}"}, containerFactory = "jmsQueue4TalentIdContainer4")
public void firstMq4(String msg) {
log.info("dev4 receive msg: {}", msg);
}
@RabbitListener(queues = {"${rabbit.mq.queue5}"}, containerFactory = "jmsQueue4TalentIdContainer5")
public void firstMq5(String msg) {
log.info("dev5 receive msg: {}", msg);
}
// @RabbitListener(queues = {"tbd_resume_id_rc_5"}, containerFactory = "secondContainerFactory")
// public void secondMq(String msg) {
// log.info("rc receive msg: {}", msg);
// }
} | repos\spring-boot-quick-master\quick-multi-rabbitmq\src\main\java\com\multi\rabbitmq\mq\RabbitMqConsumer.java | 1 |
请完成以下Java代码 | private boolean containsOnlyValidCertificates(CertificateChainInfo certificateChain) {
return validatableCertificates(certificateChain).allMatch(this::isValidCertificate);
}
private boolean containsInvalidCertificate(CertificateChainInfo certificateChain) {
return validatableCertificates(certificateChain).anyMatch(this::isNotValidCertificate);
}
private boolean containsExpiringCertificate(CertificateChainInfo certificateChain) {
return validatableCertificates(certificateChain).anyMatch(this::isExpiringCertificate);
}
private Stream<CertificateInfo> validatableCertificates(CertificateChainInfo certificateChain) {
return certificateChain.getCertificates().stream().filter((certificate) -> certificate.getValidity() != null);
}
private boolean isValidCertificate(CertificateInfo certificate) { | CertificateValidityInfo validity = certificate.getValidity();
Assert.state(validity != null, "'validity' must not be null");
return validity.getStatus().isValid();
}
private boolean isNotValidCertificate(CertificateInfo certificate) {
return !isValidCertificate(certificate);
}
private boolean isExpiringCertificate(CertificateInfo certificate) {
Instant validityEnds = certificate.getValidityEnds();
Assert.state(validityEnds != null, "'validityEnds' must not be null");
return Instant.now().plus(this.expiryThreshold).isAfter(validityEnds);
}
} | repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\application\SslHealthIndicator.java | 1 |
请完成以下Java代码 | public void run() {
Window[] w = windowManager.getWindows();
Container dialogContent = dialog.getContentPane();
dialogContent.setLayout(new BorderLayout());
final CardLayout card = new CardLayout();
final JXPanel cardContainer = new JXPanel(card);
dialogContent.add(cardContainer, BorderLayout.CENTER);
JXPanel p = createSelectionPanel();
cardContainer.add(p, "page1");
Dimension s = Toolkit.getDefaultToolkit().getScreenSize();
int width = ( s.width - 30 ) / 3;
int height = ( s.height - 30 ) / 3;
int count = 0;
JFrame frame = Env.getWindow(0);
if (frame != null && frame instanceof AMenu) {
JXTitledPanel box = createImageBox(p, dialog, width, height,
frame);
p.add(box);
count ++;
firstBox = box;
}
int page = 1;
for(int i = 0; i < w.length; i++) {
count ++;
Window window = w[i];
JXTitledPanel box = createImageBox(p, dialog, width, height,
window);
p.add(box);
if (i == 0 && firstBox == null) firstBox = box;
if ( count == 9) {
count = 0;
page++;
p = createSelectionPanel();
cardContainer.add(p, "page" + page);
}
}
for ( int i = count; i < 9; i++ ) {
p.add(Box.createGlue());
}
dialog.addWindowFocusListener(new WindowFocusListener() {
@Override
public void windowGainedFocus(WindowEvent e) {
if (firstBox != null)
firstBox.requestFocus();
}
@Override
public void windowLostFocus(WindowEvent e) {
}
});
card.first(cardContainer);
if (page > 1) {
JXPanel ctrl = new JXPanel();
JXButton previous = new JXButton("<");
JXButton next = new JXButton(">");
previous.addActionListener(new ActionListener() { | @Override
public void actionPerformed(ActionEvent e) {
card.previous(cardContainer);
}
});
next.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
card.next(cardContainer);
}
});
ctrl.add(previous);
ctrl.add(next);
dialogContent.add(ctrl, BorderLayout.NORTH);
}
dialog.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
class PreviewMouseAdapter extends MouseAdapter {
private JDialog dialog;
private Window window;
PreviewMouseAdapter(JDialog d, Window w) {
dialog = d;
window = w;
}
@Override
public void mouseClicked(MouseEvent e) {
dialog.dispose();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
AEnv.showWindow(window);
}
});
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\WindowMenu.java | 1 |
请完成以下Java代码 | public List<I_PP_Order_Qty> retrieveOrderQtys(final PPOrderId ppOrderId)
{
return retrieveOrderQtys(Env.getCtx(), ppOrderId, ITrx.TRXNAME_ThreadInherited);
}
@SuppressWarnings("SameParameterValue")
@Cached(cacheName = I_PP_Order_Qty.Table_Name + "#by#PP_Order_ID", expireMinutes = 10)
ImmutableList<I_PP_Order_Qty> retrieveOrderQtys(@CacheCtx final Properties ctx, @NonNull final PPOrderId ppOrderId, @CacheTrx final String trxName)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_PP_Order_Qty.class, ctx, trxName)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_PP_Order_Qty.COLUMN_PP_Order_ID, ppOrderId)
.orderBy(I_PP_Order_Qty.COLUMNNAME_PP_Order_Qty_ID)
.create()
.listImmutable(I_PP_Order_Qty.class);
}
@Override
public I_PP_Order_Qty retrieveOrderQtyForCostCollector(
@NonNull final PPOrderId ppOrderId,
@NonNull final PPCostCollectorId costCollectorId)
{
return retrieveOrderQtys(ppOrderId)
.stream()
.filter(cand -> cand.getPP_Cost_Collector_ID() == costCollectorId.getRepoId())
// .peek(cand -> Check.assume(cand.isProcessed(), "Candidate was expected to be processed: {}", cand))
.reduce((cand1, cand2) -> {
throw new HUException("Expected only one candidate but got: " + cand1 + ", " + cand2);
})
.orElse(null);
}
@Override
public List<I_PP_Order_Qty> retrieveOrderQtyForFinishedGoodsReceive(@NonNull final PPOrderId ppOrderId)
{
return retrieveOrderQtys(ppOrderId)
.stream() | .filter(cand -> cand.getPP_Order_BOMLine_ID() <= 0)
.collect(ImmutableList.toImmutableList());
}
@Override
public Optional<I_PP_Order_Qty> retrieveOrderQtyForHu(
@NonNull final PPOrderId ppOrderId,
@NonNull final HuId huId)
{
return retrieveOrderQtys(ppOrderId)
.stream()
.filter(cand -> cand.getM_HU_ID() == huId.getRepoId())
.reduce((cand1, cand2) -> {
throw new HUException("Expected only one candidate but got: " + cand1 + ", " + cand2);
});
}
@Override
public boolean hasUnprocessedOrderQty(@NonNull final PPOrderId ppOrderId)
{
return streamOrderQtys(ppOrderId)
.anyMatch(candidate -> !candidate.isProcessed());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\HUPPOrderQtyDAO.java | 1 |
请完成以下Java代码 | public void setUp() {
for (long i = 0; i < iterations; i++) {
employeeMap.put(i, new Employee(i, "John"));
}
//employeeMap.put(iterations, employee);
}
}
@Benchmark
public Employee testGet(MyState state) {
return state.employeeMap.get(state.iterations);
}
@Benchmark
public Employee testRemove(MyState state) {
return state.employeeMap.remove(state.iterations);
}
@Benchmark
public Employee testPut(MyState state) {
return state.employeeMap.put(state.employee.getId(), state.employee);
} | @Benchmark
public Boolean testContainsKey(MyState state) {
return state.employeeMap.containsKey(state.employee.getId());
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(HashMapBenchmark.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
} | repos\tutorials-master\core-java-modules\core-java-collections-7\src\main\java\com\baeldung\performance\HashMapBenchmark.java | 1 |
请完成以下Java代码 | public class Main implements ModelValidator
{
private int adClientId = -1;
@Override
public void initialize(final ModelValidationEngine engine, final MClient client)
{
adClientId = client == null ? -1 : client.getAD_Client_ID();
// task 08926
// invoice candidate listener
final IInvoiceCandidateListeners invoiceCandidateListeners = Services.get(IInvoiceCandidateListeners.class);
invoiceCandidateListeners.addListener(EdiInvoiceCandidateListener.instance);
// task 08926
// invoice copy handler
Services.get(ICopyHandlerBL.class).registerCopyHandler(
org.compiere.model.I_C_Invoice.class,
new IQueryFilter<ImmutablePair<org.compiere.model.I_C_Invoice, org.compiere.model.I_C_Invoice>>()
{
@Override
public boolean accept(ImmutablePair<org.compiere.model.I_C_Invoice, org.compiere.model.I_C_Invoice> model)
{
return true;
}
},
new EdiInvoiceCopyHandler());
}
@Override
public int getAD_Client_ID() | {
return adClientId;
}
@Override
public String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID)
{
return null;
}
@Override
public String modelChange(final PO po, final int type)
{
return null;
}
@Override
public String docValidate(final PO po, final int timing)
{
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\model\validator\Main.java | 1 |
请完成以下Java代码 | public class OrderConsumer {
@Autowired
OrderRepository orderRepository;
@Autowired
OrderProducer orderProducer;
@KafkaListener(topics = "orders", groupId = "orders")
public void consume(Order order) throws IOException {
log.info("Order received to process: {}", order);
if (OrderStatus.INITIATION_SUCCESS.equals(order.getOrderStatus())) {
orderRepository.findById(order.getId())
.map(o -> {
orderProducer.sendMessage(o.setOrderStatus(OrderStatus.RESERVE_INVENTORY));
return o.setOrderStatus(order.getOrderStatus())
.setResponseMessage(order.getResponseMessage());
})
.flatMap(orderRepository::save)
.subscribe();
} else if (OrderStatus.INVENTORY_SUCCESS.equals(order.getOrderStatus())) {
orderRepository.findById(order.getId())
.map(o -> {
orderProducer.sendMessage(o.setOrderStatus(OrderStatus.PREPARE_SHIPPING)); | return o.setOrderStatus(order.getOrderStatus())
.setResponseMessage(order.getResponseMessage());
})
.flatMap(orderRepository::save)
.subscribe();
} else if (OrderStatus.SHIPPING_FAILURE.equals(order.getOrderStatus())) {
orderRepository.findById(order.getId())
.map(o -> {
orderProducer.sendMessage(o.setOrderStatus(OrderStatus.REVERT_INVENTORY));
return o.setOrderStatus(order.getOrderStatus())
.setResponseMessage(order.getResponseMessage());
})
.flatMap(orderRepository::save)
.subscribe();
} else {
orderRepository.findById(order.getId())
.map(o -> {
return o.setOrderStatus(order.getOrderStatus())
.setResponseMessage(order.getResponseMessage());
})
.flatMap(orderRepository::save)
.subscribe();
}
}
} | repos\tutorials-master\reactive-systems\order-service\src\main\java\com\baeldung\async\consumer\OrderConsumer.java | 1 |
请完成以下Java代码 | public List<DecisionDefinitionDto> getDecisionDefinitions(UriInfo uriInfo, Integer firstResult, Integer maxResults) {
DecisionDefinitionQueryDto queryDto = new DecisionDefinitionQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
List<DecisionDefinitionDto> definitions = new ArrayList<DecisionDefinitionDto>();
ProcessEngine engine = getProcessEngine();
DecisionDefinitionQuery query = queryDto.toQuery(engine);
List<DecisionDefinition> matchingDefinitions = QueryUtil.list(query, firstResult, maxResults);
for (DecisionDefinition definition : matchingDefinitions) {
DecisionDefinitionDto def = DecisionDefinitionDto.fromDecisionDefinition(definition);
definitions.add(def);
}
return definitions;
} | @Override
public CountResultDto getDecisionDefinitionsCount(UriInfo uriInfo) {
DecisionDefinitionQueryDto queryDto = new DecisionDefinitionQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
ProcessEngine engine = getProcessEngine();
DecisionDefinitionQuery query = queryDto.toQuery(engine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\DecisionDefinitionRestServiceImpl.java | 1 |
请完成以下Java代码 | void skippingFirstElementInSetWithWhileLoop(Set<String> stringSet) {
final Iterator<String> iterator = stringSet.iterator();
if (iterator.hasNext()) {
iterator.next();
}
while (iterator.hasNext()) {
process(iterator.next());
}
}
void skippingFirstElementInListWithWhileLoopStoringFirstElement(List<String> stringList) {
final Iterator<String> iterator = stringList.iterator();
String firstElement = null;
if (iterator.hasNext()) {
firstElement = iterator.next();
}
while (iterator.hasNext()) {
process(iterator.next());
// additional logic using fistElement
}
}
void skippingFirstElementInMapWithStreamSkip(Map<String, String> stringMap) {
stringMap.entrySet().stream().skip(1).forEach(this::process);
}
void skippingFirstElementInListWithSubList(List<String> stringList) {
for (final String element : stringList.subList(1, stringList.size())) {
process(element);
}
}
void skippingFirstElementInListWithForLoopWithAdditionalCheck(List<String> stringList) {
for (int i = 0; i < stringList.size(); i++) { | if (i == 0) {
// do something else
} else {
process(stringList.get(i));
}
}
}
void skippingFirstElementInListWithWhileLoopWithCounter(List<String> stringList) {
int counter = 0;
while (counter < stringList.size()) {
if (counter != 0) {
process(stringList.get(counter));
}
++counter;
}
}
void skippingFirstElementInListWithReduce(List<String> stringList) {
stringList.stream().reduce((skip, element) -> {
process(element);
return element;
});
}
protected void process(String string) {
System.out.println(string);
}
protected void process(Entry<String, String> mapEntry) {
System.out.println(mapEntry);
}
} | repos\tutorials-master\core-java-modules\core-java-collections-5\src\main\java\com\baeldung\skippingfirstelement\SkipFirstElementExample.java | 1 |
请完成以下Java代码 | public void afterPropertiesSet()
{
final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
final int clearViewSelectionsRateInSeconds = sysConfigBL.getIntValue(SYSCONFIG_ClearViewSelectionsRateInSeconds, 1800);
if (clearViewSelectionsRateInSeconds > 0)
{
final ScheduledExecutorService scheduledExecutor = viewMaintenanceScheduledExecutorService();
scheduledExecutor.scheduleAtFixedRate(
SqlViewSelectionToDeleteHelper::deleteScheduledSelectionsNoFail, // command, don't fail because on failure the task won't be re-scheduled, so it's game over
clearViewSelectionsRateInSeconds, // initialDelay
clearViewSelectionsRateInSeconds, // period
TimeUnit.SECONDS // timeUnit
);
logger.info("Clearing view selections each {} seconds (see {} sysconfig)", clearViewSelectionsRateInSeconds, SYSCONFIG_ClearViewSelectionsRateInSeconds);
}
else | {
logger.info("Clearing view selections disabled (see {} sysconfig)", SYSCONFIG_ClearViewSelectionsRateInSeconds);
}
}
private ScheduledExecutorService viewMaintenanceScheduledExecutorService()
{
return Executors.newScheduledThreadPool(
1, // corePoolSize
CustomizableThreadFactory.builder()
.setDaemon(true)
.setThreadNamePrefix("webui-views-maintenance")
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewConfiguration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable Resource getCertificateLocation() {
return this.certificate;
}
public void setCertificateLocation(@Nullable Resource certificate) {
this.certificate = certificate;
}
}
}
}
/**
* Single logout details.
*/
public static class Singlelogout {
/**
* Location where SAML2 LogoutRequest gets sent to.
*/
private @Nullable String url;
/**
* Location where SAML2 LogoutResponse gets sent to.
*/
private @Nullable String responseUrl;
/**
* Whether to redirect or post logout requests.
*/
private @Nullable Saml2MessageBinding binding;
public @Nullable String getUrl() {
return this.url;
}
public void setUrl(@Nullable String url) {
this.url = url; | }
public @Nullable String getResponseUrl() {
return this.responseUrl;
}
public void setResponseUrl(@Nullable String responseUrl) {
this.responseUrl = responseUrl;
}
public @Nullable Saml2MessageBinding getBinding() {
return this.binding;
}
public void setBinding(@Nullable Saml2MessageBinding binding) {
this.binding = binding;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-security-saml2\src\main\java\org\springframework\boot\security\saml2\autoconfigure\Saml2RelyingPartyProperties.java | 2 |
请完成以下Java代码 | public boolean isCompleteAsync() {
return completeAsync;
}
public void setCompleteAsync(boolean completeAsync) {
this.completeAsync = completeAsync;
}
public Boolean getFallbackToDefaultTenant() {
return fallbackToDefaultTenant;
}
public void setFallbackToDefaultTenant(Boolean fallbackToDefaultTenant) {
this.fallbackToDefaultTenant = fallbackToDefaultTenant;
}
public void setCalledElementType(String calledElementType) {
this.calledElementType = calledElementType;
}
public String getCalledElementType() {
return calledElementType;
}
public String getProcessInstanceIdVariableName() {
return processInstanceIdVariableName;
}
public void setProcessInstanceIdVariableName(String processInstanceIdVariableName) {
this.processInstanceIdVariableName = processInstanceIdVariableName;
}
@Override
public CallActivity clone() {
CallActivity clone = new CallActivity();
clone.setValues(this);
return clone;
} | public void setValues(CallActivity otherElement) {
super.setValues(otherElement);
setCalledElement(otherElement.getCalledElement());
setCalledElementType(otherElement.getCalledElementType());
setBusinessKey(otherElement.getBusinessKey());
setInheritBusinessKey(otherElement.isInheritBusinessKey());
setInheritVariables(otherElement.isInheritVariables());
setSameDeployment(otherElement.isSameDeployment());
setUseLocalScopeForOutParameters(otherElement.isUseLocalScopeForOutParameters());
setCompleteAsync(otherElement.isCompleteAsync());
setFallbackToDefaultTenant(otherElement.getFallbackToDefaultTenant());
inParameters = new ArrayList<>();
if (otherElement.getInParameters() != null && !otherElement.getInParameters().isEmpty()) {
for (IOParameter parameter : otherElement.getInParameters()) {
inParameters.add(parameter.clone());
}
}
outParameters = new ArrayList<>();
if (otherElement.getOutParameters() != null && !otherElement.getOutParameters().isEmpty()) {
for (IOParameter parameter : otherElement.getOutParameters()) {
outParameters.add(parameter.clone());
}
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\CallActivity.java | 1 |
请完成以下Java代码 | public int getPricePrecision ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PricePrecision);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Standard Price.
@param PriceStd
Standard Price
*/
public void setPriceStd (BigDecimal PriceStd)
{
set_Value (COLUMNNAME_PriceStd, PriceStd);
}
/** Get Standard Price.
@return Standard Price
*/
public BigDecimal getPriceStd ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceStd);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
} | /** Set Product Key.
@param ProductValue
Key of the Product
*/
public void setProductValue (String ProductValue)
{
set_Value (COLUMNNAME_ProductValue, ProductValue);
}
/** Get Product Key.
@return Key of the Product
*/
public String getProductValue ()
{
return (String)get_Value(COLUMNNAME_ProductValue);
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set UOM Code.
@param X12DE355
UOM EDI X12 Code
*/
public void setX12DE355 (String X12DE355)
{
set_Value (COLUMNNAME_X12DE355, X12DE355);
}
/** Get UOM Code.
@return UOM EDI X12 Code
*/
public String getX12DE355 ()
{
return (String)get_Value(COLUMNNAME_X12DE355);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_PriceList.java | 1 |
请完成以下Java代码 | public String getAuthority() {
return name;
}
public Authority() {
}
public Authority(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Authority authority1 = (Authority) o; | return name.equals(authority1.name);
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public String toString() {
return "Authority{" +
"authority='" + name + '\'' +
'}';
}
} | repos\spring-boot-web-application-sample-master\main-app\main-orm\src\main\java\gt\app\domain\Authority.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public R save(@Valid @RequestBody Datasource datasource) {
return R.status(datasourceService.save(datasource));
}
/**
* 修改 数据源配置表
*/
@PostMapping("/update")
@ApiOperationSupport(order = 5)
@Operation(summary = "修改", description = "传入datasource")
public R update(@Valid @RequestBody Datasource datasource) {
return R.status(datasourceService.updateById(datasource));
}
/**
* 新增或修改 数据源配置表
*/
@PostMapping("/submit")
@ApiOperationSupport(order = 6)
@Operation(summary = "新增或修改", description = "传入datasource")
public R submit(@Valid @RequestBody Datasource datasource) {
datasource.setUrl(datasource.getUrl().replace("&", "&"));
return R.status(datasourceService.saveOrUpdate(datasource));
}
/**
* 删除 数据源配置表
*/
@PostMapping("/remove")
@ApiOperationSupport(order = 7) | @Operation(summary = "逻辑删除", description = "传入ids")
public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
return R.status(datasourceService.deleteLogic(Func.toLongList(ids)));
}
/**
* 数据源列表
*/
@GetMapping("/select")
@ApiOperationSupport(order = 8)
@Operation(summary = "下拉数据源", description = "查询列表")
public R<List<Datasource>> select() {
List<Datasource> list = datasourceService.list();
return R.data(list);
}
} | repos\SpringBlade-master\blade-ops\blade-develop\src\main\java\org\springblade\develop\controller\DatasourceController.java | 2 |
请完成以下Java代码 | public void setAlbertaRole (final String AlbertaRole)
{
set_Value (COLUMNNAME_AlbertaRole, AlbertaRole);
}
@Override
public String getAlbertaRole()
{
return get_ValueAsString(COLUMNNAME_AlbertaRole);
}
@Override
public void setC_BPartner_AlbertaRole_ID (final int C_BPartner_AlbertaRole_ID)
{
if (C_BPartner_AlbertaRole_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_AlbertaRole_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_AlbertaRole_ID, C_BPartner_AlbertaRole_ID);
}
@Override
public int getC_BPartner_AlbertaRole_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_AlbertaRole_ID);
} | @Override
public void setC_BPartner_ID (final int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_Value (COLUMNNAME_C_BPartner_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_ID, C_BPartner_ID);
}
@Override
public int getC_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_C_BPartner_AlbertaRole.java | 1 |
请完成以下Java代码 | private boolean isAuthenticated() {
return getUserPrincipal() != null;
}
}
private static class SecurityContextAsyncContext implements AsyncContext {
private final AsyncContext asyncContext;
SecurityContextAsyncContext(AsyncContext asyncContext) {
this.asyncContext = asyncContext;
}
@Override
public ServletRequest getRequest() {
return this.asyncContext.getRequest();
}
@Override
public ServletResponse getResponse() {
return this.asyncContext.getResponse();
}
@Override
public boolean hasOriginalRequestAndResponse() {
return this.asyncContext.hasOriginalRequestAndResponse();
}
@Override
public void dispatch() {
this.asyncContext.dispatch();
}
@Override
public void dispatch(String path) {
this.asyncContext.dispatch(path);
}
@Override
public void dispatch(ServletContext context, String path) {
this.asyncContext.dispatch(context, path);
}
@Override
public void complete() {
this.asyncContext.complete();
} | @Override
public void start(Runnable run) {
this.asyncContext.start(new DelegatingSecurityContextRunnable(run));
}
@Override
public void addListener(AsyncListener listener) {
this.asyncContext.addListener(listener);
}
@Override
public void addListener(AsyncListener listener, ServletRequest request, ServletResponse response) {
this.asyncContext.addListener(listener, request, response);
}
@Override
public <T extends AsyncListener> T createListener(Class<T> clazz) throws ServletException {
return this.asyncContext.createListener(clazz);
}
@Override
public long getTimeout() {
return this.asyncContext.getTimeout();
}
@Override
public void setTimeout(long timeout) {
this.asyncContext.setTimeout(timeout);
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\servletapi\HttpServlet3RequestFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserController {
@Autowired
private MyService service;
@GetMapping("/me/myapi")
public String me(@RequestParam String username, @RequestParam String password, HttpServletResponse responsehttp) {
try {
OAuth2AccessToken token = service.getService().getAccessTokenPasswordGrant(username, password);
OAuthRequest request = new OAuthRequest(Verb.GET, "http://localhost:8080/me");
service.getService().signRequest(token, request);
Response response = service.getService().execute(request); | return response.getBody();
} catch (Exception e) {
responsehttp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
return null;
}
@GetMapping("/me")
public Principal user(Principal principal) {
return principal;
}
} | repos\tutorials-master\libraries-security-2\src\main\java\com\baeldung\scribejava\controller\UserController.java | 2 |
请完成以下Java代码 | public final void setArtifactParameter(final String artifactParameter) {
this.artifactParameter = artifactParameter;
}
/**
* Configures the Request parameter to look for when attempting to send a request to
* CAS.
* @return the service parameter to use. Default is "service".
*/
public final String getServiceParameter() {
return this.serviceParameter;
}
public final void setServiceParameter(final String serviceParameter) {
this.serviceParameter = serviceParameter;
} | public final boolean isAuthenticateAllArtifacts() {
return this.authenticateAllArtifacts;
}
/**
* If true, then any non-null artifact (ticket) should be authenticated. Additionally,
* the service will be determined dynamically in order to ensure the service matches
* the expected value for this artifact.
* @param authenticateAllArtifacts
*/
public final void setAuthenticateAllArtifacts(final boolean authenticateAllArtifacts) {
this.authenticateAllArtifacts = authenticateAllArtifacts;
}
} | repos\spring-security-main\cas\src\main\java\org\springframework\security\cas\ServiceProperties.java | 1 |
请完成以下Java代码 | protected boolean beforeSave(boolean newRecord)
{
// Check all settings are correct by reload all data
m_mediaSize = null;
getMediaSize();
getCPaper();
return true;
}
/**
* Media Size Name
*/
class CMediaSizeName extends MediaSizeName
{
/**
*
*/
private static final long serialVersionUID = 8561532175435930293L;
/**
* CMediaSizeName
* @param code
*/
public CMediaSizeName(int code)
{
super (code);
} // CMediaSizeName
/**
* Get String Table
* @return string
*/
public String[] getStringTable ()
{
return super.getStringTable ();
}
/**
* Get Enum Value Table
* @return Media Sizes
*/
public EnumSyntax[] getEnumValueTable ()
{
return super.getEnumValueTable ();
} | } // CMediaSizeName
/**************************************************************************
* Test
* @param args args
*/
public static void main(String[] args)
{
org.compiere.Adempiere.startupEnvironment(true);
// create ("Standard Landscape", true);
// create ("Standard Portrait", false);
// Read All Papers
int[] IDs = PO.getAllIDs ("AD_PrintPaper", null, null);
for (int i = 0; i < IDs.length; i++)
{
System.out.println("--");
MPrintPaper pp = new MPrintPaper(Env.getCtx(), IDs[i], null);
pp.dump();
}
}
} // MPrintPaper | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\MPrintPaper.java | 1 |
请完成以下Java代码 | public class DD_Order_CompleteForwardBackward extends JavaProcess
{
private final DDOrderLowLevelService ddOrderLowLevelService = SpringContextHolder.instance.getBean(DDOrderLowLevelService.class);
private I_DD_Order p_ddOrder;
@Override
protected void prepare()
{
// nothing
}
@Override
protected String doIt()
{
final I_DD_Order ddOrder = getDD_Order();
ddOrderLowLevelService.completeForwardAndBackwardDDOrders(ddOrder);
return MSG_OK;
}
private I_DD_Order getDD_Order()
{
if (p_ddOrder != null)
{ | return p_ddOrder;
}
if (I_DD_Order.Table_Name.equals(getTableName()) && getRecord_ID() > 0)
{
p_ddOrder = InterfaceWrapperHelper.create(getCtx(), getRecord_ID(), I_DD_Order.class, get_TrxName());
}
if (p_ddOrder == null || p_ddOrder.getDD_Order_ID() <= 0)
{
throw new FillMandatoryException(I_DD_Order.COLUMNNAME_DD_Order_ID);
}
return p_ddOrder;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\DD_Order_CompleteForwardBackward.java | 1 |
请在Spring Boot框架中完成以下Java代码 | 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(ADMIN.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(STUDENT.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\form-based-authentication\form-based-authentication\src\main\java\uz\bepro\formbasedauthentication\security\ApplicationSecurityConfig.java | 2 |
请完成以下Java代码 | 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);
}
@Override
public void setIsEUOneStopShop (final boolean IsEUOneStopShop)
{
set_Value (COLUMNNAME_IsEUOneStopShop, IsEUOneStopShop);
}
@Override
public boolean isEUOneStopShop()
{
return get_ValueAsBoolean(COLUMNNAME_IsEUOneStopShop);
}
@Override
public void setIsSummary (final boolean IsSummary)
{
set_Value (COLUMNNAME_IsSummary, IsSummary);
}
@Override
public boolean isSummary()
{
return get_ValueAsBoolean(COLUMNNAME_IsSummary);
}
@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.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Org.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String toHandlePage(Model model, HttpServletRequest request, @RequestParam("id") String id) {
RpAccountCheckMistake mistake = rpAccountCheckMistakeService.getDataById(id);
model.addAttribute("mistake", mistake);
model.addAttribute("reconciliationMistakeTypeEnums", ReconciliationMistakeTypeEnum.toList());
model.addAttribute("tradeStatusEnums", TradeStatusEnum.toList());
return "reconciliation/mistake/handlePage";
}
/**
* 差错处理方法
*
* @param dwz
* @param model
* @param request
* @param id
* 差错id
* @param handleType
* 处理类型(平台认账、银行认账)
* @param handleRemark
* 处理备注
* @return
*/
@RequiresPermissions("recon:mistake:edit")
@RequestMapping(value = "/mistake/handle")
public String handleMistake(DwzAjax dwz, Model model, HttpServletRequest request, @RequestParam("id") String id, @RequestParam("handleType") String handleType, @RequestParam("handleRemark") String handleRemark) {
try {
// 进行差错处理 | rpAccountCheckTransactionService.handle(id, handleType, handleRemark);
} catch (BizException e) {
log.error(e);
dwz.setStatusCode(DWZ.ERROR);
dwz.setMessage(e.getMsg());
model.addAttribute("dwz", dwz);
return "common/ajaxDone";
} catch (Exception e) {
log.error(e);
dwz.setStatusCode(DWZ.ERROR);
dwz.setMessage("对账差错处理异常,请通知系统管理员!");
model.addAttribute("dwz", dwz);
return "common/ajaxDone";
}
dwz.setStatusCode(DWZ.SUCCESS);
dwz.setMessage("操作成功!");
model.addAttribute("dwz", dwz);
return "common/ajaxDone";
}
} | repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\controller\reconciliation\ReconciliationController.java | 2 |
请完成以下Java代码 | public Integer getShowStatus() {
return showStatus;
}
public void setShowStatus(Integer showStatus) {
this.showStatus = showStatus;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getReadCount() {
return readCount;
}
public void setReadCount(Integer readCount) {
this.readCount = readCount;
}
public String getContent() {
return content;
}
public void setContent(String content) { | this.content = content;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", categoryId=").append(categoryId);
sb.append(", icon=").append(icon);
sb.append(", title=").append(title);
sb.append(", showStatus=").append(showStatus);
sb.append(", createTime=").append(createTime);
sb.append(", readCount=").append(readCount);
sb.append(", content=").append(content);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsHelp.java | 1 |
请完成以下Java代码 | public static String getNameByValue(String value){
if (oConvertUtils.isEmpty(value)) {
return null;
}
for (DepartCategoryEnum val : values()) {
if (val.getValue().equals(value)) {
return val.getName();
}
}
return value;
}
/**
* 根据名称获取值
* | * @param name
* @return
*/
public static String getValueByName(String name){
if (oConvertUtils.isEmpty(name)) {
return null;
}
for (DepartCategoryEnum val : values()) {
if (val.getName().equals(name)) {
return val.getValue();
}
}
return name;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\constant\enums\DepartCategoryEnum.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OpenAPISecurityConfig {
@Value("${keycloak.auth-server-url}")
String authServerUrl;
@Value("${keycloak.realm}")
String realm;
private static final String OAUTH_SCHEME_NAME = "my_oAuth_security_schema";
@Bean
public OpenAPI openAPI() {
return new OpenAPI().components(new Components()
.addSecuritySchemes(OAUTH_SCHEME_NAME, createOAuthScheme()))
.addSecurityItem(new SecurityRequirement().addList(OAUTH_SCHEME_NAME))
.info(new Info().title("Todos Management Service")
.description("A service providing todos.")
.version("1.0"));
} | private SecurityScheme createOAuthScheme() {
OAuthFlows flows = createOAuthFlows();
return new SecurityScheme().type(SecurityScheme.Type.OAUTH2)
.flows(flows);
}
private OAuthFlows createOAuthFlows() {
OAuthFlow flow = createAuthorizationCodeFlow();
return new OAuthFlows().implicit(flow);
}
private OAuthFlow createAuthorizationCodeFlow() {
return new OAuthFlow()
.authorizationUrl(authServerUrl + "/realms/" + realm + "/protocol/openid-connect/auth")
.scopes(new Scopes().addString("read_access", "read data")
.addString("write_access", "modify data"));
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-swagger-keycloak\src\main\java\com\baeldung\swaggerkeycloak\OpenAPISecurityConfig.java | 2 |
请完成以下Java代码 | public boolean accept(final T model)
{
final Date validFrom = getDate(model, validFromColumnName);
if (validFrom != null && validFrom.compareTo(dateValue) > 0)
{
return false;
}
final Date validTo = getDate(model, validToColumnName);
if (validTo != null && validTo.compareTo(dateValue) < 0)
{
return false;
}
return true;
} | private final Date getDate(final T model, final String dateColumnName)
{
if (dateColumnName == null)
{
return null;
}
if (!InterfaceWrapperHelper.hasModelColumnName(model, dateColumnName))
{
return null;
}
final Optional<Date> date = InterfaceWrapperHelper.getValue(model, dateColumnName);
return date.orElse(null);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\ValidFromToMatchesQueryFilter.java | 1 |
请完成以下Java代码 | public void repair(Collection<String> repairParts) {
Assert.notEmpty(repairParts, "collection of repairParts mustn't be empty");
// ...
}
public void repair(Map<String, String> repairParts) {
Assert.notEmpty(repairParts, "map of repairParts mustn't be empty");
// ...
}
public void repair(String[] repairParts) {
Assert.notEmpty(repairParts, "array of repairParts must not be empty");
// ...
}
public void repairWithNoNull(String[] repairParts) {
Assert.noNullElements(repairParts, "array of repairParts must not contain null elements");
// ...
}
public static void main(String[] args) {
Car car = new Car();
car.drive(50);
car.stop();
car.fuel();
car.сhangeOil("oil"); | CarBattery carBattery = new CarBattery();
car.replaceBattery(carBattery);
car.сhangeEngine(new ToyotaEngine());
car.startWithHasLength(" ");
car.startWithHasText("t");
car.startWithNotContain("132");
List<String> repairPartsCollection = new ArrayList<>();
repairPartsCollection.add("part");
car.repair(repairPartsCollection);
Map<String, String> repairPartsMap = new HashMap<>();
repairPartsMap.put("1", "part");
car.repair(repairPartsMap);
String[] repairPartsArray = { "part" };
car.repair(repairPartsArray);
}
} | repos\tutorials-master\spring-5\src\main\java\com\baeldung\assertions\Car.java | 1 |
请完成以下Java代码 | public class GetVariableCmd implements Command<Object> {
protected String caseInstanceId;
protected String variableName;
public GetVariableCmd(String caseInstanceId, String variableName) {
this.caseInstanceId = caseInstanceId;
this.variableName = variableName;
}
@Override
public Object execute(CommandContext commandContext) {
if (caseInstanceId == null) {
throw new FlowableIllegalArgumentException("caseInstanceId is null");
}
CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext);
// In the BPMN engine, this is done by getting the variable on the execution.
// However, doing the same in CMMN will fetch the case instance and non-completed plan item instances in one query. | // Hence, why here a direct query is done here (which is cached).
VariableInstanceEntity variableInstanceEntity = cmmnEngineConfiguration.getVariableServiceConfiguration().getVariableService()
.createInternalVariableInstanceQuery()
.scopeId(caseInstanceId)
.withoutSubScopeId()
.scopeType(ScopeTypes.CMMN)
.name(variableName)
.singleResult();
if (variableInstanceEntity != null) {
return variableInstanceEntity.getValue();
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\GetVariableCmd.java | 1 |
请完成以下Java代码 | public I_AD_Role getAD_Role() throws RuntimeException
{
return (I_AD_Role)MTable.get(getCtx(), I_AD_Role.Table_Name)
.getPO(getAD_Role_ID(), get_TrxName()); }
/** Set Role.
@param AD_Role_ID
Responsibility Role
*/
public void setAD_Role_ID (int AD_Role_ID)
{
if (AD_Role_ID < 0)
set_ValueNoCheck (COLUMNNAME_AD_Role_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Role_ID, Integer.valueOf(AD_Role_ID));
}
/** Get Role.
@return Responsibility Role
*/
public int getAD_Role_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_CM_AccessProfile getCM_AccessProfile() throws RuntimeException
{
return (I_CM_AccessProfile)MTable.get(getCtx(), I_CM_AccessProfile.Table_Name)
.getPO(getCM_AccessProfile_ID(), get_TrxName()); }
/** Set Web Access Profile.
@param CM_AccessProfile_ID
Web Access Profile
*/
public void setCM_AccessProfile_ID (int CM_AccessProfile_ID)
{ | if (CM_AccessProfile_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, Integer.valueOf(CM_AccessProfile_ID));
}
/** Get Web Access Profile.
@return Web Access Profile
*/
public int getCM_AccessProfile_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_AccessProfile_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_CM_AccessListRole.java | 1 |
请完成以下Java代码 | String substituteParametersInSqlString(String sql, SqlParameterSource paramSource) {
ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql);
List<SqlParameter> declaredParams = NamedParameterUtils.buildSqlParameterList(parsedSql, paramSource);
if (declaredParams.isEmpty()) {
return sql;
}
for (SqlParameter parSQL: declaredParams) {
String paramName = parSQL.getName();
if (!paramSource.hasValue(paramName)) {
continue;
}
Object value = paramSource.getValue(paramName);
if (value instanceof SqlParameterValue) {
value = ((SqlParameterValue)value).getValue();
}
if (!(value instanceof Iterable)) {
String ValueForSQLQuery = getValueForSQLQuery(value);
sql = sql.replace(":" + paramName, ValueForSQLQuery);
continue;
}
//Iterable
int count = 0;
String valueArrayStr = "";
for (Object valueTemp: (Iterable)value) {
if (count > 0) {
valueArrayStr+=", ";
}
String valueForSQLQuery = getValueForSQLQuery(valueTemp); | valueArrayStr += valueForSQLQuery;
++count;
}
sql = sql.replace(":" + paramName, valueArrayStr);
}
return sql;
}
String getValueForSQLQuery(Object valueParameter) {
if (valueParameter instanceof String) {
return "'" + ((String) valueParameter).replaceAll("'", "''") + "'";
}
if (valueParameter instanceof UUID) {
return "'" + valueParameter + "'";
}
return String.valueOf(valueParameter);
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\query\DefaultQueryLogComponent.java | 1 |
请完成以下Java代码 | public void deleteDeployment(String deploymentId, boolean cascade) {
commandExecutor.execute(new DeleteDeploymentCmd(deploymentId, cascade));
}
@Override
public CmmnDeploymentQuery createDeploymentQuery() {
return configuration.getCmmnDeploymentEntityManager().createDeploymentQuery();
}
@Override
public CaseDefinitionQuery createCaseDefinitionQuery() {
return configuration.getCaseDefinitionEntityManager().createCaseDefinitionQuery();
}
@Override
public void addCandidateStarterUser(String caseDefinitionId, String userId) {
commandExecutor.execute(new AddIdentityLinkForCaseDefinitionCmd(caseDefinitionId, userId, null, configuration));
}
@Override
public void addCandidateStarterGroup(String caseDefinitionId, String groupId) {
commandExecutor.execute(new AddIdentityLinkForCaseDefinitionCmd(caseDefinitionId, null, groupId, configuration));
}
@Override
public void deleteCandidateStarterGroup(String caseDefinitionId, String groupId) {
commandExecutor.execute(new DeleteIdentityLinkForCaseDefinitionCmd(caseDefinitionId, null, groupId));
}
@Override
public void deleteCandidateStarterUser(String caseDefinitionId, String userId) {
commandExecutor.execute(new DeleteIdentityLinkForCaseDefinitionCmd(caseDefinitionId, userId, null));
}
@Override
public List<IdentityLink> getIdentityLinksForCaseDefinition(String caseDefinitionId) {
return commandExecutor.execute(new GetIdentityLinksForCaseDefinitionCmd(caseDefinitionId)); | }
@Override
public void setCaseDefinitionCategory(String caseDefinitionId, String category) {
commandExecutor.execute(new SetCaseDefinitionCategoryCmd(caseDefinitionId, category));
}
@Override
public void changeDeploymentParentDeploymentId(String deploymentId, String newParentDeploymentId) {
commandExecutor.execute(new SetDeploymentParentDeploymentIdCmd(deploymentId, newParentDeploymentId));
}
@Override
public List<DmnDecision> getDecisionsForCaseDefinition(String caseDefinitionId) {
return commandExecutor.execute(new GetDecisionsForCaseDefinitionCmd(caseDefinitionId));
}
@Override
public List<FormDefinition> getFormDefinitionsForCaseDefinition(String caseDefinitionId) {
return commandExecutor.execute(new GetFormDefinitionsForCaseDefinitionCmd(caseDefinitionId));
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\CmmnRepositoryServiceImpl.java | 1 |
请完成以下Java代码 | public String docType(final ICalloutField calloutField)
{
final I_C_Payment payment = calloutField.getModel(I_C_Payment.class);
final I_C_DocType docType = InterfaceWrapperHelper.load(payment.getC_DocType_ID(), I_C_DocType.class);
if (docType != null)
{
calloutField.putWindowContext("IsSOTrx", docType.isSOTrx());
final IDocumentNoInfo documentNoInfo = Services.get(IDocumentNoBuilderFactory.class)
.createPreliminaryDocumentNoBuilder()
.setNewDocType(docType)
.setOldDocumentNo(payment.getDocumentNo())
.setDocumentModel(payment)
.buildOrNull();
if (documentNoInfo != null && documentNoInfo.isDocNoControlled())
{
payment.setDocumentNo(documentNoInfo.getDocumentNo());
}
}
paymentBL.validateDocTypeIsInSync(payment);
return NO_ERROR;
} // docType
/** | * Payment_Amounts. Change of: - IsOverUnderPayment -> set OverUnderAmt to 0 -
* C_Currency_ID, C_ConvesionRate_ID -> convert all - PayAmt, DiscountAmt,
* WriteOffAmt, OverUnderAmt -> PayAmt make sure that add up to
* InvoiceOpenAmt
*/
public String amounts(final ICalloutField calloutField)
{
if (isCalloutActive()) // assuming it is resetting value
{
return NO_ERROR;
}
final I_C_Payment payment = calloutField.getModel(I_C_Payment.class);
paymentBL.updateAmounts(payment, calloutField.getColumnName(), true);
return NO_ERROR;
} // amounts
} // CalloutPayment | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\CalloutPayment.java | 1 |
请完成以下Java代码 | public int getPhase() {
return this.phase;
}
@Override
public void start() {
synchronized (this.lifeCycleMonitor) {
if (!this.running) {
logger.info("Starting...");
doStart();
this.running = true;
logger.info("Started.");
}
}
}
@Override
public void stop() {
synchronized (this.lifeCycleMonitor) {
if (this.running) {
logger.info("Stopping...");
doStop();
this.running = false;
logger.info("Stopped.");
}
}
}
@Override | public void stop(Runnable callback) {
synchronized (this.lifeCycleMonitor) {
stop();
callback.run();
}
}
@Override
public boolean isRunning() {
return this.running;
}
@Override
public void destroy() {
stop();
}
} | repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\AbstractActivitiSmartLifeCycle.java | 1 |
请完成以下Java代码 | public boolean isSuccess() {
return success;
}
public Result<R> setSuccess(boolean success) {
this.success = success;
return this;
}
public int getCode() {
return code;
}
public Result<R> setCode(int code) {
this.code = code;
return this;
}
public String getMsg() {
return msg;
}
public Result<R> setMsg(String msg) { | this.msg = msg;
return this;
}
public R getData() {
return data;
}
public Result<R> setData(R data) {
this.data = data;
return this;
}
@Override
public String toString() {
return "Result{" +
"success=" + success +
", code=" + code +
", msg='" + msg + '\'' +
", data=" + data +
'}';
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\Result.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public void setTenantIdLike(String tenantIdLike) {
this.tenantIdLike = tenantIdLike;
}
public Boolean getWithoutTenantId() {
return withoutTenantId;
} | public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Set<String> getProcessInstanceIds() {
return processInstanceIds;
}
public void setProcessInstanceIds(Set<String> processInstanceIds) {
this.processInstanceIds = processInstanceIds;
}
public Set<String> getCalledProcessInstanceIds() {
return calledProcessInstanceIds;
}
public void setCalledProcessInstanceIds(Set<String> calledProcessInstanceIds) {
this.calledProcessInstanceIds = calledProcessInstanceIds;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricActivityInstanceQueryRequest.java | 2 |
请完成以下Java代码 | public List<List<String>> getSafeInvolvedGroups() {
return safeInvolvedGroups;
}
public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) {
this.safeInvolvedGroups = safeInvolvedGroups;
}
@Override
protected void ensureVariablesInitialized() {
super.ensureVariablesInitialized();
for (PlanItemInstanceQueryImpl orQueryObject : orQueryObjects) {
orQueryObject.ensureVariablesInitialized();
}
} | public List<PlanItemInstanceQueryImpl> getOrQueryObjects() {
return orQueryObjects;
}
public List<List<String>> getSafeCaseInstanceIds() {
return safeCaseInstanceIds;
}
public void setSafeCaseInstanceIds(List<List<String>> safeProcessInstanceIds) {
this.safeCaseInstanceIds = safeProcessInstanceIds;
}
public Collection<String> getCaseInstanceIds() {
return caseInstanceIds;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\PlanItemInstanceQueryImpl.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.