instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public void setStatistic_Count (int Statistic_Count)
{
set_Value (COLUMNNAME_Statistic_Count, Integer.valueOf(Statistic_Count));
}
/** Get Statistic Count.
@return Internal statistics how often the entity was used
*/
@Override
public int getStatistic_Count ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Statistic_Count);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Statistic Milliseconds.
@param Statistic_Millis
Internal statistics how many milliseconds a process took
*/ | @Override
public void setStatistic_Millis (int Statistic_Millis)
{
set_Value (COLUMNNAME_Statistic_Millis, Integer.valueOf(Statistic_Millis));
}
/** Get Statistic Milliseconds.
@return Internal statistics how many milliseconds a process took
*/
@Override
public int getStatistic_Millis ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Statistic_Millis);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Process_Stats.java | 1 |
请完成以下Java代码 | public String getLimitApp() {
return limitApp;
}
public void setLimitApp(String limitApp) {
this.limitApp = limitApp;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
@Override
public Date getGmtCreate() {
return gmtCreate;
}
public void setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
}
public Date getGmtModified() {
return gmtModified;
}
public void setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified; | }
public int getStrategy() {
return strategy;
}
public void setStrategy(int strategy) {
this.strategy = strategy;
}
@Override
public Rule toRule(){
AuthorityRule rule=new AuthorityRule();
return rule;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\rule\nacos\entity\AuthorityRuleCorrectEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean isNested(MetadataGenerationEnvironment environment) {
return hasLombokPublicAccessor(environment, true) && super.isNested(environment);
}
private boolean hasSetter(MetadataGenerationEnvironment env) {
boolean nonFinalPublicField = !getField().getModifiers().contains(Modifier.FINAL)
&& hasLombokPublicAccessor(env, false);
return this.setter != null || nonFinalPublicField;
}
/**
* Determine if the current {@link #getField() field} defines a public accessor using
* lombok annotations.
* @param env the {@link MetadataGenerationEnvironment}
* @param getter {@code true} to look for the read accessor, {@code false} for the
* write accessor
* @return {@code true} if this field has a public accessor of the specified type
*/
private boolean hasLombokPublicAccessor(MetadataGenerationEnvironment env, boolean getter) {
String annotation = (getter ? LOMBOK_GETTER_ANNOTATION : LOMBOK_SETTER_ANNOTATION);
AnnotationMirror lombokMethodAnnotationOnField = env.getAnnotation(getField(), annotation);
if (lombokMethodAnnotationOnField != null) {
return isAccessLevelPublic(env, lombokMethodAnnotationOnField); | }
AnnotationMirror lombokMethodAnnotationOnElement = env.getAnnotation(getDeclaringElement(), annotation);
if (lombokMethodAnnotationOnElement != null) {
return isAccessLevelPublic(env, lombokMethodAnnotationOnElement);
}
return (env.hasAnnotation(getDeclaringElement(), LOMBOK_DATA_ANNOTATION)
|| env.hasAnnotation(getDeclaringElement(), LOMBOK_VALUE_ANNOTATION));
}
private boolean isAccessLevelPublic(MetadataGenerationEnvironment env, AnnotationMirror lombokAnnotation) {
Map<String, Object> values = env.getAnnotationElementValues(lombokAnnotation);
Object value = values.get("value");
return (value == null || value.toString().equals(LOMBOK_ACCESS_LEVEL_PUBLIC));
}
} | repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\LombokPropertyDescriptor.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private PickingJobOptionsCollection retrievePickingJobOptionsCollection()
{
return queryBL.createQueryBuilder(I_MobileUI_UserProfile_Picking_Job.class)
// .addOnlyActiveRecordsFilter() // all
.create()
.stream()
.map(MobileUIPickingUserProfileRepository::fromRecord)
.collect(PickingJobOptionsCollection.collect());
}
private static Map.Entry<PickingJobOptionsId, PickingJobOptions> fromRecord(final I_MobileUI_UserProfile_Picking_Job record)
{
final PickingJobOptionsId pickingJobOptionsId = PickingJobOptionsId.ofRepoId(record.getMobileUI_UserProfile_Picking_Job_ID());
final PickingJobOptions pickingJobOptions = PickingJobOptions.builder()
.aggregationType(PickingJobAggregationType.ofNullableCode(record.getPickingJobAggregationType()))
.isAlwaysSplitHUsEnabled(record.isAlwaysSplitHUsEnabled())
.isAllowPickingAnyHU(record.isAllowPickingAnyHU())
.allowedPickToStructures(extractAllowedPickToStructures(record))
.pickAttributes(PickAttributesConfig.UNKNOWN)
.isShipOnCloseLU(record.isShipOnCloseLU())
.considerSalesOrderCapacity(record.isConsiderSalesOrderCapacity())
.isCatchWeightTUPickingEnabled(record.isCatchWeightTUPickingEnabled())
.isAllowSkippingRejectedReason(record.isAllowSkippingRejectedReason())
.isShowConfirmationPromptWhenOverPick(record.isShowConfirmationPromptWhenOverPick())
.isShowLastPickedBestBeforeDateForLines(record.isShowLastPickedBestBeforeDateForLines())
.createShipmentPolicy(CreateShipmentPolicy.ofCode(record.getCreateShipmentPolicy()))
.isAllowCompletingPartialPickingJob(record.isAllowCompletingPartialPickingJob())
.isAnonymousPickHUsOnTheFly(record.isAnonymousHuPickedOnTheFly())
.displayPickingSlotSuggestions(OptionalBoolean.ofNullableString(record.getIsDisplayPickingSlotSuggestions())) | .pickingLineGroupBy(PickingLineGroupBy.ofNullableCode(record.getPickingLineGroupBy()))
.pickingLineSortBy(PickingLineSortBy.ofNullableCode(record.getPickingLineSortBy()))
.build();
return GuavaCollectors.entry(pickingJobOptionsId, pickingJobOptions);
}
private static AllowedPickToStructures extractAllowedPickToStructures(final I_MobileUI_UserProfile_Picking_Job record)
{
final HashMap<PickToStructure, Boolean> map = new HashMap<>();
OptionalBoolean.ofNullableString(record.getAllowPickToStructure_LU_TU()).ifPresent(allowed -> map.put(PickToStructure.LU_TU, allowed));
OptionalBoolean.ofNullableString(record.getAllowPickToStructure_TU()).ifPresent(allowed -> map.put(PickToStructure.TU, allowed));
OptionalBoolean.ofNullableString(record.getAllowPickToStructure_LU_CU()).ifPresent(allowed -> map.put(PickToStructure.LU_CU, allowed));
OptionalBoolean.ofNullableString(record.getAllowPickToStructure_CU()).ifPresent(allowed -> map.put(PickToStructure.CU, allowed));
return AllowedPickToStructures.ofMap(map);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\config\mobileui\MobileUIPickingUserProfileRepository.java | 2 |
请完成以下Java代码 | public class IntroductionAJR {
public static void main(String[] args) throws IOException {
ClassLoader classLoader = IntroductionAJR.class.getClassLoader();
KnowledgeService service = new KnowledgeService();
URL rulesetUrl = classLoader.getResource("rules/SalesRuleset.java");
Knowledge knowledge = service.newKnowledge(
"JAVA-SOURCE",
rulesetUrl
);
List<Customer> customers = Arrays.asList(
new Customer("Customer A"),
new Customer("Customer B"),
new Customer("Customer C")
);
Random random = new Random();
Collection<Object> sessionData = new LinkedList<>(customers); | for (int i = 0; i < 100_000; i++) {
Customer randomCustomer = customers.get(random.nextInt(customers.size()));
Invoice invoice = new Invoice(randomCustomer, 100 * random.nextDouble());
sessionData.add(invoice);
}
knowledge
.newStatelessSession()
.insert(sessionData)
.fire();
for (Customer c : customers) {
System.out.printf("%s:\t$%,.2f%n", c.getName(), c.getTotal());
}
service.shutdown();
}
} | repos\tutorials-master\rule-engines-modules\evrete\src\main\java\com\baeldung\evrete\introduction\IntroductionAJR.java | 1 |
请完成以下Java代码 | public static class TargetRecordAction implements TargetAction
{
@NonNull
public static TargetRecordAction of(@NonNull final TableRecordReference record)
{
return builder().record(record).build();
}
@Nullable
public static TargetRecordAction ofNullable(@Nullable final TableRecordReference record)
{
return record == null ? null : of(record);
}
public static TargetRecordAction ofRecordAndWindow(@NonNull final TableRecordReference record, final int adWindowId)
{
return builder().record(record).adWindowId(AdWindowId.optionalOfRepoId(adWindowId)).build();
}
public static TargetRecordAction ofRecordAndWindow(@NonNull final TableRecordReference record, @NonNull final AdWindowId adWindowId)
{
return builder().record(record).adWindowId(Optional.of(adWindowId)).build();
}
public static TargetRecordAction of(@NonNull final String tableName, final int recordId)
{
return of(TableRecordReference.of(tableName, recordId));
}
public static TargetRecordAction cast(final TargetAction targetAction)
{
return (TargetRecordAction)targetAction;
}
@NonNull @Builder.Default Optional<AdWindowId> adWindowId = Optional.empty();
@NonNull TableRecordReference record;
String recordDisplayText; | }
@lombok.Value
@lombok.Builder
public static class TargetViewAction implements TargetAction
{
public static TargetViewAction cast(final TargetAction targetAction)
{
return (TargetViewAction)targetAction;
}
@Nullable
AdWindowId adWindowId;
@NonNull
String viewId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\UserNotificationRequest.java | 1 |
请完成以下Java代码 | 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);
}
/**
* ShipmentAllocation_BestBefore_Policy AD_Reference_ID=541043
* Reference name: ShipmentAllocation_BestBefore_Policy
*/
public static final int SHIPMENTALLOCATION_BESTBEFORE_POLICY_AD_Reference_ID=541043;
/** Newest_First = N */
public static final String SHIPMENTALLOCATION_BESTBEFORE_POLICY_Newest_First = "N";
/** Expiring_First = E */
public static final String SHIPMENTALLOCATION_BESTBEFORE_POLICY_Expiring_First = "E";
@Override
public void setShipmentAllocation_BestBefore_Policy (final @Nullable java.lang.String ShipmentAllocation_BestBefore_Policy)
{
set_Value (COLUMNNAME_ShipmentAllocation_BestBefore_Policy, ShipmentAllocation_BestBefore_Policy);
}
@Override
public java.lang.String getShipmentAllocation_BestBefore_Policy()
{
return get_ValueAsString(COLUMNNAME_ShipmentAllocation_BestBefore_Policy);
}
@Override
public void setSinglePriceTag_ID (final @Nullable java.lang.String SinglePriceTag_ID)
{
set_ValueNoCheck (COLUMNNAME_SinglePriceTag_ID, SinglePriceTag_ID); | }
@Override
public java.lang.String getSinglePriceTag_ID()
{
return get_ValueAsString(COLUMNNAME_SinglePriceTag_ID);
}
@Override
public void setStatus (final @Nullable java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return get_ValueAsString(COLUMNNAME_Status);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule.java | 1 |
请完成以下Java代码 | public String getCertId() {
return certId;
}
/**
* Sets the value of the certId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCertId(String value) {
this.certId = value;
}
/**
* Gets the value of the frmsCd property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFrmsCd() {
return frmsCd;
}
/**
* Sets the value of the frmsCd property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFrmsCd(String value) {
this.frmsCd = value;
}
/**
* Gets the value of the prd property.
*
* @return
* possible object is
* {@link TaxPeriod1 }
*
*/
public TaxPeriod1 getPrd() {
return prd;
}
/**
* Sets the value of the prd property.
*
* @param value
* allowed object is
* {@link TaxPeriod1 }
*
*/
public void setPrd(TaxPeriod1 value) {
this.prd = value;
}
/**
* Gets the value of the taxAmt property.
*
* @return
* possible object is | * {@link TaxAmount1 }
*
*/
public TaxAmount1 getTaxAmt() {
return taxAmt;
}
/**
* Sets the value of the taxAmt property.
*
* @param value
* allowed object is
* {@link TaxAmount1 }
*
*/
public void setTaxAmt(TaxAmount1 value) {
this.taxAmt = value;
}
/**
* Gets the value of the addtlInf property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAddtlInf() {
return addtlInf;
}
/**
* Sets the value of the addtlInf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAddtlInf(String value) {
this.addtlInf = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TaxRecord1.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class LoginAuthenticationFilter implements Filter {
private static final String URL_SUFFIX_DOT = ".";
/**
* Some urls which needn't auth, such as /auth/login, /registry/machine and so on.
*/
@Value("#{'${auth.filter.exclude-urls}'.split(',')}")
private List<String> authFilterExcludeUrls;
/**
* Some urls with suffixes which needn't auth, such as htm, html, js and so on.
*/
@Value("#{'${auth.filter.exclude-url-suffixes}'.split(',')}")
private List<String> authFilterExcludeUrlSuffixes;
/**
* Authentication using AuthService interface.
*/
@Autowired
private AuthService<HttpServletRequest> authService;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String servletPath = httpRequest.getServletPath();
// Exclude the urls which needn't auth
if (authFilterExcludeUrls.contains(servletPath)) {
chain.doFilter(request, response);
return;
} | // Exclude the urls with suffixes which needn't auth
for (String authFilterExcludeUrlSuffix : authFilterExcludeUrlSuffixes) {
if (StringUtils.isBlank(authFilterExcludeUrlSuffix)) {
continue;
}
// Add . for url suffix so that we needn't add . in property file
if (!authFilterExcludeUrlSuffix.startsWith(URL_SUFFIX_DOT)) {
authFilterExcludeUrlSuffix = URL_SUFFIX_DOT + authFilterExcludeUrlSuffix;
}
if (servletPath.endsWith(authFilterExcludeUrlSuffix)) {
chain.doFilter(request, response);
return;
}
}
AuthService.AuthUser authUser = authService.getAuthUser(httpRequest);
HttpServletResponse httpResponse = (HttpServletResponse) response;
if (authUser == null) {
// If auth fail, set response status code to 401
httpResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
} else {
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\auth\LoginAuthenticationFilter.java | 2 |
请完成以下Java代码 | public class Weather {
@JsonProperty("location")
@JsonAlias("place")
private String location;
@JsonProperty("temp")
@JsonAlias("temperature")
private int temp;
@JsonProperty("outlook")
@JsonAlias("weather")
private String outlook;
public String getLocation() {
return location;
}
public void setLocation(String location) { | this.location = location;
}
public int getTemp() {
return temp;
}
public void setTemp(int temp) {
this.temp = temp;
}
public String getOutlook() {
return outlook;
}
public void setOutlook(String outlook) {
this.outlook = outlook;
}
} | repos\tutorials-master\jackson-modules\jackson-conversions-2\src\main\java\com\baeldung\jackson\multiplefields\Weather.java | 1 |
请完成以下Java代码 | public Map<String, List<String>> getFormParameters() {
return formParameters;
}
public void addFormParameter(String key, String value) {
if (body != null) {
throw new FlowableIllegalStateException("Cannot set both body and form parameters");
} else if (multiValueParts != null && !multiValueParts.isEmpty()) {
throw new FlowableIllegalStateException("Cannot set both multi value parts and form parameters");
}
if (formParameters == null) {
formParameters = new LinkedHashMap<>();
}
formParameters.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
} | public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public boolean isNoRedirects() {
return noRedirects;
}
public void setNoRedirects(boolean noRedirects) {
this.noRedirects = noRedirects;
}
} | repos\flowable-engine-main\modules\flowable-http-common\src\main\java\org\flowable\http\common\api\HttpRequest.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class LazyPasswordEncoder implements PasswordEncoder {
private ApplicationContext applicationContext;
private PasswordEncoder passwordEncoder;
LazyPasswordEncoder(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public String encode(CharSequence rawPassword) {
return getPasswordEncoder().encode(rawPassword);
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return getPasswordEncoder().matches(rawPassword, encodedPassword);
}
@Override
public boolean upgradeEncoding(String encodedPassword) {
return getPasswordEncoder().upgradeEncoding(encodedPassword);
}
private PasswordEncoder getPasswordEncoder() {
if (this.passwordEncoder != null) { | return this.passwordEncoder;
}
this.passwordEncoder = this.applicationContext.getBeanProvider(PasswordEncoder.class)
.getIfUnique(PasswordEncoderFactories::createDelegatingPasswordEncoder);
return this.passwordEncoder;
}
@Override
public String toString() {
return getPasswordEncoder().toString();
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\authentication\configuration\AuthenticationConfiguration.java | 2 |
请完成以下Java代码 | public int getLastProcessed_WorkPackage_ID()
{
return get_ValueAsInt(COLUMNNAME_LastProcessed_WorkPackage_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 de.metas.async.model.I_C_Async_Batch getParent_Async_Batch()
{
return get_ValueAsPO(COLUMNNAME_Parent_Async_Batch_ID, de.metas.async.model.I_C_Async_Batch.class);
}
@Override
public void setParent_Async_Batch(final de.metas.async.model.I_C_Async_Batch Parent_Async_Batch)
{
set_ValueFromPO(COLUMNNAME_Parent_Async_Batch_ID, de.metas.async.model.I_C_Async_Batch.class, Parent_Async_Batch);
}
@Override
public void setParent_Async_Batch_ID (final int Parent_Async_Batch_ID)
{
if (Parent_Async_Batch_ID < 1)
set_Value (COLUMNNAME_Parent_Async_Batch_ID, null); | else
set_Value (COLUMNNAME_Parent_Async_Batch_ID, Parent_Async_Batch_ID);
}
@Override
public int getParent_Async_Batch_ID()
{
return get_ValueAsInt(COLUMNNAME_Parent_Async_Batch_ID);
}
@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.async\src\main\java-gen\de\metas\async\model\X_C_Async_Batch.java | 1 |
请完成以下Java代码 | static boolean isRegistered(LazyDelegateFilter<? extends Filter> lazyDelegateFilter) {
return REGISTRATION.contains(lazyDelegateFilter);
}
static <T extends Filter> boolean lazyInit(LazyDelegateFilter<T> lazyDelegateFilter) {
if (APPLICATION_CONTEXT != null) {
if (isRegistered(lazyDelegateFilter)) {
lazyDelegateFilter.setInitHook(LazyInitRegistration.<T> getInitHook());
lazyDelegateFilter.lazyInit();
REGISTRATION.remove(lazyDelegateFilter);
LOGGER.info("lazy initialized {}", lazyDelegateFilter);
return true;
} else {
LOGGER.debug("skipping lazy init for {} because of no init hook registration", lazyDelegateFilter);
}
} else {
LOGGER.debug("skipping lazy init for {} because application context not initialized yet", lazyDelegateFilter);
}
return false;
}
@Override | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
APPLICATION_CONTEXT = applicationContext;
for (LazyDelegateFilter<? extends Filter> lazyDelegateFilter : getRegistrations()) {
lazyInit(lazyDelegateFilter);
}
}
@EventListener
protected void onContextClosed(ContextClosedEvent ev) {
APPLICATION_CONTEXT = null;
}
static Set<LazyDelegateFilter<? extends Filter>> getRegistrations() {
return Collections.unmodifiableSet(new HashSet<LazyDelegateFilter<? extends Filter>>(REGISTRATION));
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter-webapp-core\src\main\java\org\camunda\bpm\spring\boot\starter\webapp\filter\LazyInitRegistration.java | 1 |
请完成以下Java代码 | public String getExceptionMessage() {
return exceptionMessage;
}
public String getFailedActivityId() {
return failedActivityId;
}
public int getRetries() {
return retries;
}
public Date getDueDate() {
return dueDate;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey; | }
public boolean isSuspended() {
return suspended;
}
public long getPriority() {
return priority;
}
public String getTenantId() {
return tenantId;
}
public Date getCreateTime() {
return createTime;
}
public String getBatchId() {
return batchId;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\JobDto.java | 1 |
请完成以下Java代码 | public class WriterSO {
private long id;
private String fullName;
private String randomNum;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName; | }
public String getRandomNum() {
return randomNum;
}
public void setRandomNum(String randomNum) {
this.randomNum = randomNum;
}
@Override
public String toString() {
return "WriterSO{" +
"id=" + id +
", fullName='" + fullName + '\'' +
", randomNum='" + randomNum + '\'' +
'}';
}
} | repos\spring-boot-quick-master\quick-batch\src\main\java\com\quick\batch\model\WriterSO.java | 1 |
请完成以下Java代码 | public class MSubscriptionProgress extends X_C_SubscriptionProgress
{
private static final long serialVersionUID = -770469915391063757L;
public MSubscriptionProgress(Properties ctx, int C_SubscriptionProgress_ID, String trxName)
{
super(ctx, C_SubscriptionProgress_ID, trxName);
}
public MSubscriptionProgress(Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
}
@Override
public String toString() | {
final StringBuffer sb = new StringBuffer("MSubscriptionProgress[") //
.append(get_ID()) //
.append(", EventDate=").append(getEventDate()) //
.append(", EventType=").append(getEventType()) //
.append(", SeqNo=").append(getSeqNo());
sb.append(", Qty=").append(getQty());
sb.append(", C_Flatrate_Term_ID=").append(getC_Flatrate_Term_ID());
sb.append(", Status=").append(getStatus());
sb.append("]");
return sb.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\model\MSubscriptionProgress.java | 1 |
请完成以下Java代码 | public double getAdd() {
return add;
}
public void setAdd(double add) {
this.add = add;
}
public String getAddString() {
return addString;
}
public void setAddString(String addString) {
this.addString = addString;
}
public double getSubtract() {
return subtract;
}
public void setSubtract(double subtract) {
this.subtract = subtract;
}
public double getMultiply() {
return multiply;
}
public void setMultiply(double multiply) {
this.multiply = multiply;
}
public double getDivide() {
return divide;
}
public void setDivide(double divide) {
this.divide = divide;
}
public double getDivideAlphabetic() {
return divideAlphabetic;
}
public void setDivideAlphabetic(double divideAlphabetic) {
this.divideAlphabetic = divideAlphabetic;
}
public double getModulo() {
return modulo;
}
public void setModulo(double modulo) {
this.modulo = modulo;
} | public double getModuloAlphabetic() {
return moduloAlphabetic;
}
public void setModuloAlphabetic(double moduloAlphabetic) {
this.moduloAlphabetic = moduloAlphabetic;
}
public double getPowerOf() {
return powerOf;
}
public void setPowerOf(double powerOf) {
this.powerOf = powerOf;
}
public double getBrackets() {
return brackets;
}
public void setBrackets(double brackets) {
this.brackets = brackets;
}
@Override
public String toString() {
return "SpelArithmetic{" +
"add=" + add +
", addString='" + addString + '\'' +
", subtract=" + subtract +
", multiply=" + multiply +
", divide=" + divide +
", divideAlphabetic=" + divideAlphabetic +
", modulo=" + modulo +
", moduloAlphabetic=" + moduloAlphabetic +
", powerOf=" + powerOf +
", brackets=" + brackets +
'}';
}
} | repos\tutorials-master\spring-spel\src\main\java\com\baeldung\spring\spel\examples\SpelArithmetic.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Date getOccurredTime() {
return occurredTime;
}
public void setOccurredTime(Date occurredTime) {
this.occurredTime = occurredTime;
}
public Date getTerminatedTime() {
return terminatedTime;
}
public void setTerminatedTime(Date terminatedTime) {
this.terminatedTime = terminatedTime;
}
public Date getExitTime() {
return exitTime;
}
public void setExitTime(Date exitTime) {
this.exitTime = exitTime;
}
public Date getEndedTime() {
return endedTime;
}
public void setEndedTime(Date endedTime) {
this.endedTime = endedTime;
}
public String getStartUserId() {
return startUserId;
}
public void setStartUserId(String startUserId) {
this.startUserId = startUserId;
}
public String getReferenceId() {
return referenceId;
}
public void setReferenceId(String referenceId) {
this.referenceId = referenceId;
}
public String getReferenceType() {
return referenceType;
}
public void setReferenceType(String referenceType) {
this.referenceType = referenceType;
}
public boolean isCompletable() {
return completable;
}
public void setCompletable(boolean completable) {
this.completable = completable;
}
public String getEntryCriterionId() {
return entryCriterionId;
}
public void setEntryCriterionId(String entryCriterionId) { | this.entryCriterionId = entryCriterionId;
}
public String getExitCriterionId() {
return exitCriterionId;
}
public void setExitCriterionId(String exitCriterionId) {
this.exitCriterionId = exitCriterionId;
}
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
}
public String getCompletedBy() {
return completedBy;
}
public void setCompletedBy(String completedBy) {
this.completedBy = completedBy;
}
public String getExtraValue() {
return extraValue;
}
public void setExtraValue(String extraValue) {
this.extraValue = extraValue;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public void setLocalVariables(List<RestVariable> localVariables){
this.localVariables = localVariables;
}
public List<RestVariable> getLocalVariables() {
return localVariables;
}
public void addLocalVariable(RestVariable restVariable) {
localVariables.add(restVariable);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\planitem\PlanItemInstanceResponse.java | 2 |
请完成以下Java代码 | public int getM_DistributionList_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_DistributionList_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(getM_DistributionList_ID()));
}
/** Set Distribution List Line.
@param M_DistributionListLine_ID
Distribution List Line with Business Partner and Quantity/Percentage
*/
public void setM_DistributionListLine_ID (int M_DistributionListLine_ID)
{
if (M_DistributionListLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DistributionListLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DistributionListLine_ID, Integer.valueOf(M_DistributionListLine_ID));
}
/** Get Distribution List Line.
@return Distribution List Line with Business Partner and Quantity/Percentage
*/
public int getM_DistributionListLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_DistributionListLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Minimum Quantity.
@param MinQty
Minimum quantity for the business partner
*/
public void setMinQty (BigDecimal MinQty)
{
set_Value (COLUMNNAME_MinQty, MinQty); | }
/** Get Minimum Quantity.
@return Minimum quantity for the business partner
*/
public BigDecimal getMinQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MinQty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Ratio.
@param Ratio
Relative Ratio for Distributions
*/
public void setRatio (BigDecimal Ratio)
{
set_Value (COLUMNNAME_Ratio, Ratio);
}
/** Get Ratio.
@return Relative Ratio for Distributions
*/
public BigDecimal getRatio ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Ratio);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DistributionListLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CommissionProductService
{
private static final Logger logger = LogManager.getLogger(CommissionProductService.class);
@NonNull
public ProductId getCommissionProduct(@NonNull final ConditionsId conditionsId)
{
final I_C_Flatrate_Conditions conditionsRecord = InterfaceWrapperHelper.loadOutOfTrx(conditionsId, I_C_Flatrate_Conditions.class);
final TypeConditions typeConditions = TypeConditions.ofCode(conditionsRecord.getType_Conditions());
switch (typeConditions)
{
case COMMISSION:
final I_C_HierarchyCommissionSettings commissionSettings = InterfaceWrapperHelper.loadOutOfTrx(conditionsRecord.getC_HierarchyCommissionSettings_ID(), I_C_HierarchyCommissionSettings.class);
return ProductId.ofRepoId(commissionSettings.getCommission_Product_ID());
case MEDIATED_COMMISSION:
final I_C_MediatedCommissionSettings mediatedCommissionSettings = InterfaceWrapperHelper.loadOutOfTrx(conditionsRecord.getC_MediatedCommissionSettings_ID(), I_C_MediatedCommissionSettings.class);
return ProductId.ofRepoId(mediatedCommissionSettings.getCommission_Product_ID());
case MARGIN_COMMISSION:
final I_C_Customer_Trade_Margin customerTradeMargin = InterfaceWrapperHelper.loadOutOfTrx(conditionsRecord.getC_Customer_Trade_Margin_ID(), I_C_Customer_Trade_Margin.class);
return ProductId.ofRepoId(customerTradeMargin.getCommission_Product_ID());
case LICENSE_FEE:
final I_C_LicenseFeeSettings licenseFeeSettings = InterfaceWrapperHelper.loadOutOfTrx(conditionsRecord.getC_LicenseFeeSettings_ID(), I_C_LicenseFeeSettings.class);
return ProductId.ofRepoId(licenseFeeSettings.getCommission_Product_ID());
default:
throw new AdempiereException("Unexpected typeConditions for C_Flatrate_Conditions_ID:" + conditionsId) | .appendParametersToMessage()
.setParameter("typeConditions", typeConditions);
}
}
public boolean productPreventsCommissioning(@Nullable final ProductId productId)
{
if (productId == null)
{
return false; // no product also means nothing is prevented
}
final IProductDAO productDAO = Services.get(IProductDAO.class);
final I_M_Product productRecord = productDAO.getById(productId);
if (!productRecord.isCommissioned())
{
logger.debug("M_Product_ID={} of invoice candidate has Commissioned=false; -> not going to invoke commission system", productRecord.getM_Product_ID());
}
return !productRecord.isCommissioned();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\services\CommissionProductService.java | 2 |
请完成以下Java代码 | public List<PlanItem> getEntryDependentPlanItems() {
return entryDependentPlanItems;
}
public void setEntryDependentPlanItems(List<PlanItem> entryDependentPlanItems) {
this.entryDependentPlanItems = entryDependentPlanItems;
}
public void addEntryDependentPlanItem(PlanItem planItem) {
Optional<PlanItem> planItemWithSameId = entryDependentPlanItems.stream().filter(p -> p.getId().equals(planItem.getId())).findFirst();
if (!planItemWithSameId.isPresent()) {
entryDependentPlanItems.add(planItem);
}
}
public List<PlanItem> getExitDependentPlanItems() {
return exitDependentPlanItems;
}
public void setExitDependentPlanItems(List<PlanItem> exitDependentPlanItems) {
this.exitDependentPlanItems = exitDependentPlanItems;
}
public void addExitDependentPlanItem(PlanItem planItem) {
Optional<PlanItem> planItemWithSameId = exitDependentPlanItems.stream().filter(p -> p.getId().equals(planItem.getId())).findFirst();
if (!planItemWithSameId.isPresent()) {
exitDependentPlanItems.add(planItem);
}
}
public List<PlanItem> getAllDependentPlanItems() {
List<PlanItem> allDependentPlanItems = new ArrayList<>(entryDependentPlanItems.size() + exitDependentPlanItems.size());
allDependentPlanItems.addAll(entryDependentPlanItems);
allDependentPlanItems.addAll(exitDependentPlanItems);
return allDependentPlanItems;
} | @Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder("PlanItem");
if (getName() != null) {
stringBuilder.append(" '").append(getName()).append("'");
}
stringBuilder.append(" (id: ");
stringBuilder.append(getId());
if (getPlanItemDefinition() != null) {
stringBuilder.append(", definitionId: ").append(getPlanItemDefinition().getId());
}
stringBuilder.append(")");
return stringBuilder.toString();
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\PlanItem.java | 1 |
请完成以下Java代码 | protected boolean executeLogin(ServletRequest request, ServletResponse response)
throws Exception {
CaptchaUsernamePasswordToken token = createToken(request, response);
try {
_logger.info("KaptchaFilter.executeLogin");
/*图形验证码验证*/
doCaptchaValidate((HttpServletRequest) request, token);
Subject subject = getSubject(request, response);
subject.login(token);//正常验证
//到这里就算验证成功了,把用户信息放到session中
ManagerInfo user = ShiroKit.getUser();
((HttpServletRequest) request).getSession().setAttribute("user", user);
return onLoginSuccess(token, subject, request, response);
} catch (AuthenticationException e) {
return onLoginFailure(token, e, request, response);
}
}
@Override
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
ServletRequest request, ServletResponse response) throws Exception {
issueSuccessRedirect(request, response);
//we handled the success redirect directly, prevent the chain from continuing:
return false;
}
protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception {
WebUtils.issueRedirect(request, response, "/", null, true);
}
// 验证码校验
protected void doCaptchaValidate(HttpServletRequest request, CaptchaUsernamePasswordToken token) {
_logger.info("KaptchaFilter.doCaptchaValidate");
//session中的图形码字符串
String captcha = (String) request.getSession().getAttribute(
com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
_logger.info("session中的图形码字符串:" + captcha);
//比对
if (captcha == null || !captcha.equalsIgnoreCase(token.getCaptcha())) { | throw new IncorrectCaptchaException();
}
}
@Override
protected CaptchaUsernamePasswordToken createToken(ServletRequest request, ServletResponse response) {
String username = getUsername(request);
String password = getPassword(request);
String captcha = getCaptcha(request);
boolean rememberMe = isRememberMe(request);
String host = getHost(request);
return new CaptchaUsernamePasswordToken(username, password.toCharArray(), rememberMe, host, captcha);
}
public String getCaptchaParam() {
return captchaParam;
}
public void setCaptchaParam(String captchaParam) {
this.captchaParam = captchaParam;
}
protected String getCaptcha(ServletRequest request) {
return WebUtils.getCleanParam(request, getCaptchaParam());
}
//保存异常对象到request
@Override
protected void setFailureAttribute(ServletRequest request, AuthenticationException ae) {
request.setAttribute(getFailureKeyAttribute(), ae);
}
} | repos\SpringBootBucket-master\springboot-shiro\src\main\java\com\xncoding\pos\shiro\KaptchaFilter.java | 1 |
请完成以下Java代码 | protected void prepare()
{
p_IsFullUpdate = getParameterAsIParams().getParameterAsBool("IsFullUpdate");
}
@Override
@RunOutOfTrx
protected String doIt() throws Exception
{
final Properties ctx = getCtx();
Check.assume(Env.getAD_Client_ID(ctx) > 0, "No point in calling this process with AD_Client_ID=0");
//
// Create the updater
final InvoiceCandRecomputeTag recomputeTag = InvoiceCandRecomputeTag.ofPInstanceId(getPinstanceId()); | final IInvoiceCandInvalidUpdater updater = invoiceCandBL.updateInvalid()
.setContext(ctx, getTrxName())
.setTaggedWithNoTag()
.setRecomputeTagToUse(recomputeTag);
if (p_IsFullUpdate)
{
updater.setTaggedWithAnyTag();
}
//
// Execute the updater
updater.update();
return "@Success@";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\process\C_Invoice_Candidate_Update.java | 1 |
请完成以下Java代码 | public class WorkpackageProcessorContextFactory implements IWorkpackageProcessorContextFactory
{
private final InheritableThreadLocal<AsyncBatchId> threadLocalWorkpackageAsyncBatch = new InheritableThreadLocal<>();
private final InheritableThreadLocal<String> threadLocalPriority = new InheritableThreadLocal<>();
@Override
public String getThreadInheritedPriority()
{
return threadLocalPriority.get();
}
@Override
public void setThreadInheritedPriority(final String priority)
{
threadLocalPriority.set(priority);
} | @Override
public AsyncBatchId setThreadInheritedWorkpackageAsyncBatch(final AsyncBatchId asyncBatchId)
{
final AsyncBatchId asyncBatchIdOld = threadLocalWorkpackageAsyncBatch.get();
threadLocalWorkpackageAsyncBatch.set(asyncBatchId);
return asyncBatchIdOld;
}
@Override
public AsyncBatchId getThreadInheritedWorkpackageAsyncBatch()
{
return threadLocalWorkpackageAsyncBatch.get();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\WorkpackageProcessorContextFactory.java | 1 |
请完成以下Java代码 | public String getDescription() {
return activiti5Attachment.getDescription();
}
@Override
public void setDescription(String description) {
activiti5Attachment.setDescription(description);
}
@Override
public String getType() {
return activiti5Attachment.getType();
}
@Override
public String getTaskId() {
return activiti5Attachment.getTaskId();
}
@Override
public String getProcessInstanceId() {
return activiti5Attachment.getProcessInstanceId();
}
@Override
public String getUrl() {
return activiti5Attachment.getUrl();
}
@Override
public String getUserId() {
return activiti5Attachment.getUserId();
}
@Override
public Date getTime() { | return activiti5Attachment.getTime();
}
@Override
public void setTime(Date time) {
activiti5Attachment.setTime(time);
}
@Override
public String getContentId() {
return ((AttachmentEntity) activiti5Attachment).getContentId();
}
public org.activiti.engine.task.Attachment getRawObject() {
return activiti5Attachment;
}
} | repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5AttachmentWrapper.java | 1 |
请完成以下Java代码 | /* package */class ProductionMaterialQuery implements IProductionMaterialQuery
{
private List<ProductionMaterialType> types = null;
private I_M_Product product;
private I_PP_Order ppOrder;
@Override
public String toString()
{
return "ProductionMaterialQuery [types=" + types + ", product=" + product + ", ppOrder=" + ppOrder + "]";
}
@Override
public IProductionMaterialQuery setTypes(final ProductionMaterialType... types)
{
if (types == null || types.length == 0)
{
this.types = null;
}
else
{
this.types = Arrays.asList(types);
}
return this;
}
@Override
public List<ProductionMaterialType> getTypes()
{
if (types == null)
{
return Collections.emptyList();
} | return types;
}
@Override
public IProductionMaterialQuery setM_Product(final I_M_Product product)
{
this.product = product;
return this;
}
@Override
public I_M_Product getM_Product()
{
return product;
}
@Override
public IProductionMaterialQuery setPP_Order(final I_PP_Order ppOrder)
{
this.ppOrder = ppOrder;
return this;
}
@Override
public I_PP_Order getPP_Order()
{
return ppOrder;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\ProductionMaterialQuery.java | 1 |
请完成以下Java代码 | private IntegerLookupValue retrievePostalLookupValue(final ResultSet rs) throws SQLException
{
final int postalId = rs.getInt(I_C_Postal.COLUMNNAME_C_Postal_ID);
final String postal = rs.getString(I_C_Postal.COLUMNNAME_Postal);
final String city = rs.getString(I_C_Postal.COLUMNNAME_City);
final String township = rs.getString(I_C_Postal.COLUMNNAME_Township);
final int countryId = rs.getInt(I_C_Postal.COLUMNNAME_C_Country_ID);
final LookupValue countryLookupValue = countryLookup.getLookupValueById(countryId);
return buildPostalLookupValue(postalId, postal, city, township, countryLookupValue.getDisplayNameTrl());
}
public IntegerLookupValue getLookupValueFromLocation(final I_C_Location locationRecord)
{
final I_C_Postal postalRecord = locationRecord.getC_Postal();
if (postalRecord == null || postalRecord.getC_Postal_ID() <= 0)
{
return null;
}
final LookupValue countryLookupValue = countryLookup.getLookupValueById(postalRecord.getC_Country_ID()); | return buildPostalLookupValue(
postalRecord.getC_Postal_ID(),
postalRecord.getPostal(),
postalRecord.getCity(),
postalRecord.getTownship(),
countryLookupValue.getDisplayNameTrl());
}
private static IntegerLookupValue buildPostalLookupValue(
final int postalId,
final String postal,
final String city,
final String township,
final ITranslatableString countryName)
{
final ITranslatableString displayName = TranslatableStrings.join("", postal, " ", city, " ", township, " (", countryName, ")");
return IntegerLookupValue.of(postalId, displayName, null/* description */);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\address\AddressPostalLookupDescriptor.java | 1 |
请完成以下Java代码 | public void process()
{
saveEx();
if (getM_Product_ID() <= 0)
{
throw new FillMandatoryException(COLUMNNAME_M_Product_ID);
}
final IProductBL productBL = Services.get(IProductBL.class);
if (productBL.isStocked(ProductId.ofRepoIdOrNull(getM_Product_ID())))
{
// ** Create Material Transactions **
final MTransaction mTrx = new MTransaction(getCtx(),
getAD_Org_ID(),
MTransaction.MOVEMENTTYPE_WorkOrderPlus,
getM_Locator_ID(),
getM_Product_ID(),
getM_AttributeSetInstance_ID(),
getMovementQty().negate(),
getMovementDate(),
get_TrxName());
mTrx.setC_ProjectIssue_ID(getC_ProjectIssue_ID());
InterfaceWrapperHelper.save(mTrx); | final IWarehouseDAO warehouseDAO = Services.get(IWarehouseDAO.class);
final IStorageBL storageBL = Services.get(IStorageBL.class);
final I_M_Locator loc = warehouseDAO.getLocatorByRepoId(getM_Locator_ID());
storageBL.add(getCtx(), loc.getM_Warehouse_ID(), getM_Locator_ID(),
getM_Product_ID(), getM_AttributeSetInstance_ID(), getM_AttributeSetInstance_ID(),
getMovementQty().negate(), null, null, get_TrxName());
}
setProcessed(true);
saveEx();
}
} // MProjectIssue | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MProjectIssue.java | 1 |
请完成以下Java代码 | public class DefaultTaskAssignmentManager implements InternalTaskAssignmentManager {
@Override
public void changeAssignee(Task task, String assignee) {
TaskHelper.changeTaskAssignee((TaskEntity) task, assignee);
}
@Override
public void changeOwner(Task task, String owner) {
TaskHelper.changeTaskOwner((TaskEntity) task, owner);
}
@Override
public void addCandidateUser(Task task, IdentityLink identityLink) {
IdentityLinkUtil.handleTaskIdentityLinkAddition((TaskEntity) task, (IdentityLinkEntity) identityLink);
}
@Override
public void addCandidateUsers(Task task, List<IdentityLink> candidateUsers) {
List<IdentityLinkEntity> identityLinks = new ArrayList<>();
for (IdentityLink identityLink : candidateUsers) {
identityLinks.add((IdentityLinkEntity) identityLink);
}
IdentityLinkUtil.handleTaskIdentityLinkAdditions((TaskEntity) task, identityLinks);
}
@Override
public void addCandidateGroup(Task task, IdentityLink identityLink) {
IdentityLinkUtil.handleTaskIdentityLinkAddition((TaskEntity) task, (IdentityLinkEntity) identityLink);
}
@Override
public void addCandidateGroups(Task task, List<IdentityLink> candidateGroups) {
List<IdentityLinkEntity> identityLinks = new ArrayList<>();
for (IdentityLink identityLink : candidateGroups) { | identityLinks.add((IdentityLinkEntity) identityLink);
}
IdentityLinkUtil.handleTaskIdentityLinkAdditions((TaskEntity) task, identityLinks);
}
@Override
public void addUserIdentityLink(Task task, IdentityLink identityLink) {
IdentityLinkUtil.handleTaskIdentityLinkAddition((TaskEntity) task, (IdentityLinkEntity) identityLink);
}
@Override
public void addGroupIdentityLink(Task task, IdentityLink identityLink) {
IdentityLinkUtil.handleTaskIdentityLinkAddition((TaskEntity) task, (IdentityLinkEntity) identityLink);
}
@Override
public void deleteUserIdentityLink(Task task, IdentityLink identityLink) {
List<IdentityLinkEntity> identityLinks = new ArrayList<>();
identityLinks.add((IdentityLinkEntity) identityLink);
IdentityLinkUtil.handleTaskIdentityLinkDeletions((TaskEntity) task, identityLinks, true, true);
}
@Override
public void deleteGroupIdentityLink(Task task, IdentityLink identityLink) {
List<IdentityLinkEntity> identityLinks = new ArrayList<>();
identityLinks.add((IdentityLinkEntity) identityLink);
IdentityLinkUtil.handleTaskIdentityLinkDeletions((TaskEntity) task, identityLinks, true, true);
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cfg\DefaultTaskAssignmentManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static class ComputedWorkflowLaunchers
{
@NonNull WorkflowLaunchersList list;
@NonNull WorkflowLaunchersQuery validationKey;
private ComputedWorkflowLaunchers(@NonNull final WorkflowLaunchersList list, @NonNull final WorkflowLaunchersQuery validationKey)
{
this.list = list;
this.validationKey = validationKey;
}
public static ComputedWorkflowLaunchers ofListAndQuery(@NonNull final WorkflowLaunchersList list, @NonNull final WorkflowLaunchersQuery query)
{
return new ComputedWorkflowLaunchers(list, toValidationKey(query));
}
private static WorkflowLaunchersQuery toValidationKey(@NonNull final WorkflowLaunchersQuery query)
{ | return query.toBuilder()
.maxStaleAccepted(Duration.ZERO)
.build();
}
public boolean matches(@NonNull final WorkflowLaunchersQuery query)
{
if (list.isStaled(query.getMaxStaleAccepted()))
{
return false;
}
final WorkflowLaunchersQuery validationKeyExpected = toValidationKey(query);
return validationKey.equals(validationKeyExpected);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\lauchers\PickingWorkflowLaunchersProvider.java | 2 |
请完成以下Java代码 | public void setM_Product_Category_Matching_ID (final int M_Product_Category_Matching_ID)
{
if (M_Product_Category_Matching_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_Matching_ID, null);
else
set_Value (COLUMNNAME_M_Product_Category_Matching_ID, M_Product_Category_Matching_ID);
}
@Override
public int getM_Product_Category_Matching_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Category_Matching_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
} | @Override
public void setQtyPerDelivery (final BigDecimal QtyPerDelivery)
{
set_Value (COLUMNNAME_QtyPerDelivery, QtyPerDelivery);
}
@Override
public BigDecimal getQtyPerDelivery()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPerDelivery);
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);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_Matching.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
StringRedisSerializer stringSerializer = new StringRedisSerializer();
RedisSerializer jacksonSerializer = getJacksonSerializer();
template.setKeySerializer(stringSerializer);
template.setValueSerializer(jacksonSerializer);
template.setHashKeySerializer(stringSerializer);
template.setHashValueSerializer(jacksonSerializer);
template.setEnableTransactionSupport(true);
template.afterPropertiesSet();
return template;
}
private RedisSerializer getJacksonSerializer() {
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
ObjectMapper.DefaultTyping.NON_FINAL);
return new GenericJackson2JsonRedisSerializer(om);
}
@Bean
public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForHash();
}
@Bean
public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForValue(); | }
@Bean
public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}
@Bean
public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}
@Bean
public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}
@Bean(destroyMethod = "destroy")
public RedisLockRegistry redisLockRegistry(RedisConnectionFactory redisConnectionFactory) {
return new RedisLockRegistry(redisConnectionFactory, "lock");
}
} | repos\spring-boot-best-practice-master\spring-boot-redis\src\main\java\cn\javastack\springboot\redis\config\RedisConfig.java | 2 |
请完成以下Java代码 | public class CmmnAggregatedVariableType implements VariableType {
public static final String TYPE_NAME = "cmmnAggregation";
protected final CmmnEngineConfiguration cmmnEngineConfiguration;
public CmmnAggregatedVariableType(CmmnEngineConfiguration cmmnEngineConfiguration) {
this.cmmnEngineConfiguration = cmmnEngineConfiguration;
}
@Override
public String getTypeName() {
return TYPE_NAME;
}
@Override
public boolean isCachable() {
return true;
}
@Override
public boolean isAbleToStore(Object value) {
return value instanceof CmmnAggregation;
}
@Override
public boolean isReadOnly() {
return true;
} | @Override
public void setValue(Object value, ValueFields valueFields) {
if (value instanceof CmmnAggregation) {
valueFields.setTextValue(((CmmnAggregation) value).getPlanItemInstanceId());
} else {
valueFields.setTextValue(null);
}
}
@Override
public Object getValue(ValueFields valueFields) {
CommandContext commandContext = Context.getCommandContext();
if (commandContext != null) {
return CmmnAggregation.aggregateOverview(valueFields.getTextValue(), valueFields.getName(), commandContext);
} else {
return cmmnEngineConfiguration.getCommandExecutor()
.execute(context -> CmmnAggregation.aggregateOverview(valueFields.getTextValue(), valueFields.getName(), context));
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\variable\CmmnAggregatedVariableType.java | 1 |
请完成以下Java代码 | public void setTaskId(String taskId) {
this.taskId = taskId;
}
@Override
public Date getTimeStamp() {
return timeStamp;
}
@Override
public void setTimeStamp(Date timeStamp) {
this.timeStamp = timeStamp;
}
@Override
public String getUserId() {
return userId;
}
@Override
public void setUserId(String userId) {
this.userId = userId;
}
@Override
public byte[] getData() {
return data;
}
@Override
public void setData(byte[] data) {
this.data = data;
}
@Override
public String getLockOwner() {
return lockOwner;
}
@Override
public void setLockOwner(String lockOwner) {
this.lockOwner = lockOwner;
} | @Override
public String getLockTime() {
return lockTime;
}
@Override
public void setLockTime(String lockTime) {
this.lockTime = lockTime;
}
@Override
public int getProcessed() {
return isProcessed;
}
@Override
public void setProcessed(int isProcessed) {
this.isProcessed = isProcessed;
}
@Override
public String toString() {
return timeStamp.toString() + " : " + type;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\EventLogEntryEntityImpl.java | 1 |
请完成以下Java代码 | public List<User> executeInContext(InitialDirContext initialDirContext) {
List<User> result = new ArrayList<>();
try {
String baseDn = ldapConfigurator.getUserBaseDn() != null ? ldapConfigurator.getUserBaseDn() : ldapConfigurator.getBaseDn();
NamingEnumeration<?> namingEnum = initialDirContext.search(baseDn, searchExpression, createSearchControls());
while (namingEnum.hasMore()) {
SearchResult searchResult = (SearchResult) namingEnum.next();
UserEntity user = new UserEntityImpl();
mapSearchResultToUser(searchResult, user);
result.add(user);
}
namingEnum.close();
} catch (NamingException ne) {
LOGGER.debug("Could not execute LDAP query: {}", ne.getMessage(), ne);
return null;
}
return result;
}
});
}
protected void mapSearchResultToUser(SearchResult result, UserEntity user) throws NamingException {
if (ldapConfigurator.getUserIdAttribute() != null) {
user.setId(result.getAttributes().get(ldapConfigurator.getUserIdAttribute()).get().toString());
}
if (ldapConfigurator.getUserFirstNameAttribute() != null) {
try {
user.setFirstName(result.getAttributes().get(ldapConfigurator.getUserFirstNameAttribute()).get().toString());
} catch (NullPointerException e) {
user.setFirstName("");
}
}
if (ldapConfigurator.getUserLastNameAttribute() != null) { | try {
user.setLastName(result.getAttributes().get(ldapConfigurator.getUserLastNameAttribute()).get().toString());
} catch (NullPointerException e) {
user.setLastName("");
}
}
if (ldapConfigurator.getUserEmailAttribute() != null) {
try {
user.setEmail(result.getAttributes().get(ldapConfigurator.getUserEmailAttribute()).get().toString());
} catch (NullPointerException e) {
user.setEmail("");
}
}
}
protected SearchControls createSearchControls() {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchControls.setTimeLimit(ldapConfigurator.getSearchTimeLimit());
return searchControls;
}
} | repos\flowable-engine-main\modules\flowable-ldap\src\main\java\org\flowable\ldap\impl\LDAPUserQueryImpl.java | 1 |
请完成以下Java代码 | public String getParamValueAsString(final String filterId, final String parameterName)
{
final DocumentFilter filter = getFilterByIdOrNull(filterId);
if (filter == null)
{
return null;
}
return filter.getParameterValueAsString(parameterName);
}
public int getParamValueAsInt(final String filterId, final String parameterName, final int defaultValue)
{
final DocumentFilter filter = getFilterByIdOrNull(filterId);
if (filter == null)
{
return defaultValue; | }
return filter.getParameterValueAsInt(parameterName, defaultValue);
}
public boolean getParamValueAsBoolean(final String filterId, final String parameterName, final boolean defaultValue)
{
final DocumentFilter filter = getFilterByIdOrNull(filterId);
if (filter == null)
{
return defaultValue;
}
return filter.getParameterValueAsBoolean(parameterName, defaultValue);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\DocumentFilterList.java | 1 |
请完成以下Java代码 | public String getStrValue() {
return dataType == DataType.STRING ? strValue : null;
}
public void setStrValue(String strValue) {
this.dataType = DataType.STRING;
this.strValue = strValue;
}
public void setJsonValue(String jsonValue) {
this.dataType = DataType.JSON;
this.strValue = jsonValue;
}
public String getJsonValue() {
return dataType == DataType.JSON ? strValue : null;
}
boolean isSet() {
return dataType != null;
}
static EntityKeyValue fromString(String s) {
EntityKeyValue result = new EntityKeyValue();
result.setStrValue(s);
return result;
}
static EntityKeyValue fromBool(boolean b) {
EntityKeyValue result = new EntityKeyValue();
result.setBoolValue(b);
return result;
}
static EntityKeyValue fromLong(long l) {
EntityKeyValue result = new EntityKeyValue();
result.setLngValue(l); | return result;
}
static EntityKeyValue fromDouble(double d) {
EntityKeyValue result = new EntityKeyValue();
result.setDblValue(d);
return result;
}
static EntityKeyValue fromJson(String s) {
EntityKeyValue result = new EntityKeyValue();
result.setJsonValue(s);
return result;
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\profile\EntityKeyValue.java | 1 |
请完成以下Java代码 | public void removeDeployment(String deploymentId) {
DmnDeploymentEntity deployment = deploymentEntityManager.findById(deploymentId);
if (deployment == null) {
throw new FlowableObjectNotFoundException("Could not find a deployment with id '" + deploymentId + "'.");
}
// Remove any dmn definition from the cache
List<DmnDecision> definitions = new DecisionQueryImpl().deploymentId(deploymentId).list();
// Delete data
deploymentEntityManager.deleteDeployment(deploymentId);
for (DmnDecision definition : definitions) {
decisionCache.remove(definition.getId());
}
}
public List<Deployer> getDeployers() {
return deployers;
}
public void setDeployers(List<Deployer> deployers) {
this.deployers = deployers;
}
public DeploymentCache<DecisionCacheEntry> getDecisionCache() {
return decisionCache;
} | public void setDecisionCache(DeploymentCache<DecisionCacheEntry> decisionCache) {
this.decisionCache = decisionCache;
}
public DecisionEntityManager getDecisionEntityManager() {
return decisionEntityManager;
}
public void setDecisionEntityManager(DecisionEntityManager decisionEntityManager) {
this.decisionEntityManager = decisionEntityManager;
}
public DmnDeploymentEntityManager getDeploymentEntityManager() {
return deploymentEntityManager;
}
public void setDeploymentEntityManager(DmnDeploymentEntityManager deploymentEntityManager) {
this.deploymentEntityManager = deploymentEntityManager;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\deploy\DeploymentManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class C_InvoiceSchedule
{
@ModelChange(
timings = { ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_AFTER_DELETE },
ifColumnsChanged = {
I_C_InvoiceSchedule.COLUMNNAME_InvoiceDistance,
I_C_InvoiceSchedule.COLUMNNAME_InvoiceFrequency,
I_C_InvoiceSchedule.COLUMNNAME_InvoiceDay,
I_C_InvoiceSchedule.COLUMNNAME_InvoiceWeekDay,
I_C_InvoiceSchedule.COLUMNNAME_IsAmount,
I_C_InvoiceSchedule.COLUMNNAME_Amt
})
public void invalidateICs(@NonNull final I_C_InvoiceSchedule invoiceSchedule)
{
invoiceCandBL.invalidateForInvoiceSchedule(invoiceSchedule);
} | private final IInvoiceCandBL invoiceCandBL = Services.get(IInvoiceCandBL.class);
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_BEFORE_NEW },
ifColumnsChanged = I_C_InvoiceSchedule.COLUMNNAME_InvoiceFrequency)
@CalloutMethod(columnNames = I_C_InvoiceSchedule.COLUMNNAME_InvoiceFrequency)
public void setInvoiceDistance(@NonNull final I_C_InvoiceSchedule invoiceSchedule)
{
if (X_C_InvoiceSchedule.INVOICEFREQUENCY_TwiceMonthly.equals(invoiceSchedule.getInvoiceFrequency()))
{
// actually, invoiceDistance is not validated in this case, but for the UI's sake, we set it to one
invoiceSchedule.setInvoiceDistance(1);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\modelvalidator\C_InvoiceSchedule.java | 2 |
请完成以下Java代码 | class CTableViewRowSorter extends TableRowSorter<TableModel>
{
private CTableModelRowSorter modelRowSorter = null;
public CTableViewRowSorter()
{
super();
setMaxSortKeys(1);
}
public CTableViewRowSorter setModelRowSorter(final CTableModelRowSorter modelRowSorter)
{
this.modelRowSorter = modelRowSorter;
return this;
}
@Override
public void toggleSortOrder(final int modelColumnIndex)
{
super.toggleSortOrder(modelColumnIndex);
// Update our internal map, because that's the place where renderer is checking | if (modelRowSorter != null)
{
modelRowSorter.setSortKeys(getSortKeys());
}
}
public final SortOrder getSortOrder(final int modelColumnIndex)
{
final List<? extends SortKey> sortKeys = getSortKeys();
for (final SortKey sortKey : sortKeys)
{
if (sortKey.getColumn() == modelColumnIndex)
{
return sortKey.getSortOrder();
}
}
return SortOrder.UNSORTED;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\swing\CTableViewRowSorter.java | 1 |
请完成以下Java代码 | public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DataAssociation.class, BPMN_ELEMENT_DATA_ASSOCIATION)
.namespaceUri(BPMN20_NS)
.extendsType(BaseElement.class)
.instanceProvider(new ModelTypeInstanceProvider<DataAssociation>() {
public DataAssociation newInstance(ModelTypeInstanceContext instanceContext) {
return new DataAssociationImpl(instanceContext);
}
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
sourceRefCollection = sequenceBuilder.elementCollection(SourceRef.class)
.idElementReferenceCollection(ItemAwareElement.class)
.build();
targetRefChild = sequenceBuilder.element(TargetRef.class)
.required()
.idElementReference(ItemAwareElement.class)
.build();
transformationChild = sequenceBuilder.element(Transformation.class)
.build();
assignmentCollection = sequenceBuilder.elementCollection(Assignment.class)
.build();
typeBuilder.build();
}
public DataAssociationImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public Collection<ItemAwareElement> getSources() {
return sourceRefCollection.getReferenceTargetElements(this);
}
public ItemAwareElement getTarget() {
return targetRefChild.getReferenceTargetElement(this); | }
public void setTarget(ItemAwareElement target) {
targetRefChild.setReferenceTargetElement(this, target);
}
public FormalExpression getTransformation() {
return transformationChild.getChild(this);
}
public void setTransformation(Transformation transformation) {
transformationChild.setChild(this, transformation);
}
public Collection<Assignment> getAssignments() {
return assignmentCollection.get(this);
}
public BpmnEdge getDiagramElement() {
return (BpmnEdge) super.getDiagramElement();
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\DataAssociationImpl.java | 1 |
请完成以下Spring Boot application配置 | spring:
application:
name: demo-admin-server # Spring 应用名
cloud:
nacos:
# Nacos 作为注册中心的配置项,对应 NacosDiscoveryProperties 配置类
discovery:
server-addr: 127.0.0.1:8848 # Nacos 服务器地址
| service: ${spring.application.name} # 注册到 Nacos 的服务名。默认值为 ${spring.application.name}。 | repos\SpringBoot-Labs-master\labx-15\labx-15-admin-02-adminserver\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | 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 |
请在Spring Boot框架中完成以下Java代码 | private Throwable getRootError(final WebRequest webRequest)
{
final Throwable error = getError(webRequest);
return error != null ? unboxRootError(error) : null;
}
public Throwable unboxRootError(@NonNull final java.lang.Throwable error)
{
Throwable rootError = error;
while (rootError instanceof ServletException)
{
final Throwable cause = AdempiereException.extractCause(rootError);
if (cause == rootError)
{
return rootError;
} | else
{
rootError = cause;
}
}
return rootError;
}
@SuppressWarnings("unchecked")
private static <T> T getAttribute(final RequestAttributes requestAttributes, final String name)
{
return (T)requestAttributes.getAttribute(name, RequestAttributes.SCOPE_REQUEST);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\config\WebuiExceptionHandler.java | 2 |
请完成以下Java代码 | public final class ContentSecurityPolicyHeaderWriter implements HeaderWriter {
private static final String CONTENT_SECURITY_POLICY_HEADER = "Content-Security-Policy";
private static final String CONTENT_SECURITY_POLICY_REPORT_ONLY_HEADER = "Content-Security-Policy-Report-Only";
private static final String DEFAULT_SRC_SELF_POLICY = "default-src 'self'";
private String policyDirectives;
private boolean reportOnly;
/**
* Creates a new instance. Default value: default-src 'self'
*/
public ContentSecurityPolicyHeaderWriter() {
setPolicyDirectives(DEFAULT_SRC_SELF_POLICY);
this.reportOnly = false;
}
/**
* Creates a new instance
* @param policyDirectives maps to {@link #setPolicyDirectives(String)}
* @throws IllegalArgumentException if policyDirectives is null or empty
*/
public ContentSecurityPolicyHeaderWriter(String policyDirectives) {
setPolicyDirectives(policyDirectives);
this.reportOnly = false;
}
/**
* @see org.springframework.security.web.header.HeaderWriter#writeHeaders(jakarta.servlet.http.HttpServletRequest,
* jakarta.servlet.http.HttpServletResponse)
*/
@Override
public void writeHeaders(HttpServletRequest request, HttpServletResponse response) {
String headerName = (!this.reportOnly) ? CONTENT_SECURITY_POLICY_HEADER
: CONTENT_SECURITY_POLICY_REPORT_ONLY_HEADER;
if (!response.containsHeader(headerName)) {
response.setHeader(headerName, this.policyDirectives);
}
} | /**
* Sets the security policy directive(s) to be used in the response header.
* @param policyDirectives the security policy directive(s)
* @throws IllegalArgumentException if policyDirectives is null or empty
*/
public void setPolicyDirectives(String policyDirectives) {
Assert.hasLength(policyDirectives, "policyDirectives cannot be null or empty");
this.policyDirectives = policyDirectives;
}
/**
* If true, includes the Content-Security-Policy-Report-Only header in the response,
* otherwise, defaults to the Content-Security-Policy header.
* @param reportOnly set to true for reporting policy violations only
*/
public void setReportOnly(boolean reportOnly) {
this.reportOnly = reportOnly;
}
@Override
public String toString() {
return getClass().getName() + " [policyDirectives=" + this.policyDirectives + "; reportOnly=" + this.reportOnly
+ "]";
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\writers\ContentSecurityPolicyHeaderWriter.java | 1 |
请完成以下Java代码 | void get_oracle_actions_onestep(List<Integer> heads,
List<Integer> deprels,
List<Integer> sigma,
int[] beta,
List<Integer> output,
List<Action> actions)
{
int top0 = (sigma.size() > 0 ? sigma.get(sigma.size() - 1) : -1);
int top1 = (sigma.size() > 1 ? sigma.get(sigma.size() - 2) : -1);
boolean all_descendents_reduced = true;
if (top0 >= 0)
{
for (int i = 0; i < heads.size(); ++i)
{
if (heads.get(i) == top0 && output.get(i) != top0)
{
// _INFO << i << " " << output[i];
all_descendents_reduced = false;
break;
}
}
}
if (top1 >= 0 && heads.get(top1) == top0)
{
actions.add(ActionFactory.make_left_arc(deprels.get(top1))); | output.set(top1, top0);
sigma.remove(sigma.size() - 1);
sigma.set(sigma.size() - 1, top0);
}
else if (top1 >= 0 && heads.get(top0) == top1 && all_descendents_reduced)
{
actions.add(ActionFactory.make_right_arc(deprels.get(top0)));
output.set(top0, top1);
sigma.remove(sigma.size() - 1);
}
else if (beta[0] < heads.size())
{
actions.add(ActionFactory.make_shift ());
sigma.add(beta[0]);
++beta[0];
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\nnparser\action\ActionUtils.java | 1 |
请完成以下Java代码 | public class CompositeFacetCollector<ModelType> extends AbstractFacetCollector<ModelType>
{
private static final transient Logger logger = LogManager.getLogger(CompositeFacetCollector.class);
private final Set<IFacetCollector<ModelType>> facetCollectors = new LinkedHashSet<>();
public void addFacetCollector(final IFacetCollector<ModelType> facetCollector)
{
Check.assumeNotNull(facetCollector, "facetCollector not null");
facetCollectors.add(facetCollector);
}
/** @return true if this composite has at least one collector */
public boolean hasCollectors()
{
return !facetCollectors.isEmpty();
}
@Override
public IFacetCollectorResult<ModelType> collect(final FacetCollectorRequestBuilder<ModelType> request)
{
final FacetCollectorResult.Builder<ModelType> aggregatedResult = FacetCollectorResult.builder();
for (final IFacetCollector<ModelType> facetCollector : facetCollectors)
{
try
{
final IFacetCollectorResult<ModelType> result = facetCollector.collect(request);
aggregatedResult.addFacetCollectorResult(result);
}
catch (Exception e)
{ | final AdempiereException ex = new AdempiereException("Failed to collect facets from collector"
+ "\n Collector: " + facetCollector
+ "\n Request: " + request
, e);
logger.warn("Skip collector because it failed", ex);
}
}
return aggregatedResult.build();
}
@Override
public List<IFacetCategory> getAllFacetCategories()
{
// NOTE: teoretically we could cache this list, but i am thinking to Composite in Composite case, on which, caching approach will fail.
final ImmutableList.Builder<IFacetCategory> aggregatedFacetCategories = ImmutableList.builder();
for (final IFacetCollector<ModelType> facetCollector : facetCollectors)
{
final List<IFacetCategory> facetCategories = facetCollector.getAllFacetCategories();
facetCategories.addAll(facetCategories);
}
return aggregatedFacetCategories.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\impl\CompositeFacetCollector.java | 1 |
请完成以下Java代码 | public int hashCode()
{
if (_hashCode == null)
{
_hashCode = Objects.hash(rootDocumentPath, detailId, quickInputId);
}
return _hashCode;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
else if (obj instanceof QuickInputPath)
{
final QuickInputPath other = (QuickInputPath)obj;
return Objects.equals(rootDocumentPath, other.rootDocumentPath)
&& Objects.equals(detailId, other.detailId)
&& Objects.equals(quickInputId, other.quickInputId);
}
else | {
return false;
}
}
public DocumentPath getRootDocumentPath()
{
return rootDocumentPath;
}
public DetailId getDetailId()
{
return detailId;
}
public DocumentId getQuickInputId()
{
return quickInputId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\QuickInputPath.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setIDENTIFICATIONDATE4(String value) {
this.identificationdate4 = value;
}
/**
* Gets the value of the quantity property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getQUANTITY() {
return quantity;
}
/**
* Sets the value of the quantity property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setQUANTITY(String value) {
this.quantity = value;
}
/**
* Gets the value of the quantitymeasureunit property.
*
* @return
* possible object is
* {@link String } | *
*/
public String getQUANTITYMEASUREUNIT() {
return quantitymeasureunit;
}
/**
* Sets the value of the quantitymeasureunit property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setQUANTITYMEASUREUNIT(String value) {
this.quantitymeasureunit = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DMARK1.java | 2 |
请完成以下Java代码 | public class SslContextBuilder {
public static SSLContext buildSslContext()
throws IOException, CertificateException, InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException,
KeyManagementException {
final Properties props = System.getProperties();
props.setProperty("jdk.internal.httpclient.disableHostnameVerification", Boolean.TRUE.toString());
String privateKeyPath = "src/main/resources/keys/client.key.pkcs8";
String publicKeyPath = "src/main/resources/keys/client.crt";
final byte[] publicData = Files.readAllBytes(Path.of(publicKeyPath));
final byte[] privateData = Files.readAllBytes(Path.of(privateKeyPath));
String privateString = new String(privateData, Charset.defaultCharset()).replace("-----BEGIN PRIVATE KEY-----", "")
.replaceAll(System.lineSeparator(), "")
.replace("-----END PRIVATE KEY-----", "");
byte[] encoded = Base64.getDecoder()
.decode(privateString);
final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
final Collection<? extends Certificate> chain = certificateFactory.generateCertificates(new ByteArrayInputStream(publicData));
Key key = KeyFactory.getInstance("RSA")
.generatePrivate(new PKCS8EncodedKeySpec(encoded));
KeyStore clientKeyStore = KeyStore.getInstance("jks");
final char[] pwdChars = "test".toCharArray();
clientKeyStore.load(null, null);
clientKeyStore.setKeyEntry("test", key, pwdChars, chain.toArray(new Certificate[0]));
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); | keyManagerFactory.init(clientKeyStore, pwdChars);
TrustManager[] acceptAllTrustManager = { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), acceptAllTrustManager, new java.security.SecureRandom());
return sslContext;
}
} | repos\tutorials-master\core-java-modules\core-java-httpclient\src\main\java\com\baeldung\mtls\calls\SslContextBuilder.java | 1 |
请完成以下Java代码 | public void addLookupDataSource(@NonNull final LookupDataSource lookupDataSource)
{
synchronized (lookupDataSources)
{
lookupDataSources.add(new WeakReference<>(lookupDataSource));
}
}
private List<LookupDataSource> purgeAndGet()
{
synchronized (lookupDataSources)
{
final List<LookupDataSource> result = new ArrayList<>(lookupDataSources.size());
for (final Iterator<WeakReference<LookupDataSource>> it = lookupDataSources.iterator(); it.hasNext(); )
{
final LookupDataSource lookupDataSource = it.next().get();
if (lookupDataSource == null)
{
it.remove();
continue;
}
result.add(lookupDataSource); | }
return result;
}
}
public void cacheInvalidate()
{
for (final LookupDataSource lookupDataSource : purgeAndGet())
{
try
{
lookupDataSource.cacheInvalidate();
logger.debug("Cache invalidated {} on {} record changed", lookupDataSource, tableName);
}
catch (final Exception ex)
{
logger.warn("Failed invalidating {}. Skipped", lookupDataSource, ex);
}
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\LookupDataSourceFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void delete(String id) {
bucket.remove(id);
}
@Override
public List<T> readBulk(Iterable<String> ids) {
final AsyncBucket asyncBucket = bucket.async();
Observable<JsonDocument> asyncOperation = Observable.from(ids).flatMap(new Func1<String, Observable<JsonDocument>>() {
public Observable<JsonDocument> call(String key) {
return asyncBucket.get(key);
}
});
final List<T> items = new ArrayList<T>();
try {
asyncOperation.toBlocking().forEach(new Action1<JsonDocument>() {
public void call(JsonDocument doc) {
T item = converter.fromDocument(doc);
items.add(item);
}
});
} catch (Exception e) {
logger.error("Error during bulk get", e);
}
return items;
}
@Override
public void createBulk(Iterable<T> items) {
final AsyncBucket asyncBucket = bucket.async();
Observable.from(items).flatMap(new Func1<T, Observable<JsonDocument>>() {
@SuppressWarnings("unchecked")
@Override
public Observable<JsonDocument> call(final T t) {
if (t.getId() == null) {
t.setId(UUID.randomUUID().toString());
}
JsonDocument doc = converter.toDocument(t);
return asyncBucket.insert(doc).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build());
}
}).last().toBlocking().single();
}
@Override
public void updateBulk(Iterable<T> items) { | final AsyncBucket asyncBucket = bucket.async();
Observable.from(items).flatMap(new Func1<T, Observable<JsonDocument>>() {
@SuppressWarnings("unchecked")
@Override
public Observable<JsonDocument> call(final T t) {
JsonDocument doc = converter.toDocument(t);
return asyncBucket.upsert(doc).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build());
}
}).last().toBlocking().single();
}
@Override
public void deleteBulk(Iterable<String> ids) {
final AsyncBucket asyncBucket = bucket.async();
Observable.from(ids).flatMap(new Func1<String, Observable<JsonDocument>>() {
@SuppressWarnings("unchecked")
@Override
public Observable<JsonDocument> call(String key) {
return asyncBucket.remove(key).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build());
}
}).last().toBlocking().single();
}
@Override
public boolean exists(String id) {
return bucket.exists(id);
}
} | repos\tutorials-master\persistence-modules\couchbase\src\main\java\com\baeldung\couchbase\async\service\AbstractCrudService.java | 2 |
请完成以下Java代码 | private static CalculatePricingConditionsRequest createCalculateDiscountRequest(@NonNull final PriceLimitEnforceContext context)
{
final IPricingBL pricingBL = Services.get(IPricingBL.class);
final IProductBL productBL = Services.get(IProductBL.class);
final PricingConditionsBreak pricingConditionsBreak = context.getPricingConditionsBreak();
final PricingConditionsBreakMatchCriteria matchCriteria = pricingConditionsBreak.getMatchCriteria();
final ProductId productId = matchCriteria.getProductId();
final BigDecimal qty = matchCriteria.getBreakValue();
final IEditablePricingContext pricingCtx = pricingBL.createPricingContext();
pricingCtx.setConvertPriceToContextUOM(true);
pricingCtx.setProductId(productId);
pricingCtx.setUomId(productBL.getStockUOMId(productId));
pricingCtx.setSOTrx(context.getSoTrx());
pricingCtx.setQty(qty);
pricingCtx.setProperty(IPriceLimitRule.OPTION_SkipCheckingBPartnerEligible);
pricingCtx.setCountryId(context.getCountryId());
final CalculatePricingConditionsRequest request = CalculatePricingConditionsRequest.builder()
.pricingConditionsId(pricingConditionsBreak.getPricingConditionsIdOrNull()) | .forcePricingConditionsBreak(pricingConditionsBreak)
// .qty(pricingCtx.getQty())
// .price(BigDecimal.ZERO) // N/A
// .productId(pricingCtx.getM_Product_ID())
.pricingCtx(pricingCtx)
.build();
return request;
}
@lombok.Value
@lombok.Builder
private static class PriceLimitEnforceContext
{
@NonNull
final PricingConditionsBreak pricingConditionsBreak;
@NonNull
final SOTrx soTrx;
@NonNull
private CountryId countryId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\interceptor\M_DiscountSchemaBreak.java | 1 |
请完成以下Java代码 | public class Customer {
private CustomerType type;
private int years;
private int discount;
public Customer(CustomerType type, int numOfYears) {
super();
this.type = type;
this.years = numOfYears;
}
public CustomerType getType() {
return type;
}
public void setType(CustomerType type) {
this.type = type;
} | public int getYears() {
return years;
}
public void setYears(int years) {
this.years = years;
}
public int getDiscount() {
return discount;
}
public void setDiscount(int discount) {
this.discount = discount;
}
public enum CustomerType {
INDIVIDUAL, BUSINESS;
}
} | repos\tutorials-master\drools\src\main\java\com\baeldung\drools\model\Customer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<Resource> discoverDeploymentResources(String prefix, List<String> suffixes, boolean loadResources) throws IOException {
if (loadResources) {
List<Resource> result = new ArrayList<>();
for (String suffix : suffixes) {
String path = prefix + suffix;
Resource[] resources = resourcePatternResolver.getResources(path);
if (resources != null && resources.length > 0) {
Collections.addAll(result, resources);
}
}
if (result.isEmpty()) {
logger.info("No deployment resources were found for autodeployment");
}
return result;
}
return new ArrayList<>();
} | protected Set<Class<?>> getCustomMybatisMapperClasses(List<String> customMyBatisMappers) {
Set<Class<?>> mybatisMappers = new HashSet<>();
for (String customMybatisMapperClassName : customMyBatisMappers) {
try {
Class customMybatisClass = Class.forName(customMybatisMapperClassName);
mybatisMappers.add(customMybatisClass);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Class " + customMybatisMapperClassName + " has not been found.", e);
}
}
return mybatisMappers;
}
protected String defaultText(String deploymentName, String defaultName) {
if (StringUtils.hasText(deploymentName)) {
return deploymentName;
}
return defaultName;
}
} | repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\AbstractEngineAutoConfiguration.java | 2 |
请完成以下Java代码 | public final void addParametersConverter(Converter<T, MultiValueMap<String, String>> parametersConverter) {
Assert.notNull(parametersConverter, "parametersConverter cannot be null");
Converter<T, MultiValueMap<String, String>> currentParametersConverter = this.parametersConverter;
this.parametersConverter = (authorizationGrantRequest) -> {
MultiValueMap<String, String> parameters = currentParametersConverter.convert(authorizationGrantRequest);
if (parameters == null) {
parameters = new LinkedMultiValueMap<>();
}
MultiValueMap<String, String> parametersToAdd = parametersConverter.convert(authorizationGrantRequest);
if (parametersToAdd != null) {
parameters.addAll(parametersToAdd);
}
return parameters;
};
this.requestEntityConverter = this::populateRequest;
}
/**
* Sets the {@link Consumer} used for customizing the OAuth 2.0 Access Token
* parameters, which allows for parameters to be added, overwritten or removed.
* @param parametersCustomizer the {@link Consumer} to customize the parameters
*/
public void setParametersCustomizer(Consumer<MultiValueMap<String, String>> parametersCustomizer) {
Assert.notNull(parametersCustomizer, "parametersCustomizer cannot be null");
this.parametersCustomizer = parametersCustomizer; | }
/**
* Sets the {@link BodyExtractor} that will be used to decode the
* {@link OAuth2AccessTokenResponse}
* @param bodyExtractor the {@link BodyExtractor} that will be used to decode the
* {@link OAuth2AccessTokenResponse}
* @since 5.6
*/
public final void setBodyExtractor(
BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> bodyExtractor) {
Assert.notNull(bodyExtractor, "bodyExtractor cannot be null");
this.bodyExtractor = bodyExtractor;
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\endpoint\AbstractWebClientReactiveOAuth2AccessTokenResponseClient.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getInfoMessage()
{
return getValue(NAME_InfoMessage);
}
@Override
public void setInfoMessage(@Nullable final String infoMessage)
{
setValue(NAME_InfoMessage, infoMessage);
}
@SuppressWarnings("SameParameterValue")
@Nullable
private String getValue(@NonNull final String name)
{
final Setting setting = settingsRepo.findByName(name);
return setting != null ? setting.getValue() : null; | }
@Transactional
public void setValue(@NonNull final String name, @Nullable final String value)
{
Setting setting = settingsRepo.findByName(name);
if (setting == null)
{
setting = new Setting();
setting.setName(name);
}
setting.setValue(value);
settingsRepo.saveAndFlush(setting);
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\service\impl\SettingsService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class AuthGatewayFilterFactory extends AbstractGatewayFilterFactory<AuthGatewayFilterFactory.Config> {
public AuthGatewayFilterFactory() {
super(AuthGatewayFilterFactory.Config.class);
}
@Override
public GatewayFilter apply(Config config) {
// token 和 userId 的映射
Map<String, Integer> tokenMap = new HashMap<>();
tokenMap.put("yunai", 1);
// 创建 GatewayFilter 对象
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 获得 token
ServerHttpRequest request = exchange.getRequest();
HttpHeaders headers = request.getHeaders();
String token = headers.getFirst(config.getTokenHeaderName());
// 如果没有 token,则不进行认证。因为可能是无需认证的 API 接口
if (!StringUtils.hasText(token)) {
return chain.filter(exchange);
}
// 进行认证
ServerHttpResponse response = exchange.getResponse();
Integer userId = tokenMap.get(token);
// 通过 token 获取不到 userId,说明认证不通过
if (userId == null) {
// 响应 401 状态码
response.setStatusCode(HttpStatus.UNAUTHORIZED);
// 响应提示
DataBuffer buffer = exchange.getResponse().bufferFactory().wrap("认证不通过".getBytes());
return response.writeWith(Flux.just(buffer));
}
// 认证通过,将 userId 添加到 Header 中
request = request.mutate().header(config.getUserIdHeaderName(), String.valueOf(userId))
.build(); | return chain.filter(exchange.mutate().request(request).build());
}
};
}
public static class Config {
private static final String DEFAULT_TOKEN_HEADER_NAME = "token";
private static final String DEFAULT_HEADER_NAME = "user-id";
private String tokenHeaderName = DEFAULT_TOKEN_HEADER_NAME;
private String userIdHeaderName = DEFAULT_HEADER_NAME;
public String getTokenHeaderName() {
return tokenHeaderName;
}
public String getUserIdHeaderName() {
return userIdHeaderName;
}
public Config setTokenHeaderName(String tokenHeaderName) {
this.tokenHeaderName = tokenHeaderName;
return this;
}
public Config setUserIdHeaderName(String userIdHeaderName) {
this.userIdHeaderName = userIdHeaderName;
return this;
}
}
} | repos\SpringBoot-Labs-master\labx-08-spring-cloud-gateway\labx-08-sc-gateway-demo05-custom-gateway-filter\src\main\java\cn\iocoder\springcloud\labx08\gatewaydemo\filter\AuthGatewayFilterFactory.java | 2 |
请完成以下Java代码 | 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 |
请完成以下Spring Boot application配置 | spring.application.name=Currency Converter
# Redis Configuration
spring.redis.host=localhost
spring.redis.port=6379
# spring.redis.password=
spring.redis.timeout=2000
# Cache Configuration
spring.cache.type=redis
# Open Exchange Rates API Configuration
openexchanger | ates.url=https://openexchangerates.org
openexchangerates.app_id=<APPLICATION_ID>
openexchangerates.base_currency=USD | repos\tutorials-master\libraries-apm\new-relic\currency-converter\src\main\resources\application.properties | 2 |
请在Spring Boot框架中完成以下Java代码 | public void process(final Exchange exchange) throws Exception
{
final JsonResponseComposite jsonResponseComposite = exchange.getIn().getBody(JsonResponseComposite.class);
final ExportBPartnerRouteContext routeContext = ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_EXPORT_BPARTNER_CONTEXT, ExportBPartnerRouteContext.class);
final ObjectMapper objectMapper = JsonObjectMapperHolder.sharedJsonObjectMapper();
final String payload = objectMapper.writeValueAsString(jsonResponseComposite);
final JsonRabbitMQHttpMessage jsonRabbitMQHttpMessage = JsonRabbitMQHttpMessage.builder()
.routingKey(routeContext.getRoutingKey())
.jsonRabbitMQProperties(getDefaultRabbitMQProperties())
.payload(payload)
.payloadEncoding(RABBIT_MQ_PAYLOAD_ENCODING)
.build();
final DispatchMessageRequest dispatchMessageRequest = DispatchMessageRequest.builder()
.url(routeContext.getRemoteUrl()) | .authToken(routeContext.getAuthToken())
.message(jsonRabbitMQHttpMessage)
.build();
exchange.getIn().setBody(dispatchMessageRequest);
}
@NonNull
private JsonRabbitMQProperties getDefaultRabbitMQProperties()
{
return JsonRabbitMQProperties.builder()
.delivery_mode(RABBITMQ_PROPS_PERSISTENT_DELIVERY_MODE)
.header(RABBITMQ_HEADERS_SUBJECT, RABBITMQ_HEADERS_METASFRESH_BUSINESS_PARTNER_SYNC)
.build();
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-rabbitmq\src\main\java\de\metas\camel\externalsystems\rabbitmq\bpartner\processor\BPartnerDispatchMessageProcessor.java | 2 |
请完成以下Java代码 | public Integer getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Integer departmentId) {
this.departmentId = departmentId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getOccurCount() {
return occurCount;
}
public void setOccurCount(Integer occurCount) {
this.occurCount = occurCount;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public Date getResponsedTime() {
return responsedTime;
}
public void setResponsedTime(Date responsedTime) {
this.responsedTime = responsedTime;
}
public String getResponsedBy() {
return responsedBy;
}
public void setResponsedBy(String responsedBy) {
this.responsedBy = responsedBy;
}
public Date getResolvedTime() {
return resolvedTime;
}
public void setResolvedTime(Date resolvedTime) {
this.resolvedTime = resolvedTime;
}
public String getResolvedBy() {
return resolvedBy;
}
public void setResolvedBy(String resolvedBy) {
this.resolvedBy = resolvedBy;
} | public Date getClosedTime() {
return closedTime;
}
public void setClosedTime(Date closedTime) {
this.closedTime = closedTime;
}
public String getClosedBy() {
return closedBy;
}
public void setClosedBy(String closedBy) {
this.closedBy = closedBy;
}
@Override
public String toString() {
return "Event{" +
"id=" + id +
", rawEventId=" + rawEventId +
", host=" + host +
", ip=" + ip +
", source=" + source +
", type=" + type +
", startTime=" + startTime +
", endTime=" + endTime +
", content=" + content +
", dataType=" + dataType +
", suggest=" + suggest +
", businessSystemId=" + businessSystemId +
", departmentId=" + departmentId +
", status=" + status +
", occurCount=" + occurCount +
", owner=" + owner +
", responsedTime=" + responsedTime +
", responsedBy=" + responsedBy +
", resolvedTime=" + resolvedTime +
", resolvedBy=" + resolvedBy +
", closedTime=" + closedTime +
", closedBy=" + closedBy +
'}';
}
} | repos\springBoot-master\springboot-shiro\src\main\java\com\us\bean\Event.java | 1 |
请完成以下Java代码 | public String getSchema() {
return this.schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
public @Nullable String getPlatform() {
return this.platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public DatabaseInitializationMode getInitializeSchema() {
return this.initializeSchema;
} | public void setInitializeSchema(DatabaseInitializationMode initializeSchema) {
this.initializeSchema = initializeSchema;
}
public boolean isContinueOnError() {
return this.continueOnError;
}
public void setContinueOnError(boolean continueOnError) {
this.continueOnError = continueOnError;
}
public abstract String getDefaultSchemaLocation();
} | repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\init\DatabaseInitializationProperties.java | 1 |
请完成以下Java代码 | protected String encryptPassword(String password, String salt) {
if (password == null) {
return null;
} else {
String saltedPassword = saltPassword(password, salt);
return Context.getProcessEngineConfiguration()
.getPasswordManager()
.encrypt(saltedPassword);
}
}
protected String generateSalt() {
return Context.getProcessEngineConfiguration()
.getSaltGenerator()
.generateSalt();
}
public boolean checkPasswordAgainstPolicy() {
PasswordPolicyResult result = Context.getProcessEngineConfiguration()
.getIdentityService()
.checkPasswordAgainstPolicy(newPassword, this);
return result.isValid();
}
public boolean hasNewPassword() {
return newPassword != null; | }
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", revision=" + revision
+ ", firstName=" + firstName
+ ", lastName=" + lastName
+ ", email=" + email
+ ", password=******" // sensitive for logging
+ ", salt=******" // sensitive for logging
+ ", lockExpirationTime=" + lockExpirationTime
+ ", attempts=" + attempts
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\UserEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
ConfigDataLocation other = (ConfigDataLocation) obj;
return this.value.equals(other.value);
}
@Override
public int hashCode() {
return this.value.hashCode();
}
@Override
public String toString() { | return (!this.optional) ? this.value : OPTIONAL_PREFIX + this.value;
}
/**
* Factory method to create a new {@link ConfigDataLocation} from a string.
* @param location the location string
* @return the {@link ConfigDataLocation} (which may be empty)
*/
public static ConfigDataLocation of(@Nullable String location) {
boolean optional = location != null && location.startsWith(OPTIONAL_PREFIX);
String value = (location != null && optional) ? location.substring(OPTIONAL_PREFIX.length()) : location;
return (StringUtils.hasText(value)) ? new ConfigDataLocation(optional, value, null) : EMPTY;
}
static boolean isNotEmpty(@Nullable ConfigDataLocation location) {
return (location != null) && !location.getValue().isEmpty();
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigDataLocation.java | 2 |
请完成以下Java代码 | public void initMap() {
// to do nothing
}
};
// freemarker
String templatePath = "/templates/mapper.xml.ftl";
// FileOutConfig
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// Mapper
String xmlUrl = projectPath + "/src/main/resources/mapper/" + module
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
System.out.println("xml path:"+xmlUrl);
return xmlUrl;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// templateConfig
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// StrategyConfig
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel); | strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// common file
//strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("tablename,multi can be seperated ,").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
//isAnnotationEnable
strategy.setEntityTableFieldAnnotationEnable(true);
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
} | repos\springboot-demo-master\dynamic-datasource\src\main\java\com\et\dynamic\datasource\GeneratorCode.java | 1 |
请完成以下Java代码 | public boolean isGenerated() {
return generated;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime; | }
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", name=" + name
+ ", deploymentId=" + deploymentId
+ ", generated=" + generated
+ ", tenantId=" + tenantId
+ ", type=" + type
+ ", createTime=" + createTime
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ResourceEntity.java | 1 |
请完成以下Java代码 | /* package */class SetColumnNameQueryUpdater<T> implements ISqlQueryUpdater<T>
{
private final String columnName;
private final Object value;
private final ModelColumnNameValue<?> valueColumn;
public SetColumnNameQueryUpdater(@NonNull final String columnName, @Nullable final Object value)
{
Check.assumeNotEmpty(columnName, "columnName not empty");
this.columnName = columnName;
if (value instanceof ModelColumnNameValue<?>)
{
this.valueColumn = (ModelColumnNameValue<?>)value;
this.value = null;
}
else
{
this.valueColumn = null;
this.value = value;
}
}
@Override
public String getSql(final Properties ctx, final List<Object> params)
{
final StringBuilder sql = new StringBuilder();
if (valueColumn != null)
{
sql.append(columnName).append("=").append(valueColumn.getColumnName());
}
else
{
sql.append(columnName).append("=?");
params.add(value);
}
return sql.toString();
}
@Override
public boolean update(final T model)
{
final Object valueToSet;
if (valueColumn != null)
{ | valueToSet = InterfaceWrapperHelper.getValueOrNull(model, valueColumn.getColumnName());
}
else
{
valueToSet = convertToPOValue(value);
}
return InterfaceWrapperHelper.setValue(model, columnName, valueToSet);
}
@Nullable
private static Object convertToPOValue(@Nullable final Object value)
{
if (value == null)
{
return null;
}
else if (value instanceof RepoIdAware)
{
return ((RepoIdAware)value).getRepoId();
}
else if (TimeUtil.isDateOrTimeObject(value))
{
return TimeUtil.asTimestamp(value);
}
else
{
return value;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\SetColumnNameQueryUpdater.java | 1 |
请完成以下Java代码 | public int getC_CashBook_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_CashBook_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_Currency getC_Currency() throws RuntimeException
{
return (I_C_Currency)MTable.get(getCtx(), I_C_Currency.Table_Name)
.getPO(getC_Currency_ID(), get_TrxName()); }
/** Set Currency.
@param C_Currency_ID
The Currency for this record
*/
public void setC_Currency_ID (int C_Currency_ID)
{
if (C_Currency_ID < 1)
set_Value (COLUMNNAME_C_Currency_ID, null);
else
set_Value (COLUMNNAME_C_Currency_ID, Integer.valueOf(C_Currency_ID));
}
/** Get Currency.
@return The Currency for this record
*/
public int getC_Currency_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Currency_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 Default.
@param IsDefault
Default value
*/
public void setIsDefault (boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
} | /** Get Default.
@return Default value
*/
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
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());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CashBook.java | 1 |
请完成以下Java代码 | public void recordVariableRemoved(VariableInstanceEntity variable) {
if (isHistoryLevelAtLeast(HistoryLevel.ACTIVITY)) {
HistoricVariableInstanceEntity historicProcessVariable = getEntityCache().findInCache(
HistoricVariableInstanceEntity.class,
variable.getId()
);
if (historicProcessVariable == null) {
historicProcessVariable =
getHistoricVariableInstanceEntityManager().findHistoricVariableInstanceByVariableInstanceId(
variable.getId()
);
}
if (historicProcessVariable != null) {
getHistoricVariableInstanceEntityManager().delete(historicProcessVariable);
}
}
} | protected String parseActivityType(FlowElement element) {
String elementType = element.getClass().getSimpleName();
elementType = elementType.substring(0, 1).toLowerCase() + elementType.substring(1);
return elementType;
}
protected EntityCache getEntityCache() {
return getSession(EntityCache.class);
}
public HistoryLevel getHistoryLevel() {
return historyLevel;
}
public void setHistoryLevel(HistoryLevel historyLevel) {
this.historyLevel = historyLevel;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\history\DefaultHistoryManager.java | 1 |
请完成以下Java代码 | public class Client {
@TableId(type = IdType.AUTO)
private Long id;
private String firstName;
private String lastName;
private String email;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime creationDate;
@TableField(fill = FieldFill.UPDATE)
private LocalDateTime lastModifiedDate;
@TableLogic
private Integer deleted;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) { | this.email = email;
}
public LocalDateTime getCreationDate() {
return creationDate;
}
public void setCreationDate(LocalDateTime creationDate) {
this.creationDate = creationDate;
}
public LocalDateTime getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(LocalDateTime lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
public Integer getDeleted() {
return deleted;
}
public void setDeleted(Integer deleted) {
this.deleted = deleted;
}
@Override
public String toString() {
return id + ":" +lastName + "," + firstName;
}
} | repos\tutorials-master\mybatis-plus\src\main\java\com\baeldung\mybatisplus\entity\Client.java | 1 |
请完成以下Java代码 | public class ScrewMain {
private static final String DB_URL = "jdbc:mysql://400-infra.server.iocoder.cn:3306";
private static final String DB_NAME = "mall_system";
private static final String DB_USERNAME = "root";
private static final String DB_PASSWORD = "3WLiVUBEwTbvAfsh";
private static final String FILE_OUTPUT_DIR = "/Users/yunai/screw_test";
private static final EngineFileType FILE_OUTPUT_TYPE = EngineFileType.HTML; // 可以设置 Word 或者 Markdown 格式
private static final String DOC_FILE_NAME = "数据库文档";
private static final String DOC_VERSION = "1.0.0";
private static final String DOC_DESCRIPTION = "文档描述";
public static void main(String[] args) {
// 创建 screw 的配置
Configuration config = Configuration.builder()
.version(DOC_VERSION) // 版本
.description(DOC_DESCRIPTION) // 描述
.dataSource(buildDataSource()) // 数据源
.engineConfig(buildEngineConfig()) // 引擎配置
.produceConfig(buildProcessConfig()) // 处理配置
.build();
// 执行 screw,生成数据库文档
new DocumentationExecute(config).execute();
}
/**
* 创建数据源
*/
private static DataSource buildDataSource() {
// 创建 HikariConfig 配置类
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setDriverClassName("com.mysql.cj.jdbc.Driver");
hikariConfig.setJdbcUrl(DB_URL + "/" + DB_NAME);
hikariConfig.setUsername(DB_USERNAME);
hikariConfig.setPassword(DB_PASSWORD);
hikariConfig.addDataSourceProperty("useInformationSchema", "true"); // 设置可以获取 tables remarks 信息
// 创建数据源
return new HikariDataSource(hikariConfig);
}
/**
* 创建 screw 的引擎配置 | */
private static EngineConfig buildEngineConfig() {
return EngineConfig.builder()
.fileOutputDir(FILE_OUTPUT_DIR) // 生成文件路径
.openOutputDir(false) // 打开目录
.fileType(FILE_OUTPUT_TYPE) // 文件类型
.produceType(EngineTemplateType.freemarker) // 文件类型
.fileName(DOC_FILE_NAME) // 自定义文件名称
.build();
}
/**
* 创建 screw 的处理配置,一般可忽略
* 指定生成逻辑、当存在指定表、指定表前缀、指定表后缀时,将生成指定表,其余表不生成、并跳过忽略表配置
*/
private static ProcessConfig buildProcessConfig() {
return ProcessConfig.builder()
.designatedTableName(Collections.<String>emptyList()) // 根据名称指定表生成
.designatedTablePrefix(Collections.<String>emptyList()) //根据表前缀生成
.designatedTableSuffix(Collections.<String>emptyList()) // 根据表后缀生成
.ignoreTableName(Arrays.asList("test_user", "test_group")) // 忽略表名
.ignoreTablePrefix(Collections.singletonList("test_")) // 忽略表前缀
.ignoreTableSuffix(Collections.singletonList("_test")) // 忽略表后缀
.build();
}
} | repos\SpringBoot-Labs-master\lab-70-db-doc\lab-70-db-doc-screw-01\src\main\java\ScrewMain.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setINSTITUTIONBRANCHID(String value) {
this.institutionbranchid = value;
}
/**
* Gets the value of the institutionname property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getINSTITUTIONNAME() {
return institutionname;
}
/**
* Sets the value of the institutionname property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setINSTITUTIONNAME(String value) {
this.institutionname = value;
}
/**
* Gets the value of the institutionlocation property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getINSTITUTIONLOCATION() {
return institutionlocation;
}
/**
* Sets the value of the institutionlocation property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setINSTITUTIONLOCATION(String value) {
this.institutionlocation = value;
} | /**
* Gets the value of the country property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCOUNTRY() {
return country;
}
/**
* Sets the value of the country property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCOUNTRY(String value) {
this.country = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\HFINI1.java | 2 |
请完成以下Java代码 | public class PerceptronPOSTagger extends PerceptronTagger implements POSTagger
{
public PerceptronPOSTagger(LinearModel model)
{
super(model);
if (model.featureMap.tagSet.type != TaskType.POS)
{
throw new IllegalArgumentException(String.format("错误的模型类型: 传入的不是词性标注模型,而是 %s 模型", model.featureMap.tagSet.type));
}
}
public PerceptronPOSTagger(String modelPath) throws IOException
{
this(new LinearModel(modelPath));
}
/**
* 加载配置文件指定的模型
*
* @throws IOException
*/
public PerceptronPOSTagger() throws IOException
{
this(HanLP.Config.PerceptronPOSModelPath);
}
/**
* 标注
*
* @param words
* @return
*/
@Override
public String[] tag(String... words)
{
POSInstance instance = new POSInstance(words, model.featureMap);
return tag(instance);
}
public String[] tag(POSInstance instance)
{
instance.tagArray = new int[instance.featureMatrix.length];
model.viterbiDecode(instance, instance.tagArray);
return instance.tags(model.tagSet());
}
/**
* 标注
*
* @param wordList
* @return
*/
@Override
public String[] tag(List<String> wordList)
{
String[] termArray = new String[wordList.size()];
wordList.toArray(termArray);
return tag(termArray);
} | /**
* 在线学习
*
* @param segmentedTaggedSentence 人民日报2014格式的句子
* @return 是否学习成功(失败的原因是参数错误)
*/
public boolean learn(String segmentedTaggedSentence)
{
return learn(POSInstance.create(segmentedTaggedSentence, model.featureMap));
}
/**
* 在线学习
*
* @param wordTags [单词]/[词性]数组
* @return 是否学习成功(失败的原因是参数错误)
*/
public boolean learn(String... wordTags)
{
String[] words = new String[wordTags.length];
String[] tags = new String[wordTags.length];
for (int i = 0; i < wordTags.length; i++)
{
String[] wordTag = wordTags[i].split("//");
words[i] = wordTag[0];
tags[i] = wordTag[1];
}
return learn(new POSInstance(words, tags, model.featureMap));
}
@Override
protected Instance createInstance(Sentence sentence, FeatureMap featureMap)
{
for (Word word : sentence.toSimpleWordList())
{
if (!model.featureMap.tagSet.contains(word.getLabel()))
throw new IllegalArgumentException("在线学习不可能学习新的标签: " + word + " ;请标注语料库后重新全量训练。");
}
return POSInstance.create(sentence, featureMap);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\PerceptronPOSTagger.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public AuthenticationManager authenticationManager(UserDetailsService userDetailsService) {
var authenticationProvider = new DaoAuthenticationProvider(userDetailsService);
return new ProviderManager(authenticationProvider);
}
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.withUsername("in28minutes")
.password("{noop}dummy")
.authorities("read")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
@Bean
public JWKSource<SecurityContext> jwkSource() {
JWKSet jwkSet = new JWKSet(rsaKey());
return (((jwkSelector, securityContext)
-> jwkSelector.select(jwkSet)));
}
@Bean
JwtEncoder jwtEncoder(JWKSource<SecurityContext> jwkSource) {
return new NimbusJwtEncoder(jwkSource);
}
@Bean
JwtDecoder jwtDecoder() throws JOSEException {
return NimbusJwtDecoder
.withPublicKey(rsaKey().toRSAPublicKey())
.build();
}
@Bean
public RSAKey rsaKey() { | KeyPair keyPair = keyPair();
return new RSAKey
.Builder((RSAPublicKey) keyPair.getPublic())
.privateKey((RSAPrivateKey) keyPair.getPrivate())
.keyID(UUID.randomUUID().toString())
.build();
}
@Bean
public KeyPair keyPair() {
try {
var keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
return keyPairGenerator.generateKeyPair();
} catch (Exception e) {
throw new IllegalStateException(
"Unable to generate an RSA Key Pair", e);
}
}
} | repos\spring-boot-examples-master\spring-boot-react-examples\spring-boot-react-jwt-auth-login-logout\backend-spring-boot-react-jwt-auth-login-logout\src\main\java\com\in28minutes\fullstack\springboot\jwt\basic\authentication\springbootjwtauthloginlogout\jwt\JwtSecurityConfig.java | 2 |
请完成以下Java代码 | static JsonDocument replaceExample(Bucket bucket, String id) {
JsonDocument document = bucket.get(id);
JsonObject content = document.content();
content.put("homeTown", "Milwaukee");
JsonDocument replaced = bucket.replace(document);
return replaced;
}
static JsonDocument removeExample(Bucket bucket, String id) {
JsonDocument removed = bucket.remove(id);
return removed;
}
static JsonDocument getFirstFromReplicaExample(Bucket bucket, String id) {
try {
return bucket.get(id);
} catch (CouchbaseException e) {
List<JsonDocument> list = bucket.getFromReplica(id, ReplicaMode.FIRST);
if (!list.isEmpty()) {
return list.get(0); | }
}
return null;
}
static JsonDocument getLatestReplicaVersion(Bucket bucket, String id) {
long maxCasValue = -1;
JsonDocument latest = null;
for (JsonDocument replica : bucket.getFromReplica(id, ReplicaMode.ALL)) {
if (replica.cas() > maxCasValue) {
latest = replica;
maxCasValue = replica.cas();
}
}
return latest;
}
} | repos\tutorials-master\persistence-modules\couchbase\src\main\java\com\baeldung\couchbase\intro\CodeSnippets.java | 1 |
请完成以下Java代码 | public static void assertInGroup(final I_C_OrderLine orderLine)
{
if (!isInGroup(orderLine))
{
throw new AdempiereException("Order line " + orderLine.getLine() + " shall be part of a compensation group");
}
}
public static void assertNotInGroup(final I_C_OrderLine orderLine)
{
if (isInGroup(orderLine))
{
throw new AdempiereException("Order line " + orderLine.getLine() + " shall NOT be part of a compensation group");
}
}
public static boolean isInGroup(final I_C_OrderLine orderLine)
{
return orderLine.getC_Order_CompensationGroup_ID() > 0;
}
public static boolean isNotInGroup(final I_C_OrderLine orderLine)
{
return !isInGroup(orderLine);
}
public static BigDecimal adjustAmtByCompensationType(@NonNull final BigDecimal compensationAmt, @NonNull final GroupCompensationType compensationType)
{
if (compensationType == GroupCompensationType.Discount)
{ | return compensationAmt.negate();
}
else if (compensationType == GroupCompensationType.Surcharge)
{
return compensationAmt;
}
else
{
throw new AdempiereException("Unknown compensationType: " + compensationType);
}
}
public static boolean isGeneratedLine(final I_C_OrderLine orderLine)
{
final GroupTemplateLineId groupSchemaLineId = extractGroupTemplateLineId(orderLine);
return isGeneratedLine(groupSchemaLineId);
}
@Nullable
public static GroupTemplateLineId extractGroupTemplateLineId(@NonNull final I_C_OrderLine orderLine)
{
return GroupTemplateLineId.ofRepoIdOrNull(orderLine.getC_CompensationGroup_SchemaLine_ID());
}
public static boolean isGeneratedLine(@Nullable final GroupTemplateLineId groupSchemaLineId)
{
return groupSchemaLineId != null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\compensationGroup\OrderGroupCompensationUtils.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void validateIdentityLinkArguments(String family, String identityId, String type) {
if (family == null || (!CmmnRestUrls.SEGMENT_IDENTITYLINKS_FAMILY_GROUPS.equals(family) && !CmmnRestUrls.SEGMENT_IDENTITYLINKS_FAMILY_USERS.equals(family))) {
throw new FlowableIllegalArgumentException("Identity link family should be 'users' or 'groups'.");
}
if (identityId == null) {
throw new FlowableIllegalArgumentException("IdentityId is required.");
}
if (type == null) {
throw new FlowableIllegalArgumentException("Type is required.");
}
}
protected IdentityLink getIdentityLink(String family, String identityId, String type, String taskId) {
boolean isUser = family.equals(CmmnRestUrls.SEGMENT_IDENTITYLINKS_FAMILY_USERS);
// Perhaps it would be better to offer getting a single identitylink
// from the API
List<IdentityLink> allLinks = taskService.getIdentityLinksForTask(taskId); | for (IdentityLink link : allLinks) {
boolean rightIdentity = false;
if (isUser) {
rightIdentity = identityId.equals(link.getUserId());
} else {
rightIdentity = identityId.equals(link.getGroupId());
}
if (rightIdentity && link.getType().equals(type)) {
return link;
}
}
throw new FlowableObjectNotFoundException("Could not find the requested identity link.", IdentityLink.class);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskIdentityLinkResource.java | 2 |
请完成以下Java代码 | public void setAD_Message_ID (final int AD_Message_ID)
{
if (AD_Message_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Message_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Message_ID, AD_Message_ID);
}
@Override
public int getAD_Message_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Message_ID);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
@Override
public void setEntityType (final java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
@Override
public java.lang.String getEntityType()
{
return get_ValueAsString(COLUMNNAME_EntityType);
}
@Override
public void setErrorCode (final @Nullable java.lang.String ErrorCode)
{
set_Value (COLUMNNAME_ErrorCode, ErrorCode);
}
@Override
public java.lang.String getErrorCode()
{
return get_ValueAsString(COLUMNNAME_ErrorCode);
}
@Override
public void setMsgText (final java.lang.String MsgText)
{
set_Value (COLUMNNAME_MsgText, MsgText);
}
@Override
public java.lang.String getMsgText() | {
return get_ValueAsString(COLUMNNAME_MsgText);
}
@Override
public void setMsgTip (final @Nullable java.lang.String MsgTip)
{
set_Value (COLUMNNAME_MsgTip, MsgTip);
}
@Override
public java.lang.String getMsgTip()
{
return get_ValueAsString(COLUMNNAME_MsgTip);
}
/**
* MsgType AD_Reference_ID=103
* Reference name: AD_Message Type
*/
public static final int MSGTYPE_AD_Reference_ID=103;
/** Fehler = E */
public static final String MSGTYPE_Fehler = "E";
/** Information = I */
public static final String MSGTYPE_Information = "I";
/** Menü = M */
public static final String MSGTYPE_Menue = "M";
@Override
public void setMsgType (final java.lang.String MsgType)
{
set_Value (COLUMNNAME_MsgType, MsgType);
}
@Override
public java.lang.String getMsgType()
{
return get_ValueAsString(COLUMNNAME_MsgType);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Message.java | 1 |
请完成以下Java代码 | private PurchaseProfitInfo convertToCurrencyIfPossible(
final PurchaseProfitInfo profitInfo,
final CurrencyId currencyIdTo)
{
if (profitInfo == null)
{
return null;
}
if (currencyIdTo == null)
{
return profitInfo;
}
try
{
return purchaseProfitInfoService.convertToCurrency(profitInfo, currencyIdTo);
}
catch (final Exception ex)
{
logger.warn("Failed converting {} to {}. Returning profitInfo as is.", profitInfo, currencyIdTo, ex);
return profitInfo;
}
}
public PurchaseRow createGroupRow(
@NonNull final PurchaseDemand demand,
@NonNull final List<PurchaseRow> rows)
{
return PurchaseRow.groupRowBuilder()
.lookups(lookups)
.demand(demand)
.qtyAvailableToPromise(getQtyAvailableToPromise(demand))
.includedRows(rows)
.build();
}
private Quantity getQtyAvailableToPromise(final PurchaseDemand demand)
{
final ProductId productId = demand.getProductId();
final AttributesKey attributesKey = AttributesKeys
.createAttributesKeyFromASIStorageAttributes(demand.getAttributeSetInstanceId()) | .orElse(AttributesKey.ALL);
final AvailableToPromiseQuery query = AvailableToPromiseQuery.builder()
.productId(productId.getRepoId())
.date(demand.getSalesPreparationDate())
.storageAttributesKeyPattern(AttributesKeyPatternsUtil.ofAttributeKey(attributesKey))
.build();
final BigDecimal qtyAvailableToPromise = availableToPromiseRepository.retrieveAvailableStockQtySum(query);
final I_C_UOM uom = productsBL.getStockUOM(productId);
return Quantity.of(qtyAvailableToPromise, uom);
}
@Builder(builderMethodName = "availabilityDetailSuccessBuilder", builderClassName = "AvailabilityDetailSuccessBuilder")
private PurchaseRow buildRowFromFromAvailabilityResult(
@NonNull final PurchaseRow lineRow,
@NonNull final AvailabilityResult availabilityResult)
{
return PurchaseRow.availabilityDetailSuccessBuilder()
.lineRow(lineRow)
.availabilityResult(availabilityResult)
.build();
}
@Builder(builderMethodName = "availabilityDetailErrorBuilder", builderClassName = "AvailabilityDetailErrorBuilder")
private PurchaseRow buildRowFromFromThrowable(
@NonNull final PurchaseRow lineRow,
@NonNull final Throwable throwable)
{
return PurchaseRow.availabilityDetailErrorBuilder()
.lineRow(lineRow)
.throwable(throwable)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseRowFactory.java | 1 |
请完成以下Java代码 | private void registerExpressionEvaluationHints(RuntimeHints hints) {
hints.reflection()
.registerTypes(
List.of(TypeReference.of(SecurityExpressionOperations.class),
TypeReference.of(SecurityExpressionRoot.class)),
(builder) -> builder.withMembers(MemberCategory.ACCESS_DECLARED_FIELDS,
MemberCategory.INVOKE_DECLARED_METHODS));
}
private void registerExceptionEventsHints(RuntimeHints hints) {
hints.reflection()
.registerTypes(getDefaultAuthenticationExceptionEventPublisherTypes(),
(builder) -> builder.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS));
}
private List<TypeReference> getDefaultAuthenticationExceptionEventPublisherTypes() {
return Stream
.of(AuthenticationFailureBadCredentialsEvent.class, AuthenticationFailureCredentialsExpiredEvent.class,
AuthenticationFailureDisabledEvent.class, AuthenticationFailureExpiredEvent.class, | AuthenticationFailureLockedEvent.class, AuthenticationFailureProviderNotFoundEvent.class,
AuthenticationFailureProxyUntrustedEvent.class, AuthenticationFailureServiceExceptionEvent.class,
AuthenticationServiceException.class, AccountExpiredException.class, BadCredentialsException.class,
CredentialsExpiredException.class, DisabledException.class, LockedException.class,
UsernameNotFoundException.class, ProviderNotFoundException.class)
.map(TypeReference::of)
.toList();
}
private void registerDefaultJdbcSchemaFileHint(RuntimeHints hints) {
hints.resources().registerPattern(JdbcDaoImpl.DEFAULT_USER_SCHEMA_DDL_LOCATION);
}
private void registerSecurityContextHints(RuntimeHints hints) {
hints.reflection()
.registerType(SecurityContextImpl.class,
(builder) -> builder.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS));
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\aot\hint\CoreSecurityRuntimeHints.java | 1 |
请完成以下Java代码 | private String mkStacktrace()
{
return mkStacktrace(Thread.currentThread());
}
private String mkStacktrace(final Thread thread)
{
final StringBuilder sb = new StringBuilder();
for (final StackTraceElement ste : thread.getStackTrace())
{
sb.append("\tat " + ste + "\n");
}
return sb.toString();
}
@Override
public void onRollback(final ITrx trx)
{
removeTimeoutTimer(trx);
final String stacktraceOnTimerStart = mkStacktrace();
trxName2Stacktrace.put(trx.getTrxName(), stacktraceOnTimerStart);
startTimeoutTimer(trx, stacktraceOnTimerStart);
}
@Override
public void onSetSavepoint(final ITrx trx, final ITrxSavepoint savepoint)
{
final ITrxConstraints constraints = getConstraints();
if (Services.get(ITrxConstraintsBL.class).isDisabled(constraints))
{
return; // nothing to do
}
if (constraints.isActive())
{
if (constraints.getMaxSavepoints() < getSavepointsForTrxName(trx.getTrxName()).size())
{
throw new TrxConstraintException("Transaction '" +
trx + "' has too many unreleased savepoints: " + getSavepointsForTrxName(trx.getTrxName()));
}
}
}
@Override
public void onReleaseSavepoint(final ITrx trx, final ITrxSavepoint savepoint)
{
getSavepointsForTrxName(trx.getTrxName()).remove(savepoint);
}
private static ITrxConstraints getConstraints()
{
return Services.get(ITrxConstraintsBL.class).getConstraints();
}
private Collection<String> getTrxNamesForCurrentThread()
{
return getTrxNamesForThreadId(Thread.currentThread().getId());
}
private Collection<String> getTrxNamesForThreadId(final long threadId)
{
synchronized (threadId2TrxName)
{
Collection<String> trxNames = threadId2TrxName.get(threadId);
if (trxNames == null)
{
trxNames = new HashSet<String>();
threadId2TrxName.put(threadId, trxNames);
}
return trxNames;
}
}
private Collection<ITrxSavepoint> getSavepointsForTrxName(final String trxName) | {
synchronized (trxName2SavePoint)
{
Collection<ITrxSavepoint> savepoints = trxName2SavePoint.get(trxName);
if (savepoints == null)
{
savepoints = new HashSet<ITrxSavepoint>();
trxName2SavePoint.put(trxName, savepoints);
}
return savepoints;
}
}
private String mkStacktraceInfo(final Thread thread, final String beginStacktrace)
{
final StringBuilder msgSB = new StringBuilder();
msgSB.append(">>> Stacktrace at trx creation, commit or rollback:\n");
msgSB.append(beginStacktrace);
msgSB.append(">>> Current stacktrace of the creating thread:\n");
if (thread.isAlive())
{
msgSB.append(mkStacktrace(thread));
}
else
{
msgSB.append("\t(Thread already finished)\n");
}
final String msg = msgSB.toString();
return msg;
}
@Override
public String getCreationStackTrace(final String trxName)
{
return trxName2Stacktrace.get(trxName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\trxConstraints\api\impl\OpenTrxBL.java | 1 |
请完成以下Spring Boot application配置 | spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/javastack
username: root
password: 12345678
druid:
one:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/javastack
username: root
password: 12345678
initial-size: 10
max-active: 10
min-idle: 5
max-wait: 60000
two:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/javastack
username: root
password: 12345678
initial-size: 10
max-active: 10
min-idle: 5
max-wait: 60000
# 不兼容最新 Spring Boot
# web-stat-filter:
# enabled: true
# url-pattern: /
# stat-view-se | rvlet:
# enabled: true
# url-pattern: /druid/*
# login-username: root
# login-password: root
sql:
init:
mode: always
schemaLocations:
- classpath:sql/create_t_user.sql
dataLocations:
- classpath:sql/insert_t_user.sql
jdbc:
template:
max-rows: 3 | repos\spring-boot-best-practice-master\spring-boot-datasource\src\main\resources\application.yml | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getPayWayCode() {
return payWayCode;
}
public void setPayWayCode(String payWayCode) {
this.payWayCode = payWayCode == null ? null : payWayCode.trim();
}
public String getPayWayName() {
return payWayName;
}
public void setPayWayName(String payWayName) {
this.payWayName = payWayName == null ? null : payWayName.trim();
}
public String getPayTypeCode() {
return payTypeCode;
}
public void setPayTypeCode(String payTypeCode) {
this.payTypeCode = payTypeCode == null ? null : payTypeCode.trim();
}
public String getPayTypeName() {
return payTypeName;
}
public void setPayTypeName(String payTypeName) {
this.payTypeName = payTypeName == null ? null : payTypeName.trim();
}
public String getPayProductCode() {
return payProductCode;
}
public void setPayProductCode(String payProductCode) {
this.payProductCode = payProductCode == null ? null : payProductCode.trim(); | }
public Integer getSorts() {
return sorts;
}
public void setSorts(Integer sorts) {
this.sorts = sorts;
}
public Double getPayRate() {
return payRate;
}
public void setPayRate(Double payRate) {
this.payRate = payRate;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\entity\RpPayWay.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public DirectExchange demo06Exchange() {
return new DirectExchange(Demo06Message.EXCHANGE,
true, // durable: 是否持久化
false); // exclusive: 是否排它
}
// 创建 Binding
// Exchange:Demo06Message.EXCHANGE
// Routing key:Demo06Message.ROUTING_KEY
// Queue:Demo06Message.QUEUE
@Bean
public Binding demo06Binding() {
return BindingBuilder.bind(demo06Queue()).to(demo06Exchange()).with(Demo06Message.ROUTING_KEY);
}
} | @Bean(name = "consumerBatchContainerFactory")
public SimpleRabbitListenerContainerFactory consumerBatchContainerFactory(
SimpleRabbitListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) {
// 创建 SimpleRabbitListenerContainerFactory 对象
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
configurer.configure(factory, connectionFactory);
// 额外添加批量消费的属性
factory.setBatchListener(true);
factory.setBatchSize(10);
factory.setReceiveTimeout(30 * 1000L);
factory.setConsumerBatchEnabled(true);
return factory;
}
} | repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-demo-batch-consume-02\src\main\java\cn\iocoder\springboot\lab04\rabbitmqdemo\config\RabbitConfig.java | 2 |
请完成以下Java代码 | public TbQueueProducer<TbProtoQueueMsg<ToTransportMsg>> getTransportNotificationsMsgProducer() {
return toTransport;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToRuleEngineMsg>> getRuleEngineMsgProducer() {
return toRuleEngine;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToRuleEngineNotificationMsg>> getRuleEngineNotificationsMsgProducer() {
return toRuleEngineNotifications;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToCoreMsg>> getTbCoreMsgProducer() {
return toTbCore;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToCoreNotificationMsg>> getTbCoreNotificationsMsgProducer() {
return toTbCoreNotifications;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToUsageStatsServiceMsg>> getTbUsageStatsMsgProducer() {
return toUsageStats;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToVersionControlServiceMsg>> getTbVersionControlMsgProducer() {
return toVersionControl;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToHousekeeperServiceMsg>> getHousekeeperMsgProducer() {
return toHousekeeper;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToEdgeMsg>> getTbEdgeMsgProducer() {
return toEdge; | }
@Override
public TbQueueProducer<TbProtoQueueMsg<ToEdgeNotificationMsg>> getTbEdgeNotificationsMsgProducer() {
return toEdgeNotifications;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> getTbEdgeEventsMsgProducer() {
return toEdgeEvents;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCalculatedFieldMsg>> getCalculatedFieldsMsgProducer() {
return toCalculatedFields;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToCalculatedFieldNotificationMsg>> getCalculatedFieldsNotificationsMsgProducer() {
return toCalculatedFieldNotifications;
}
} | repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\provider\TbCoreQueueProducerProvider.java | 1 |
请完成以下Java代码 | public String getNewState() {
return PlanItemInstanceState.TERMINATED;
}
@Override
public String getLifeCycleTransition() {
return PlanItemTransition.TERMINATE;
}
@Override
public boolean isEvaluateRepetitionRule() {
return false;
}
@Override
protected boolean shouldAggregateForSingleInstance() {
return false;
}
@Override
protected boolean shouldAggregateForMultipleInstances() {
return false;
}
@Override
protected void internalExecute() {
planItemInstanceEntity.setEndedTime(getCurrentTime(commandContext));
planItemInstanceEntity.setTerminatedTime(planItemInstanceEntity.getEndedTime());
CommandContextUtil.getCmmnHistoryManager(commandContext).recordPlanItemInstanceTerminated(planItemInstanceEntity);
}
@Override
protected Map<String, String> getAsyncLeaveTransitionMetadata() {
Map<String, String> metadata = new HashMap<>(); | metadata.put(OperationSerializationMetadata.FIELD_PLAN_ITEM_INSTANCE_ID, planItemInstanceEntity.getId());
metadata.put(OperationSerializationMetadata.FIELD_EXIT_TYPE, exitType);
metadata.put(OperationSerializationMetadata.FIELD_EXIT_EVENT_TYPE, exitEventType);
return metadata;
}
@Override
public boolean abortOperationIfNewStateEqualsOldState() {
return true;
}
@Override
public String getOperationName() {
return "[Terminate plan item]";
}
public String getExitType() {
return exitType;
}
public void setExitType(String exitType) {
this.exitType = exitType;
}
public String getExitEventType() {
return exitEventType;
}
public void setExitEventType(String exitEventType) {
this.exitEventType = exitEventType;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\TerminatePlanItemInstanceOperation.java | 1 |
请完成以下Java代码 | public T getElement() throws NullPointerException {
throw new NullPointerException();
}
@Override
public void detach() {
return;
}
@Override
public DoublyLinkedList<T> getListReference() {
return list;
}
@Override
public LinkedListNode<T> setPrev(LinkedListNode<T> next) {
return next;
}
@Override
public LinkedListNode<T> setNext(LinkedListNode<T> prev) {
return prev;
} | @Override
public LinkedListNode<T> getPrev() {
return this;
}
@Override
public LinkedListNode<T> getNext() {
return this;
}
@Override
public LinkedListNode<T> search(T value) {
return this;
}
} | repos\tutorials-master\data-structures\src\main\java\com\baeldung\lrucache\DummyNode.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private BeanDefinitionRegistry getBeanDefinitionRegistry(ApplicationContext applicationContext) {
AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory();
if (beanFactory instanceof BeanDefinitionRegistry) {
return (BeanDefinitionRegistry) beanFactory;
}
throw new IllegalStateException("");
}
/**
* Resolve the unique {@link ApplicationConfig} Bean
* @param registry {@link BeanDefinitionRegistry} instance
* @param beanFactory {@link ConfigurableListableBeanFactory} instance
* @see EnableDubboConfig
*/
private void resolveUniqueApplicationConfigBean(BeanDefinitionRegistry registry, ListableBeanFactory beanFactory) {
String[] beansNames = beanNamesForTypeIncludingAncestors(beanFactory, ApplicationConfig.class);
if (beansNames.length < 2) { // If the number of ApplicationConfig beans is less than two, return immediately.
return;
}
Environment environment = beanFactory.getBean(ENVIRONMENT_BEAN_NAME, Environment.class);
// Remove ApplicationConfig Beans that are configured by "dubbo.application.*"
Stream.of(beansNames)
.filter(beansName -> isConfiguredApplicationConfigBeanName(environment, beansName))
.forEach(registry::removeBeanDefinition);
beansNames = beanNamesForTypeIncludingAncestors(beanFactory, ApplicationConfig.class);
if (beansNames.length > 1) { | throw new IllegalStateException(String.format("There are more than one instances of %s, whose bean definitions : %s",
ApplicationConfig.class.getSimpleName(),
Stream.of(beansNames)
.map(registry::getBeanDefinition)
.collect(Collectors.toList()))
);
}
}
private boolean isConfiguredApplicationConfigBeanName(Environment environment, String beanName) {
boolean removed = BeanFactoryUtils.isGeneratedBeanName(beanName)
// Dubbo ApplicationConfig id as bean name
|| Objects.equals(beanName, environment.getProperty("dubbo.application.id"));
if (removed) {
if (logger.isDebugEnabled()) {
logger.debug("The {} bean [ name : {} ] has been removed!", ApplicationConfig.class.getSimpleName(), beanName);
}
}
return removed;
}
@Override
public int getOrder() {
return LOWEST_PRECEDENCE;
}
} | repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\autoconfigure\src\main\java\org\apache\dubbo\spring\boot\context\event\DubboConfigBeanDefinitionConflictApplicationListener.java | 2 |
请完成以下Java代码 | /* package */final class JavaAssistInterceptorInstance implements IInterceptorInstance
{
private final Class<? extends Annotation> annotationClass;
private final Object interceptorImpl;
private final Method aroundInvokeMethod;
public JavaAssistInterceptorInstance(final Class<? extends Annotation> annotationClass, final Object interceptorImpl)
{
super();
Check.assumeNotNull(annotationClass, "annotationClass not null");
this.annotationClass = annotationClass;
Check.assumeNotNull(interceptorImpl, "interceptorImpl not null");
this.interceptorImpl = interceptorImpl;
final Class<? extends Object> interceptorImplClass = interceptorImpl.getClass();
@SuppressWarnings("unchecked")
final Set<Method> aroundInvokeMethods = ReflectionUtils.getAllMethods(interceptorImplClass, ReflectionUtils.withAnnotation(AroundInvoke.class));
Check.errorIf(aroundInvokeMethods.size() != 1, "Class {} needs to have exactly one method annotated with @AroundInvoke. It has:{}", interceptorImpl, aroundInvokeMethods);
this.aroundInvokeMethod = aroundInvokeMethods.iterator().next();
Check.assumeNotNull(aroundInvokeMethod, "aroundInvokeMethod not null for {}", interceptorImplClass);
}
@Override
public String toString() | {
return "JavaAssistInterceptorInstance ["
+ "annotationClass=" + annotationClass
+ ", aroundInvokeMethod=" + aroundInvokeMethod
+ ", interceptorImpl=" + interceptorImpl
+ "]";
}
@Override
public Class<? extends Annotation> getAnnotationClass()
{
return annotationClass;
}
@Override
public Object invoke(final IInvocationContext invocationCtx) throws Exception
{
// invoke the interceptor's registered "around" method
return aroundInvokeMethod.invoke(interceptorImpl, invocationCtx);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\proxy\impl\JavaAssistInterceptorInstance.java | 1 |
请完成以下Java代码 | protected void registerInterceptors(IModelValidationEngine engine)
{
engine.addModelValidator(new ESR_Import());
engine.addModelValidator(new ESR_ImportLine());
engine.addModelValidator(new C_PaySelection());
}
public void registerFactories()
{
//
// Register payment action handlers.
final IESRImportBL esrImportBL = Services.get(IESRImportBL.class);
esrImportBL.registerActionHandler(X_ESR_ImportLine.ESR_PAYMENT_ACTION_Write_Off_Amount, new WriteoffESRActionHandler());
esrImportBL.registerActionHandler(X_ESR_ImportLine.ESR_PAYMENT_ACTION_Keep_For_Dunning, new DunningESRActionHandler());
esrImportBL.registerActionHandler(X_ESR_ImportLine.ESR_PAYMENT_ACTION_Money_Was_Transfered_Back_to_Partner, new MoneyTransferedBackESRActionHandler());
esrImportBL.registerActionHandler(X_ESR_ImportLine.ESR_PAYMENT_ACTION_Allocate_Payment_With_Next_Invoice, new WithNextInvoiceESRActionHandler());
esrImportBL.registerActionHandler(X_ESR_ImportLine.ESR_PAYMENT_ACTION_Allocate_Payment_With_Current_Invoice, new WithCurrenttInvoiceESRActionHandler());
esrImportBL.registerActionHandler(X_ESR_ImportLine.ESR_PAYMENT_ACTION_Unable_To_Assign_Income, new UnableToAssignESRActionHandler());
esrImportBL.registerActionHandler(X_ESR_ImportLine.ESR_PAYMENT_ACTION_Discount, new DiscountESRActionHandler());
esrImportBL.registerActionHandler(X_ESR_ImportLine.ESR_PAYMENT_ACTION_Duplicate_Payment, new DuplicatePaymentESRActionHandler());
esrImportBL.registerActionHandler(X_ESR_ImportLine.ESR_PAYMENT_ACTION_Unknown_Invoice, new UnknownInvoiceESRActionHandler());
// | // Register ESR Payment Parsers
final IPaymentStringParserFactory paymentStringParserFactory = Services.get(IPaymentStringParserFactory.class);
paymentStringParserFactory.registerParser(PaymentParserType.ESRRegular.getType(), ESRRegularLineParser.instance);
paymentStringParserFactory.registerParser(PaymentParserType.ESRCreaLogix.getType(), ESRCreaLogixStringParser.instance);
paymentStringParserFactory.registerParser(PaymentParserType.QRCode.getType(), new QRCodeStringParser());
//
// Payment batch provider for Bank Statement matching
Services.get(IPaymentBatchFactory.class).addPaymentBatchProvider(new ESRPaymentBatchProvider());
//
// Bank statement listener
Services.get(IBankStatementListenerService.class).addListener(new ESRBankStatementListener(esrImportBL));
//
// ESR match listener
Services.get(IESRLineHandlersService.class).registerESRLineListener(new DefaultESRLineHandler()); // 08741
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\model\validator\ESR_Main_Validator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | SysDepartModel queryCompByOrgCode(@RequestParam(name = "sysCode") String orgCode) {
return sysBaseApi.queryCompByOrgCode(orgCode);
}
/**
* 根据部门编码和层次查询上级公司
*
* @param orgCode 部门编码
* @param level 可以传空 默认为1级 最小值为1
* @return
*/
@GetMapping(value = "/queryCompByOrgCodeAndLevel")
SysDepartModel queryCompByOrgCodeAndLevel(@RequestParam("orgCode") String orgCode, @RequestParam("level") Integer level){
return sysBaseApi.queryCompByOrgCodeAndLevel(orgCode,level);
}
/**
* 运行AIRag流程
* for [QQYUN-13634]在baseapi里面封装方法,方便其他模块调用
* @param airagFlowDTO
* @return 流程执行结果,可能是String或者Map
* @return
*/
@PostMapping(value = "/runAiragFlow")
Object runAiragFlow(@RequestBody AiragFlowDTO airagFlowDTO) {
return sysBaseApi.runAiragFlow(airagFlowDTO);
}
/**
* 根据部门code或部门id获取部门名称(当前和上级部门)
*
* @param orgCode 部门编码
* @param depId 部门id
* @return String 部门名称 | */
@GetMapping(value = "/getDepartPathNameByOrgCode")
String getDepartPathNameByOrgCode(@RequestParam(name = "orgCode", required = false) String orgCode, @RequestParam(name = "depId", required = false) String depId) {
return sysBaseApi.getDepartPathNameByOrgCode(orgCode, depId);
}
/**
* 根据部门ID查询用户ID
* @param deptIds
* @return
*/
@GetMapping("/queryUserIdsByCascadeDeptIds")
public List<String> queryUserIdsByCascadeDeptIds(@RequestParam("deptIds") List<String> deptIds){
return sysBaseApi.queryUserIdsByCascadeDeptIds(deptIds);
}
/**
* 推送uniapp 消息
* @param pushMessageDTO
* @return
*/
@PostMapping("/uniPushMsgToUser")
public void uniPushMsgToUser(@RequestBody PushMessageDTO pushMessageDTO){
sysBaseApi.uniPushMsgToUser(pushMessageDTO);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\api\controller\SystemApiController.java | 2 |
请完成以下Java代码 | public List<EventSubscriptionDto> queryEventSubscriptions(EventSubscriptionQueryDto queryDto, Integer firstResult, Integer maxResults) {
ProcessEngine engine = getProcessEngine();
queryDto.setObjectMapper(getObjectMapper());
EventSubscriptionQuery query = queryDto.toQuery(engine);
List<EventSubscription> matchingEventSubscriptions = QueryUtil.list(query, firstResult, maxResults);
List<EventSubscriptionDto> eventSubscriptionResults = new ArrayList<EventSubscriptionDto>();
for (EventSubscription eventSubscription : matchingEventSubscriptions) {
EventSubscriptionDto resultEventSubscription = EventSubscriptionDto.fromEventSubscription(eventSubscription);
eventSubscriptionResults.add(resultEventSubscription);
}
return eventSubscriptionResults;
}
@Override
public CountResultDto getEventSubscriptionsCount(UriInfo uriInfo) {
EventSubscriptionQueryDto queryDto = new EventSubscriptionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); | return queryEventSubscriptionsCount(queryDto);
}
public CountResultDto queryEventSubscriptionsCount(EventSubscriptionQueryDto queryDto) {
ProcessEngine engine = getProcessEngine();
queryDto.setObjectMapper(getObjectMapper());
EventSubscriptionQuery query = queryDto.toQuery(engine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\EventSubscriptionRestServiceImpl.java | 1 |
请完成以下Java代码 | public void updateEffectiveValues(final I_M_ShipmentSchedule shipmentSchedule)
{
if (shipmentSchedule.getC_OrderLine_ID() > 0)
{
huShipmentScheduleBL.updateHURelatedValuesFromOrderLine(shipmentSchedule);
}
huShipmentScheduleBL.updateEffectiveValues(shipmentSchedule);
if (shipmentSchedule.getC_OrderLine_ID() > 0)
{
// update orderLine
final I_C_OrderLine orderLine = InterfaceWrapperHelper.create(shipmentSchedule.getC_OrderLine(), I_C_OrderLine.class);
// task 09005: make sure the correct qtyOrdered is taken from the shipmentSchedule
final BigDecimal qtyOrderedEffective = shipmentScheduleEffectiveBL.computeQtyOrdered(shipmentSchedule);
orderLine.setQtyOrdered(qtyOrderedEffective);
InterfaceWrapperHelper.save(orderLine);
}
}
/**
* Note: it's important that the schedule is only invalidated on certain value changes.<br>
* For example, a change of lock status or valid status may not cause an invalidation.<br>
*/
@ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE, //
ifColumnsChanged = {
I_M_ShipmentSchedule.COLUMNNAME_QtyOrdered_Override,
I_M_ShipmentSchedule.COLUMNNAME_QtyTU_Calculated,
I_M_ShipmentSchedule.COLUMNNAME_QtyTU_Override,
I_M_ShipmentSchedule.COLUMNNAME_QtyOrdered_Calculated, | I_M_ShipmentSchedule.COLUMNNAME_M_HU_PI_Item_Product_Override_ID,
I_M_ShipmentSchedule.COLUMNNAME_M_HU_PI_Item_Product_ID,
I_M_ShipmentSchedule.COLUMNNAME_M_HU_PI_Item_Product_Calculated_ID,
I_M_ShipmentSchedule.COLUMNNAME_QtyOrdered
})
public void invalidate(final I_M_ShipmentSchedule shipmentSchedule)
{
// If shipment schedule updater is currently running in this thread, it means that updater changed this record so there is NO need to invalidate it again.
if (shipmentScheduleUpdater.isRunning())
{
return;
}
if (shipmentScheduleBL.isDoNotInvalidateOnChange(shipmentSchedule))
{
return;
}
invalidSchedulesService.notifySegmentChangedForShipmentScheduleInclSched(shipmentSchedule); // 08746: make sure that at any rate, the schedule itself is invalidated, even if it has delivery
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\M_ShipmentSchedule.java | 1 |
请完成以下Java代码 | private PayPalOrder updateFromAPIOrderAndSave(
@NonNull final I_PayPal_Order record,
@NonNull final com.paypal.orders.Order apiOrder)
{
PayPalOrder order = toPayPalOrder(record);
order = updateFromAPIOrder(order, apiOrder);
updateRecord(record, order);
saveRecord(record);
order = order.withId(PayPalOrderId.ofRepoId(record.getPayPal_Order_ID()));
return order;
}
private static PayPalOrderAuthorizationId extractAuthorizationIdOrNull(@NonNull final com.paypal.orders.Order apiOrder)
{
final List<PurchaseUnit> purchaseUnits = apiOrder.purchaseUnits();
if (purchaseUnits == null || purchaseUnits.isEmpty())
{
return null;
}
final PaymentCollection payments = purchaseUnits.get(0).payments();
if (payments == null)
{
return null;
}
final List<Authorization> authorizations = payments.authorizations();
if (authorizations == null || authorizations.isEmpty())
{
return null;
}
return PayPalOrderAuthorizationId.ofString(authorizations.get(0).id());
}
private static String extractApproveUrlOrNull(@NonNull final com.paypal.orders.Order apiOrder)
{
return extractUrlOrNull(apiOrder, "approve");
}
private static String extractUrlOrNull(@NonNull final com.paypal.orders.Order apiOrder, @NonNull final String rel)
{
for (final LinkDescription link : apiOrder.links())
{ | if (rel.contentEquals(link.rel()))
{
return link.href();
}
}
return null;
}
private static String toJson(final com.paypal.orders.Order apiOrder)
{
if (apiOrder == null)
{
return "";
}
try
{
// IMPORTANT: we shall use paypal's JSON serializer, else we won't get any result
return new com.braintreepayments.http.serializer.Json().serialize(apiOrder);
}
catch (final Exception ex)
{
logger.warn("Failed converting {} to JSON. Returning toString()", apiOrder, ex);
return apiOrder.toString();
}
}
public PayPalOrder markRemoteDeleted(@NonNull final PayPalOrderId id)
{
final I_PayPal_Order existingRecord = getRecordById(id);
final PayPalOrder order = toPayPalOrder(existingRecord)
.toBuilder()
.status(PayPalOrderStatus.REMOTE_DELETED)
.build();
updateRecord(existingRecord, order);
saveRecord(existingRecord);
return order;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\client\PayPalOrderRepository.java | 1 |
请完成以下Java代码 | public String getDisplayName()
{
return displayName;
}
public void setDisplayName(final String displayName)
{
this.displayName = displayName;
}
@Override
public boolean isEditable()
{
return editable;
}
public void setEditable(final boolean editable)
{
if (this.editable == editable)
{
return;
}
final boolean editableOld = this.editable;
this.editable = editable;
pcs.firePropertyChange(PROPERTY_Editable, editableOld, editable);
}
public boolean isVisible()
{
return visible;
}
public void setVisible(boolean visible)
{
if (this.visible == visible)
{
return;
}
final boolean visibleOld = this.visible;
this.visible = visible;
pcs.firePropertyChange(PROPERTY_Visible, visibleOld, visible);
}
@Override
public Method getReadMethod()
{
return readMethod;
}
@Override
public Method getWriteMethod()
{
return writeMethod;
}
void setWriteMethod(final Method writeMethod)
{
this.writeMethod = writeMethod;
}
void setSeqNo(final int seqNo)
{
this.seqNo = seqNo;
}
@Override
public int getSeqNo()
{ | return seqNo;
}
@Override
public String getLookupTableName()
{
return lookupTableName;
}
void setLookupTableName(final String lookupTableName)
{
this.lookupTableName = lookupTableName;
}
@Override
public String getLookupColumnName()
{
return lookupColumnName;
}
void setLookupColumnName(final String lookupColumnName)
{
this.lookupColumnName = lookupColumnName;
}
@Override
public String getPrototypeValue()
{
return prototypeValue;
}
void setPrototypeValue(final String prototypeValue)
{
this.prototypeValue = prototypeValue;
}
public int getDisplayType(final int defaultDisplayType)
{
return displayType > 0 ? displayType : defaultDisplayType;
}
public int getDisplayType()
{
return displayType;
}
void setDisplayType(int displayType)
{
this.displayType = displayType;
}
public boolean isSelectionColumn()
{
return selectionColumn;
}
public void setSelectionColumn(boolean selectionColumn)
{
this.selectionColumn = selectionColumn;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\swing\table\TableColumnInfo.java | 1 |
请完成以下Java代码 | public <D> List<D> toEntityList(Class<D> elementType) {
List<D> list = toEntity(ResolvableType.forClassWithGenerics(List.class, elementType));
return (list != null) ? list : Collections.emptyList();
}
@Override
public <D> List<D> toEntityList(ParameterizedTypeReference<D> elementType) {
List<D> list = toEntity(ResolvableType.forClassWithGenerics(List.class, ResolvableType.forType(elementType)));
return (list != null) ? list : Collections.emptyList();
}
@SuppressWarnings("unchecked")
private @Nullable <T> T toEntity(ResolvableType targetType) {
if (getValue() == null) {
if (this.response.isValid() && getErrors().isEmpty()) {
return null;
}
throw new FieldAccessException(this.response.getRequest(), this.response, this);
} | DataBufferFactory bufferFactory = DefaultDataBufferFactory.sharedInstance;
MimeType mimeType = MimeTypeUtils.APPLICATION_JSON;
Map<String, Object> hints = Collections.emptyMap();
try {
DataBuffer buffer = ((Encoder<T>) this.response.getEncoder()).encodeValue(
(T) getValue(), bufferFactory, ResolvableType.forInstance(getValue()), mimeType, hints);
return ((Decoder<T>) this.response.getDecoder()).decode(buffer, targetType, mimeType, hints);
}
catch (Throwable ex) {
throw new GraphQlClientException("Cannot read field '" + this.field.getPath() + "'", ex, this.response.getRequest());
}
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\DefaultClientResponseField.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public JsonWeeklyReport getWeeklyReport(
@PathVariable("weekYear") @NonNull final String weekYearStr,
@PathVariable("productId") final long productId)
{
final YearWeek yearWeek = YearWeekUtil.parse(weekYearStr);
return getWeeklyReport(yearWeek, productId);
}
private JsonWeeklyReport getWeeklyReport(
@NonNull final YearWeek yearWeek,
final long singleProductId)
{
final User user = loginService.getLoggedInUser();
return JsonWeeklyReportProducer.builder()
.productSuppliesService(productSuppliesService)
.userConfirmationService(userConfirmationService)
.user(user)
.locale(loginService.getLocale())
.week(yearWeek)
.singleProductId(singleProductId)
.build()
.execute();
} | @PostMapping("/nextWeekTrend")
public JsonSetNextWeekTrendResponse setNextWeekTrend(@RequestBody @NonNull final JsonSetNextWeekTrendRequest request)
{
final User user = loginService.getLoggedInUser();
final Product product = productSuppliesService.getProductById(Long.parseLong(request.getProductId()));
final YearWeek week = YearWeekUtil.parse(request.getWeek());
final @NonNull Trend trend = request.getTrend();
final WeekSupply weeklyForecast = productSuppliesService.setNextWeekTrend(
user.getBpartner(),
product,
week,
trend);
return JsonSetNextWeekTrendResponse.builder()
.productId(weeklyForecast.getProductIdAsString())
.week(YearWeekUtil.toJsonString(weeklyForecast.getWeek()))
.trend(weeklyForecast.getTrend())
.build();
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\rest\weeklyReport\WeeklyReportRestController.java | 2 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email; | }
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Employee employee = (Employee) o;
return Objects.equals(id, employee.id) && Objects.equals(firstName, employee.firstName) && Objects.equals(lastName, employee.lastName) && Objects.equals(email, employee.email);
}
@Override
public int hashCode() {
return Objects.hash(id, firstName, lastName, email);
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-repo-2\src\main\java\com\baeldung\spring\data\persistence\springdatajpadifference\model\Employee.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.