instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public class LiquibaseConfiguration {
private final Logger log = LoggerFactory.getLogger(LiquibaseConfiguration.class);
private final Environment env;
public LiquibaseConfiguration(Environment env) {
this.env = env;
}
@Bean
public SpringLiquibase liquibase(@Qualifier("taskExecutor") TaskExecutor taskExecutor,
DataSource dataSource, LiquibaseProperties liquibaseProperties) {
// Use liquibase.integration.spring.SpringLiquibase if you don't want Liquibase to start asynchronously | SpringLiquibase liquibase = new AsyncSpringLiquibase(taskExecutor, env);
liquibase.setDataSource(dataSource);
liquibase.setChangeLog("classpath:config/liquibase/master.xml");
liquibase.setContexts(liquibaseProperties.getContexts());
liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema());
liquibase.setDropFirst(liquibaseProperties.isDropFirst());
liquibase.setChangeLogParameters(liquibaseProperties.getParameters());
if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_NO_LIQUIBASE)) {
liquibase.setShouldRun(false);
} else {
liquibase.setShouldRun(liquibaseProperties.isEnabled());
log.debug("Configuring Liquibase");
}
return liquibase;
}
} | repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\config\LiquibaseConfiguration.java | 2 |
请完成以下Java代码 | public class ChannelEventKeyDetection {
protected String fixedValue;
protected String jsonField;
protected String jsonPointerExpression;
protected String xmlXPathExpression;
protected String delegateExpression;
public String getFixedValue() {
return fixedValue;
}
public void setFixedValue(String fixedValue) {
this.fixedValue = fixedValue;
}
public String getJsonField() {
return jsonField;
}
public void setJsonField(String jsonField) {
this.jsonField = jsonField;
}
public String getJsonPointerExpression() { | return jsonPointerExpression;
}
public void setJsonPointerExpression(String jsonPointerExpression) {
this.jsonPointerExpression = jsonPointerExpression;
}
public String getXmlXPathExpression() {
return xmlXPathExpression;
}
public void setXmlXPathExpression(String xmlXPathExpression) {
this.xmlXPathExpression = xmlXPathExpression;
}
public String getDelegateExpression() {
return delegateExpression;
}
public void setDelegateExpression(String delegateExpression) {
this.delegateExpression = delegateExpression;
}
} | repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\ChannelEventKeyDetection.java | 1 |
请完成以下Java代码 | private final MutableComboBoxModel getDelegateToUse()
{
if (delegate == null)
{
return COMBOBOXMODEL_NULL;
}
return delegate;
}
public void setDelegate(final MutableComboBoxModel delegateNew)
{
if (this.delegate == delegateNew)
{
// nothing changed
return;
}
// Unregister listeners on old lookup
final MutableComboBoxModel delegateOld = this.delegate;
if (delegateOld != null)
{
for (ListDataListener l : listenerList.getListeners(ListDataListener.class))
{
delegateOld.removeListDataListener(l);
}
}
//
// Setup new Lookup
this.delegate = delegateNew;
// Register listeners on new lookup
if (this.delegate != null)
{
for (ListDataListener l : listenerList.getListeners(ListDataListener.class))
{
this.delegate.addListDataListener(l);
}
}
}
@Override
public void addListDataListener(final ListDataListener l)
{
listenerList.add(ListDataListener.class, l);
if (delegate != null)
{
delegate.addListDataListener(l);
}
}
@Override
public void removeListDataListener(final ListDataListener l)
{
listenerList.remove(ListDataListener.class, l);
if (delegate != null)
{
delegate.removeListDataListener(l);
}
}
@Override
public int getSize()
{
return getDelegateToUse().getSize();
}
@Override
public Object getElementAt(int index)
{
return getDelegateToUse().getElementAt(index);
}
@Override | public void setSelectedItem(Object anItem)
{
getDelegateToUse().setSelectedItem(anItem);
}
@Override
public Object getSelectedItem()
{
return getDelegateToUse().getSelectedItem();
}
@Override
public void addElement(Object obj)
{
getDelegateToUse().addElement(obj);
}
@Override
public void removeElement(Object obj)
{
getDelegateToUse().removeElement(obj);
}
@Override
public void insertElementAt(Object obj, int index)
{
getDelegateToUse().insertElementAt(obj, index);
}
@Override
public void removeElementAt(int index)
{
getDelegateToUse().removeElementAt(index);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\MutableComboBoxModelProxy.java | 1 |
请完成以下Java代码 | public boolean getShouldPerformAuthorizatioCheck() {
return isAuthorizationCheckEnabled && !isPermissionChecksEmpty();
}
public void setShouldPerformAuthorizatioCheck(boolean shouldPerformAuthorizatioCheck) {
this.shouldPerformAuthorizatioCheck = shouldPerformAuthorizatioCheck;
}
protected boolean isPermissionChecksEmpty() {
return permissionChecks.getAtomicChecks().isEmpty() && permissionChecks.getCompositeChecks().isEmpty();
}
public String getAuthUserId() {
return authUserId;
}
public void setAuthUserId(String authUserId) {
this.authUserId = authUserId;
}
public List<String> getAuthGroupIds() {
return authGroupIds;
}
public void setAuthGroupIds(List<String> authGroupIds) {
this.authGroupIds = authGroupIds;
}
public int getAuthDefaultPerm() {
return authDefaultPerm;
}
public void setAuthDefaultPerm(int authDefaultPerm) {
this.authDefaultPerm = authDefaultPerm;
}
// authorization check parameters
public CompositePermissionCheck getPermissionChecks() {
return permissionChecks;
}
public void setAtomicPermissionChecks(List<PermissionCheck> permissionChecks) {
this.permissionChecks.setAtomicChecks(permissionChecks);
} | public void addAtomicPermissionCheck(PermissionCheck permissionCheck) {
permissionChecks.addAtomicCheck(permissionCheck);
}
public void setPermissionChecks(CompositePermissionCheck permissionChecks) {
this.permissionChecks = permissionChecks;
}
public boolean isRevokeAuthorizationCheckEnabled() {
return isRevokeAuthorizationCheckEnabled;
}
public void setRevokeAuthorizationCheckEnabled(boolean isRevokeAuthorizationCheckEnabled) {
this.isRevokeAuthorizationCheckEnabled = isRevokeAuthorizationCheckEnabled;
}
public void setHistoricInstancePermissionsEnabled(boolean historicInstancePermissionsEnabled) {
this.historicInstancePermissionsEnabled = historicInstancePermissionsEnabled;
}
/**
* Used in SQL mapping
*/
public boolean isHistoricInstancePermissionsEnabled() {
return historicInstancePermissionsEnabled;
}
public boolean isUseLeftJoin() {
return useLeftJoin;
}
public void setUseLeftJoin(boolean useLeftJoin) {
this.useLeftJoin = useLeftJoin;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\AuthorizationCheck.java | 1 |
请完成以下Java代码 | public class GenerateDeliveryDays extends JavaProcess implements IProcessPrecondition
{
//
// Services
private final ITourBL tourBL = Services.get(ITourBL.class);
@Param(parameterName = "DateFrom")
private Timestamp p_DateFrom;
@Param(parameterName = "DateTo")
private Timestamp p_DateTo;
private I_M_Tour p_tour = null;
private I_M_TourVersion p_tourVersion = null;
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected void prepare()
{
if (I_M_Tour.Table_Name.equals(getTableName()) && getRecord_ID() > 0)
{
p_tour = InterfaceWrapperHelper.create(getCtx(), getRecord_ID(), I_M_Tour.class, ITrx.TRXNAME_None);
}
if (I_M_TourVersion.Table_Name.equals(getTableName()) && getRecord_ID() > 0)
{
p_tourVersion = InterfaceWrapperHelper.create(getCtx(), getRecord_ID(), I_M_TourVersion.class, ITrx.TRXNAME_None);
p_tour = p_tourVersion.getM_Tour();
}
}
@Override
protected String doIt() throws Exception
{
Check.assumeNotNull(p_DateFrom, "p_DateFrom not null");
Check.assumeNotNull(p_DateTo, "p_DateTo not null");
Check.assumeNotNull(p_tour, "p_tour not null"); | //
// Create generator instance and configure it
final IDeliveryDayGenerator generator = tourBL.createDeliveryDayGenerator(this);
generator.setDateFrom(TimeUtil.asLocalDate(p_DateFrom));
generator.setDateTo(TimeUtil.asLocalDate(p_DateTo));
generator.setM_Tour(p_tour);
//
// Generate delivery days
if (p_tourVersion == null)
{
generator.generate(getTrxName());
}
else
{
generator.generateForTourVersion(getTrxName(), p_tourVersion);
}
final int countGeneratedDeliveryDays = generator.getCountGeneratedDeliveryDays();
//
// Return result
return "@Created@ #" + countGeneratedDeliveryDays;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\process\GenerateDeliveryDays.java | 1 |
请完成以下Java代码 | private ILockCommand toWorkPackageElementsLocker(final @NonNull DDOrderCandidateEnqueueRequest request)
{
final PInstanceId selectionId = request.getSelectionId();
final LockOwner lockOwner = LockOwner.newOwner(LOCK_OWNER_PREFIX, selectionId.getRepoId());
return lockManager
.lock()
.setOwner(lockOwner)
.setAutoCleanup(false)
.setFailIfAlreadyLocked(true)
.setRecordsBySelection(I_DD_Order_Candidate.class, selectionId);
}
private static String toJsonString(@NonNull final DDOrderCandidateEnqueueRequest request)
{
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().writeValueAsString(request);
}
catch (final JsonProcessingException e)
{
throw new AdempiereException("Cannot convert to json: " + request, e); | }
}
public static DDOrderCandidateEnqueueRequest extractRequest(@NonNull final IParams params)
{
final String jsonString = params.getParameterAsString(WP_PARAM_request);
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(jsonString, DDOrderCandidateEnqueueRequest.class);
}
catch (final JsonProcessingException e)
{
throw new AdempiereException("Cannot read json: " + jsonString, e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddordercandidate\async\DDOrderCandidateEnqueueService.java | 1 |
请完成以下Java代码 | public final class VATCodeMatchingRequest
{
public static final Builder builder()
{
return new Builder();
}
private final int C_AcctSchema_ID;
private final int C_Tax_ID;
private final boolean isSOTrx;
private final Date date;
private VATCodeMatchingRequest(final Builder builder)
{
super();
C_AcctSchema_ID = builder.C_AcctSchema_ID;
C_Tax_ID = builder.C_Tax_ID;
isSOTrx = builder.isSOTrx;
date = (Date)builder.date.clone();
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("C_AcctSchema_ID", C_AcctSchema_ID)
.add("C_Tax_ID", C_Tax_ID)
.add("IsSOTrx", isSOTrx)
.add("Date", date)
.toString();
}
public int getC_AcctSchema_ID()
{
return C_AcctSchema_ID;
}
public int getC_Tax_ID()
{
return C_Tax_ID;
}
public boolean isSOTrx()
{
return isSOTrx;
}
public Date getDate()
{
return (Date)date.clone();
}
public static final class Builder
{
private Integer C_AcctSchema_ID;
private Integer C_Tax_ID;
private Boolean isSOTrx;
private Date date; | private Builder()
{
super();
}
public VATCodeMatchingRequest build()
{
return new VATCodeMatchingRequest(this);
}
public Builder setC_AcctSchema_ID(final int C_AcctSchema_ID)
{
this.C_AcctSchema_ID = C_AcctSchema_ID;
return this;
}
public Builder setC_Tax_ID(final int C_Tax_ID)
{
this.C_Tax_ID = C_Tax_ID;
return this;
}
public Builder setIsSOTrx(final boolean isSOTrx)
{
this.isSOTrx = isSOTrx;
return this;
}
public Builder setDate(final Date date)
{
this.date = date;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\vatcode\VATCodeMatchingRequest.java | 1 |
请完成以下Java代码 | public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
public boolean isSameDeployment() {
return sameDeployment;
}
public void setSameDeployment(boolean sameDeployment) {
this.sameDeployment = sameDeployment;
}
public String getValidateFormFields() {
return validateFormFields;
}
public void setValidateFormFields(String validateFormFields) {
this.validateFormFields = validateFormFields;
}
@Override
public void addExitCriterion(Criterion exitCriterion) {
exitCriteria.add(exitCriterion);
}
public Integer getDisplayOrder() {
return displayOrder;
}
public void setDisplayOrder(Integer displayOrder) {
this.displayOrder = displayOrder;
} | public String getIncludeInStageOverview() {
return includeInStageOverview;
}
public void setIncludeInStageOverview(String includeInStageOverview) {
this.includeInStageOverview = includeInStageOverview;
}
@Override
public List<Criterion> getExitCriteria() {
return exitCriteria;
}
@Override
public void setExitCriteria(List<Criterion> exitCriteria) {
this.exitCriteria = exitCriteria;
}
public String getBusinessStatus() {
return businessStatus;
}
public void setBusinessStatus(String businessStatus) {
this.businessStatus = businessStatus;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\Stage.java | 1 |
请完成以下Java代码 | public String toString() {
return "Product [name=" + name + ", price=" + price + ", sales=" + sales + "]";
}
// getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price; | }
public void setPrice(double price) {
this.price = price;
}
public int getSales() {
return sales;
}
public void setSales(int sales) {
this.sales = sales;
}
} | repos\tutorials-master\core-java-modules\core-java-lang-oop-generics-2\src\main\java\com\baeldung\generics\Product.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected GrantedAuthoritiesMapper grantedAuthoritiesMapper() {
logger.debug("Registering OAuth2GrantedAuthoritiesMapper");
return new OAuth2GrantedAuthoritiesMapper(oAuth2Properties);
}
@Bean
@ConditionalOnProperty(name = "sso-logout.enabled", havingValue = "true", prefix = OAuth2Properties.PREFIX)
protected SsoLogoutSuccessHandler ssoLogoutSuccessHandler(ClientRegistrationRepository clientRegistrationRepository) {
logger.debug("Registering SsoLogoutSuccessHandler");
return new SsoLogoutSuccessHandler(clientRegistrationRepository, oAuth2Properties);
}
@Bean
protected AuthorizeTokenFilter authorizeTokenFilter(OAuth2AuthorizedClientManager clientManager) {
logger.debug("Registering AuthorizeTokenFilter");
return new AuthorizeTokenFilter(clientManager);
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http,
AuthorizeTokenFilter authorizeTokenFilter,
@Nullable SsoLogoutSuccessHandler ssoLogoutSuccessHandler) throws Exception {
logger.info("Enabling Camunda Spring Security oauth2 integration");
// @formatter:off
http.authorizeHttpRequests(c -> c
.requestMatchers(webappPath + "/app/**").authenticated() | .requestMatchers(webappPath + "/api/**").authenticated()
.anyRequest().permitAll()
)
.addFilterAfter(authorizeTokenFilter, OAuth2AuthorizationRequestRedirectFilter.class)
.anonymous(AbstractHttpConfigurer::disable)
.oidcLogout(c -> c.backChannel(Customizer.withDefaults()))
.oauth2Login(Customizer.withDefaults())
.logout(c -> c
.clearAuthentication(true)
.invalidateHttpSession(true)
)
.oauth2Client(Customizer.withDefaults())
.cors(AbstractHttpConfigurer::disable)
.csrf(AbstractHttpConfigurer::disable);
// @formatter:on
if (oAuth2Properties.getSsoLogout().isEnabled()) {
http.logout(c -> c.logoutSuccessHandler(ssoLogoutSuccessHandler));
}
return http.build();
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter-security\src\main\java\org\camunda\bpm\spring\boot\starter\security\oauth2\CamundaSpringSecurityOAuth2AutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class WebSessionServerCsrfTokenRepository implements ServerCsrfTokenRepository {
private static final String DEFAULT_CSRF_PARAMETER_NAME = "_csrf";
private static final String DEFAULT_CSRF_HEADER_NAME = "X-CSRF-TOKEN";
private static final String DEFAULT_CSRF_TOKEN_ATTR_NAME = WebSessionServerCsrfTokenRepository.class.getName()
.concat(".CSRF_TOKEN");
private String parameterName = DEFAULT_CSRF_PARAMETER_NAME;
private String headerName = DEFAULT_CSRF_HEADER_NAME;
private String sessionAttributeName = DEFAULT_CSRF_TOKEN_ATTR_NAME;
@Override
public Mono<CsrfToken> generateToken(ServerWebExchange exchange) {
return Mono.fromCallable(() -> createCsrfToken()).subscribeOn(Schedulers.boundedElastic());
}
@Override
public Mono<Void> saveToken(ServerWebExchange exchange, @Nullable CsrfToken token) {
return exchange.getSession()
.doOnNext((session) -> putToken(session.getAttributes(), token))
.flatMap((session) -> session.changeSessionId());
}
private void putToken(Map<String, Object> attributes, @Nullable CsrfToken token) {
if (token == null) {
attributes.remove(this.sessionAttributeName);
}
else {
attributes.put(this.sessionAttributeName, token);
}
}
@Override
@SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290
public Mono<CsrfToken> loadToken(ServerWebExchange exchange) {
return exchange.getSession()
.filter((session) -> session.getAttributes().containsKey(this.sessionAttributeName))
.mapNotNull((session) -> session.getAttribute(this.sessionAttributeName));
}
/**
* Sets the {@link ServerWebExchange} parameter name that the {@link CsrfToken} is
* expected to appear on
* @param parameterName the new parameter name to use
*/
public void setParameterName(String parameterName) {
Assert.hasLength(parameterName, "parameterName cannot be null or empty");
this.parameterName = parameterName;
} | /**
* Sets the header name that the {@link CsrfToken} is expected to appear on and the
* header that the response will contain the {@link CsrfToken}.
* @param headerName the new header name to use
*/
public void setHeaderName(String headerName) {
Assert.hasLength(headerName, "headerName cannot be null or empty");
this.headerName = headerName;
}
/**
* Sets the {@link WebSession} attribute name that the {@link CsrfToken} is stored in
* @param sessionAttributeName the new attribute name to use
*/
public void setSessionAttributeName(String sessionAttributeName) {
Assert.hasLength(sessionAttributeName, "sessionAttributeName cannot be null or empty");
this.sessionAttributeName = sessionAttributeName;
}
private CsrfToken createCsrfToken() {
return new DefaultCsrfToken(this.headerName, this.parameterName, createNewToken());
}
private String createNewToken() {
return UUID.randomUUID().toString();
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\csrf\WebSessionServerCsrfTokenRepository.java | 2 |
请完成以下Java代码 | public void recycle() {
entity = null;
super.recycle();
}
public DbEntity getEntity() {
return entity;
}
public void setEntity(DbEntity dbEntity) {
this.entityType = dbEntity.getClass();
this.entity = dbEntity;
}
public void setFlushRelevantEntityReferences(Set<String> flushRelevantEntityReferences) {
this.flushRelevantEntityReferences = flushRelevantEntityReferences;
}
public Set<String> getFlushRelevantEntityReferences() {
return flushRelevantEntityReferences;
}
public String toString() {
return operationType + " " + ClassNameUtil.getClassNameWithoutPackage(entity)+"["+entity.getId()+"]";
}
public void setDependency(DbOperation owner) {
dependentOperation = owner;
}
public DbOperation getDependentOperation() {
return dependentOperation;
} | @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((entity == null) ? 0 : entity.hashCode());
result = prime * result + ((operationType == null) ? 0 : operationType.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DbEntityOperation other = (DbEntityOperation) obj;
if (entity == null) {
if (other.entity != null)
return false;
} else if (!entity.equals(other.entity))
return false;
if (operationType != other.operationType)
return false;
return true;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\entitymanager\operation\DbEntityOperation.java | 1 |
请完成以下Java代码 | public static DebugProperties ofNullableMap(final Map<String, ?> map)
{
if (map == null || map.isEmpty())
{
return EMPTY;
}
return new DebugProperties(ImmutableMap.copyOf(map));
}
public boolean isEmpty()
{
return map.isEmpty();
}
public Map<String, Object> toMap()
{
return map;
}
public DebugProperties withProperty(@NonNull final String propertyName, final Object propertyValue)
{
final Object existingValue = map.get(propertyName);
if (Objects.equals(propertyValue, existingValue)) | {
return this;
}
final LinkedHashMap<String, Object> newMap = new LinkedHashMap<>(map);
if (propertyValue == null)
{
newMap.remove(propertyName);
}
else
{
newMap.put(propertyName, propertyValue);
}
return ofNullableMap(newMap);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DebugProperties.java | 1 |
请完成以下Java代码 | private LeichMehlPluFileConfigGroup toLeichMehlPluFileConfigGroup(@NonNull final I_LeichMehl_PluFile_ConfigGroup configGroupRecord)
{
final LeichMehlPluFileConfigGroupId leichMehlPluFileConfigGroupId = LeichMehlPluFileConfigGroupId.ofRepoId(configGroupRecord.getLeichMehl_PluFile_ConfigGroup_ID());
final LeichMehlPluFileConfigGroup.LeichMehlPluFileConfigGroupBuilder builder = LeichMehlPluFileConfigGroup.builder()
.id(leichMehlPluFileConfigGroupId)
.name(configGroupRecord.getName())
.externalSystemLeichMehlPluFileConfigs(getExternalSystemLeichMehlPluFileConfigs(leichMehlPluFileConfigGroupId));
if (configGroupRecord.isAdditionalCustomQuery() && configGroupRecord.getAD_Process_CustomQuery_ID() > 0)
{
final AdProcessId processId = AdProcessId.ofRepoId(configGroupRecord.getAD_Process_CustomQuery_ID());
final I_AD_Process processRecord = Check.assumeNotNull(processDAO.getById(processId),
"Missing AD_Process record for AD_Process_ID={}", processId.getRepoId());
builder.customQueryProcessValue(processRecord.getValue());
}
return builder.build();
}
@NonNull
private List<ExternalSystemLeichMehlPluFileConfig> getExternalSystemLeichMehlPluFileConfigs(@NonNull final LeichMehlPluFileConfigGroupId leichMehlPluFileConfigGroupId)
{
return queryBL.createQueryBuilder(I_LeichMehl_PluFile_Config.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_LeichMehl_PluFile_Config.COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, leichMehlPluFileConfigGroupId)
.create()
.stream()
.map(ExternalSystemLeichMehlConfigProductMappingRepository::toExternalSystemLeichMehlPluFileConfig)
.collect(ImmutableList.toImmutableList()); | }
@NonNull
private static ExternalSystemLeichMehlPluFileConfig toExternalSystemLeichMehlPluFileConfig(@NonNull final I_LeichMehl_PluFile_Config record)
{
return ExternalSystemLeichMehlPluFileConfig.builder()
.id(ExternalSystemLeichMehlPluFileConfigId.ofRepoId(record.getLeichMehl_PluFile_Config_ID()))
.leichMehlPluFileConfigGroupId(LeichMehlPluFileConfigGroupId.ofRepoId(record.getLeichMehl_PluFile_ConfigGroup_ID()))
.targetFieldName(record.getTargetFieldName())
.targetFieldType(TargetFieldType.ofCode(record.getTargetFieldType()))
.replacement(record.getReplacement())
.replaceRegExp(record.getReplaceRegExp())
.replacementSource(ReplacementSource.ofCode(record.getReplacementSource()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\ExternalSystemLeichMehlConfigProductMappingRepository.java | 1 |
请完成以下Java代码 | public class OptimizedApproach {
public static boolean areArraysEqual(int[][] arr1, int[][] arr2, double similarityThreshold, double samplingWeight) {
if (arr1 == null || arr2 == null || arr1.length != arr2.length ||
arr1[0].length != arr2[0].length || samplingWeight <= 0 || samplingWeight > 1) {
return false;
}
int similarElements = 0;
int checkedElements = 0;
// Calculate sampling step based on the sampling weight
int step = Math.max(1, (int)(1 / samplingWeight)); | // Iterate through the arrays using the calculated step
for (int i = 0; i < arr1.length; i += step) {
for (int j = 0; j < arr1[0].length; j += step) {
if (Math.abs(arr1[i][j] - arr2[i][j]) <= 1) {
similarElements++;
}
checkedElements++;
}
}
// Calculate similarity ratio and compare with the threshold
return (double) similarElements / checkedElements >= similarityThreshold;
}
} | repos\tutorials-master\core-java-modules\core-java-arrays-operations-basic-2\src\main\java\com\baeldung\array\comparing2Darrays\OptimizedApproach.java | 1 |
请完成以下Java代码 | public void addRule(DecisionRule rule) {
this.rules.add(rule);
}
public HitPolicy getHitPolicy() {
return hitPolicy;
}
public void setHitPolicy(HitPolicy hitPolicy) {
this.hitPolicy = hitPolicy;
}
public BuiltinAggregator getAggregation() {
return aggregation;
}
public void setAggregation(BuiltinAggregator aggregation) {
this.aggregation = aggregation; | }
public DecisionTableOrientation getPreferredOrientation() {
return preferredOrientation;
}
public void setPreferredOrientation(DecisionTableOrientation preferredOrientation) {
this.preferredOrientation = preferredOrientation;
}
public String getOutputLabel() {
return outputLabel;
}
public void setOutputLabel(String outputLabel) {
this.outputLabel = outputLabel;
}
} | repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\DecisionTable.java | 1 |
请完成以下Java代码 | public void setC_Job_ID (int C_Job_ID)
{
if (C_Job_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Job_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Job_ID, Integer.valueOf(C_Job_ID));
}
/** Get Position.
@return Job Position
*/
public int getC_Job_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Job_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getC_Job_ID()));
}
/** 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 Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{ | set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_JobAssignment.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class QtyDemandSupplyRepository
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
@NonNull
public ProductWithDemandSupplyCollection getByProductIds(@NonNull final Collection<ProductId> productIds)
{
if (productIds.isEmpty())
{
return ProductWithDemandSupplyCollection.of(ImmutableMap.of());
}
final ArrayList<Object> sqlParams = new ArrayList<>();
final String sql = "SELECT * FROM getQtyDemandQtySupply( p_M_Product_IDs :=" + DB.TO_ARRAY(productIds, sqlParams) + ")";
return DB.retrieveRows(sql, sqlParams, QtyDemandSupplyRepository::ofResultSet)
.stream()
.collect(ProductWithDemandSupplyCollection.toProductsWithDemandSupply());
}
@NonNull
private static ProductWithDemandSupply ofResultSet(@NonNull final ResultSet rs) throws SQLException
{
return ProductWithDemandSupply.builder()
.warehouseId(WarehouseId.ofRepoIdOrNull(rs.getInt("M_Warehouse_ID")))
.attributesKey(AttributesKey.ofString(rs.getString("AttributesKey")))
.productId(ProductId.ofRepoId(rs.getInt("M_Product_ID")))
.uomId(UomId.ofRepoId(rs.getInt("C_UOM_ID")))
.qtyReserved(rs.getBigDecimal("QtyReserved"))
.qtyToMove(rs.getBigDecimal("QtyToMove"))
.build(); | }
public QtyDemandQtySupply getById(@NonNull final QtyDemandQtySupplyId id)
{
final I_QtyDemand_QtySupply_V po = queryBL.createQueryBuilder(I_QtyDemand_QtySupply_V.class)
.addEqualsFilter(I_QtyDemand_QtySupply_V.COLUMNNAME_QtyDemand_QtySupply_V_ID, id)
.create()
.firstOnly(I_QtyDemand_QtySupply_V.class);
return fromPO(po);
}
private QtyDemandQtySupply fromPO(@NonNull final I_QtyDemand_QtySupply_V po)
{
final UomId uomId = UomId.ofRepoId(po.getC_UOM_ID());
return QtyDemandQtySupply.builder()
.id(QtyDemandQtySupplyId.ofRepoId(po.getQtyDemand_QtySupply_V_ID()))
.productId(ProductId.ofRepoId(po.getM_Product_ID()))
.warehouseId(WarehouseId.ofRepoId(po.getM_Warehouse_ID()))
.attributesKey(AttributesKey.ofString(po.getAttributesKey()))
.qtyToMove(Quantitys.of(po.getQtyToMove(), uomId))
.qtyReserved(Quantitys.of(po.getQtyReserved(), uomId))
.qtyForecasted(Quantitys.of(po.getQtyForecasted(), uomId))
.qtyToProduce(Quantitys.of(po.getQtyToProduce(), uomId))
.qtyStock(Quantitys.of(po.getQtyStock(), uomId))
.orgId(OrgId.ofRepoId(po.getAD_Org_ID()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\QtyDemandSupplyRepository.java | 2 |
请完成以下Java代码 | public int getM_AttributeValue_ID()
{
return get_ValueAsInt(COLUMNNAME_M_AttributeValue_ID);
}
@Override
public void setRecord_Attribute_ID (final int Record_Attribute_ID)
{
if (Record_Attribute_ID < 1)
set_ValueNoCheck (COLUMNNAME_Record_Attribute_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_Attribute_ID, Record_Attribute_ID);
}
@Override
public int getRecord_Attribute_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_Attribute_ID);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setValueDate (final @Nullable java.sql.Timestamp ValueDate)
{
set_Value (COLUMNNAME_ValueDate, ValueDate);
}
@Override
public java.sql.Timestamp getValueDate() | {
return get_ValueAsTimestamp(COLUMNNAME_ValueDate);
}
@Override
public void setValueNumber (final @Nullable BigDecimal ValueNumber)
{
set_Value (COLUMNNAME_ValueNumber, ValueNumber);
}
@Override
public BigDecimal getValueNumber()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumber);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValueString (final @Nullable java.lang.String ValueString)
{
set_Value (COLUMNNAME_ValueString, ValueString);
}
@Override
public java.lang.String getValueString()
{
return get_ValueAsString(COLUMNNAME_ValueString);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Record_Attribute.java | 1 |
请完成以下Java代码 | public void setAD_Printer_Tray_ID (int AD_Printer_Tray_ID)
{
if (AD_Printer_Tray_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Printer_Tray_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Printer_Tray_ID, Integer.valueOf(AD_Printer_Tray_ID));
}
@Override
public int getAD_Printer_Tray_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Printer_Tray_ID);
}
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{ | return (java.lang.String)get_Value(COLUMNNAME_Description);
}
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_Printer_Tray.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DefaultProcessEngineConfiguration extends AbstractCamundaConfiguration implements CamundaProcessEngineConfiguration {
@Autowired
private Optional<IdGenerator> idGenerator;
@Override
public void preInit(SpringProcessEngineConfiguration configuration) {
setProcessEngineName(configuration);
setDefaultSerializationFormat(configuration);
setIdGenerator(configuration);
setJobExecutorAcquireByPriority(configuration);
setDefaultNumberOfRetries(configuration);
}
private void setIdGenerator(SpringProcessEngineConfiguration configuration) {
idGenerator.ifPresent(configuration::setIdGenerator);
}
private void setDefaultSerializationFormat(SpringProcessEngineConfiguration configuration) {
String defaultSerializationFormat = camundaBpmProperties.getDefaultSerializationFormat();
if (StringUtils.hasText(defaultSerializationFormat)) {
configuration.setDefaultSerializationFormat(defaultSerializationFormat);
} else {
logger.warn("Ignoring invalid defaultSerializationFormat='{}'", defaultSerializationFormat);
}
}
private void setProcessEngineName(SpringProcessEngineConfiguration configuration) {
String processEngineName = StringUtils.trimAllWhitespace(camundaBpmProperties.getProcessEngineName());
if (!StringUtils.isEmpty(processEngineName) && !processEngineName.contains("-")) {
if (camundaBpmProperties.getGenerateUniqueProcessEngineName()) {
if (!processEngineName.equals(ProcessEngines.NAME_DEFAULT)) {
throw new RuntimeException(String.format("A unique processEngineName cannot be generated " | + "if a custom processEngineName is already set: %s", processEngineName));
}
processEngineName = CamundaBpmProperties.getUniqueName(camundaBpmProperties.UNIQUE_ENGINE_NAME_PREFIX);
}
configuration.setProcessEngineName(processEngineName);
} else {
logger.warn("Ignoring invalid processEngineName='{}' - must not be null, blank or contain hyphen", camundaBpmProperties.getProcessEngineName());
}
}
private void setJobExecutorAcquireByPriority(SpringProcessEngineConfiguration configuration) {
Optional.ofNullable(camundaBpmProperties.getJobExecutorAcquireByPriority())
.ifPresent(configuration::setJobExecutorAcquireByPriority);
}
private void setDefaultNumberOfRetries(SpringProcessEngineConfiguration configuration) {
Optional.ofNullable(camundaBpmProperties.getDefaultNumberOfRetries())
.ifPresent(configuration::setDefaultNumberOfRetries);
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\configuration\impl\DefaultProcessEngineConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected ServiceController<ProcessEngine> getProcessEngineServiceController(ServiceName processEngineServiceName) {
ServiceController<ProcessEngine> serviceController = (ServiceController<ProcessEngine>) serviceContainer.getRequiredService(processEngineServiceName);
return serviceController;
}
protected void startTrackingServices() {
processEngineServiceTracker = new ServiceTracker<>(ServiceNames.forManagedProcessEngines(), processEngines);
serviceContainer.addListener(processEngineServiceTracker);
processApplicationServiceTracker = new ServiceTracker<>(ServiceNames.forManagedProcessApplications(), processApplications);
serviceContainer.addListener(processApplicationServiceTracker);
}
protected void stopTrackingServices() {
serviceContainer.removeListener(processEngineServiceTracker);
serviceContainer.removeListener(processApplicationServiceTracker);
}
/**
* <p>invoked by the {@link MscManagedProcessEngine} and {@link MscManagedProcessEngineController}
* when a process engine is started</p>
*/
public void processEngineStarted(ProcessEngine processEngine) {
processEngines.add(processEngine);
}
/**
* <p>invoked by the {@link MscManagedProcessEngine} and {@link MscManagedProcessEngineController}
* when a process engine is stopped</p> | */
public void processEngineStopped(ProcessEngine processEngine) {
processEngines.remove(processEngine);
}
@SuppressWarnings("unchecked")
protected MscManagedProcessApplication getManagedProcessApplication(String name) {
ServiceController<MscManagedProcessApplication> serviceController = (ServiceController<MscManagedProcessApplication>) serviceContainer
.getService(ServiceNames.forManagedProcessApplication(name));
if (serviceController != null) {
return serviceController.getValue();
}
else {
return null;
}
}
} | repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\MscRuntimeContainerDelegate.java | 2 |
请完成以下Java代码 | public String filterType() {
return "pre";
}
@Override
public int filterOrder() {
return 10;
}
@Override
public boolean shouldFilter() {
// specific APIs can be filtered out using
// if (RequestContext.getCurrentContext().getRequest().getRequestURI().startsWith("/api")) { ... }
return true;
}
@Override
public Object run() {
String bucketId = getId(RequestContext.getCurrentContext().getRequest());
Bucket bucket = buckets.getProxy(bucketId, getConfigSupplier());
if (bucket.tryConsume(1)) {
// the limit is not exceeded
log.debug("API rate limit OK for {}", bucketId);
} else {
// limit is exceeded
log.info("API rate limit exceeded for {}", bucketId);
apiLimitExceeded();
}
return null;
}
private Supplier<BucketConfiguration> getConfigSupplier() {
return () -> {
JHipsterProperties.Gateway.RateLimiting rateLimitingProperties =
jHipsterProperties.getGateway().getRateLimiting(); | return Bucket4j.configurationBuilder()
.addLimit(Bandwidth.simple(rateLimitingProperties.getLimit(),
Duration.ofSeconds(rateLimitingProperties.getDurationInSeconds())))
.build();
};
}
/**
* Create a Zuul response error when the API limit is exceeded.
*/
private void apiLimitExceeded() {
RequestContext ctx = RequestContext.getCurrentContext();
ctx.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
if (ctx.getResponseBody() == null) {
ctx.setResponseBody("API rate limit exceeded");
ctx.setSendZuulResponse(false);
}
}
/**
* The ID that will identify the limit: the user login or the user IP address.
*/
private String getId(HttpServletRequest httpServletRequest) {
return SecurityUtils.getCurrentUserLogin().orElse(httpServletRequest.getRemoteAddr());
}
} | repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\gateway\ratelimiting\RateLimitingFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SecurityConfig {
@Autowired
private OAuth2RestTemplate restTemplate;
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring()
.antMatchers("/resources/**");
}
@Bean
public OpenIdConnectFilter myFilter() {
final OpenIdConnectFilter filter = new OpenIdConnectFilter("/google-login");
filter.setRestTemplate(restTemplate);
return filter;
} | @Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.addFilterAfter(new OAuth2ClientContextFilter(), AbstractPreAuthenticatedProcessingFilter.class)
.addFilterAfter(myFilter(), OAuth2ClientContextFilter.class)
.httpBasic()
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/google-login"))
.and()
.authorizeRequests()
// .antMatchers("/","/index*").permitAll()
.anyRequest()
.authenticated();
return http.build();
}
} | repos\tutorials-master\spring-security-modules\spring-security-legacy-oidc\src\main\java\com\baeldung\openid\oidc\SecurityConfig.java | 2 |
请完成以下Java代码 | public Long wrongCountRecordsByTableName(String tableName) {
try (Connection c = dataSource.getConnection(); PreparedStatement p = c.prepareStatement("select count(*) from ?")) {
p.setString(1, tableName);
ResultSet rs = p.executeQuery();
rs.next();
return rs.getLong(1);
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
/** | * Invalid placeholder usage example - JPA
*
* @param tableName
* @return
*/
public Long wrongJpaCountRecordsByTableName(String tableName) {
String jql = "select count(*) from :tableName";
TypedQuery<Long> q = em.createQuery(jql, Long.class)
.setParameter("tableName", tableName);
return q.getSingleResult();
}
} | repos\tutorials-master\security-modules\sql-injection-samples\src\main\java\com\baeldung\examples\security\sql\AccountDAO.java | 1 |
请完成以下Java代码 | public void copyPreliminaryValues (final org.compiere.model.I_C_Invoice from, final org.compiere.model.I_C_Invoice to)
{
// nothing to do
}
@Override
public void copyValues(@NonNull final org.compiere.model.I_C_Invoice from, @NonNull final org.compiere.model.I_C_Invoice to)
{
final I_C_Invoice fromToUse = InterfaceWrapperHelper.create(from, I_C_Invoice.class);
final I_C_Invoice toToUse = InterfaceWrapperHelper.create(to, I_C_Invoice.class);
// task 08926
// Make sure the EdiEnabled flag is inherited if the invoice is created form another invoice
ediDocumentBL.setEdiEnabled(toToUse, fromToUse.isEdiEnabled()); | }
@Override
public Class<org.compiere.model.I_C_Invoice> getSupportedItemsClass()
{
return org.compiere.model.I_C_Invoice.class;
}
@Override
public IDocLineCopyHandler<org.compiere.model.I_C_InvoiceLine> getDocLineCopyHandler()
{
return Services.get(ICopyHandlerBL.class).getNullDocLineCopyHandler();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\spi\impl\EdiInvoiceCopyHandler.java | 1 |
请完成以下Java代码 | public static PPOrderQuantities ofQtyRequiredToProduce(@NonNull final Quantity qtyRequiredToProduce)
{
return builder().qtyRequiredToProduce(qtyRequiredToProduce).build();
}
public Quantity getQtyRemainingToProduce()
{
return getQtyRequiredToProduce()
.subtract(getQtyReceived())
.subtract(getQtyScrapped());
}
public PPOrderQuantities reduce(@NonNull final OrderQtyChangeRequest request)
{
return toBuilder()
.qtyReceived(getQtyReceived().add(request.getQtyReceivedToAdd()))
.qtyScrapped(getQtyScrapped().add(request.getQtyScrappedToAdd()))
.qtyRejected(getQtyRejected().add(request.getQtyRejectedToAdd()))
.qtyReserved(getQtyReserved().subtract(request.getQtyReceivedToAdd()))
.build();
}
public PPOrderQuantities close()
{
return toBuilder()
.qtyRequiredToProduce(getQtyReceived())
.qtyRequiredToProduceBeforeClose(getQtyRequiredToProduce())
.build();
}
public PPOrderQuantities unclose()
{
return toBuilder()
.qtyRequiredToProduce(getQtyRequiredToProduceBeforeClose())
.qtyRequiredToProduceBeforeClose(getQtyRequiredToProduceBeforeClose().toZero())
.build();
}
public PPOrderQuantities voidQtys()
{ | return toBuilder()
.qtyRequiredToProduce(getQtyRequiredToProduce().toZero())
.build();
}
public PPOrderQuantities convertQuantities(@NonNull final UnaryOperator<Quantity> converter)
{
return toBuilder()
.qtyRequiredToProduce(converter.apply(getQtyRequiredToProduce()))
.qtyRequiredToProduceBeforeClose(converter.apply(getQtyRequiredToProduceBeforeClose()))
.qtyReceived(converter.apply(getQtyReceived()))
.qtyScrapped(converter.apply(getQtyScrapped()))
.qtyRejected(converter.apply(getQtyRejected()))
.qtyReserved(converter.apply(getQtyReserved()))
.build();
}
public boolean isSomethingReported()
{
return getQtyReceived().signum() != 0
|| getQtyScrapped().signum() != 0
|| getQtyRejected().signum() != 0;
}
public PPOrderQuantities withQtyRequiredToProduce(@NonNull final Quantity qtyRequiredToProduce)
{
return toBuilder().qtyRequiredToProduce(qtyRequiredToProduce).build();
}
public boolean isSomethingReceived()
{
return qtyReceived.signum() > 0;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\PPOrderQuantities.java | 1 |
请完成以下Java代码 | void addWriteMethod(Method writeMethod) {
this.writeMethods.add(writeMethod);
}
}
static final class BeanPropertiesStandalone extends BeanELResolver.BeanProperties {
BeanPropertiesStandalone(Class<?> type) throws ELException {
super(type);
PropertyDescriptor[] pds = getPropertyDescriptors(this.type);
for (PropertyDescriptor pd : pds) {
this.properties.put(pd.getName(), new BeanPropertyStandalone(type, pd));
}
/*
* Populating from any interfaces causes default methods to be included.
*/
populateFromInterfaces(type);
}
private void populateFromInterfaces(Class<?> aClass) {
Class<?>[] interfaces = aClass.getInterfaces();
for (Class<?> ifs : interfaces) {
PropertyDescriptor[] pds = getPropertyDescriptors(type);
for (PropertyDescriptor pd : pds) {
if (!this.properties.containsKey(pd.getName())) {
this.properties.put(pd.getName(), new BeanPropertyStandalone(this.type, pd));
}
}
populateFromInterfaces(ifs);
}
Class<?> superclass = aClass.getSuperclass();
if (superclass != null) {
populateFromInterfaces(superclass);
}
}
}
static final class BeanPropertyStandalone extends BeanELResolver.BeanProperty {
private final String name;
private final Method readMethod;
private final Method writeMethod;
BeanPropertyStandalone(Class<?> owner, PropertyDescriptor pd) {
super(owner, pd.getType()); | name = pd.getName();
readMethod = pd.getReadMethod();
writeMethod = pd.getWriteMethod();
}
@Override
String getName() {
return name;
}
@Override
Method getReadMethod() {
return readMethod;
}
@Override
Method getWriteMethod() {
return writeMethod;
}
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\BeanSupportStandalone.java | 1 |
请完成以下Java代码 | public void setDeliveryDate (final @Nullable java.sql.Timestamp DeliveryDate)
{
set_Value (COLUMNNAME_DeliveryDate, DeliveryDate);
}
@Override
public java.sql.Timestamp getDeliveryDate()
{
return get_ValueAsTimestamp(COLUMNNAME_DeliveryDate);
}
@Override
public void setIsDifferentInvoicingPartner (final boolean IsDifferentInvoicingPartner)
{
throw new IllegalArgumentException ("IsDifferentInvoicingPartner is virtual column"); }
@Override
public boolean isDifferentInvoicingPartner()
{
return get_ValueAsBoolean(COLUMNNAME_IsDifferentInvoicingPartner);
}
@Override
public void setIsForeignCustomer (final boolean IsForeignCustomer)
{
throw new IllegalArgumentException ("IsForeignCustomer is virtual column"); }
@Override
public boolean isForeignCustomer()
{
return get_ValueAsBoolean(COLUMNNAME_IsForeignCustomer);
}
@Override
public void setIsPrintoutForOtherUser (final boolean IsPrintoutForOtherUser)
{
set_Value (COLUMNNAME_IsPrintoutForOtherUser, IsPrintoutForOtherUser);
}
@Override
public boolean isPrintoutForOtherUser()
{
return get_ValueAsBoolean(COLUMNNAME_IsPrintoutForOtherUser);
}
/**
* ItemName AD_Reference_ID=540735
* Reference name: ItemName
*/
public static final int ITEMNAME_AD_Reference_ID=540735;
/** Rechnung = Rechnung */
public static final String ITEMNAME_Rechnung = "Rechnung";
/** Mahnung = Mahnung */
public static final String ITEMNAME_Mahnung = "Mahnung";
/** Mitgliedsausweis = Mitgliedsausweis */
public static final String ITEMNAME_Mitgliedsausweis = "Mitgliedsausweis"; | /** Brief = Brief */
public static final String ITEMNAME_Brief = "Brief";
/** Sofort-Druck PDF = Sofort-Druck PDF */
public static final String ITEMNAME_Sofort_DruckPDF = "Sofort-Druck PDF";
/** PDF = PDF */
public static final String ITEMNAME_PDF = "PDF";
/** Versand/Wareneingang = Versand/Wareneingang */
public static final String ITEMNAME_VersandWareneingang = "Versand/Wareneingang";
@Override
public void setItemName (final @Nullable java.lang.String ItemName)
{
set_Value (COLUMNNAME_ItemName, ItemName);
}
@Override
public java.lang.String getItemName()
{
return get_ValueAsString(COLUMNNAME_ItemName);
}
@Override
public void setPrintingQueueAggregationKey (final @Nullable java.lang.String PrintingQueueAggregationKey)
{
set_Value (COLUMNNAME_PrintingQueueAggregationKey, PrintingQueueAggregationKey);
}
@Override
public java.lang.String getPrintingQueueAggregationKey()
{
return get_ValueAsString(COLUMNNAME_PrintingQueueAggregationKey);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Printing_Queue.java | 1 |
请完成以下Java代码 | public void setAD_Language (final java.lang.String AD_Language)
{
set_ValueNoCheck (COLUMNNAME_AD_Language, AD_Language);
}
@Override
public java.lang.String getAD_Language()
{
return get_ValueAsString(COLUMNNAME_AD_Language);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setDescription_Customized (final @Nullable java.lang.String Description_Customized)
{
set_Value (COLUMNNAME_Description_Customized, Description_Customized);
}
@Override
public java.lang.String getDescription_Customized()
{
return get_ValueAsString(COLUMNNAME_Description_Customized);
}
@Override
public void setIsTranslated (final boolean IsTranslated)
{
set_Value (COLUMNNAME_IsTranslated, IsTranslated);
}
@Override
public boolean isTranslated()
{
return get_ValueAsBoolean(COLUMNNAME_IsTranslated);
}
@Override
public void setIsUseCustomization (final boolean IsUseCustomization)
{
set_Value (COLUMNNAME_IsUseCustomization, IsUseCustomization);
}
@Override
public boolean isUseCustomization()
{
return get_ValueAsBoolean(COLUMNNAME_IsUseCustomization);
}
@Override
public void setMobile_Application_ID (final int Mobile_Application_ID)
{
if (Mobile_Application_ID < 1) | set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, Mobile_Application_ID);
}
@Override
public int getMobile_Application_ID()
{
return get_ValueAsInt(COLUMNNAME_Mobile_Application_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setName_Customized (final @Nullable java.lang.String Name_Customized)
{
set_Value (COLUMNNAME_Name_Customized, Name_Customized);
}
@Override
public java.lang.String getName_Customized()
{
return get_ValueAsString(COLUMNNAME_Name_Customized);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Mobile_Application_Trl.java | 1 |
请完成以下Java代码 | private KeyNamePair retrieveBPartnerKNPById(@NonNull final BPartnerId bpartnerId)
{
final I_C_BPartner bpartner = bpartnerDAO.getByIdOutOfTrx(bpartnerId);
return bpartner != null ? toKeyNamePair(bpartner) : null;
}
@Nullable
@Override
public AttributeValueId getAttributeValueIdOrNull(final Object valueKey)
{
return null;
}
private List<KeyNamePair> getCachedVendors()
{
final ImmutableList<KeyNamePair> vendors = vendorsCache.getOrLoad(0, this::retrieveVendorKeyNamePairs);
return ImmutableList.<KeyNamePair>builder()
.add(staticNullValue())
.addAll(vendors)
.build();
}
private QueryLimit getMaxVendors()
{
final int maxVendorsInt = sysconfigBL.getIntValue(SYSCONFIG_MAX_VENDORS, DEFAULT_MAX_VENDORS);
return QueryLimit.ofInt(maxVendorsInt);
} | private ImmutableList<KeyNamePair> retrieveVendorKeyNamePairs()
{
return bpartnerDAO.retrieveVendors(getMaxVendors())
.stream()
.map(HUVendorBPartnerAttributeValuesProvider::toKeyNamePair)
.sorted(Comparator.comparing(KeyNamePair::getName))
.collect(ImmutableList.toImmutableList());
}
private static KeyNamePair toKeyNamePair(@NonNull final I_C_BPartner bpartner)
{
return KeyNamePair.of(bpartner.getC_BPartner_ID(), bpartner.getName(), bpartner.getDescription());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\HUVendorBPartnerAttributeValuesProvider.java | 1 |
请在Spring Boot框架中完成以下Java代码 | boolean isMapKeyHints() {
return (this.id != null && this.id.endsWith(KEY_SUFFIX));
}
boolean isMapValueHints() {
return (this.id != null && this.id.endsWith(VALUE_SUFFIX));
}
String resolveId() {
if (isMapKeyHints()) {
return this.id.substring(0, this.id.length() - KEY_SUFFIX.length());
}
if (isMapValueHints()) {
return this.id.substring(0, this.id.length() - VALUE_SUFFIX.length());
}
return this.id;
} | String getId() {
return this.id;
}
void setId(String id) {
this.id = id;
}
List<ValueHint> getValueHints() {
return this.valueHints;
}
List<ValueProvider> getValueProviders() {
return this.valueProviders;
}
} | repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-metadata\src\main\java\org\springframework\boot\configurationmetadata\ConfigurationMetadataHint.java | 2 |
请完成以下Java代码 | public static PPOrderRef ofPPOrderBOMLineId(@NonNull final RepoIdAware ppOrderId, final int ppOrderBOMLineId)
{
return ofPPOrderBOMLineId(ppOrderId.getRepoId(), ppOrderBOMLineId);
}
public static PPOrderRef ofPPOrderBOMLineId(final int ppOrderId, final int ppOrderBOMLineId)
{
return ofPPOrderBOMLineId(PPOrderId.ofRepoId(ppOrderId), PPOrderBOMLineId.ofRepoId(ppOrderBOMLineId));
}
public static PPOrderRef ofPPOrderBOMLineId(@NonNull final PPOrderId ppOrderId, @NonNull final PPOrderBOMLineId ppOrderBOMLineId)
{
return builder().ppOrderId(ppOrderId).ppOrderBOMLineId(ppOrderBOMLineId).build();
}
public static PPOrderRef ofPPOrderBOMLineId(@NonNull final PPOrderAndBOMLineId ppOrderAndBOMLineId)
{
return ofPPOrderBOMLineId(ppOrderAndBOMLineId.getPpOrderId(), ppOrderAndBOMLineId.getLineId());
}
@Nullable
public static PPOrderRef ofPPOrderAndLineIdOrNull(final int ppOrderRepoId, final int ppOrderBOMLineRepoId)
{
final PPOrderId ppOrderId = PPOrderId.ofRepoIdOrNull(ppOrderRepoId);
if (ppOrderId == null)
{
return null;
}
return builder().ppOrderId(ppOrderId).ppOrderBOMLineId(PPOrderBOMLineId.ofRepoIdOrNull(ppOrderBOMLineRepoId)).build();
}
public boolean isFinishedGoods()
{
return !isBOMLine();
}
public boolean isBOMLine()
{
return ppOrderBOMLineId != null;
}
public PPOrderRef withPPOrderAndBOMLineId(@Nullable final PPOrderAndBOMLineId newPPOrderAndBOMLineId)
{
final PPOrderId ppOrderIdNew = newPPOrderAndBOMLineId != null ? newPPOrderAndBOMLineId.getPpOrderId() : null;
final PPOrderBOMLineId lineIdNew = newPPOrderAndBOMLineId != null ? newPPOrderAndBOMLineId.getLineId() : null;
return PPOrderId.equals(this.ppOrderId, ppOrderIdNew)
&& PPOrderBOMLineId.equals(this.ppOrderBOMLineId, lineIdNew)
? this
: toBuilder().ppOrderId(ppOrderIdNew).ppOrderBOMLineId(lineIdNew).build();
}
public PPOrderRef withPPOrderId(@Nullable final PPOrderId ppOrderId)
{
if (PPOrderId.equals(this.ppOrderId, ppOrderId))
{
return this;
}
return toBuilder().ppOrderId(ppOrderId).build();
}
@Nullable
public static PPOrderRef withPPOrderId(@Nullable final PPOrderRef ppOrderRef, @Nullable final PPOrderId newPPOrderId)
{ | if (ppOrderRef != null)
{
return ppOrderRef.withPPOrderId(newPPOrderId);
}
else if (newPPOrderId != null)
{
return ofPPOrderId(newPPOrderId);
}
else
{
return null;
}
}
@Nullable
public static PPOrderRef withPPOrderAndBOMLineId(@Nullable final PPOrderRef ppOrderRef, @Nullable final PPOrderAndBOMLineId newPPOrderAndBOMLineId)
{
if (ppOrderRef != null)
{
return ppOrderRef.withPPOrderAndBOMLineId(newPPOrderAndBOMLineId);
}
else if (newPPOrderAndBOMLineId != null)
{
return ofPPOrderBOMLineId(newPPOrderAndBOMLineId);
}
else
{
return null;
}
}
@Nullable
public PPOrderAndBOMLineId getPpOrderAndBOMLineId() {return PPOrderAndBOMLineId.ofNullable(ppOrderId, ppOrderBOMLineId);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\pporder\PPOrderRef.java | 1 |
请完成以下Java代码 | protected void executeJob(String nextJobId, CommandExecutor commandExecutor, JobFailureCollector jobFailureCollector) {
JobExecutionHandlerActivation jobHandlerActivation = ra.getJobHandlerActivation();
if(jobHandlerActivation == null) {
// TODO: stop acquisition / only activate acquisition if MDB active?
log.warning("Cannot execute acquired job, no JobExecutionHandler MDB deployed.");
return;
}
MessageEndpoint endpoint = null;
try {
endpoint = jobHandlerActivation.getMessageEndpointFactory().createEndpoint(null);
try {
endpoint.beforeDelivery(method);
} catch (NoSuchMethodException e) {
log.log(Level.WARNING, "NoSuchMethodException while invoking beforeDelivery() on MessageEndpoint '"+endpoint+"'", e);
} catch (ResourceException e) {
log.log(Level.WARNING, "ResourceException while invoking beforeDelivery() on MessageEndpoint '"+endpoint+"'", e);
}
try {
jobFailureCollector = ((JobExecutionHandler)endpoint).executeJob(nextJobId, commandExecutor);
}catch (Exception e) {
if(ProcessEngineLogger.shouldLogJobException(processEngine.getProcessEngineConfiguration(), jobFailureCollector.getJob())) {
log.log(Level.WARNING, "Exception while executing job with id '"+nextJobId+"'.", e);
}
}
try {
endpoint.afterDelivery();
} catch (ResourceException e) {
log.log(Level.WARNING, "ResourceException while invoking afterDelivery() on MessageEndpoint '"+endpoint+"'", e);
}
} catch (UnavailableException e) {
log.log(Level.SEVERE, "UnavailableException while attempting to create messaging endpoint for executing job", e);
} finally {
if(endpoint != null) {
endpoint.release(); | }
}
}
protected void loadMethod() {
try {
method = JobExecutionHandler.class.getMethod("executeJob", new Class[] {String.class, CommandExecutor.class});
} catch (SecurityException e) {
throw new RuntimeException("SecurityException while invoking getMethod() on class "+JobExecutionHandler.class, e);
} catch (NoSuchMethodException e) {
throw new RuntimeException("NoSuchMethodException while invoking getMethod() on class "+JobExecutionHandler.class, e);
}
}
/**
* Context class loader switch is not necessary since
* the loader used for job execution is successor of the engine's
* @see org.camunda.bpm.engine.impl.jobexecutor.ExecuteJobsRunnable#switchClassLoader()
*
* @return the context class loader of the current thread.
*/
@Override
protected ClassLoader switchClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
} | repos\camunda-bpm-platform-master\javaee\jobexecutor-ra\src\main\java\org\camunda\bpm\container\impl\threading\ra\inflow\JcaInflowExecuteJobsRunnable.java | 1 |
请完成以下Java代码 | public void loseWeight()
{
if (size == data.length)
{
return;
}
int[] newData = new int[size];
System.arraycopy(this.data, 0, newData, 0, size);
this.data = newData;
}
public int size()
{
return this.size;
}
public int getLinearExpandFactor()
{
return this.linearExpandFactor;
}
public void set(int index, int value)
{
this.data[index] = value;
}
public int get(int index)
{
return this.data[index];
}
public void removeLast()
{
--size;
}
public int getLast()
{
return data[size - 1];
}
public void setLast(int value)
{
data[size - 1] = value;
}
public int pop()
{
return data[--size];
}
@Override
public void save(DataOutputStream out) throws IOException
{
out.writeInt(size);
for (int i = 0; i < size; i++)
{
out.writeInt(data[i]);
}
out.writeInt(linearExpandFactor);
out.writeBoolean(exponentialExpanding);
out.writeDouble(exponentialExpandFactor);
}
@Override
public boolean load(ByteArray byteArray)
{
if (byteArray == null)
{
return false;
} | size = byteArray.nextInt();
data = new int[size];
for (int i = 0; i < size; i++)
{
data[i] = byteArray.nextInt();
}
linearExpandFactor = byteArray.nextInt();
exponentialExpanding = byteArray.nextBoolean();
exponentialExpandFactor = byteArray.nextDouble();
return true;
}
private void writeObject(ObjectOutputStream out) throws IOException
{
loseWeight();
out.writeInt(size);
out.writeObject(data);
out.writeInt(linearExpandFactor);
out.writeBoolean(exponentialExpanding);
out.writeDouble(exponentialExpandFactor);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
{
size = in.readInt();
data = (int[]) in.readObject();
linearExpandFactor = in.readInt();
exponentialExpanding = in.readBoolean();
exponentialExpandFactor = in.readDouble();
}
@Override
public String toString()
{
ArrayList<Integer> head = new ArrayList<Integer>(20);
for (int i = 0; i < Math.min(size, 20); ++i)
{
head.add(data[i]);
}
return head.toString();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\datrie\IntArrayList.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DeviceConfig.Builder setAssignedAttributeCodes(final Collection<AttributeCode> assignedAttributeCodes)
{
this.assignedAttributeCodes = assignedAttributeCodes;
return this;
}
private ImmutableSet<AttributeCode> getAssignedAttributeCodes()
{
Check.assumeNotEmpty(assignedAttributeCodes, "assignedAttributeCodes is not empty");
return ImmutableSet.copyOf(assignedAttributeCodes);
}
public DeviceConfig.Builder setDeviceClassname(final String deviceClassname)
{
this.deviceClassname = deviceClassname;
return this;
}
private String getDeviceClassname()
{
Check.assumeNotEmpty(deviceClassname, "deviceClassname is not empty");
return deviceClassname;
}
public DeviceConfig.Builder setParameterValueSupplier(final IDeviceParameterValueSupplier parameterValueSupplier)
{
this.parameterValueSupplier = parameterValueSupplier;
return this;
}
private IDeviceParameterValueSupplier getParameterValueSupplier()
{
Check.assumeNotNull(parameterValueSupplier, "Parameter parameterValueSupplier is not null");
return parameterValueSupplier;
}
public DeviceConfig.Builder setRequestClassnamesSupplier(final IDeviceRequestClassnamesSupplier requestClassnamesSupplier)
{
this.requestClassnamesSupplier = requestClassnamesSupplier;
return this;
}
private IDeviceRequestClassnamesSupplier getRequestClassnamesSupplier()
{
Check.assumeNotNull(requestClassnamesSupplier, "Parameter requestClassnamesSupplier is not null");
return requestClassnamesSupplier;
}
public DeviceConfig.Builder setAssignedWarehouseIds(final Set<WarehouseId> assignedWareouseIds)
{
this.assignedWareouseIds = assignedWareouseIds;
return this;
}
private ImmutableSet<WarehouseId> getAssignedWarehouseIds()
{
return assignedWareouseIds == null ? ImmutableSet.of() : ImmutableSet.copyOf(assignedWareouseIds);
}
@NonNull
private ImmutableSet<LocatorId> getAssignedLocatorIds()
{
return assignedLocatorIds == null ? ImmutableSet.of() : ImmutableSet.copyOf(assignedLocatorIds);
}
@NonNull
public DeviceConfig.Builder setAssignedLocatorIds(final Set<LocatorId> assignedLocatorIds)
{
this.assignedLocatorIds = assignedLocatorIds; | return this;
}
@NonNull
public DeviceConfig.Builder setBeforeHooksClassname(@NonNull final ImmutableList<String> beforeHooksClassname)
{
this.beforeHooksClassname = beforeHooksClassname;
return this;
}
@NonNull
private ImmutableList<String> getBeforeHooksClassname()
{
return Optional.ofNullable(beforeHooksClassname).orElseGet(ImmutableList::of);
}
@NonNull
public DeviceConfig.Builder setDeviceConfigParams(@NonNull final ImmutableMap<String, String> deviceConfigParams)
{
this.deviceConfigParams = deviceConfigParams;
return this;
}
@NonNull
private ImmutableMap<String, String> getDeviceConfigParams()
{
return deviceConfigParams == null ? ImmutableMap.of() : deviceConfigParams;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\config\DeviceConfig.java | 2 |
请完成以下Java代码 | public void setPostingType (java.lang.String PostingType)
{
set_Value (COLUMNNAME_PostingType, PostingType);
}
/** Get Buchungsart.
@return Die Art des gebuchten Betrages dieser Transaktion
*/
@Override
public java.lang.String getPostingType ()
{
return (java.lang.String)get_Value(COLUMNNAME_PostingType);
}
/** Set Processing Tag.
@param ProcessingTag Processing Tag */
@Override
public void setProcessingTag (java.lang.String ProcessingTag)
{
set_Value (COLUMNNAME_ProcessingTag, ProcessingTag);
}
/** Get Processing Tag.
@return Processing Tag */
@Override
public java.lang.String getProcessingTag ()
{
return (java.lang.String)get_Value(COLUMNNAME_ProcessingTag);
} | /** Set Menge.
@param Qty
Menge
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Menge
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Fact_Acct_Log.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public CommonErrorHandler errorHandler(KafkaOperations<Object, Object> template) {
return new DefaultErrorHandler(
new DeadLetterPublishingRecoverer(template), new FixedBackOff(1000L, 2));
}
@Bean
public RecordMessageConverter converter() {
JsonMessageConverter converter = new JsonMessageConverter();
DefaultJackson2JavaTypeMapper typeMapper = new DefaultJackson2JavaTypeMapper();
typeMapper.setTypePrecedence(TypePrecedence.TYPE_ID);
typeMapper.addTrustedPackages("com.common");
Map<String, Class<?>> mappings = new HashMap<>();
mappings.put("foo", Foo2.class);
mappings.put("bar", Bar2.class);
typeMapper.setIdClassMapping(mappings);
converter.setTypeMapper(typeMapper);
return converter;
}
@Bean
public NewTopic foos() { | return new NewTopic("foos", 1, (short) 1);
}
@Bean
public NewTopic bars() {
return new NewTopic("bars", 1, (short) 1);
}
@Bean
@Profile("default") // Don't run from test(s)
public ApplicationRunner runner() {
return args -> {
System.out.println("Hit Enter to terminate...");
System.in.read();
};
}
} | repos\spring-kafka-main\samples\sample-02\src\main\java\com\example\Application.java | 2 |
请完成以下Java代码 | protected List<ConditionHandlerResult> evaluateConditionStartByProcessDefinitionId(CommandContext commandContext, ConditionSet conditionSet,
String processDefinitionId) {
DeploymentCache deploymentCache = commandContext.getProcessEngineConfiguration().getDeploymentCache();
ProcessDefinitionEntity processDefinition = deploymentCache.findDeployedProcessDefinitionById(processDefinitionId);
List<ConditionHandlerResult> results = new ArrayList<ConditionHandlerResult>();
if (processDefinition != null && !processDefinition.isSuspended()) {
List<ActivityImpl> activities = findConditionalStartEventActivities(processDefinition);
if (activities.isEmpty()) {
throw LOG.exceptionWhenEvaluatingConditionalStartEventByProcessDefinition(processDefinitionId);
}
for (ActivityImpl activity : activities) {
if (evaluateCondition(conditionSet, activity)) {
results.add(new ConditionHandlerResult(processDefinition, activity));
}
}
}
return results;
}
protected List<ActivityImpl> findConditionalStartEventActivities(ProcessDefinitionEntity processDefinition) {
List<ActivityImpl> activities = new ArrayList<ActivityImpl>();
for (EventSubscriptionDeclaration declaration : ConditionalEventDefinition.getDeclarationsForScope(processDefinition).values()) {
if (isConditionStartEvent(declaration)) {
activities.add(((ConditionalEventDefinition) declaration).getConditionalActivity());
}
} | return activities;
}
protected boolean isConditionStartEvent(EventSubscriptionDeclaration declaration) {
return EventType.CONDITONAL.name().equals(declaration.getEventType()) && declaration.isStartEvent();
}
protected boolean evaluateCondition(ConditionSet conditionSet, ActivityImpl activity) {
ExecutionEntity temporaryExecution = new ExecutionEntity();
if (conditionSet.getVariables() != null) {
temporaryExecution.initializeVariableStore(conditionSet.getVariables());
}
temporaryExecution.setProcessDefinition(activity.getProcessDefinition());
ConditionalEventDefinition conditionalEventDefinition = activity.getProperties().get(BpmnProperties.CONDITIONAL_EVENT_DEFINITION);
if (conditionalEventDefinition.getVariableName() == null || conditionSet.getVariables().containsKey(conditionalEventDefinition.getVariableName())) {
return conditionalEventDefinition.tryEvaluate(temporaryExecution);
} else {
return false;
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\runtime\DefaultConditionHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getType() { | return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isSaveProcessInstanceId() {
return saveProcessInstanceId;
}
public void setSaveProcessInstanceId(boolean saveProcessInstanceId) {
this.saveProcessInstanceId = saveProcessInstanceId;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\engine\CommentRequest.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class DataSourceConfig {
/**
* 创建 orders 数据源的配置对象
*/
@Primary
@Bean(name = "ordersDataSourceProperties")
@ConfigurationProperties(prefix = "spring.datasource.orders") // 读取 spring.datasource.orders 配置到 DataSourceProperties 对象
public DataSourceProperties ordersDataSourceProperties() {
return new DataSourceProperties();
}
/**
* 创建 orders 数据源
*/
@Bean(name = "ordersDataSource")
@ConfigurationProperties(prefix = "spring.datasource.orders.hikari") // 读取 spring.datasource.orders 配置到 HikariDataSource 对象
public DataSource ordersDataSource() {
// 获得 DataSourceProperties 对象
DataSourceProperties properties = this.ordersDataSourceProperties();
// 创建 HikariDataSource 对象
return createHikariDataSource(properties);
}
/**
* 创建 users 数据源的配置对象
*/
@Bean(name = "usersDataSourceProperties")
@ConfigurationProperties(prefix = "spring.datasource.users") // 读取 spring.datasource.users 配置到 DataSourceProperties 对象
public DataSourceProperties usersDataSourceProperties() {
return new DataSourceProperties();
}
/**
* 创建 users 数据源
*/
@Bean(name = "usersDataSource")
@ConfigurationProperties(prefix = "spring.datasource.users.hikari")
public DataSource usersDataSource() {
// 获得 DataSourceProperties 对象 | DataSourceProperties properties = this.usersDataSourceProperties();
// 创建 HikariDataSource 对象
return createHikariDataSource(properties);
}
private static HikariDataSource createHikariDataSource(DataSourceProperties properties) {
// 创建 HikariDataSource 对象
HikariDataSource dataSource = properties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
// 设置线程池名
if (StringUtils.hasText(properties.getName())) {
dataSource.setPoolName(properties.getName());
}
return dataSource;
}
// /**
// * 创建 orders 数据源
// */
// @Bean(name = "ordersDataSource")
// @ConfigurationProperties(prefix = "spring.datasource.orders")
// public DataSource ordersDataSource() {
// return DataSourceBuilder.create().build();
// }
} | repos\SpringBoot-Labs-master\lab-19\lab-19-datasource-pool-hikaricp-multiple\src\main\java\cn\iocoder\springboot\lab19\datasourcepool\config\DataSourceConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class MessageController {
@Autowired
private MessageRepository messageRepository;
@GetMapping(value = "messages")
public List<Message> list() {
List<Message> messages = this.messageRepository.findAll();
return messages;
}
@PostMapping(value = "message")
public Message create(Message message) {
message = this.messageRepository.save(message);
return message;
}
@PutMapping(value = "message")
public Message modify(Message message) {
Message messageResult=this.messageRepository.update(message);
return messageResult;
} | @PatchMapping(value="/message/text")
public Message patch(Message message) {
Message messageResult=this.messageRepository.updateText(message);
return messageResult;
}
@GetMapping(value = "message/{id}")
public Message get(@PathVariable Long id) {
Message message = this.messageRepository.findMessage(id);
return message;
}
@DeleteMapping(value = "message/{id}")
public void delete(@PathVariable("id") Long id) {
this.messageRepository.deleteMessage(id);
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 2-8 课: Spring Boot 构建一个 RESTful Web 服务\spring-boot-web-restful\src\main\java\com\neo\controller\MessageController.java | 2 |
请完成以下Java代码 | protected ExecutionEntity resolveExecution(EventSubscriptionEntity context) {
return context.getExecution();
}
protected JobHandlerConfiguration resolveJobHandlerConfiguration(EventSubscriptionEntity context) {
return new EventSubscriptionJobConfiguration(context.getId());
}
@SuppressWarnings("unchecked")
public static List<EventSubscriptionJobDeclaration> getDeclarationsForActivity(PvmActivity activity) {
Object result = activity.getProperty(BpmnParse.PROPERTYNAME_EVENT_SUBSCRIPTION_JOB_DECLARATION);
if (result != null) {
return (List<EventSubscriptionJobDeclaration>) result;
} else {
return Collections.emptyList();
}
} | /**
* Assumes that an activity has at most one declaration of a certain eventType.
*/
public static EventSubscriptionJobDeclaration findDeclarationForSubscription(EventSubscriptionEntity eventSubscription) {
List<EventSubscriptionJobDeclaration> declarations = getDeclarationsForActivity(eventSubscription.getActivity());
for (EventSubscriptionJobDeclaration declaration : declarations) {
if (declaration.getEventType().equals(eventSubscription.getEventType())) {
return declaration;
}
}
return null;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\EventSubscriptionJobDeclaration.java | 1 |
请完成以下Java代码 | public class HUJoinBL implements IHUJoinBL
{
@Override
public void assignTradingUnitToLoadingUnit(final IHUContext huContext,
final I_M_HU loadingUnit,
final I_M_HU tradingUnit) throws NoCompatibleHUItemParentFoundException
{
//
// Services
final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class);
final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class);
final IHUTrxBL huTrxBL = Services.get(IHUTrxBL.class);
// why is that?
// Check.errorIf(handlingUnitsBL.isAggregateHU(tradingUnit), "Param 'tradingUnit' can't be an aggregate HU; tradingUnit={}", tradingUnit);
//
// iterate existing items of 'lodingUnit' and see if one fits to our 'tradingUnit'
final List<I_M_HU_Item> luItems = handlingUnitsDAO.retrieveItems(loadingUnit);
for (final I_M_HU_Item luItem : luItems)
{
if (!X_M_HU_PI_Item.ITEMTYPE_HandlingUnit.equals(handlingUnitsBL.getItemType(luItem)))
{
continue; // Item type needs to be handling unit
}
if (handlingUnitsBL.isVirtual(tradingUnit))
{
// We assign virtual PI to any loading unit.
huTrxBL.setParentHU(huContext, luItem, tradingUnit);
return; // we are done
}
if (handlingUnitsBL.getPIItem(luItem).getIncluded_HU_PI_ID() != handlingUnitsBL.getPIVersion(tradingUnit).getM_HU_PI_ID())
{ | continue; // Item not supported by this handling unit
}
// Assign HU to the luItem which we just found
huTrxBL.setParentHU(huContext, luItem, tradingUnit);
return; // we are done
}
// we did not find a compatible item for 'tradingUnit' to attach.
// try if we can create one on the fly
final I_M_HU_PI_Item luPI = handlingUnitsDAO.retrieveParentPIItemForChildHUOrNull(loadingUnit, handlingUnitsBL.getPI(tradingUnit), huContext);
if (luPI != null)
{
final I_M_HU_Item newLUItem = handlingUnitsDAO.createHUItem(loadingUnit, luPI);
// Assign HU to the newLUItem which we just created
huTrxBL.setParentHU(huContext, newLUItem, tradingUnit);
return; // we are done
}
// We did not succeed; thorw an exception.
// This does not need to be translated, as it will be handled later (internal error message)
throw new NoCompatibleHUItemParentFoundException("TU could not be attached to the specified LU because no LU-PI Item supports it"
+ "\nLoading Unit (LU): " + loadingUnit
+ "\nTrading Unit (TU): " + tradingUnit);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\impl\HUJoinBL.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean exists(ResourcePatternResolver resolver) {
Assert.notNull(resolver, "'resolver' must not be null");
if (resolver.getResource(this.path).exists()) {
return true;
}
try {
return anyExists(resolver);
}
catch (IOException ex) {
return false;
}
}
private boolean anyExists(ResourcePatternResolver resolver) throws IOException {
String searchPath = this.path;
if (searchPath.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX)) {
searchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
+ searchPath.substring(ResourceLoader.CLASSPATH_URL_PREFIX.length());
}
if (searchPath.startsWith(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX)) { | Resource[] resources = resolver.getResources(searchPath);
for (Resource resource : resources) {
if (resource.exists()) {
return true;
}
}
}
return false;
}
@Override
public String toString() {
return this.path;
}
} | repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\template\TemplateLocation.java | 2 |
请完成以下Java代码 | static JavaType constructType(Object value) {
TypeFactory typeFactory = TypeFactory.defaultInstance();
if (value instanceof Collection<?>) {
Collection<?> collection = (Collection<?>) value;
int size = collection.size();
if (size > 0) {
Iterator<?> iterator = collection.iterator();
Object element = null;
do {
element = iterator.next();
if (bindingsArePresent(value.getClass(), 1) && (element != null || size == 1)) {
JavaType elementType = constructType(element);
return typeFactory.constructCollectionType(guessCollectionType(value), elementType);
}
} while (iterator.hasNext() && element == null);
}
} else if (value instanceof Map<?, ?>) {
Map<?, ?> map = (Map<?, ?>) value;
int size = map.size();
if (size > 0) {
Set<? extends Map.Entry<?, ?>> entries = map.entrySet();
Iterator<? extends Map.Entry<?, ?>> iterator = entries.iterator();
Map.Entry<?, ?> entry = null;
do {
entry = iterator.next();
if (bindingsArePresent(value.getClass(), 2) && (entry.getValue() != null || size == 1)) {
JavaType keyType = constructType(entry.getKey());
JavaType valueType = constructType(entry.getValue());
return typeFactory.constructMapType(Map.class, keyType, valueType);
}
} while (iterator.hasNext() && entry.getValue() == null);
JavaType keyType = constructType(entry.getKey());
return typeFactory.constructMapType(Map.class, keyType, TypeFactory.unknownType());
}
}
if (value != null) { | return typeFactory.constructType(value.getClass());
} else {
return TypeFactory.unknownType();
}
}
/**
* Guess collection class.
*
* @param value collection.
* @return class of th collection implementation.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
static Class<? extends Collection> guessCollectionType(Object value) {
if (value instanceof Collection<?>) {
return (Class<? extends Collection>) value.getClass();
} else {
throw new IllegalArgumentException(
"Could not detect class for " + value + " of type " + value.getClass().getName());
}
}
} | repos\camunda-bpm-platform-master\spin\dataformat-json-jackson\src\main\java\org\camunda\spin\impl\json\jackson\format\TypeHelper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean put(TenantId tenantId, TenantProfileId profileId) {
log.trace("[{}] put: {}", tenantId, profileId);
TenantProfileId oldProfileId = tenantIds.get(tenantId);
if (oldProfileId != null && !oldProfileId.equals(profileId)) {
tenantProfileIds.computeIfAbsent(oldProfileId, id -> ConcurrentHashMap.newKeySet()).remove(tenantId);
tenantIds.put(tenantId, profileId);
tenantProfileIds.computeIfAbsent(profileId, id -> ConcurrentHashMap.newKeySet()).add(tenantId);
return true;
} else {
return false;
}
}
@Override
public Set<TenantId> remove(TenantProfileId profileId) {
Set<TenantId> tenants = tenantProfileIds.remove(profileId);
if (tenants != null) {
tenants.forEach(tenantIds::remove);
}
profiles.remove(profileId);
return tenants;
}
private TenantProfile getTenantProfile(TenantId tenantId) {
TenantProfile profile = null;
TenantProfileId tenantProfileId = tenantIds.get(tenantId);
if (tenantProfileId != null) {
profile = profiles.get(tenantProfileId);
}
if (profile == null) {
tenantProfileFetchLock.lock();
try {
tenantProfileId = tenantIds.get(tenantId);
if (tenantProfileId != null) {
profile = profiles.get(tenantProfileId);
}
if (profile == null) {
TransportProtos.GetEntityProfileRequestMsg msg = TransportProtos.GetEntityProfileRequestMsg.newBuilder()
.setEntityType(EntityType.TENANT.name())
.setEntityIdMSB(tenantId.getId().getMostSignificantBits())
.setEntityIdLSB(tenantId.getId().getLeastSignificantBits())
.build(); | TransportProtos.GetEntityProfileResponseMsg entityProfileMsg = transportService.getEntityProfile(msg);
profile = ProtoUtils.fromProto(entityProfileMsg.getTenantProfile());
TenantProfile existingProfile = profiles.get(profile.getId());
if (existingProfile != null) {
profile = existingProfile;
} else {
profiles.put(profile.getId(), profile);
}
tenantProfileIds.computeIfAbsent(profile.getId(), id -> ConcurrentHashMap.newKeySet()).add(tenantId);
tenantIds.put(tenantId, profile.getId());
ApiUsageState apiUsageState = ProtoUtils.fromProto(entityProfileMsg.getApiState());
rateLimitService.update(tenantId, apiUsageState.isTransportEnabled());
}
} finally {
tenantProfileFetchLock.unlock();
}
}
return profile;
}
} | repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\service\DefaultTransportTenantProfileCache.java | 2 |
请完成以下Java代码 | public static <T> ValueRestriction<T> equalsToOrNull(@Nullable final T onlyValue)
{
return onlyValue != null
? new ValueRestriction<>(Type.EQUALS_TO_OR_NULL, onlyValue)
: isNull();
}
private enum Type
{
ANY, IS_NULL, NOT_NULL, EQUALS_TO, EQUALS_TO_OR_NULL
}
private static final ValueRestriction<Object> ANY = new ValueRestriction<>(Type.ANY, null);
private static final ValueRestriction<Object> IS_NULL = new ValueRestriction<>(Type.IS_NULL, null);
private static final ValueRestriction<Object> NOT_NULL = new ValueRestriction<>(Type.NOT_NULL, null);
private final @NonNull Type type;
private final @Nullable T onlyValue;
private ValueRestriction(final @NonNull Type type, final @Nullable T onlyValue)
{
this.type = type;
this.onlyValue = onlyValue;
}
public interface CaseMappingFunction<T, R>
{
R anyValue();
R valueIsNull();
R valueIsNotNull();
R valueEqualsTo(@NonNull T value);
R valueEqualsToOrNull(@NonNull T value);
}
public <R> R map(@NonNull final CaseMappingFunction<T, R> mappingFunction)
{
switch (type)
{
case ANY:
return mappingFunction.anyValue();
case IS_NULL:
return mappingFunction.valueIsNull();
case NOT_NULL:
return mappingFunction.valueIsNotNull();
case EQUALS_TO:
return mappingFunction.valueEqualsTo(Objects.requireNonNull(onlyValue));
case EQUALS_TO_OR_NULL:
return mappingFunction.valueEqualsToOrNull(Objects.requireNonNull(onlyValue));
default:
throw new AdempiereException("Unhandled type: " + type); // shall not happen
}
}
public <RecordType> void appendFilter(@NonNull final IQueryBuilder<RecordType> queryBuilder, @NonNull final String columnName)
{
map(new CaseMappingFunction<T, Void>()
{
@Override
public Void anyValue() | {
// do nothing
return null;
}
@Override
public Void valueIsNull()
{
queryBuilder.addEqualsFilter(columnName, null);
return null;
}
@Override
public Void valueIsNotNull()
{
queryBuilder.addNotNull(columnName);
return null;
}
@Override
public Void valueEqualsTo(@NonNull final T value)
{
queryBuilder.addEqualsFilter(columnName, value);
return null;
}
@Override
public Void valueEqualsToOrNull(@NonNull final T value)
{
//noinspection unchecked
queryBuilder.addInArrayFilter(columnName, null, value);
return null;
}
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dao\ValueRestriction.java | 1 |
请完成以下Java代码 | public boolean isStorno() {
if (storno == null) {
return false;
} else {
return storno;
}
}
/**
* Sets the value of the storno property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setStorno(Boolean value) {
this.storno = value;
}
/**
* Gets the value of the copy property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public boolean isCopy() {
if (copy == null) {
return false;
} else {
return copy;
}
}
/**
* Sets the value of the copy property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setCopy(Boolean value) {
this.copy = value;
}
/**
* Gets the value of the ifStornoFollowupInvoiceProbable property.
*
* @return
* possible object is | * {@link Boolean }
*
*/
public boolean isIfStornoFollowupInvoiceProbable() {
if (ifStornoFollowupInvoiceProbable == null) {
return true;
} else {
return ifStornoFollowupInvoiceProbable;
}
}
/**
* Sets the value of the ifStornoFollowupInvoiceProbable property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setIfStornoFollowupInvoiceProbable(Boolean value) {
this.ifStornoFollowupInvoiceProbable = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\request\PayloadType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EsController {
public static final String INDEX_JAVASTACK = "javastack";
private final ElasticsearchTemplate elasticsearchTemplate;
private final UserRepository userRepository;
@RequestMapping("/es/insert")
public User insert(@RequestParam("name") String name, @RequestParam("sex") int sex) throws InterruptedException {
// 新增
User user = new User(RandomUtils.nextInt(), name, sex);
IndexCoordinates indexCoordinates = IndexCoordinates.of(INDEX_JAVASTACK);
User save = elasticsearchTemplate.save(user, indexCoordinates);
// 可能有延迟,休眠一秒再查询
Thread.sleep(1000l); | Query query = new CriteriaQuery(Criteria.where("name").is(name));
return elasticsearchTemplate.searchOne(query, User.class, indexCoordinates).getContent();
}
@RequestMapping("/es/repo/insert")
public User repoInsert(@RequestParam("name") String name, @RequestParam("sex") int sex) {
// 新增
User user = new User(RandomUtils.nextInt(), name, sex);
userRepository.save(user);
// 查询
return userRepository.findByName(name).get(0);
}
} | repos\spring-boot-best-practice-master\spring-boot-elasticsearch\src\main\java\cn\javastack\springboot\es\EsController.java | 2 |
请完成以下Java代码 | public final class CacheConstants {
private CacheConstants() {}
public static final String DEVICE_CREDENTIALS_CACHE = "deviceCredentials";
public static final String RELATIONS_CACHE = "relations";
public static final String DEVICE_CACHE = "devices";
public static final String SESSIONS_CACHE = "sessions";
public static final String ASSET_CACHE = "assets";
public static final String CUSTOMER_CACHE = "customers";
public static final String USER_CACHE = "users";
public static final String ENTITY_VIEW_CACHE = "entityViews";
public static final String EDGE_CACHE = "edges";
public static final String EDGE_SESSIONS_CACHE = "edgeSessions";
public static final String RELATED_EDGES_CACHE = "relatedEdges";
public static final String CLAIM_DEVICES_CACHE = "claimDevices";
public static final String SECURITY_SETTINGS_CACHE = "securitySettings";
public static final String TENANT_PROFILE_CACHE = "tenantProfiles";
public static final String TENANTS_CACHE = "tenants";
public static final String TENANTS_EXIST_CACHE = "tenantsExist";
public static final String DEVICE_PROFILE_CACHE = "deviceProfiles";
public static final String NOTIFICATION_SETTINGS_CACHE = "notificationSettings";
public static final String SENT_NOTIFICATIONS_CACHE = "sentNotifications";
public static final String TRENDZ_SETTINGS_CACHE = "trendzSettings";
public static final String AI_MODEL_CACHE = "aiModel";
public static final String API_KEYS_CACHE = "apiKeys";
public static final String ASSET_PROFILE_CACHE = "assetProfiles";
public static final String ATTRIBUTES_CACHE = "attributes";
public static final String TS_LATEST_CACHE = "tsLatest";
public static final String USERS_SESSION_INVALIDATION_CACHE = "userSessionsInvalidation"; | public static final String OTA_PACKAGE_CACHE = "otaPackages";
public static final String OTA_PACKAGE_DATA_CACHE = "otaPackagesData";
public static final String REPOSITORY_SETTINGS_CACHE = "repositorySettings";
public static final String AUTO_COMMIT_SETTINGS_CACHE = "autoCommitSettings";
public static final String TWO_FA_VERIFICATION_CODES_CACHE = "twoFaVerificationCodes";
public static final String VERSION_CONTROL_TASK_CACHE = "versionControlTask";
public static final String USER_SETTINGS_CACHE = "userSettings";
public static final String DASHBOARD_TITLES_CACHE = "dashboardTitles";
public static final String ENTITY_COUNT_CACHE = "entityCount";
public static final String RESOURCE_INFO_CACHE = "resourceInfo";
public static final String ALARM_TYPES_CACHE = "alarmTypes";
public static final String QR_CODE_SETTINGS_CACHE = "qrCodeSettings";
public static final String MOBILE_SECRET_KEY_CACHE = "mobileSecretKey";
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\CacheConstants.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void setOwner(TenantId tenantId, WidgetsBundle widgetsBundle, IdProvider idProvider) {
widgetsBundle.setTenantId(tenantId);
}
@Override
protected WidgetsBundle prepare(EntitiesImportCtx ctx, WidgetsBundle widgetsBundle, WidgetsBundle old, WidgetsBundleExportData exportData, IdProvider idProvider) {
return widgetsBundle;
}
@Override
protected WidgetsBundle saveOrUpdate(EntitiesImportCtx ctx, WidgetsBundle widgetsBundle, WidgetsBundleExportData exportData, IdProvider idProvider, CompareResult compareResult) {
if (CollectionsUtil.isNotEmpty(exportData.getWidgets())) {
exportData.getWidgets().forEach(widgetTypeNode -> {
String bundleAlias = widgetTypeNode.remove("bundleAlias").asText();
String alias = widgetTypeNode.remove("alias").asText();
String fqn = String.format("%s.%s", bundleAlias, alias);
exportData.addFqn(fqn);
WidgetTypeDetails widgetType = JacksonUtil.treeToValue(widgetTypeNode, WidgetTypeDetails.class);
widgetType.setTenantId(ctx.getTenantId());
widgetType.setFqn(fqn);
var existingWidgetType = widgetTypeService.findWidgetTypeByTenantIdAndFqn(ctx.getTenantId(), fqn);
if (existingWidgetType == null) {
widgetType.setId(null);
} else {
widgetType.setId(existingWidgetType.getId());
widgetType.setCreatedTime(existingWidgetType.getCreatedTime());
}
widgetTypeService.saveWidgetType(widgetType);
}); | }
WidgetsBundle savedWidgetsBundle = widgetsBundleService.saveWidgetsBundle(widgetsBundle);
widgetTypeService.updateWidgetsBundleWidgetFqns(ctx.getTenantId(), savedWidgetsBundle.getId(), exportData.getFqns());
return savedWidgetsBundle;
}
@Override
protected CompareResult compare(EntitiesImportCtx ctx, WidgetsBundleExportData exportData, WidgetsBundle prepared, WidgetsBundle existing) {
return new CompareResult(true);
}
@Override
protected WidgetsBundle deepCopy(WidgetsBundle widgetsBundle) {
return new WidgetsBundle(widgetsBundle);
}
@Override
public EntityType getEntityType() {
return EntityType.WIDGETS_BUNDLE;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\WidgetsBundleImportService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String attributes(ModelMap map) {
// 更改 h1 内容
map.put("title", "Thymeleaf 标签演示");
// 更改 id、name、value
map.put("th_id", "thymeleaf-input");
map.put("th_name", "thymeleaf-input");
map.put("th_value", "13");
// 更改 class、href
map.put("th_class", "thymeleaf-class");
map.put("th_href", "http://13blog.site");
return "attributes";
}
@GetMapping("/simple")
public String simple(ModelMap map) {
map.put("thymeleafText", "lanqiao");
map.put("number1", 2025);
map.put("number2", 3);
return "simple";
} | @GetMapping("/test")
public String test(ModelMap map) {
map.put("title", "Thymeleaf 语法测试");
map.put("testString", "玩转 Spring Boot");
map.put("bool", true);
map.put("testArray", new Integer[]{2023,2024,2025,2026});
map.put("testList", Arrays.asList("Spring","Spring Boot","Thymeleaf","MyBatis","Java"));
Map testMap = new HashMap();
testMap.put("platform", "lanqiao");
testMap.put("title", "玩转 Spring Boot 3");
testMap.put("author", "十三");
map.put("testMap", testMap);
map.put("testDate", new Date());
return "test";
}
} | repos\spring-boot-projects-main\玩转SpringBoot系列案例源码\spring-boot-web-thymeleaf-syntax\src\main\java\cn\lanqiao\springboot3\controller\ThymeleafController.java | 2 |
请完成以下Java代码 | public V get(char[] key)
{
return get(new String(key));
}
public V get(String key)
{
int id = exactMatchSearch(key);
if (id == -1) return null;
return valueArray[id];
}
@Override
public V[] getValueArray(V[] a)
{
return valueArray;
}
/**
* 前缀查询
* @param key
* @param offset
* @param maxResults
* @return
*/
public ArrayList<Pair<String, V>> commonPrefixSearch(String key, int offset, int maxResults)
{
byte[] keyBytes = key.getBytes(utf8);
List<Pair<Integer, Integer>> pairList = commonPrefixSearch(keyBytes, offset, maxResults);
ArrayList<Pair<String, V>> resultList = new ArrayList<Pair<String, V>>(pairList.size());
for (Pair<Integer, Integer> pair : pairList)
{
resultList.add(new Pair<String, V>(new String(keyBytes, 0, pair.first), valueArray[pair.second]));
}
return resultList;
}
public ArrayList<Pair<String, V>> commonPrefixSearch(String key)
{
return commonPrefixSearch(key, 0, Integer.MAX_VALUE);
}
@Override
public V put(String key, V value)
{
throw new UnsupportedOperationException("双数组不支持增量式插入");
}
@Override
public V remove(Object key)
{
throw new UnsupportedOperationException("双数组不支持删除");
} | @Override
public void putAll(Map<? extends String, ? extends V> m)
{
throw new UnsupportedOperationException("双数组不支持增量式插入");
}
@Override
public void clear()
{
throw new UnsupportedOperationException("双数组不支持");
}
@Override
public Set<String> keySet()
{
throw new UnsupportedOperationException("双数组不支持");
}
@Override
public Collection<V> values()
{
return Arrays.asList(valueArray);
}
@Override
public Set<Entry<String, V>> entrySet()
{
throw new UnsupportedOperationException("双数组不支持");
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\DartMap.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Xrech4H {
@XmlElement(name = "HEADER", required = true)
protected HEADERXrech header;
@XmlElement(name = "TRAILR", required = true)
protected TRAILR trailr;
/**
* Gets the value of the header property.
*
* @return
* possible object is
* {@link HEADERXrech }
*
*/
public HEADERXrech getHEADER() {
return header;
}
/**
* Sets the value of the header property.
*
* @param value
* allowed object is
* {@link HEADERXrech }
*
*/
public void setHEADER(HEADERXrech value) {
this.header = value;
}
/**
* Gets the value of the trailr property.
* | * @return
* possible object is
* {@link TRAILR }
*
*/
public TRAILR getTRAILR() {
return trailr;
}
/**
* Sets the value of the trailr property.
*
* @param value
* allowed object is
* {@link TRAILR }
*
*/
public void setTRAILR(TRAILR value) {
this.trailr = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_invoic\de\metas\edi\esb\jaxb\stepcom\invoic\Xrech4H.java | 2 |
请完成以下Java代码 | public int getC_ChargeType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_ChargeType_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 Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name | Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ChargeType.java | 1 |
请完成以下Java代码 | private <T extends PO> List<T> retrieveList(final String sql, final Object[] params, final Class<T> clazz, final String trxName)
{
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, trxName);
DB.setParameters(pstmt, params);
rs = pstmt.executeQuery();
final Properties ctx = Env.getCtx();
final String tableName = InterfaceWrapperHelper.getTableName(clazz);
final List<T> result = new ArrayList<>();
while (rs.next())
{ | final T newPO = TableModelLoader.instance.retrieveModel(ctx, tableName, clazz, rs, trxName);
result.add(newPO);
}
return result;
}
catch (SQLException e)
{
throw new DBException(e, sql, params);
}
finally
{
DB.close(rs, pstmt);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\document\impl\RecurringPA.java | 1 |
请完成以下Java代码 | private Sign getAmountSign()
{
Check.assumeNotNull(_amountSign, "amountSign not null");
return _amountSign;
}
public GLDistributionBuilder setQtyToDistribute(final BigDecimal qtyToDistribute)
{
_qtyToDistribute = qtyToDistribute;
return this;
}
private BigDecimal getQtyToDistribute()
{
Check.assumeNotNull(_qtyToDistribute, "qtyToDistribute not null");
return _qtyToDistribute; | }
public GLDistributionBuilder setAccountDimension(final AccountDimension accountDimension)
{
_accountDimension = accountDimension;
return this;
}
private AccountDimension getAccountDimension()
{
Check.assumeNotNull(_accountDimension, "_accountDimension not null");
return _accountDimension;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gldistribution\GLDistributionBuilder.java | 1 |
请完成以下Java代码 | public float similarity(String what, String with)
{
Vector A = query(what);
if (A == null) return -1f;
Vector B = query(with);
if (B == null) return -1f;
return A.cosineForUnitVector(B);
}
public Segment getSegment()
{
return segment;
}
public void setSegment(Segment segment)
{
this.segment = segment;
}
/**
* 是否激活了停用词过滤器
*
* @return | */
public boolean isFilterEnabled()
{
return filter;
}
/**
* 激活/关闭停用词过滤器
*
* @param filter
*/
public void enableFilter(boolean filter)
{
this.filter = filter;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\DocVectorModel.java | 1 |
请完成以下Java代码 | public void setEntityType (java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitäts-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public java.lang.String getEntityType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName () | {
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/**
* Type AD_Reference_ID=540533
* Reference name: C_Aggregation_Attribute_Type
*/
public static final int TYPE_AD_Reference_ID=540533;
/** Attribute = A */
public static final String TYPE_Attribute = "A";
/** Set Art.
@param Type
Type of Validation (SQL, Java Script, Java Language)
*/
@Override
public void setType (java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
/** Get Art.
@return Type of Validation (SQL, Java Script, Java Language)
*/
@Override
public java.lang.String getType ()
{
return (java.lang.String)get_Value(COLUMNNAME_Type);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java-gen\de\metas\aggregation\model\X_C_Aggregation_Attribute.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public HistoricTaskLogEntryQuery from(Date fromDate) {
this.fromDate = fromDate;
return this;
}
@Override
public HistoricTaskLogEntryQuery to(Date toDate) {
this.toDate = toDate;
return this;
}
@Override
public HistoricTaskLogEntryQuery tenantId(String tenantId) {
this.tenantId = tenantId;
return this;
}
@Override
public HistoricTaskLogEntryQuery fromLogNumber(long fromLogNumber) {
this.fromLogNumber = fromLogNumber;
return this;
}
@Override
public HistoricTaskLogEntryQuery toLogNumber(long toLogNumber) {
this.toLogNumber = toLogNumber;
return this;
}
public String getTaskId() {
return taskId;
}
public String getType() {
return type;
}
public String getUserId() {
return userId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getScopeId() {
return scopeId;
}
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public String getSubScopeId() {
return subScopeId;
} | public String getScopeType() {
return scopeType;
}
public Date getFromDate() {
return fromDate;
}
public Date getToDate() {
return toDate;
}
public String getTenantId() {
return tenantId;
}
public long getFromLogNumber() {
return fromLogNumber;
}
public long getToLogNumber() {
return toLogNumber;
}
@Override
public long executeCount(CommandContext commandContext) {
return taskServiceConfiguration.getHistoricTaskLogEntryEntityManager().findHistoricTaskLogEntriesCountByQueryCriteria(this);
}
@Override
public List<HistoricTaskLogEntry> executeList(CommandContext commandContext) {
return taskServiceConfiguration.getHistoricTaskLogEntryEntityManager().findHistoricTaskLogEntriesByQueryCriteria(this);
}
@Override
public HistoricTaskLogEntryQuery orderByLogNumber() {
orderBy(HistoricTaskLogEntryQueryProperty.LOG_NUMBER);
return this;
}
@Override
public HistoricTaskLogEntryQuery orderByTimeStamp() {
orderBy(HistoricTaskLogEntryQueryProperty.TIME_STAMP);
return this;
}
} | repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\HistoricTaskLogEntryQueryImpl.java | 2 |
请完成以下Java代码 | public final void addQtysToInvoice(@NonNull final StockQtyAndUOMQty qtysToInvoiceToAdd)
{
final StockQtyAndUOMQty qtysToInvoiceOld = getQtysToInvoice();
final StockQtyAndUOMQty qtysToInvoiceNew;
if (qtysToInvoiceOld == null)
{
qtysToInvoiceNew = qtysToInvoiceToAdd;
}
else
{
qtysToInvoiceNew = qtysToInvoiceOld.add(qtysToInvoiceToAdd);
}
setQtysToInvoice(qtysToInvoiceNew);
}
@Nullable
@Override
public String getDescription()
{
return description;
}
@Override
public void setDescription(@Nullable final String description)
{
this.description = description;
}
@Override
public Collection<Integer> getC_InvoiceCandidate_InOutLine_IDs()
{
return iciolIds;
}
@Override
public void negateAmounts()
{
setQtysToInvoice(getQtysToInvoice().negate());
setNetLineAmt(getNetLineAmt().negate());
}
@Override
public int getC_Activity_ID()
{
return activityID;
}
@Override
public void setC_Activity_ID(final int activityID)
{
this.activityID = activityID;
}
@Override
public Tax getC_Tax()
{
return tax;
}
@Override
public void setC_Tax(final Tax tax)
{
this.tax = tax;
}
@Override
public boolean isPrinted()
{
return printed;
}
@Override
public void setPrinted(final boolean printed)
{
this.printed = printed;
}
@Override | public int getLineNo()
{
return lineNo;
}
@Override
public void setLineNo(final int lineNo)
{
this.lineNo = lineNo;
}
@Override
public void setInvoiceLineAttributes(@NonNull final List<IInvoiceLineAttribute> invoiceLineAttributes)
{
this.invoiceLineAttributes = ImmutableList.copyOf(invoiceLineAttributes);
}
@Override
public List<IInvoiceLineAttribute> getInvoiceLineAttributes()
{
return invoiceLineAttributes;
}
@Override
public List<InvoiceCandidateInOutLineToUpdate> getInvoiceCandidateInOutLinesToUpdate()
{
return iciolsToUpdate;
}
@Override
public int getC_PaymentTerm_ID()
{
return C_PaymentTerm_ID;
}
@Override
public void setC_PaymentTerm_ID(final int paymentTermId)
{
C_PaymentTerm_ID = paymentTermId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceLineImpl.java | 1 |
请完成以下Java代码 | public class UmsAdmin implements Serializable {
private Long id;
private String username;
private String password;
@ApiModelProperty(value = "头像")
private String icon;
@ApiModelProperty(value = "邮箱")
private String email;
@ApiModelProperty(value = "昵称")
private String nickName;
@ApiModelProperty(value = "备注信息")
private String note;
@ApiModelProperty(value = "创建时间")
private Date createTime;
@ApiModelProperty(value = "最后登录时间")
private Date loginTime;
@ApiModelProperty(value = "帐号启用状态:0->禁用;1->启用")
private Integer status;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getNickName() { | return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getLoginTime() {
return loginTime;
}
public void setLoginTime(Date loginTime) {
this.loginTime = loginTime;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
@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(", username=").append(username);
sb.append(", password=").append(password);
sb.append(", icon=").append(icon);
sb.append(", email=").append(email);
sb.append(", nickName=").append(nickName);
sb.append(", note=").append(note);
sb.append(", createTime=").append(createTime);
sb.append(", loginTime=").append(loginTime);
sb.append(", status=").append(status);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsAdmin.java | 1 |
请完成以下Java代码 | public boolean isLiteralText() {
return node.isLiteralText();
}
@Override
public ValueReference getValueReference(ELContext context) {
return node.getValueReference(bindings, context);
}
/**
* Answer <code>true</code> if this could be used as an lvalue.
* This is the case for eval expressions consisting of a simple identifier or
* a nonliteral prefix, followed by a sequence of property operators (<code>.</code> or <code>[]</code>)
*/
public boolean isLeftValue() {
return node.isLeftValue();
}
/**
* Answer <code>true</code> if this is a deferred expression (containing
* sub-expressions starting with <code>#{</code>)
*/
public boolean isDeferred() {
return deferred;
}
/**
* Expressions are compared using the concept of a <em>structural id</em>:
* variable and function names are anonymized such that two expressions with
* same tree structure will also have the same structural id and vice versa.
* Two value expressions are equal if
* <ol>
* <li>their structural id's are equal</li>
* <li>their bindings are equal</li>
* <li>their expected types are equal</li>
* </ol>
*/
@Override
public boolean equals(Object obj) {
if (obj != null && obj.getClass() == getClass()) {
TreeValueExpression other = (TreeValueExpression) obj;
if (!builder.equals(other.builder)) {
return false;
}
if (type != other.type) {
return false;
} | return (getStructuralId().equals(other.getStructuralId()) && bindings.equals(other.bindings));
}
return false;
}
@Override
public int hashCode() {
return getStructuralId().hashCode();
}
@Override
public String toString() {
return "TreeValueExpression(" + expr + ")";
}
/**
* Print the parse tree.
* @param writer
*/
public void dump(PrintWriter writer) {
NodePrinter.dump(writer, node);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
try {
node = builder.build(expr).getRoot();
} catch (ELException e) {
throw new IOException(e.getMessage());
}
}
} | repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\TreeValueExpression.java | 1 |
请完成以下Java代码 | public ExternalTaskHandler getExternalTaskHandler() {
return externalTaskHandler;
}
@Override
public List<String> getVariableNames() {
return subscriptionConfiguration.getVariableNames();
}
@Override
public boolean isLocalVariables() {
return subscriptionConfiguration.getLocalVariables();
}
@Override
public String getBusinessKey() {
return subscriptionConfiguration.getBusinessKey();
}
@Override
public String getProcessDefinitionId() {
return subscriptionConfiguration.getProcessDefinitionId();
}
@Override
public List<String> getProcessDefinitionIdIn() {
return subscriptionConfiguration.getProcessDefinitionIdIn();
}
@Override
public String getProcessDefinitionKey() {
return subscriptionConfiguration.getProcessDefinitionKey();
}
@Override
public List<String> getProcessDefinitionKeyIn() {
return subscriptionConfiguration.getProcessDefinitionKeyIn();
}
@Override
public String getProcessDefinitionVersionTag() { | return subscriptionConfiguration.getProcessDefinitionVersionTag();
}
@Override
public Map<String, Object> getProcessVariables() {
return subscriptionConfiguration.getProcessVariables();
}
@Override
public boolean isWithoutTenantId() {
return subscriptionConfiguration.getWithoutTenantId();
}
@Override
public List<String> getTenantIdIn() {
return subscriptionConfiguration.getTenantIdIn();
}
@Override
public boolean isIncludeExtensionProperties() {
return subscriptionConfiguration.getIncludeExtensionProperties();
}
protected String[] toArray(List<String> list) {
return list.toArray(new String[0]);
}
@Override
public void afterPropertiesSet() throws Exception {
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter-client\spring\src\main\java\org\camunda\bpm\client\spring\impl\subscription\SpringTopicSubscriptionImpl.java | 1 |
请完成以下Java代码 | public PrivateKey getPrivateKey(Resource resource, KeyFormat format) {
byte[] keyBytes = getResourceBytes(resource);
if (format == KeyFormat.PEM) {
keyBytes = decodePem(keyBytes, PRIVATE_KEY_HEADER, PRIVATE_KEY_FOOTER);
}
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}
/**
* <p>getPublicKey.</p>
*
* @param resourceLocation a {@link java.lang.String} object
* @param format a {@link com.ulisesbocchio.jasyptspringboot.util.AsymmetricCryptography.KeyFormat} object
* @return a {@link java.security.PublicKey} object
*/
@SneakyThrows
public PublicKey getPublicKey(String resourceLocation, KeyFormat format) {
return getPublicKey(resourceLoader.getResource(resourceLocation), format);
}
/**
* <p>getPublicKey.</p>
*
* @param resource a {@link org.springframework.core.io.Resource} object
* @param format a {@link com.ulisesbocchio.jasyptspringboot.util.AsymmetricCryptography.KeyFormat} object
* @return a {@link java.security.PublicKey} object
*/
@SneakyThrows
public PublicKey getPublicKey(Resource resource, KeyFormat format) {
byte[] keyBytes = getResourceBytes(resource);
if (format == KeyFormat.PEM) {
keyBytes = decodePem(keyBytes, PUBLIC_KEY_HEADER, PUBLIC_KEY_FOOTER);
}
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
/**
* <p>encrypt.</p>
*
* @param msg an array of {@link byte} objects
* @param key a {@link java.security.PublicKey} object | * @return an array of {@link byte} objects
*/
@SneakyThrows
public byte[] encrypt(byte[] msg, PublicKey key) {
final Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(msg);
}
/**
* <p>decrypt.</p>
*
* @param msg an array of {@link byte} objects
* @param key a {@link java.security.PrivateKey} object
* @return an array of {@link byte} objects
*/
@SneakyThrows
public byte[] decrypt(byte[] msg, PrivateKey key) {
final Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(msg);
}
public enum KeyFormat {
DER,
PEM;
}
} | repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\util\AsymmetricCryptography.java | 1 |
请完成以下Java代码 | public class ProductXML {
@XmlAttribute
private long productNumber = 0;
@PrimaryKey
private String name = null;
private Double price = 0.0;
public ProductXML() {
this.productNumber = 0;
this.name = null;
this.price = 0.0;
}
public ProductXML(long productNumber, String name, Double price) {
this.productNumber = productNumber;
this.name = name;
this.price = price;
} | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
} | repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\jdo\ProductXML.java | 1 |
请完成以下Java代码 | public Set<Entry<String, ClassLoaderFile>> getFileEntries() {
return Collections.unmodifiableSet(this.filesByName.entrySet());
}
/**
* An individual source directory that is being managed by the collection.
*/
public static class SourceDirectory implements Serializable {
@Serial
private static final long serialVersionUID = 1;
private final String name;
private final Map<String, ClassLoaderFile> files = new LinkedHashMap<>();
SourceDirectory(String name) {
this.name = name;
}
public Set<Entry<String, ClassLoaderFile>> getFilesEntrySet() {
return this.files.entrySet();
}
protected final void add(String name, ClassLoaderFile file) {
this.files.put(name, file);
}
protected final void remove(String name) { | this.files.remove(name);
}
protected final @Nullable ClassLoaderFile get(String name) {
return this.files.get(name);
}
/**
* Return the name of the source directory.
* @return the name of the source directory
*/
public String getName() {
return this.name;
}
/**
* Return all {@link ClassLoaderFile ClassLoaderFiles} in the collection that are
* contained in this source directory.
* @return the files contained in the source directory
*/
public Collection<ClassLoaderFile> getFiles() {
return Collections.unmodifiableCollection(this.files.values());
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\restart\classloader\ClassLoaderFiles.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable Set<String> getExclude() {
return this.exclude;
}
public void setExclude(@Nullable Set<String> exclude) {
this.exclude = exclude;
}
@Override
public @Nullable Show getShowDetails() {
return this.showDetails;
}
public void setShowDetails(@Nullable Show showDetails) {
this.showDetails = showDetails;
}
public @Nullable String getAdditionalPath() {
return this.additionalPath;
}
public void setAdditionalPath(@Nullable String additionalPath) {
this.additionalPath = additionalPath;
}
} | /**
* Health logging properties.
*/
public static class Logging {
/**
* Threshold after which a warning will be logged for slow health indicators.
*/
private Duration slowIndicatorThreshold = Duration.ofSeconds(10);
public Duration getSlowIndicatorThreshold() {
return this.slowIndicatorThreshold;
}
public void setSlowIndicatorThreshold(Duration slowIndicatorThreshold) {
this.slowIndicatorThreshold = slowIndicatorThreshold;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\autoconfigure\actuate\endpoint\HealthEndpointProperties.java | 2 |
请完成以下Java代码 | public void setGuaranteeDaysMin (final int GuaranteeDaysMin)
{
set_ValueNoCheck (COLUMNNAME_GuaranteeDaysMin, GuaranteeDaysMin);
}
@Override
public int getGuaranteeDaysMin()
{
return get_ValueAsInt(COLUMNNAME_GuaranteeDaysMin);
}
@Override
public void setHU_BestBeforeDate (final @Nullable java.sql.Timestamp HU_BestBeforeDate)
{
set_ValueNoCheck (COLUMNNAME_HU_BestBeforeDate, HU_BestBeforeDate);
}
@Override
public java.sql.Timestamp getHU_BestBeforeDate()
{
return get_ValueAsTimestamp(COLUMNNAME_HU_BestBeforeDate);
}
@Override
public void setHU_Expired (final @Nullable java.lang.String HU_Expired)
{
set_ValueNoCheck (COLUMNNAME_HU_Expired, HU_Expired);
}
@Override
public java.lang.String getHU_Expired()
{ | return get_ValueAsString(COLUMNNAME_HU_Expired);
}
@Override
public void setHU_ExpiredWarnDate (final @Nullable java.sql.Timestamp HU_ExpiredWarnDate)
{
set_ValueNoCheck (COLUMNNAME_HU_ExpiredWarnDate, HU_ExpiredWarnDate);
}
@Override
public java.sql.Timestamp getHU_ExpiredWarnDate()
{
return get_ValueAsTimestamp(COLUMNNAME_HU_ExpiredWarnDate);
}
@Override
public void setM_HU_ID (final int M_HU_ID)
{
if (M_HU_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_ID, M_HU_ID);
}
@Override
public int getM_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_BestBefore_V.java | 1 |
请完成以下Java代码 | public final class HeaderUtil {
private static final Logger log = LoggerFactory.getLogger(HeaderUtil.class);
private static final String APPLICATION_NAME = "bookstoreApp";
private HeaderUtil() {
}
public static HttpHeaders createAlert(String message, String param) {
HttpHeaders headers = new HttpHeaders();
headers.add("X-" + APPLICATION_NAME + "-alert", message);
headers.add("X-" + APPLICATION_NAME + "-params", param);
return headers;
}
public static HttpHeaders createEntityCreationAlert(String entityName, String param) {
return createAlert("A new " + entityName + " is created with identifier " + param, param);
}
public static HttpHeaders createEntityUpdateAlert(String entityName, String param) { | return createAlert("A " + entityName + " is updated with identifier " + param, param);
}
public static HttpHeaders createEntityDeletionAlert(String entityName, String param) {
return createAlert("A " + entityName + " is deleted with identifier " + param, param);
}
public static HttpHeaders createFailureAlert(String entityName, String errorKey, String defaultMessage) {
log.error("Entity processing failed, {}", defaultMessage);
HttpHeaders headers = new HttpHeaders();
headers.add("X-" + APPLICATION_NAME + "-error", defaultMessage);
headers.add("X-" + APPLICATION_NAME + "-params", entityName);
return headers;
}
} | repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\web\rest\util\HeaderUtil.java | 1 |
请完成以下Java代码 | protected String doIt() throws Exception
{
final IQueryFilter<I_C_OLCand> queryFilter = getProcessInfo().getQueryFilterOrElseFalse();
final IQueryBuilder<I_C_OLCand> queryBuilder = queryBL.createQueryBuilder(I_C_OLCand.class, getCtx(), get_TrxName())
.addEqualsFilter(I_C_OLCand.COLUMNNAME_Processed, false) // already processed records shall not be validated
.filter(queryFilter);
final Iterator<I_C_OLCand> selectedCands = queryBuilder
.create()
.iterate(I_C_OLCand.class); // working with a iterator, because the there might be *a lot* of C_OLCands, and the issue-solver that we use in the endcustomer.project also iterates.
olCandValidatorService.setValidationProcessInProgress(true); // avoid the InterfaceWrapperHelper.save to trigger another validation from a MV.
try
{
int candidatesWithError = 0;
for (final I_C_OLCand olCand : IteratorUtils.asIterable(selectedCands))
{
olCandValidatorService.validate(olCand); | if (olCand.isError())
{
candidatesWithError++;
}
InterfaceWrapperHelper.save(olCand);
}
return msgBL.getMsg(getCtx(), OLCandValidatorService.MSG_ERRORS_FOUND, new Object[] { candidatesWithError });
}
finally
{
olCandValidatorService.setValidationProcessInProgress(false);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\process\C_OLCand_Validate_Selected.java | 1 |
请完成以下Java代码 | public KeyName[] getLowCardinalityKeyNames() {
return TemplateLowCardinalityTags.values();
}
};
/**
* Low cardinality tags.
*/
public enum TemplateLowCardinalityTags implements KeyName {
/**
* Bean name of the template.
*/
BEAN_NAME {
@Override
public String asString() {
return "spring.rabbit.template.name";
}
},
/**
* The destination exchange (empty if default exchange).
* @since 3.2
*/
EXCHANGE {
@Override
public String asString() {
return "messaging.destination.name";
}
},
/**
* The destination routing key.
* @since 3.2
*/
ROUTING_KEY {
@Override
public String asString() {
return "messaging.rabbitmq.destination.routing_key";
} | }
}
/**
* Default {@link RabbitTemplateObservationConvention} for Rabbit template key values.
*/
public static class DefaultRabbitTemplateObservationConvention implements RabbitTemplateObservationConvention {
/**
* A singleton instance of the convention.
*/
public static final DefaultRabbitTemplateObservationConvention INSTANCE =
new DefaultRabbitTemplateObservationConvention();
@Override
public KeyValues getLowCardinalityKeyValues(RabbitMessageSenderContext context) {
return KeyValues.of(
TemplateLowCardinalityTags.BEAN_NAME.asString(), context.getBeanName(),
TemplateLowCardinalityTags.EXCHANGE.asString(), context.getExchange(),
TemplateLowCardinalityTags.ROUTING_KEY.asString(), context.getRoutingKey()
);
}
@Override
public String getContextualName(RabbitMessageSenderContext context) {
return context.getDestination() + " send";
}
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\support\micrometer\RabbitTemplateObservation.java | 1 |
请完成以下Java代码 | public void setRemark(String value) {
this.remark = value;
}
/**
* Gets the value of the recordId property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getRecordId() {
return recordId;
}
/**
* Sets the value of the recordId property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setRecordId(Integer value) {
this.recordId = value;
}
/**
* Gets the value of the costUnit property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCostUnit() {
return costUnit;
}
/**
* Sets the value of the costUnit property.
*
* @param value
* allowed object is
* {@link String }
* | */
public void setCostUnit(String value) {
this.costUnit = value;
}
/**
* Gets the value of the status property.
*
*/
public int getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
*/
public void setStatus(int value) {
this.status = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\ValidationResultType.java | 1 |
请完成以下Java代码 | private String getProperty(final String propertyName, final String defaultValue)
{
if (properties == null)
{
throw new IllegalStateException("Settings were not configured");
}
return properties.getProperty(propertyName, defaultValue);
}
public String getDbName()
{
return getProperty(PROP_DB_NAME, "metasfresh");
}
public String getDbUser()
{
return getProperty(PROP_DB_USER, "metasfresh");
}
public String getDbType()
{
return getProperty(PROP_DB_TYPE, "postgresql");
}
public String getDbHostname()
{
return getProperty(PROP_DB_SERVER, "localhost");
}
public String getDbPort()
{
return getProperty(PROP_DB_PORT, "5432");
}
public String getDbPassword()
{
return getProperty(PROP_DB_PASSWORD,
// Default value is null because in case is not configured we shall use other auth methods
IDatabase.PASSWORD_NA);
} | @Override
public String toString()
{
final HashMap<Object, Object> result = new HashMap<>(properties);
result.put(PROP_DB_PASSWORD, "******");
return result.toString();
}
public DBConnectionSettings toDBConnectionSettings()
{
return DBConnectionSettings.builder()
.dbHostname(getDbHostname())
.dbPort(getDbPort())
.dbName(getDbName())
.dbUser(getDbUser())
.dbPassword(getDbPassword())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\rollout_migrate\DBConnectionSettingProperties.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DeploymentBuilder tenantId(String tenantId) {
deployment.setTenantId(tenantId);
return this;
}
public DeploymentBuilder enableDuplicateFiltering() {
this.isDuplicateFilterEnabled = true;
return this;
}
public DeploymentBuilder activateProcessDefinitionsOn(Date date) {
this.processDefinitionsActivationDate = date;
return this;
}
@Override
public DeploymentBuilder deploymentProperty(String propertyKey, Object propertyValue) {
deploymentProperties.put(propertyKey, propertyValue);
return this;
}
public Deployment deploy() {
return repositoryService.deploy(this);
}
// getters and setters
// ////////////////////////////////////////////////////// | public DeploymentEntity getDeployment() {
return deployment;
}
public boolean isProcessValidationEnabled() {
return isProcessValidationEnabled;
}
public boolean isBpmn20XsdValidationEnabled() {
return isBpmn20XsdValidationEnabled;
}
public boolean isDuplicateFilterEnabled() {
return isDuplicateFilterEnabled;
}
public Date getProcessDefinitionsActivationDate() {
return processDefinitionsActivationDate;
}
public Map<String, Object> getDeploymentProperties() {
return deploymentProperties;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\repository\DeploymentBuilderImpl.java | 2 |
请完成以下Java代码 | public PlanItem getSource() {
return sourceRefAttribute.getReferenceTargetElement(this);
}
public void setSource(PlanItem source) {
sourceRefAttribute.setReferenceTargetElement(this, source);
}
public PlanItemTransition getStandardEvent() {
PlanItemTransitionStandardEvent child = standardEventChild.getChild(this);
return child.getValue();
}
public void setStandardEvent(PlanItemTransition standardEvent) {
PlanItemTransitionStandardEvent child = standardEventChild.getChild(this);
child.setValue(standardEvent);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(PlanItemStartTrigger.class, CMMN_ELEMENT_PLAN_ITEM_START_TRIGGER)
.extendsType(StartTrigger.class)
.namespaceUri(CMMN11_NS)
.instanceProvider(new ModelTypeInstanceProvider<PlanItemStartTrigger>() {
public PlanItemStartTrigger newInstance(ModelTypeInstanceContext instanceContext) {
return new PlanItemStartTriggerImpl(instanceContext);
} | });
sourceRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REF)
.idAttributeReference(PlanItem.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
standardEventChild = sequenceBuilder.element(PlanItemTransitionStandardEvent.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\PlanItemStartTriggerImpl.java | 1 |
请完成以下Java代码 | public class FlowableComponent extends DefaultComponent {
protected IdentityService identityService;
protected RuntimeService runtimeService;
protected RepositoryService repositoryService;
protected ManagementService managementService;
protected boolean copyVariablesToProperties;
protected boolean copyVariablesToBodyAsMap;
protected boolean copyCamelBodyToBody;
public FlowableComponent() {
}
@Override
public void setCamelContext(CamelContext context) {
super.setCamelContext(context);
identityService = getByType(context, IdentityService.class);
runtimeService = getByType(context, RuntimeService.class);
repositoryService = getByType(context, RepositoryService.class);
managementService = getByType(context, ManagementService.class);
}
private <T> T getByType(CamelContext ctx, Class<T> kls) {
Map<String, T> looked = ctx.getRegistry().findByTypeWithName(kls);
if (looked.isEmpty()) {
return null;
}
return looked.values().iterator().next();
}
@Override
protected Endpoint createEndpoint(String s, String s1, Map<String, Object> parameters) throws Exception {
FlowableEndpoint ae = new FlowableEndpoint(s, getCamelContext());
ae.setComponent(this);
ae.setIdentityService(identityService);
ae.setRuntimeService(runtimeService);
ae.setRepositoryService(repositoryService);
ae.setManagementService(managementService);
ae.setCopyVariablesToProperties(this.copyVariablesToProperties);
ae.setCopyVariablesToBodyAsMap(this.copyVariablesToBodyAsMap);
ae.setCopyCamelBodyToBody(this.copyCamelBodyToBody);
Map<String, Object> returnVars = PropertiesHelper.extractProperties(parameters, "var.return."); | if (returnVars != null && returnVars.size() > 0) {
ae.getReturnVarMap().putAll(returnVars);
}
return ae;
}
public boolean isCopyVariablesToProperties() {
return copyVariablesToProperties;
}
public void setCopyVariablesToProperties(boolean copyVariablesToProperties) {
this.copyVariablesToProperties = copyVariablesToProperties;
}
public boolean isCopyCamelBodyToBody() {
return copyCamelBodyToBody;
}
public void setCopyCamelBodyToBody(boolean copyCamelBodyToBody) {
this.copyCamelBodyToBody = copyCamelBodyToBody;
}
public boolean isCopyVariablesToBodyAsMap() {
return copyVariablesToBodyAsMap;
}
public void setCopyVariablesToBodyAsMap(boolean copyVariablesToBodyAsMap) {
this.copyVariablesToBodyAsMap = copyVariablesToBodyAsMap;
}
} | repos\flowable-engine-main\modules\flowable-camel\src\main\java\org\flowable\camel\FlowableComponent.java | 1 |
请完成以下Java代码 | public static String getDefaultCodeset()
{
return codeset;
}
/**
position of tag relative to start and end.
*/
public static int getDefaultPosition()
{
return position;
}
/**
Default value to set case type
*/
public static int getDefaultCaseType()
{
return case_type;
} | public static char getDefaultStartTag()
{
return start_tag;
}
public static char getDefaultEndTag()
{
return end_tag;
}
/**
Should we print html in a more readable format?
*/
public static boolean getDefaultPrettyPrint()
{
return pretty_print;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\ECSDefaults.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
public AppClusterClientStateWrapVO setId(String id) {
this.id = id;
return this;
}
public String getIp() {
return ip;
}
public AppClusterClientStateWrapVO setIp(String ip) {
this.ip = ip;
return this;
}
public ClusterClientStateVO getState() {
return state;
}
public AppClusterClientStateWrapVO setState(ClusterClientStateVO state) {
this.state = state;
return this;
} | public Integer getCommandPort() {
return commandPort;
}
public AppClusterClientStateWrapVO setCommandPort(Integer commandPort) {
this.commandPort = commandPort;
return this;
}
@Override
public String toString() {
return "AppClusterClientStateWrapVO{" +
"id='" + id + '\'' +
", commandPort=" + commandPort +
", ip='" + ip + '\'' +
", state=" + state +
'}';
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\state\AppClusterClientStateWrapVO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DeploymentBuilder activateProcessDefinitionsOn(Date date) {
this.processDefinitionsActivationDate = date;
return this;
}
@Override
public DeploymentBuilder deploymentProperty(String propertyKey, Object propertyValue) {
deploymentProperties.put(propertyKey, propertyValue);
return this;
}
public Deployment deploy() {
return repositoryService.deploy(this);
}
// getters and setters
// //////////////////////////////////////////////////////
public DeploymentEntity getDeployment() {
return deployment;
}
public boolean isProcessValidationEnabled() {
return isProcessValidationEnabled;
} | public boolean isBpmn20XsdValidationEnabled() {
return isBpmn20XsdValidationEnabled;
}
public boolean isDuplicateFilterEnabled() {
return isDuplicateFilterEnabled;
}
public Date getProcessDefinitionsActivationDate() {
return processDefinitionsActivationDate;
}
public Map<String, Object> getDeploymentProperties() {
return deploymentProperties;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\repository\DeploymentBuilderImpl.java | 2 |
请完成以下Java代码 | public void setSerNo (String SerNo)
{
set_ValueNoCheck (COLUMNNAME_SerNo, SerNo);
}
/** Get Serial No.
@return Product Serial Number
*/
public String getSerNo ()
{
return (String)get_Value(COLUMNNAME_SerNo);
}
/** Set Details.
@param TextDetails Details */
public void setTextDetails (String TextDetails)
{
set_ValueNoCheck (COLUMNNAME_TextDetails, TextDetails);
}
/** Get Details.
@return Details */
public String getTextDetails ()
{
return (String)get_Value(COLUMNNAME_TextDetails);
}
/** Set Usable Life - Months.
@param UseLifeMonths
Months of the usable life of the asset
*/
public void setUseLifeMonths (int UseLifeMonths)
{
set_ValueNoCheck (COLUMNNAME_UseLifeMonths, Integer.valueOf(UseLifeMonths));
}
/** Get Usable Life - Months.
@return Months of the usable life of the asset
*/
public int getUseLifeMonths ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseLifeMonths);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Usable Life - Years.
@param UseLifeYears
Years of the usable life of the asset
*/
public void setUseLifeYears (int UseLifeYears)
{
set_ValueNoCheck (COLUMNNAME_UseLifeYears, Integer.valueOf(UseLifeYears));
}
/** Get Usable Life - Years.
@return Years of the usable life of the asset
*/
public int getUseLifeYears () | {
Integer ii = (Integer)get_Value(COLUMNNAME_UseLifeYears);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Use units.
@param UseUnits
Currently used units of the assets
*/
public void setUseUnits (int UseUnits)
{
set_Value (COLUMNNAME_UseUnits, Integer.valueOf(UseUnits));
}
/** Get Use units.
@return Currently used units of the assets
*/
public int getUseUnits ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseUnits);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Version No.
@param VersionNo
Version Number
*/
public void setVersionNo (String VersionNo)
{
set_ValueNoCheck (COLUMNNAME_VersionNo, VersionNo);
}
/** Get Version No.
@return Version Number
*/
public String getVersionNo ()
{
return (String)get_Value(COLUMNNAME_VersionNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Change.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class StoreController {
private final StoreService storeService;
private final Javers javers;
public StoreController(StoreService customerService, Javers javers) {
this.storeService = customerService;
this.javers = javers;
}
@PostMapping("/stores/{storeId}/products/random")
public void createRandomProduct(@PathVariable final Integer storeId) {
storeService.createRandomProduct(storeId);
}
@PostMapping("/stores/{storeId}/rebrand")
public void rebrandStore(@PathVariable final Integer storeId, @RequestBody RebrandStoreDto rebrandStoreDto) {
storeService.rebrandStore(storeId, rebrandStoreDto.name);
}
@PostMapping(value = "/stores/{storeId}/products/{productId}/price", consumes = MediaType.APPLICATION_JSON_VALUE)
public void updateProductPrice(@PathVariable final Integer productId, @PathVariable String storeId, @RequestBody UpdatePriceDto priceDto) {
storeService.updateProductPrice(productId, priceDto.price);
}
@GetMapping("/products/{productId}/changes")
public String getProductChanges(@PathVariable int productId) {
Product product = storeService.findProductById(productId);
QueryBuilder jqlQuery = QueryBuilder.byInstance(product);
Changes changes = javers.findChanges(jqlQuery.build());
return javers.getJsonConverter().toJson(changes);
} | @GetMapping("/products/snapshots")
public String getProductSnapshots() {
QueryBuilder jqlQuery = QueryBuilder.byClass(Product.class);
List<CdoSnapshot> snapshots = javers.findSnapshots(jqlQuery.build());
return javers.getJsonConverter().toJson(snapshots);
}
@GetMapping("/stores/{storeId}/shadows")
public String getStoreShadows(@PathVariable int storeId) {
Store store = storeService.findStoreById(storeId);
JqlQuery jqlQuery = QueryBuilder.byInstance(store)
.withChildValueObjects().build();
List<Shadow<Store>> shadows = javers.findShadows(jqlQuery);
return javers.getJsonConverter().toJson(shadows.get(0));
}
@GetMapping("/stores/snapshots")
public String getStoresSnapshots() {
QueryBuilder jqlQuery = QueryBuilder.byClass(Store.class);
List<CdoSnapshot> snapshots = javers.findSnapshots(jqlQuery.build());
return javers.getJsonConverter().toJson(snapshots);
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-data-2\src\main\java\com\baeldung\javers\web\StoreController.java | 2 |
请完成以下Java代码 | public class ProductPlanningSchema
{
@Nullable
private ProductPlanningSchemaId id;
@NonNull
private final ProductPlanningSchemaSelector selector;
@NonNull
private final OrgId orgId;
@Nullable
private final ResourceId plantId;
@Nullable
private final WarehouseId warehouseId;
private final boolean attributeDependant;
@Nullable
private final UserId plannerId; | @Nullable
private final Boolean manufactured;
private final boolean createPlan;
private final boolean completeGeneratedDocuments;
private final boolean pickDirectlyIfFeasible;
@Nullable
private final PPRoutingId routingId;
// @Nullable
private final DistributionNetworkId distributionNetworkId;
@NonNull
private final OnMaterialReceiptWithDestWarehouse onMaterialReceiptWithDestWarehouse;
private final int manufacturingAggregationId;
public ProductPlanningSchemaId getIdNotNull() {return Check.assumeNotNull(id, "id is set {}", this);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\ProductPlanningSchema.java | 1 |
请完成以下Java代码 | public String getParentCaseActivityInstanceId() {
return parentCaseActivityInstanceId;
}
public void setParentCaseActivityInstanceId(String parentCaseActivityInstanceId) {
this.parentCaseActivityInstanceId = parentCaseActivityInstanceId;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getCalledProcessInstanceId() {
return calledProcessInstanceId;
}
public void setCalledProcessInstanceId(String calledProcessInstanceId) {
this.calledProcessInstanceId = calledProcessInstanceId;
}
public String getCalledCaseInstanceId() {
return calledCaseInstanceId;
}
public void setCalledCaseInstanceId(String calledCaseInstanceId) {
this.calledCaseInstanceId = calledCaseInstanceId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public Date getCreateTime() {
return startTime;
}
public void setCreateTime(Date createTime) {
setStartTime(createTime);
}
public boolean isRequired() {
return required;
}
public void setRequired(boolean required) {
this.required = required;
} | public boolean isAvailable() {
return caseActivityInstanceState == AVAILABLE.getStateCode();
}
public boolean isEnabled() {
return caseActivityInstanceState == ENABLED.getStateCode();
}
public boolean isDisabled() {
return caseActivityInstanceState == DISABLED.getStateCode();
}
public boolean isActive() {
return caseActivityInstanceState == ACTIVE.getStateCode();
}
public boolean isSuspended() {
return caseActivityInstanceState == SUSPENDED.getStateCode();
}
public boolean isCompleted() {
return caseActivityInstanceState == COMPLETED.getStateCode();
}
public boolean isTerminated() {
return caseActivityInstanceState == TERMINATED.getStateCode();
}
public String toString() {
return this.getClass().getSimpleName()
+ "[caseActivityId=" + caseActivityId
+ ", caseActivityName=" + caseActivityName
+ ", caseActivityInstanceId=" + id
+ ", caseActivityInstanceState=" + caseActivityInstanceState
+ ", parentCaseActivityInstanceId=" + parentCaseActivityInstanceId
+ ", taskId=" + taskId
+ ", calledProcessInstanceId=" + calledProcessInstanceId
+ ", calledCaseInstanceId=" + calledCaseInstanceId
+ ", durationInMillis=" + durationInMillis
+ ", createTime=" + startTime
+ ", endTime=" + endTime
+ ", eventType=" + eventType
+ ", caseExecutionId=" + caseExecutionId
+ ", caseDefinitionId=" + caseDefinitionId
+ ", caseInstanceId=" + caseInstanceId
+ ", tenantId=" + tenantId
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricCaseActivityInstanceEventEntity.java | 1 |
请完成以下Java代码 | protected ProductsProposalRowsLoader createRowsLoaderFromRecord(final TableRecordReference recordRef)
{
final IBPartnerDAO bpartnersRepo = Services.get(IBPartnerDAO.class);
final IPriceListDAO priceListsRepo = Services.get(IPriceListDAO.class);
recordRef.assertTableName(I_C_BPartner.Table_Name);
final BPartnerId bpartnerId = BPartnerId.ofRepoId(recordRef.getRecord_ID());
final Set<CountryId> countryIds = bpartnersRepo.retrieveBPartnerLocationCountryIds(bpartnerId);
if (countryIds.isEmpty())
{
throw new AdempiereException("@NotFound@ @C_BPartner_Location_ID@");
}
final I_C_BPartner bpartnerRecord = bpartnersRepo.getById(bpartnerId);
PricingSystemId pricingSystemId = null;
SOTrx soTrx = null;
if (bpartnerRecord.isCustomer())
{
pricingSystemId = PricingSystemId.ofRepoIdOrNull(bpartnerRecord.getM_PricingSystem_ID());
soTrx = SOTrx.SALES;
}
if (pricingSystemId == null && bpartnerRecord.isVendor())
{
pricingSystemId = PricingSystemId.ofRepoIdOrNull(bpartnerRecord.getPO_PricingSystem_ID());
soTrx = SOTrx.PURCHASE;
}
if (pricingSystemId == null)
{ | throw new AdempiereException("@NotFound@ @M_PricingSystem_ID@");
}
final ZonedDateTime today = SystemTime.asZonedDateTime();
final Set<PriceListVersionId> priceListVersionIds = priceListsRepo.retrievePriceListsCollectionByPricingSystemId(pricingSystemId)
.filterAndStreamIds(countryIds)
.map(priceListId -> priceListsRepo.retrievePriceListVersionId(priceListId, today))
.collect(ImmutableSet.toImmutableSet());
return ProductsProposalRowsLoader.builder()
.lookupDataSourceFactory(lookupDataSourceFactory)
.bpartnerProductStatsService(bpartnerProductStatsService)
.orderProductProposalsService(orderProductProposalsService)
.priceListVersionIds(priceListVersionIds)
.bpartnerId(bpartnerId)
.soTrx(soTrx)
.build();
}
@Override
protected List<RelatedProcessDescriptor> getRelatedProcessDescriptors()
{
return ImmutableList.of(
createProcessDescriptor(WEBUI_ProductsProposal_SaveProductPriceToCurrentPriceListVersion.class),
createProcessDescriptor(WEBUI_ProductsProposal_ShowProductsToAddFromBasePriceList.class));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\view\BPartnerProductsProposalViewFactory.java | 1 |
请完成以下Java代码 | public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) {
return this.delegate.writeHttpHeaders(exchange);
}
/**
* Sets the value of the X-XSS-PROTECTION header. Defaults to
* {@link HeaderValue#DISABLED}
* <p>
* If {@link HeaderValue#DISABLED}, will specify that X-XSS-Protection is disabled.
* For example:
*
* <pre>
* X-XSS-Protection: 0
* </pre>
* <p>
* If {@link HeaderValue#ENABLED}, will contain a value of 1, but will not specify the
* mode as blocked. In this instance, any content will be attempted to be fixed. For
* example:
*
* <pre>
* X-XSS-Protection: 1
* </pre>
* <p>
* If {@link HeaderValue#ENABLED_MODE_BLOCK}, will contain a value of 1 and will
* specify mode as blocked. The content will be replaced with "#". For example:
*
* <pre>
* X-XSS-Protection: 1; mode=block
* </pre>
* @param headerValue the new headerValue
* @throws IllegalArgumentException if headerValue is null
* @since 5.8
*/
public void setHeaderValue(HeaderValue headerValue) {
Assert.notNull(headerValue, "headerValue cannot be null");
this.headerValue = headerValue;
updateDelegate();
}
/**
* The value of the x-xss-protection header. One of: "0", "1", "1; mode=block"
* | * @author Daniel Garnier-Moiroux
* @since 5.8
*/
public enum HeaderValue {
DISABLED("0"), ENABLED("1"), ENABLED_MODE_BLOCK("1; mode=block");
private final String value;
HeaderValue(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
}
private void updateDelegate() {
Builder builder = StaticServerHttpHeadersWriter.builder();
builder.header(X_XSS_PROTECTION, this.headerValue.toString());
this.delegate = builder.build();
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\header\XXssProtectionServerHttpHeadersWriter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public AdminUser selectById(Long id) {
return adminUserDao.getAdminUserById(id);
}
@Override
public AdminUser selectByUserName(String userName) {
return adminUserDao.getAdminUserByUserName(userName);
}
@Override
public int save(AdminUser user) {
//密码加密
user.setPassword(MD5Util.MD5Encode(user.getPassword(), "UTF-8"));
return adminUserDao.addUser(user);
} | @Override
public int updatePassword(AdminUser user) {
return adminUserDao.updateUserPassword(user.getId(), MD5Util.MD5Encode(user.getPassword(), "UTF-8"));
}
@Override
public int deleteBatch(Integer[] ids) {
return adminUserDao.deleteBatch(ids);
}
@Override
public AdminUser getAdminUserByToken(String userToken) {
return adminUserDao.getAdminUserByToken(userToken);
}
} | repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\service\impl\AdminUserServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class SpelRegex {
@Value("#{100 matches '\\d+' }")
private boolean validNumericStringResult;
@Value("#{'100fghdjf' matches '\\d+' }")
private boolean invalidNumericStringResult;
@Value("#{'valid alphabetic string' matches '[a-zA-Z\\s]+' }")
private boolean validAlphabeticStringResult;
@Value("#{'invalid alphabetic string #$1' matches '[a-zA-Z\\s]+' }")
private boolean invalidAlphabeticStringResult;
@Value("#{engine.horsePower matches '\\d+'}")
private boolean validFormatOfHorsePower;
public boolean isValidNumericStringResult() {
return validNumericStringResult;
}
public void setValidNumericStringResult(boolean validNumericStringResult) {
this.validNumericStringResult = validNumericStringResult;
}
public boolean isInvalidNumericStringResult() {
return invalidNumericStringResult;
}
public void setInvalidNumericStringResult(boolean invalidNumericStringResult) {
this.invalidNumericStringResult = invalidNumericStringResult;
}
public boolean isValidAlphabeticStringResult() {
return validAlphabeticStringResult;
}
public void setValidAlphabeticStringResult(boolean validAlphabeticStringResult) {
this.validAlphabeticStringResult = validAlphabeticStringResult;
}
public boolean isInvalidAlphabeticStringResult() {
return invalidAlphabeticStringResult;
}
public void setInvalidAlphabeticStringResult(boolean invalidAlphabeticStringResult) {
this.invalidAlphabeticStringResult = invalidAlphabeticStringResult; | }
public boolean isValidFormatOfHorsePower() {
return validFormatOfHorsePower;
}
public void setValidFormatOfHorsePower(boolean validFormatOfHorsePower) {
this.validFormatOfHorsePower = validFormatOfHorsePower;
}
@Override
public String toString() {
return "SpelRegex{" +
"validNumericStringResult=" + validNumericStringResult +
", invalidNumericStringResult=" + invalidNumericStringResult +
", validAlphabeticStringResult=" + validAlphabeticStringResult +
", invalidAlphabeticStringResult=" + invalidAlphabeticStringResult +
", validFormatOfHorsePower=" + validFormatOfHorsePower +
'}';
}
} | repos\tutorials-master\spring-spel\src\main\java\com\baeldung\spring\spel\examples\SpelRegex.java | 2 |
请完成以下Java代码 | public void setC_Queue_WorkPackage_Log_ID (int C_Queue_WorkPackage_Log_ID)
{
if (C_Queue_WorkPackage_Log_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_Log_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_Log_ID, Integer.valueOf(C_Queue_WorkPackage_Log_ID));
}
/** Get Workpackage audit/log table.
@return Workpackage audit/log table */
@Override
public int getC_Queue_WorkPackage_Log_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_WorkPackage_Log_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Message Text.
@param MsgText
Textual Informational, Menu or Error Message
*/ | @Override
public void setMsgText (java.lang.String MsgText)
{
set_ValueNoCheck (COLUMNNAME_MsgText, MsgText);
}
/** Get Message Text.
@return Textual Informational, Menu or Error Message
*/
@Override
public java.lang.String getMsgText ()
{
return (java.lang.String)get_Value(COLUMNNAME_MsgText);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_WorkPackage_Log.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setCarrier_Product_ID (final int Carrier_Product_ID)
{
if (Carrier_Product_ID < 1)
set_Value (COLUMNNAME_Carrier_Product_ID, null);
else
set_Value (COLUMNNAME_Carrier_Product_ID, Carrier_Product_ID);
}
@Override
public int getCarrier_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_Carrier_Product_ID);
}
@Override
public void setC_Workplace_Carrier_Product_ID (final int C_Workplace_Carrier_Product_ID)
{
if (C_Workplace_Carrier_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Workplace_Carrier_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Workplace_Carrier_Product_ID, C_Workplace_Carrier_Product_ID);
}
@Override
public int getC_Workplace_Carrier_Product_ID()
{ | return get_ValueAsInt(COLUMNNAME_C_Workplace_Carrier_Product_ID);
}
@Override
public void setC_Workplace_ID (final int C_Workplace_ID)
{
if (C_Workplace_ID < 1)
set_Value (COLUMNNAME_C_Workplace_ID, null);
else
set_Value (COLUMNNAME_C_Workplace_ID, C_Workplace_ID);
}
@Override
public int getC_Workplace_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Workplace_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Workplace_Carrier_Product.java | 1 |
请完成以下Spring Boot application配置 | server:
port: 7002
spring:
application:
name: jeecg-demo
cloud:
nacos:
config:
server-addr: @config.server-addr@
group: @config.group@
namespace: @config.namespace@
username: @config.username@
password: @config.password@
discovery:
server-addr: ${spring.cloud.nacos.config.server-addr}
group: @config.group@
namespace: @config.name | space@
username: @config.username@
password: @config.password@
config:
import:
- optional:nacos:jeecg.yaml
- optional:nacos:jeecg-@profile.name@.yaml | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-demo-cloud-start\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public void removeInOutFromBalance(final I_M_InOut inout)
{
final IMaterialBalanceDetailDAO materialBalanceDetailDAO = Services.get(IMaterialBalanceDetailDAO.class);
materialBalanceDetailDAO.deleteBalanceDetailsForInOut(inout);
}
@Override
public List<I_M_Material_Balance_Detail> retrieveBalanceDetailsForInOut(final I_M_InOut inout)
{
final IQueryBuilder<I_M_Material_Balance_Detail> queryBuilder = createQueryBuilderForInout(inout);
return queryBuilder
.create()
.list();
}
private IQueryBuilder<I_M_Material_Balance_Detail> createQueryBuilderForInout(final I_M_InOut inout)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final IQueryBuilder<I_M_Material_Balance_Detail> queryBuilder = queryBL.createQueryBuilder(I_M_Material_Balance_Detail.class, inout)
.filterByClientId()
.addOnlyActiveRecordsFilter();
// same inout id ( possible because all the balance details have both inoutline and inout)
queryBuilder.addEqualsFilter(I_M_Material_Balance_Detail.COLUMNNAME_M_InOut_ID, inout.getM_InOut_ID());
return queryBuilder;
}
@Override
public List<I_M_Material_Balance_Detail> retrieveDetailsForConfigAndDate(final MaterialBalanceConfig config, final Timestamp resetDate)
{
final IQueryBL queryBL = Services.get(IQueryBL.class); | final IQueryBuilder<I_M_Material_Balance_Detail> queryBuilder = queryBL.createQueryBuilder(I_M_Material_Balance_Detail.class)
.filterByClientId()
.addOnlyActiveRecordsFilter();
if (config != null)
{
queryBuilder.addEqualsFilter(I_M_Material_Balance_Detail.COLUMNNAME_M_Material_Balance_Config_ID, config.getRepoId());
}
queryBuilder.addCompareFilter(I_M_Material_Balance_Detail.COLUMNNAME_MovementDate, Operator.LESS, resetDate);
return queryBuilder
.create()
.list();
}
@Override
public void deleteBalanceDetailsForInOut(final I_M_InOut inout)
{
final IQueryBuilder<I_M_Material_Balance_Detail> queryBuilder = createQueryBuilderForInout(inout);
// delete directly all the entries
queryBuilder
.create()
.deleteDirectly();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\api\impl\MaterialBalanceDetailDAO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Builder setCtx(final Properties ctx)
{
this.ctx = ctx;
return this;
}
public Builder setAD_Process_ID(final AdProcessId AD_Process_ID)
{
this.AD_Process_ID = AD_Process_ID;
return this;
}
public Builder setPInstanceId(final PInstanceId pinstanceId)
{
this.pinstanceId = pinstanceId;
return this;
}
public Builder setAD_Language(final String AD_Language)
{
this.AD_Language = AD_Language;
return this;
}
public Builder setOutputType(final OutputType outputType)
{
this.outputType = outputType;
return this;
}
public Builder setType(@NonNull final ProcessType type)
{
this.type = type;
return this;
}
public Builder setJSONPath(final String JSONPath)
{
this.JSONPath = JSONPath;
return this;
}
public Builder setRecord(final int AD_Table_ID, final int Record_ID)
{
this.AD_Table_ID = AD_Table_ID;
this.Record_ID = Record_ID;
return this;
}
public Builder setReportTemplatePath(final String reportTemplatePath)
{
this.reportTemplatePath = reportTemplatePath;
return this;
}
public Builder setSQLStatement(final String sqlStatement)
{
this.sqlStatement = sqlStatement;
return this;
} | public Builder setApplySecuritySettings(final boolean applySecuritySettings)
{
this.applySecuritySettings = applySecuritySettings;
return this;
}
private ImmutableList<ProcessInfoParameter> getProcessInfoParameters()
{
return Services.get(IADPInstanceDAO.class).retrieveProcessInfoParameters(pinstanceId)
.stream()
.map(this::transformProcessInfoParameter)
.collect(ImmutableList.toImmutableList());
}
private ProcessInfoParameter transformProcessInfoParameter(final ProcessInfoParameter piParam)
{
//
// Corner case: REPORT_SQL_QUERY
// => replace @AD_PInstance_ID@ placeholder with actual value
if (ReportConstants.REPORT_PARAM_SQL_QUERY.equals(piParam.getParameterName()))
{
final String parameterValue = piParam.getParameterAsString();
if (parameterValue != null)
{
final String parameterValueEffective = parameterValue.replace(ReportConstants.REPORT_PARAM_SQL_QUERY_AD_PInstance_ID_Placeholder, String.valueOf(pinstanceId.getRepoId()));
return ProcessInfoParameter.of(ReportConstants.REPORT_PARAM_SQL_QUERY, parameterValueEffective);
}
}
//
// Default: don't touch the original parameter
return piParam;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\server\ReportContext.java | 2 |
请完成以下Java代码 | public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setPOReference (final @Nullable java.lang.String POReference)
{
set_Value (COLUMNNAME_POReference, POReference);
}
@Override
public java.lang.String getPOReference()
{
return get_ValueAsString(COLUMNNAME_POReference);
}
@Override
public void setQtyDeliveredInUOM (final @Nullable BigDecimal QtyDeliveredInUOM)
{
set_Value (COLUMNNAME_QtyDeliveredInUOM, QtyDeliveredInUOM);
}
@Override
public BigDecimal getQtyDeliveredInUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredInUOM);
return bd != null ? bd : BigDecimal.ZERO;
} | @Override
public void setQtyEntered (final BigDecimal QtyEntered)
{
set_Value (COLUMNNAME_QtyEntered, QtyEntered);
}
@Override
public BigDecimal getQtyEntered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEntered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyInvoicedInUOM (final @Nullable BigDecimal QtyInvoicedInUOM)
{
set_Value (COLUMNNAME_QtyInvoicedInUOM, QtyInvoicedInUOM);
}
@Override
public BigDecimal getQtyInvoicedInUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInvoicedInUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_CallOrderSummary.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public OtaPackageInfo saveOtaPackageData(OtaPackageInfo otaPackageInfo, String checksum, ChecksumAlgorithm checksumAlgorithm,
byte[] data, String filename, String contentType, User user) throws ThingsboardException {
ActionType actionType = ActionType.UPDATED;
TenantId tenantId = otaPackageInfo.getTenantId();
OtaPackageId otaPackageId = otaPackageInfo.getId();
try {
if (StringUtils.isEmpty(checksum)) {
checksum = otaPackageService.generateChecksum(checksumAlgorithm, ByteBuffer.wrap(data));
}
OtaPackage otaPackage = new OtaPackage(otaPackageId);
otaPackage.setCreatedTime(otaPackageInfo.getCreatedTime());
otaPackage.setTenantId(tenantId);
otaPackage.setDeviceProfileId(otaPackageInfo.getDeviceProfileId());
otaPackage.setType(otaPackageInfo.getType());
otaPackage.setTitle(otaPackageInfo.getTitle());
otaPackage.setVersion(otaPackageInfo.getVersion());
otaPackage.setTag(otaPackageInfo.getTag());
otaPackage.setAdditionalInfo(otaPackageInfo.getAdditionalInfo());
otaPackage.setChecksumAlgorithm(checksumAlgorithm);
otaPackage.setChecksum(checksum);
otaPackage.setFileName(filename);
otaPackage.setContentType(contentType);
otaPackage.setData(ByteBuffer.wrap(data));
otaPackage.setDataSize((long) data.length);
OtaPackageInfo savedOtaPackage = new OtaPackageInfo(otaPackageService.saveOtaPackage(otaPackage));
logEntityActionService.logEntityAction(tenantId, savedOtaPackage.getId(), savedOtaPackage, null, actionType, user);
return savedOtaPackage;
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.OTA_PACKAGE), actionType, user, e, otaPackageId.toString());
throw e; | }
}
@Override
public void delete(OtaPackageInfo otaPackageInfo, User user) throws ThingsboardException {
ActionType actionType = ActionType.DELETED;
TenantId tenantId = otaPackageInfo.getTenantId();
OtaPackageId otaPackageId = otaPackageInfo.getId();
try {
otaPackageService.deleteOtaPackage(tenantId, otaPackageId);
logEntityActionService.logEntityAction(tenantId, otaPackageId, otaPackageInfo, null,
actionType, user, otaPackageInfo.getId().toString());
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.OTA_PACKAGE),
actionType, user, e, otaPackageId.toString());
throw e;
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\ota\DefaultTbOtaPackageService.java | 2 |
请完成以下Java代码 | public class X_C_OLCand_Paypal extends org.compiere.model.PO implements I_C_OLCand_Paypal, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 865508190L;
/** Standard Constructor */
public X_C_OLCand_Paypal (final Properties ctx, final int C_OLCand_Paypal_ID, @Nullable final String trxName)
{
super (ctx, C_OLCand_Paypal_ID, trxName);
}
/** Load Constructor */
public X_C_OLCand_Paypal (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_OLCand_ID (final int C_OLCand_ID)
{
if (C_OLCand_ID < 1)
set_Value (COLUMNNAME_C_OLCand_ID, null);
else
set_Value (COLUMNNAME_C_OLCand_ID, C_OLCand_ID);
}
@Override
public int getC_OLCand_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OLCand_ID);
}
@Override
public void setC_OLCand_Paypal_ID (final int C_OLCand_Paypal_ID)
{
if (C_OLCand_Paypal_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_OLCand_Paypal_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_OLCand_Paypal_ID, C_OLCand_Paypal_ID);
} | @Override
public int getC_OLCand_Paypal_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OLCand_Paypal_ID);
}
@Override
public void setPayPal_Token (final @Nullable java.lang.String PayPal_Token)
{
set_Value (COLUMNNAME_PayPal_Token, PayPal_Token);
}
@Override
public java.lang.String getPayPal_Token()
{
return get_ValueAsString(COLUMNNAME_PayPal_Token);
}
@Override
public void setPayPal_Transaction_ID (final @Nullable java.lang.String PayPal_Transaction_ID)
{
set_Value (COLUMNNAME_PayPal_Transaction_ID, PayPal_Transaction_ID);
}
@Override
public java.lang.String getPayPal_Transaction_ID()
{
return get_ValueAsString(COLUMNNAME_PayPal_Transaction_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java-gen\de\metas\payment\paypal\model\X_C_OLCand_Paypal.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ImmutableSet<BPartnerRelatedRecordId> getRecords(final @NonNull PARENT_ID parentId)
{
return queryRecords(parentId)
.stream()
.map(this::extractRecordId)
.distinct()
.collect(ImmutableSet.toImmutableSet());
}
// see also: de.metas.ui.web.window.model.sql.SqlDocumentsRepository.saveLabels
public void saveAttributes(
@NonNull final ImmutableSet<BPartnerRelatedRecordId> recordIdsSet,
@NonNull final PARENT_ID parentId)
{
final HashMap<BPartnerRelatedRecordId, T> existingRecords = queryRecords(parentId) | .stream()
.collect(GuavaCollectors.toHashMapByKey(this::extractRecordId));
for (final BPartnerRelatedRecordId recordId : recordIdsSet)
{
final T existingRecord = existingRecords.remove(recordId);
if (existingRecord == null)
{
createNewRecord(parentId, recordId);
}
}
deleteRecords(existingRecords.values());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\attributes\related\service\adapter\RelatedRecordsAdapter.java | 2 |
请完成以下Java代码 | protected InstanceBuilder<T> getThis() {
return this;
}
@Override
protected void validate() {
Objects.requireNonNull(this.instance, "instance may not be null");
}
@Override
protected T doBind() {
T toBind = getTargetObject(this.instance);
Bindable<T> bindable = Bindable.ofInstance(toBind);
return bindOrCreate(bindable, this.normalizedProperties, this.name, this.service.validator.get(),
this.service.conversionService.get());
}
}
public static abstract class AbstractBuilder<T, B extends AbstractBuilder<T, B>> {
protected final ConfigurationService service;
protected BiFunction<T, Map<String, Object>, ApplicationEvent> eventFunction;
protected String name;
protected Map<String, Object> normalizedProperties;
protected Map<String, String> properties;
public AbstractBuilder(ConfigurationService service) {
this.service = service;
}
protected abstract B getThis();
public B name(String name) {
this.name = name;
return getThis();
}
public B eventFunction(BiFunction<T, Map<String, Object>, ApplicationEvent> eventFunction) {
this.eventFunction = eventFunction;
return getThis();
}
public B normalizedProperties(Map<String, Object> normalizedProperties) {
this.normalizedProperties = normalizedProperties;
return getThis();
}
public B properties(Map<String, String> properties) {
this.properties = properties;
return getThis();
}
protected abstract void validate();
protected Map<String, Object> normalizeProperties() { | Map<String, Object> normalizedProperties = new HashMap<>();
this.properties.forEach(normalizedProperties::put);
return normalizedProperties;
}
protected abstract T doBind();
public T bind() {
validate();
Assert.hasText(this.name, "name may not be empty");
Assert.isTrue(this.properties != null || this.normalizedProperties != null,
"properties and normalizedProperties both may not be null");
if (this.normalizedProperties == null) {
this.normalizedProperties = normalizeProperties();
}
T bound = doBind();
if (this.eventFunction != null && this.service.publisher != null) {
ApplicationEvent applicationEvent = this.eventFunction.apply(bound, this.normalizedProperties);
this.service.publisher.publishEvent(applicationEvent);
}
return bound;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\support\ConfigurationService.java | 1 |
请完成以下Java代码 | public java.lang.String getProjInvoiceRule()
{
return get_ValueAsString(COLUMNNAME_ProjInvoiceRule);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo); | }
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setStartDate (final @Nullable java.sql.Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
@Override
public java.sql.Timestamp getStartDate()
{
return get_ValueAsTimestamp(COLUMNNAME_StartDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ProjectPhase.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.