instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public final class SecurityObservationSettings {
private final boolean observeRequests;
private final boolean observeAuthentications;
private final boolean observeAuthorizations;
private SecurityObservationSettings(boolean observeRequests, boolean observeAuthentications,
boolean observeAuthorizations) {
this.observeRequests = observeRequests;
this.observeAuthentications = observeAuthentications;
this.observeAuthorizations = observeAuthorizations;
}
/**
* Make no Spring Security observations
* @return a {@link SecurityObservationSettings} with all exclusions turned on
*/
public static SecurityObservationSettings noObservations() {
return new SecurityObservationSettings(false, false, false);
}
/**
* Begin the configuration of a {@link SecurityObservationSettings}
* @return a {@link Builder} where filter chain observations are off and authn/authz
* observations are on
*/
public static Builder withDefaults() {
return new Builder(false, true, true);
}
public boolean shouldObserveRequests() {
return this.observeRequests;
}
public boolean shouldObserveAuthentications() {
return this.observeAuthentications;
}
public boolean shouldObserveAuthorizations() {
return this.observeAuthorizations;
}
/**
* A builder for configuring a {@link SecurityObservationSettings}
*/
public static final class Builder {
private boolean observeRequests;
private boolean observeAuthentications;
private boolean observeAuthorizations;
Builder(boolean observeRequests, boolean observeAuthentications, boolean observeAuthorizations) {
|
this.observeRequests = observeRequests;
this.observeAuthentications = observeAuthentications;
this.observeAuthorizations = observeAuthorizations;
}
public Builder shouldObserveRequests(boolean excludeFilters) {
this.observeRequests = excludeFilters;
return this;
}
public Builder shouldObserveAuthentications(boolean excludeAuthentications) {
this.observeAuthentications = excludeAuthentications;
return this;
}
public Builder shouldObserveAuthorizations(boolean excludeAuthorizations) {
this.observeAuthorizations = excludeAuthorizations;
return this;
}
public SecurityObservationSettings build() {
return new SecurityObservationSettings(this.observeRequests, this.observeAuthentications,
this.observeAuthorizations);
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\observation\SecurityObservationSettings.java
| 2
|
请完成以下Java代码
|
public boolean isCanExport ()
{
Object oo = get_Value(COLUMNNAME_IsCanExport);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Kann Berichte erstellen.
@param IsCanReport
Users with this role can create reports
*/
@Override
public void setIsCanReport (boolean IsCanReport)
{
set_Value (COLUMNNAME_IsCanReport, Boolean.valueOf(IsCanReport));
}
/** Get Kann Berichte erstellen.
@return Users with this role can create reports
*/
@Override
public boolean isCanReport ()
{
Object oo = get_Value(COLUMNNAME_IsCanReport);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Ausschluß.
@param IsExclude
Exclude access to the data - if not selected Include access to the data
*/
@Override
public void setIsExclude (boolean IsExclude)
{
set_Value (COLUMNNAME_IsExclude, Boolean.valueOf(IsExclude));
}
/** Get Ausschluß.
@return Exclude access to the data - if not selected Include access to the data
*/
|
@Override
public boolean isExclude ()
{
Object oo = get_Value(COLUMNNAME_IsExclude);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Schreibgeschützt.
@param IsReadOnly
Field is read only
*/
@Override
public void setIsReadOnly (boolean IsReadOnly)
{
set_Value (COLUMNNAME_IsReadOnly, Boolean.valueOf(IsReadOnly));
}
/** Get Schreibgeschützt.
@return Field is read only
*/
@Override
public boolean isReadOnly ()
{
Object oo = get_Value(COLUMNNAME_IsReadOnly);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Table_Access.java
| 1
|
请完成以下Java代码
|
private static boolean isEligible(@Nullable final I_PP_Order ppOrder)
{
if (ppOrder == null)
{
return false;
}
final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(ppOrder.getDocStatus());
return docStatus.isDraftedOrInProgress();
}
@Override
protected String doIt()
{
final PPOrderId ppOrderId = getPPOrderId(getRecord_ID());
final OrderLineId orderLineId = getOrderLienId();
setC_OrderLine_ID(ppOrderId, orderLineId);
|
return MSG_OK;
}
private PPOrderId getPPOrderId(int ppOrderId)
{
return PPOrderId.ofRepoId(ppOrderId);
}
private OrderLineId getOrderLienId()
{
return OrderLineId.ofRepoId(p_C_OrderLine_ID);
}
private void setC_OrderLine_ID(@NonNull final PPOrderId ppOrderId, @NonNull final OrderLineId orderLineId)
{
ppOrderBL.setC_OrderLine(ppOrderId, orderLineId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\PP_Order_SetC_OrderLine.java
| 1
|
请完成以下Java代码
|
public Set<Map.Entry<String, Object>> entrySet() {
Set<Map.Entry<String, Object>> entries = new HashSet<>();
for (String key : inputVariableContainer.getVariableNames()) {
entries.add(Pair.of(key, inputVariableContainer.getVariable(key)));
}
return entries;
}
@Override
public Set<String> keySet() {
return inputVariableContainer.getVariableNames();
}
@Override
public int size() {
return inputVariableContainer.getVariableNames().size();
}
@Override
public Collection<Object> values() {
Set<String> variableNames = inputVariableContainer.getVariableNames();
List<Object> values = new ArrayList<>(variableNames.size());
for (String key : variableNames) {
values.add(inputVariableContainer.getVariable(key));
}
return values;
}
@Override
public void putAll(Map<? extends String, ? extends Object> toMerge) {
throw new UnsupportedOperationException();
}
@Override
public Object remove(Object key) {
if (UNSTORED_KEYS.contains(key)) {
return null;
}
return defaultBindings.remove(key);
}
|
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public boolean containsValue(Object value) {
throw new UnsupportedOperationException();
}
@Override
public boolean isEmpty() {
throw new UnsupportedOperationException();
}
public void addUnstoredKey(String unstoredKey) {
UNSTORED_KEYS.add(unstoredKey);
}
protected Map<String, Object> getVariables() {
if (this.scopeContainer instanceof VariableScope) {
return ((VariableScope) this.scopeContainer).getVariables();
}
return Collections.emptyMap();
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\scripting\ScriptBindings.java
| 1
|
请完成以下Java代码
|
private ReportResult printLabel()
{
final AdProcessId adProcessId = getLabelConfig()
.get()
.getPrintFormatProcessId();
final PInstanceRequest pinstanceRequest = createPInstanceRequest(adProcessId);
final PInstanceId pinstanceId = adPInstanceDAO.createADPinstanceAndADPInstancePara(pinstanceRequest);
final ProcessInfo jasperProcessInfo = ProcessInfo.builder()
.setCtx(getCtx())
.setProcessCalledFrom(ProcessCalledFrom.WebUI)
.setAD_Process_ID(adProcessId)
.setAD_PInstance(adPInstanceDAO.getById(pinstanceId))
.setReportLanguage(getProcessInfo().getReportLanguage())
.setJRDesiredOutputType(OutputType.PDF)
.build();
final ReportsClient reportsClient = ReportsClient.get();
return reportsClient.report(jasperProcessInfo);
|
}
private PInstanceRequest createPInstanceRequest(@NonNull final AdProcessId adProcessId)
{
return PInstanceRequest.builder()
.processId(adProcessId)
.processParams(ImmutableList.of(
ProcessInfoParameter.of("AD_PInstance_ID", getPinstanceId())))
.build();
}
private String buildFilename()
{
final String instance = String.valueOf(getPinstanceId().getRepoId());
final String title = getProcessInfo().getTitle();
return Joiner.on("_").skipNulls().join(instance, title) + ".pdf";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_PrintFinishedGoodsLabel.java
| 1
|
请完成以下Java代码
|
public String getSpringBootVersion() {
return this.springBootVersion;
}
public StartupTimeline getTimeline() {
return this.timeline;
}
}
static class StartupEndpointRuntimeHints implements RuntimeHintsRegistrar {
private static final TypeReference DEFAULT_TAG = TypeReference
.of("org.springframework.boot.context.metrics.buffering.BufferedStartupStep$DefaultTag");
private static final TypeReference BUFFERED_STARTUP_STEP = TypeReference
.of("org.springframework.boot.context.metrics.buffering.BufferedStartupStep");
private static final TypeReference FLIGHT_RECORDER_TAG = TypeReference
.of("org.springframework.core.metrics.jfr.FlightRecorderStartupStep$FlightRecorderTag");
|
private static final TypeReference FLIGHT_RECORDER_STARTUP_STEP = TypeReference
.of("org.springframework.core.metrics.jfr.FlightRecorderStartupStep");
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.reflection()
.registerType(DEFAULT_TAG, (typeHint) -> typeHint.onReachableType(BUFFERED_STARTUP_STEP)
.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS));
hints.reflection()
.registerType(FLIGHT_RECORDER_TAG, (typeHint) -> typeHint.onReachableType(FLIGHT_RECORDER_STARTUP_STEP)
.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS));
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\startup\StartupEndpoint.java
| 1
|
请完成以下Java代码
|
public void validate(BpmnModel bpmnModel, List<ValidationError> errors) {
if (!bpmnModel.getLocationMap().isEmpty()) {
// Location map
for (String bpmnReference : bpmnModel.getLocationMap().keySet()) {
if (bpmnModel.getFlowElement(bpmnReference) == null) {
// ACT-1625: don't warn when artifacts are referenced from
// DI
if (bpmnModel.getArtifact(bpmnReference) == null) {
// check if it's a Pool or Lane, then DI is ok
if (bpmnModel.getPool(bpmnReference) == null && bpmnModel.getLane(bpmnReference) == null) {
addWarning(errors, Problems.DI_INVALID_REFERENCE, null, bpmnModel.getFlowElement(bpmnReference), "Invalid reference in diagram interchange definition: could not find " + bpmnReference);
}
}
} else if (!(bpmnModel.getFlowElement(bpmnReference) instanceof FlowNode)) {
addWarning(errors, Problems.DI_DOES_NOT_REFERENCE_FLOWNODE, null, bpmnModel.getFlowElement(bpmnReference), "Invalid reference in diagram interchange definition: " + bpmnReference
+ " does not reference a flow node");
}
}
}
|
if (!bpmnModel.getFlowLocationMap().isEmpty()) {
// flowlocation map
for (String bpmnReference : bpmnModel.getFlowLocationMap().keySet()) {
if (bpmnModel.getFlowElement(bpmnReference) == null) {
// ACT-1625: don't warn when artifacts are referenced from
// DI
if (bpmnModel.getArtifact(bpmnReference) == null) {
addWarning(errors, Problems.DI_INVALID_REFERENCE, null, bpmnModel.getFlowElement(bpmnReference), "Invalid reference in diagram interchange definition: could not find " + bpmnReference);
}
} else if (!(bpmnModel.getFlowElement(bpmnReference) instanceof SequenceFlow)) {
addWarning(errors, Problems.DI_DOES_NOT_REFERENCE_SEQ_FLOW, null, bpmnModel.getFlowElement(bpmnReference), "Invalid reference in diagram interchange definition: " + bpmnReference
+ " does not reference a sequence flow");
}
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-process-validation\src\main\java\org\flowable\validation\validator\impl\DiagramInterchangeInfoValidator.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
LdapContextSource ldapContextSource(LdapConnectionDetails connectionDetails, LdapProperties properties,
ObjectProvider<DirContextAuthenticationStrategy> dirContextAuthenticationStrategy) {
LdapContextSource source = new LdapContextSource();
dirContextAuthenticationStrategy.ifUnique(source::setAuthenticationStrategy);
PropertyMapper propertyMapper = PropertyMapper.get();
propertyMapper.from(connectionDetails.getUsername()).to(source::setUserDn);
propertyMapper.from(connectionDetails.getPassword()).to(source::setPassword);
propertyMapper.from(properties.getAnonymousReadOnly()).to(source::setAnonymousReadOnly);
propertyMapper.from(properties.getReferral())
.as(((referral) -> referral.name().toLowerCase(Locale.ROOT)))
.to(source::setReferral);
propertyMapper.from(connectionDetails.getBase()).to(source::setBase);
propertyMapper.from(connectionDetails.getUrls()).to(source::setUrls);
propertyMapper.from(properties.getBaseEnvironment())
.to((baseEnvironment) -> source.setBaseEnvironmentProperties(Collections.unmodifiableMap(baseEnvironment)));
return source;
}
@Bean
@ConditionalOnMissingBean
ObjectDirectoryMapper objectDirectoryMapper() {
ApplicationConversionService conversionService = new ApplicationConversionService();
ConverterUtils.addDefaultConverters(conversionService);
DefaultObjectDirectoryMapper objectDirectoryMapper = new DefaultObjectDirectoryMapper();
objectDirectoryMapper.setConversionService(conversionService);
return objectDirectoryMapper;
}
@Bean
|
@ConditionalOnMissingBean(LdapOperations.class)
LdapTemplate ldapTemplate(LdapProperties properties, ContextSource contextSource,
ObjectDirectoryMapper objectDirectoryMapper) {
Template template = properties.getTemplate();
PropertyMapper propertyMapper = PropertyMapper.get();
LdapTemplate ldapTemplate = new LdapTemplate(contextSource);
ldapTemplate.setObjectDirectoryMapper(objectDirectoryMapper);
propertyMapper.from(template.isIgnorePartialResultException())
.to(ldapTemplate::setIgnorePartialResultException);
propertyMapper.from(template.isIgnoreNameNotFoundException()).to(ldapTemplate::setIgnoreNameNotFoundException);
propertyMapper.from(template.isIgnoreSizeLimitExceededException())
.to(ldapTemplate::setIgnoreSizeLimitExceededException);
return ldapTemplate;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-ldap\src\main\java\org\springframework\boot\ldap\autoconfigure\LdapAutoConfiguration.java
| 2
|
请完成以下Java代码
|
Constraint teacherTimeEfficiency(ConstraintFactory constraintFactory) {
// A teacher prefers to teach sequential lessons and dislikes gaps between lessons.
return constraintFactory
.forEach(Lesson.class)
.join(Lesson.class, Joiners.equal(Lesson::getTeacher),
Joiners.equal((lesson) -> lesson.getTimeslot().getDayOfWeek()))
.filter((lesson1, lesson2) -> {
Duration between = Duration.between(lesson1.getTimeslot().getEndTime(),
lesson2.getTimeslot().getStartTime());
return !between.isNegative() && between.compareTo(Duration.ofMinutes(30)) <= 0;
})
.reward(HardSoftScore.ONE_SOFT)
.justifyWith((lesson1, lesson2, score) -> new TeacherTimeEfficiencyJustification(lesson1.getTeacher(), lesson1, lesson2))
.asConstraint("Teacher time efficiency");
}
Constraint studentGroupSubjectVariety(ConstraintFactory constraintFactory) {
// A student group dislikes sequential lessons on the same subject.
return constraintFactory
.forEach(Lesson.class)
|
.join(Lesson.class,
Joiners.equal(Lesson::getSubject),
Joiners.equal(Lesson::getStudentGroup),
Joiners.equal((lesson) -> lesson.getTimeslot().getDayOfWeek()))
.filter((lesson1, lesson2) -> {
Duration between = Duration.between(lesson1.getTimeslot().getEndTime(),
lesson2.getTimeslot().getStartTime());
return !between.isNegative() && between.compareTo(Duration.ofMinutes(30)) <= 0;
})
.penalize(HardSoftScore.ONE_SOFT)
.justifyWith((lesson1, lesson2, score) -> new StudentGroupSubjectVarietyJustification(lesson1.getStudentGroup(), lesson1, lesson2))
.asConstraint("Student group subject variety");
}
}
|
repos\springboot-demo-master\Timefold Solver\src\main\java\org\acme\schooltimetabling\solver\TimetableConstraintProvider.java
| 1
|
请完成以下Java代码
|
public final class C_Order_CreateFromProposal extends C_Order_CreationProcess implements IProcessDefaultParametersProvider
{
private static final String PARAM_IsKeepProposalPrices = "IsKeepProposalPrices";
private static final String PARAM_DEFAULT_VALUE_YES = "Y";
private final IOrderBL orderBL = Services.get(IOrderBL.class);
private final IDocTypeBL docTypeBL = Services.get(IDocTypeBL.class);
@Param(parameterName = "C_DocType_ID", mandatory = true)
private DocTypeId newOrderDocTypeId;
@Param(parameterName = "DateOrdered")
private Timestamp newOrderDateOrdered;
@Param(parameterName = "POReference")
private String poReference;
@Param(parameterName = "CompleteIt")
private boolean completeIt;
@Param(parameterName = PARAM_IsKeepProposalPrices)
private boolean keepProposalPrices;
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull I_C_Order order)
{
final DocStatus quotationDocStatus = DocStatus.ofNullableCodeOrUnknown(order.getDocStatus());
if (!quotationDocStatus.isCompleted())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("not a completed quotation");
}
if (!orderBL.isSalesProposalOrQuotation(order))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("is not sales proposal or quotation");
}
return ProcessPreconditionsResolution.accept();
}
@Nullable
|
@Override
public Object getParameterDefaultValue(@NonNull final IProcessDefaultParameter parameter)
{
if (PARAM_IsKeepProposalPrices.contentEquals(parameter.getColumnName()))
{
final I_C_Order proposal = orderBL.getById(OrderId.ofRepoId(getRecord_ID()));
if (docTypeBL.isSalesQuotation(DocTypeId.ofRepoId(proposal.getC_DocType_ID())))
{
return PARAM_DEFAULT_VALUE_YES;
}
}
return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE;
}
@Override
protected String doIt()
{
final I_C_Order newSalesOrder = CreateSalesOrderFromProposalCommand.builder()
.fromProposalId(OrderId.ofRepoId(getRecord_ID()))
.newOrderDocTypeId(newOrderDocTypeId)
.newOrderDateOrdered(newOrderDateOrdered)
.poReference(poReference)
.completeIt(completeIt)
.isKeepProposalPrices(keepProposalPrices)
.build()
.execute();
openOrder(newSalesOrder);
return newSalesOrder.getDocumentNo();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\process\C_Order_CreateFromProposal.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_CostClassification_Category_ID (final int C_CostClassification_Category_ID)
{
if (C_CostClassification_Category_ID < 1)
set_Value (COLUMNNAME_C_CostClassification_Category_ID, null);
else
set_Value (COLUMNNAME_C_CostClassification_Category_ID, C_CostClassification_Category_ID);
}
@Override
public int getC_CostClassification_Category_ID()
{
return get_ValueAsInt(COLUMNNAME_C_CostClassification_Category_ID);
}
@Override
public void setC_CostClassification_ID (final int C_CostClassification_ID)
{
if (C_CostClassification_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_CostClassification_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_CostClassification_ID, C_CostClassification_ID);
}
@Override
public int getC_CostClassification_ID()
{
return get_ValueAsInt(COLUMNNAME_C_CostClassification_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
|
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setValue (final @Nullable 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_C_CostClassification.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setContent(String content) {
this.content = content;
}
public UserEntity getUserEntity() {
return userEntity;
}
public void setUserEntity(UserEntity userEntity) {
this.userEntity = userEntity;
}
public List<CommentEntity> getCommentEntityList() {
return commentEntityList;
}
|
public void setCommentEntityList(List<CommentEntity> commentEntityList) {
this.commentEntityList = commentEntityList;
}
@Override
public String toString() {
return "ArticleEntity{" +
"id='" + id + '\'' +
", title='" + title + '\'' +
", content='" + content + '\'' +
", userEntity=" + userEntity +
", commentEntityList=" + commentEntityList +
'}';
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\user\ArticleEntity.java
| 2
|
请完成以下Java代码
|
public String getDefaultThemeName() {
return defaultThemeName;
}
public void setDefaultThemeName(String defaultThemeName) {
this.defaultThemeName = defaultThemeName;
}
@Override
public String resolveThemeName(HttpServletRequest request) {
String themeName = findThemeFromRequest(request).orElse(findUserPreferredTheme().orElse(getDefaultThemeName()));
request.setAttribute(THEME_REQUEST_ATTRIBUTE_NAME, themeName);
return themeName;
}
private Optional<String> findUserPreferredTheme() {
Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
UserPreference userPreference = getUserPreference(authentication).orElse(new UserPreference());
return Optional.ofNullable(userPreference.getTheme());
}
private Optional<String> findThemeFromRequest(HttpServletRequest request) {
return Optional.ofNullable((String) request.getAttribute(THEME_REQUEST_ATTRIBUTE_NAME));
}
|
private Optional<UserPreference> getUserPreference(Authentication authentication) {
return isAuthenticated(authentication) ? userPreferenceRepository.findById(((User) authentication.getPrincipal()).getUsername()) : Optional.empty();
}
private boolean isAuthenticated(Authentication authentication) {
return authentication != null && authentication.isAuthenticated();
}
@Override
public void setThemeName(HttpServletRequest request, HttpServletResponse response, String theme) {
Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
if (isAuthenticated(authentication)) {
request.setAttribute(THEME_REQUEST_ATTRIBUTE_NAME, theme);
UserPreference userPreference = getUserPreference(authentication).orElse(new UserPreference());
userPreference.setUsername(((User) authentication.getPrincipal()).getUsername());
userPreference.setTheme(StringUtils.hasText(theme) ? theme : null);
userPreferenceRepository.save(userPreference);
}
}
}
|
repos\tutorials-master\spring-web-modules\spring-mvc-views\src\main\java\com\baeldung\themes\resolver\UserPreferenceThemeResolver.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Result upload(@RequestParam("file") MultipartFile multipartFile) {
Result result = new Result();
try {
ossFileService.upload(multipartFile);
result.success("上传成功!");
}
catch (Exception ex) {
log.info(ex.getMessage(), ex);
result.error500("上传失败");
}
return result;
}
@ResponseBody
@DeleteMapping("/delete")
public Result delete(@RequestParam(name = "id") String id) {
Result result = new Result();
OssFile file = ossFileService.getById(id);
if (file == null) {
result.error500("未找到对应实体");
}else {
boolean ok = ossFileService.delete(file);
result.success("删除成功!");
}
return result;
}
/**
* 通过id查询.
|
*/
@ResponseBody
@GetMapping("/queryById")
public Result<OssFile> queryById(@RequestParam(name = "id") String id) {
Result<OssFile> result = new Result<>();
OssFile file = ossFileService.getById(id);
if (file == null) {
result.error500("未找到对应实体");
}
else {
result.setResult(file);
result.setSuccess(true);
}
return result;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\oss\controller\OssFileController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public UserDetailsService userDetailService(DataSource dataSource) {
var user = User.withUsername("in28minutes")
//.password("{noop}dummy")
.password("dummy")
.passwordEncoder(str -> passwordEncoder().encode(str))
.roles("USER")
.build();
var admin = User.withUsername("admin")
//.password("{noop}dummy")
.password("dummy")
.passwordEncoder(str -> passwordEncoder().encode(str))
.roles("ADMIN", "USER")
.build();
var jdbcUserDetailsManager = new JdbcUserDetailsManager(dataSource);
jdbcUserDetailsManager.createUser(user);
jdbcUserDetailsManager.createUser(admin);
return jdbcUserDetailsManager;
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public KeyPair keyPair() {
try {
var keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
return keyPairGenerator.generateKeyPair();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@Bean
public RSAKey rsaKey(KeyPair keyPair) {
|
return new RSAKey
.Builder((RSAPublicKey)keyPair.getPublic())
.privateKey(keyPair.getPrivate())
.keyID(UUID.randomUUID().toString())
.build();
}
@Bean
public JWKSource<SecurityContext> jwkSource(RSAKey rsaKey) {
var jwkSet = new JWKSet(rsaKey);
return (jwkSelector, context) -> jwkSelector.select(jwkSet);
}
@Bean
public JwtDecoder jwtDecoder(RSAKey rsaKey) throws JOSEException {
return NimbusJwtDecoder
.withPublicKey(rsaKey.toRSAPublicKey())
.build();
}
@Bean
public JwtEncoder jwtEncoder(JWKSource<SecurityContext> jwkSource) {
return new NimbusJwtEncoder(jwkSource);
}
}
|
repos\master-spring-and-spring-boot-main\71-spring-security\src\main\java\com\in28minutes\learnspringsecurity\jwt\JwtSecurityConfiguration.java
| 2
|
请完成以下Java代码
|
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Price.
@param Price
Price
*/
public void setPrice (BigDecimal Price)
{
set_Value (COLUMNNAME_Price, Price);
}
/** Get Price.
@return Price
*/
public BigDecimal getPrice ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Price);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Product.
@param Product Product */
public void setProduct (String Product)
{
set_Value (COLUMNNAME_Product, Product);
}
/** Get Product.
@return Product */
public String getProduct ()
{
return (String)get_Value(COLUMNNAME_Product);
}
/** Set Quantity.
@param Qty
Quantity
*/
public void setQty (BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Quantity.
@return Quantity
*/
public BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
|
return bd;
}
public I_W_Basket getW_Basket() throws RuntimeException
{
return (I_W_Basket)MTable.get(getCtx(), I_W_Basket.Table_Name)
.getPO(getW_Basket_ID(), get_TrxName()); }
/** Set W_Basket_ID.
@param W_Basket_ID
Web Basket
*/
public void setW_Basket_ID (int W_Basket_ID)
{
if (W_Basket_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_Basket_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_Basket_ID, Integer.valueOf(W_Basket_ID));
}
/** Get W_Basket_ID.
@return Web Basket
*/
public int getW_Basket_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_Basket_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Basket Line.
@param W_BasketLine_ID
Web Basket Line
*/
public void setW_BasketLine_ID (int W_BasketLine_ID)
{
if (W_BasketLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_BasketLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_BasketLine_ID, Integer.valueOf(W_BasketLine_ID));
}
/** Get Basket Line.
@return Web Basket Line
*/
public int getW_BasketLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_BasketLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_BasketLine.java
| 1
|
请完成以下Java代码
|
public class DeleteHistoricDecisionInstancesDto {
protected List<String> historicDecisionInstanceIds;
protected HistoricDecisionInstanceQueryDto historicDecisionInstanceQuery;
protected String deleteReason;
public List<String> getHistoricDecisionInstanceIds() {
return historicDecisionInstanceIds;
}
public void setHistoricDecisionInstanceIds(List<String> historicDecisionInstanceIds) {
this.historicDecisionInstanceIds = historicDecisionInstanceIds;
}
public HistoricDecisionInstanceQueryDto getHistoricDecisionInstanceQuery() {
|
return historicDecisionInstanceQuery;
}
public void setHistoricDecisionInstanceQuery(HistoricDecisionInstanceQueryDto historicDecisionInstanceQuery) {
this.historicDecisionInstanceQuery = historicDecisionInstanceQuery;
}
public String getDeleteReason() {
return deleteReason;
}
public void setDeleteReason(String deleteReason) {
this.deleteReason = deleteReason;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\batch\DeleteHistoricDecisionInstancesDto.java
| 1
|
请完成以下Java代码
|
public List<Book> getBookList() {
return bookService.findAll();
}
/**
* 获取 Book
* 处理 "/book/{id}" 的 GET 请求,用来获取 Book 信息
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Book getBook(@PathVariable Long id) {
return bookService.findById(id);
}
/**
* 创建 Book
* 处理 "/book/create" 的 POST 请求,用来新建 Book 信息
* 通过 @RequestBody 绑定实体参数,也通过 @RequestParam 传递参数
*/
@RequestMapping(value = "/create", method = RequestMethod.POST)
public ResponseEntity<Void> postBook(@RequestBody Book book, UriComponentsBuilder ucBuilder) {
LOG.info("creating new book: {}", book);
if (book.getName().equals("conflict")){
LOG.info("a book with name " + book.getName() + " already exists");
return new ResponseEntity<>(HttpStatus.CONFLICT);
}
bookService.insertByBook(book);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/book/{id}").buildAndExpand(book.getId()).toUri());
return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
|
/**
* 更新 Book
* 处理 "/update" 的 PUT 请求,用来更新 Book 信息
*/
@RequestMapping(value = "/update", method = RequestMethod.PUT)
public Book putBook(@RequestBody Book book) {
return bookService.update(book);
}
/**
* 删除 Book
* 处理 "/book/{id}" 的 GET 请求,用来删除 Book 信息
*/
@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
public Book deleteBook(@PathVariable Long id) {
return bookService.delete(id);
}
}
|
repos\springboot-learning-example-master\chapter-3-spring-boot-web\src\main\java\demo\springboot\web\BookController.java
| 1
|
请完成以下Java代码
|
public void updateProductDocumentNote(final I_C_OrderLine orderLine)
{
orderLineBL.updateProductDocumentNote(orderLine);
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE },
ifColumnsChanged = { I_C_OrderLine.COLUMNNAME_IsGroupCompensationLine, I_C_OrderLine.COLUMNNAME_C_Order_CompensationGroup_ID })
public void renumberLinesIfCompensationGroupChanged(@NonNull final I_C_OrderLine orderLine)
{
if (!OrderGroupCompensationUtils.isInGroup(orderLine))
{
return;
}
groupChangesHandler.renumberOrderLinesForOrderId(OrderId.ofRepoId(orderLine.getC_Order_ID()));
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_AFTER_DELETE },
ifColumnsChanged = { I_C_OrderLine.COLUMNNAME_M_Product_ID, I_C_OrderLine.COLUMNNAME_QtyOrdered })
public void updateWeight(@NonNull final I_C_OrderLine orderLine)
{
final I_C_Order order = orderBL.getById(OrderId.ofRepoId(orderLine.getC_Order_ID()));
orderBL.setWeightFromLines(order);
saveRecord(order);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, //
ifColumnsChanged = { I_C_OrderLine.COLUMNNAME_IsWithoutCharge, I_C_OrderLine.COLUMNNAME_PriceActual, I_C_OrderLine.COLUMNNAME_PriceEntered })
public void updatePriceToZero(final I_C_OrderLine orderLine)
{
if (orderLine.isWithoutCharge())
{
orderLine.setPriceActual(BigDecimal.ZERO);
orderLine.setPriceEntered(BigDecimal.ZERO);
orderLine.setIsManualPrice(true);
final IOrderLineBL orderLineBL = Services.get(IOrderLineBL.class);
|
orderLineBL.updateLineNetAmtFromQtyEntered(orderLine);
}
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE }, //
ifColumnsChanged = { I_C_OrderLine.COLUMNNAME_IsWithoutCharge})
public void updatePriceToStd(final I_C_OrderLine orderLine)
{
if (!orderLine.isWithoutCharge())
{
orderLine.setPriceActual(orderLine.getPriceStd());
orderLine.setPriceEntered(orderLine.getPriceStd());
orderLine.setIsManualPrice(false);
final IOrderLineBL orderLineBL = Services.get(IOrderLineBL.class);
orderLineBL.updateLineNetAmtFromQtyEntered(orderLine);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\model\interceptor\C_OrderLine.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public DocOutboundConfig getByQuery(@NonNull final DocOutboundConfigQuery query)
{
return getDocOutboundConfigMap().getByQuery(query);
}
@NonNull
private DocOutboundConfigMap getDocOutboundConfigMap()
{
return cache.getOrLoadNonNull(0, this::retrieveDocOutboundConfigMap);
}
@NotNull
private DocOutboundConfigMap retrieveDocOutboundConfigMap()
{
final ImmutableList<DocOutboundConfig> docOutboundConfig = queryBL.createQueryBuilder(I_C_Doc_Outbound_Config.class)
.addOnlyActiveRecordsFilter()
.create()
.stream()
.map(DocOutboundConfigRepository::ofRecord)
.collect(ImmutableList.toImmutableList());
return new DocOutboundConfigMap(docOutboundConfig);
}
private static DocOutboundConfig ofRecord(@NotNull final I_C_Doc_Outbound_Config record)
|
{
return DocOutboundConfig.builder()
.id(DocOutboundConfigId.ofRepoId(record.getC_Doc_Outbound_Config_ID()))
.tableId(AdTableId.ofRepoId(record.getAD_Table_ID()))
.docBaseType(DocBaseType.ofNullableCode(record.getDocBaseType()))
.printFormatId(PrintFormatId.ofRepoIdOrNull(record.getAD_PrintFormat_ID()))
.ccPath(record.getCCPath())
.isDirectProcessQueueItem(record.isDirectProcessQueueItem())
.isDirectEnqueue(record.isDirectEnqueue())
.isAutoSendDocument(record.isAutoSendDocument())
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.build();
}
@NonNull
public ImmutableSet<AdTableId> getDistinctConfigTableIds()
{
return getDocOutboundConfigMap().getTableIds();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\config\DocOutboundConfigRepository.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getTRANPORTTERMSCODE() {
return tranporttermscode;
}
/**
* Sets the value of the tranporttermscode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTRANPORTTERMSCODE(String value) {
this.tranporttermscode = value;
}
/**
* Gets the value of the tranporttermsdesc property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTRANPORTTERMSDESC() {
return tranporttermsdesc;
}
/**
* Sets the value of the tranporttermsdesc property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTRANPORTTERMSDESC(String value) {
this.tranporttermsdesc = value;
}
/**
* Gets the value of the locationqual property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLOCATIONQUAL() {
return locationqual;
}
/**
* Sets the value of the locationqual property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLOCATIONQUAL(String value) {
this.locationqual = value;
}
/**
* Gets the value of the locationcode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLOCATIONCODE() {
return locationcode;
}
/**
* Sets the value of the locationcode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLOCATIONCODE(String value) {
this.locationcode = value;
}
/**
* Gets the value of the locationname property.
|
*
* @return
* possible object is
* {@link String }
*
*/
public String getLOCATIONNAME() {
return locationname;
}
/**
* Sets the value of the locationname property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLOCATIONNAME(String value) {
this.locationname = value;
}
/**
* Gets the value of the locationdate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLOCATIONDATE() {
return locationdate;
}
/**
* Sets the value of the locationdate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLOCATIONDATE(String value) {
this.locationdate = 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\HTRSC1.java
| 2
|
请完成以下Java代码
|
public final class AuthorizationServerContextHolder {
private static final ThreadLocal<AuthorizationServerContext> holder = new ThreadLocal<>();
private AuthorizationServerContextHolder() {
}
/**
* Returns the {@link AuthorizationServerContext} bound to the current thread.
* @return the {@link AuthorizationServerContext}
*/
public static AuthorizationServerContext getContext() {
return holder.get();
}
/**
* Bind the given {@link AuthorizationServerContext} to the current thread.
* @param authorizationServerContext the {@link AuthorizationServerContext}
*/
public static void setContext(AuthorizationServerContext authorizationServerContext) {
if (authorizationServerContext == null) {
|
resetContext();
}
else {
holder.set(authorizationServerContext);
}
}
/**
* Reset the {@link AuthorizationServerContext} bound to the current thread.
*/
public static void resetContext() {
holder.remove();
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\context\AuthorizationServerContextHolder.java
| 1
|
请完成以下Java代码
|
public final class ValueNamePairList
{
@JsonCreator
public static final ValueNamePairList of(@JsonProperty("l") final List<ValueNamePair> values)
{
if (values == null || values.isEmpty())
{
return EMPTY;
}
return new ValueNamePairList(values);
}
public static final ValueNamePairList of(final ValueNamePair[] arr)
{
if (arr == null || arr.length == 0)
{
return EMPTY;
}
return new ValueNamePairList(ImmutableList.copyOf(arr));
}
public static final ValueNamePairList of()
{
return EMPTY;
}
|
public static final ValueNamePairList EMPTY = new ValueNamePairList(ImmutableList.<ValueNamePair> of());
@JsonProperty("l")
private final List<ValueNamePair> values;
private ValueNamePairList(final List<ValueNamePair> values)
{
super();
this.values = ImmutableList.copyOf(values);
}
public List<ValueNamePair> getValues()
{
return values;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\ValueNamePairList.java
| 1
|
请完成以下Java代码
|
public Builder setName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
name_ = value;
onChanged();
return this;
}
/**
* <code>required string name = 2;</code>
*/
public Builder clearName() {
bitField0_ = (bitField0_ & ~0x00000002);
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
* <code>required string name = 2;</code>
*/
public Builder setNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
name_ = value;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:baeldung.Foo)
}
static {
defaultInstance = new Foo(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:baeldung.Foo)
}
|
private static final com.google.protobuf.Descriptors.Descriptor internal_static_baeldung_Foo_descriptor;
private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_baeldung_Foo_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor descriptor;
static {
java.lang.String[] descriptorData = { "\n\017FooProtos.proto\022\010baeldung\"\037\n\003Foo\022\n\n\002id" + "\030\001 \002(\003\022\014\n\004name\030\002 \002(\tB!\n\024com.baeldung.web" + ".dtoB\tFooProtos" };
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner);
internal_static_baeldung_Foo_descriptor = getDescriptor().getMessageTypes().get(0);
internal_static_baeldung_Foo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable(internal_static_baeldung_Foo_descriptor, new java.lang.String[] { "Id", "Name", });
}
// @@protoc_insertion_point(outer_class_scope)
}
|
repos\tutorials-master\spring-web-modules\spring-rest-simple\src\main\java\com\baeldung\web\dto\FooProtos.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public int hashCode()
{
return Objects.hash(lineItemId, quantity);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class LineItemReference {\n");
sb.append(" lineItemId: ").append(toIndentedString(lineItemId)).append("\n");
sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n");
sb.append("}");
return sb.toString();
}
|
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\LineItemReference.java
| 2
|
请完成以下Java代码
|
protected void suspendAcquisition(long millis) {
if (millis <= 0) {
return;
}
try {
LOG.debugJobAcquisitionThreadSleeping(millis);
synchronized (MONITOR) {
if(!isInterrupted) {
isWaiting.set(true);
MONITOR.wait(millis);
}
}
LOG.jobExecutorThreadWokeUp();
}
catch (InterruptedException e) {
LOG.jobExecutionWaitInterrupted();
}
finally {
isWaiting.set(false);
}
}
public void stop() {
synchronized (MONITOR) {
isInterrupted = true;
if(isWaiting.compareAndSet(true, false)) {
MONITOR.notifyAll();
}
}
}
|
public void jobWasAdded() {
isJobAdded = true;
if(isWaiting.compareAndSet(true, false)) {
// ensures we only notify once
// I am OK with the race condition
synchronized (MONITOR) {
MONITOR.notifyAll();
}
}
}
protected void clearJobAddedNotification() {
isJobAdded = false;
}
public boolean isJobAdded() {
return isJobAdded;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\AcquireJobsRunnable.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
final class DefaultDocCopyHandler<HT, LT> implements IDocCopyHandler<HT, LT>
{
private final Class<HT> headerClass;
private final Class<LT> lineClass;
public DefaultDocCopyHandler(Class<HT> headerClass, Class<LT> lineClass)
{
this.headerClass = headerClass;
this.lineClass = lineClass;
}
@Override
public void copyPreliminaryValues(final HT from, final HT to)
{
InterfaceWrapperHelper.copyValues(from, to);
}
@Override
public void copyValues(final HT from, final HT to)
{
|
// nothing should happen in the default handler
}
@Override
public IDocLineCopyHandler<LT> getDocLineCopyHandler()
{
return new DefaultDocLineCopyHandler<>(lineClass);
}
@Override
public Class<HT> getSupportedItemsClass()
{
return headerClass;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\service\impl\DefaultDocCopyHandler.java
| 2
|
请完成以下Java代码
|
private static @Nullable String getMetadataValue(Instance instance, String[] keys) {
Map<String, String> metadata = instance.getRegistration().getMetadata();
for (String key : keys) {
String value = metadata.get(key);
if (value != null) {
return value;
}
}
return null;
}
private static String base64Encode(byte[] src) {
if (src.length == 0) {
return "";
}
byte[] dest = Base64.getEncoder().encode(src);
return new String(dest, StandardCharsets.UTF_8);
}
@lombok.Data
@lombok.NoArgsConstructor
@lombok.AllArgsConstructor
public static class InstanceCredentials {
|
/**
* user name for this instance
*/
@lombok.NonNull
private String userName;
/**
* user password for this instance
*/
@lombok.NonNull
private String userPassword;
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\web\client\BasicAuthHttpHeaderProvider.java
| 1
|
请完成以下Java代码
|
public void setValidationMessage(String validationMessage) {
this.validationMessage = validationMessage;
}
public Boolean isStrictMode() {
return strictMode;
}
public void setStrictMode(Boolean strictMode) {
this.strictMode = strictMode;
}
public Map<String, String> getInputVariableTypes() {
return inputVariableTypes;
}
public void setInputVariableTypes(Map<String, String> inputVariableTypes) {
this.inputVariableTypes = inputVariableTypes;
}
public Map<String, String> getDecisionResultTypes() {
return decisionResultTypes;
}
public void addDecisionResultType(String decisionResultId, String decisionResultType) {
this.decisionResultTypes.put(decisionResultId, decisionResultType);
}
protected static boolean isBoolean(Object obj) {
return obj instanceof Boolean;
}
protected static boolean isDate(Object obj) {
return (obj instanceof Date || obj instanceof DateTime || obj instanceof LocalDate || obj instanceof java.time.LocalDate || obj instanceof LocalDateTime
|| obj instanceof Instant);
}
protected static boolean isNumber(Object obj) {
return obj instanceof Number;
}
protected Map<String, Object> createDefensiveCopyInputVariables(Map<String, Object> inputVariables) {
|
Map<String, Object> defensiveCopyMap = new HashMap<>();
if (inputVariables != null) {
for (Map.Entry<String, Object> entry : inputVariables.entrySet()) {
Object newValue = null;
if (entry.getValue() == null) {
// do nothing
} else if (entry.getValue() instanceof Long) {
newValue = Long.valueOf(((Long) entry.getValue()).longValue());
} else if (entry.getValue() instanceof Double) {
newValue = Double.valueOf(((Double) entry.getValue()).doubleValue());
} else if (entry.getValue() instanceof Integer) {
newValue = Integer.valueOf(((Integer) entry.getValue()).intValue());
} else if (entry.getValue() instanceof Date) {
newValue = new Date(((Date) entry.getValue()).getTime());
} else if (entry.getValue() instanceof Boolean) {
newValue = Boolean.valueOf(((Boolean) entry.getValue()).booleanValue());
} else {
newValue = new String(entry.getValue().toString());
}
defensiveCopyMap.put(entry.getKey(), newValue);
}
}
return defensiveCopyMap;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-api\src\main\java\org\flowable\dmn\api\DecisionExecutionAuditContainer.java
| 1
|
请完成以下Java代码
|
protected void setOutgoingTransitions(List<TransitionImpl> outgoingTransitions) {
this.outgoingTransitions = outgoingTransitions;
}
protected void setParent(ScopeImpl parent) {
this.parent = parent;
}
protected void setIncomingTransitions(List<TransitionImpl> incomingTransitions) {
this.incomingTransitions = incomingTransitions;
}
// getters and setters //////////////////////////////////////////////////////
@Override
@SuppressWarnings("unchecked")
public List<PvmTransition> getOutgoingTransitions() {
return (List) outgoingTransitions;
}
public ActivityBehavior getActivityBehavior() {
return activityBehavior;
}
public void setActivityBehavior(ActivityBehavior activityBehavior) {
this.activityBehavior = activityBehavior;
}
@Override
public ScopeImpl getParent() {
return parent;
}
@Override
@SuppressWarnings("unchecked")
public List<PvmTransition> getIncomingTransitions() {
return (List) incomingTransitions;
}
public Map<String, Object> getVariables() {
return variables;
}
public void setVariables(Map<String, Object> variables) {
this.variables = variables;
}
public boolean isScope() {
return isScope;
}
public void setScope(boolean isScope) {
this.isScope = isScope;
}
@Override
public int getX() {
return x;
}
@Override
public void setX(int x) {
this.x = x;
}
@Override
public int getY() {
return y;
}
|
@Override
public void setY(int y) {
this.y = y;
}
@Override
public int getWidth() {
return width;
}
@Override
public void setWidth(int width) {
this.width = width;
}
@Override
public int getHeight() {
return height;
}
@Override
public void setHeight(int height) {
this.height = height;
}
@Override
public boolean isAsync() {
return isAsync;
}
public void setAsync(boolean isAsync) {
this.isAsync = isAsync;
}
@Override
public boolean isExclusive() {
return isExclusive;
}
public void setExclusive(boolean isExclusive) {
this.isExclusive = isExclusive;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\ActivityImpl.java
| 1
|
请完成以下Java代码
|
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public void setResources(Map<String, ResourceEntity> resources) {
this.resources = resources;
}
public Date getDeploymentTime() {
return deploymentTime;
}
public void setDeploymentTime(Date deploymentTime) {
this.deploymentTime = deploymentTime;
}
public boolean isNew() {
return isNew;
}
public void setNew(boolean isNew) {
this.isNew = isNew;
}
|
public String getEngineVersion() {
return engineVersion;
}
public void setEngineVersion(String engineVersion) {
this.engineVersion = engineVersion;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public String getProjectReleaseVersion() {
return projectReleaseVersion;
}
public void setProjectReleaseVersion(String projectReleaseVersion) {
this.projectReleaseVersion = projectReleaseVersion;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "DeploymentEntity[id=" + id + ", name=" + name + "]";
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\DeploymentEntityImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
@OneToMany(cascade = CascadeType.ALL)
private List<BookAuthorEntity> bookAuthorEntities;
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 List<BookAuthorEntity> getBookAuthorEntities() {
return bookAuthorEntities;
}
public void setBookAuthorEntities(List<BookAuthorEntity> bookAuthorEntities) {
this.bookAuthorEntities = bookAuthorEntities;
}
@Override
public String toString() {
return "Author{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", books=" + bookAuthorEntities + '}';
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\specifications\join\Author.java
| 2
|
请完成以下Java代码
|
public class CustomLayers implements Layers {
private final List<Layer> layers;
private final List<ContentSelector<String>> applicationSelectors;
private final List<ContentSelector<Library>> librarySelectors;
public CustomLayers(List<Layer> layers, List<ContentSelector<String>> applicationSelectors,
List<ContentSelector<Library>> librarySelectors) {
Assert.notNull(layers, "'layers' must not be null");
Assert.notNull(applicationSelectors, "'applicationSelectors' must not be null");
validateSelectorLayers(applicationSelectors, layers);
Assert.notNull(librarySelectors, "'librarySelectors' must not be null");
validateSelectorLayers(librarySelectors, layers);
this.layers = new ArrayList<>(layers);
this.applicationSelectors = new ArrayList<>(applicationSelectors);
this.librarySelectors = new ArrayList<>(librarySelectors);
}
private static <T> void validateSelectorLayers(List<ContentSelector<T>> selectors, List<Layer> layers) {
for (ContentSelector<?> selector : selectors) {
validateSelectorLayers(selector, layers);
}
}
private static void validateSelectorLayers(ContentSelector<?> selector, List<Layer> layers) {
Layer layer = selector.getLayer();
Assert.state(layer != null, "Missing content selector layer");
Assert.state(layers.contains(layer),
() -> "Content selector layer '" + selector.getLayer() + "' not found in " + layers);
}
@Override
public Iterator<Layer> iterator() {
return this.layers.iterator();
}
@Override
public Stream<Layer> stream() {
return this.layers.stream();
}
@Override
|
public Layer getLayer(String resourceName) {
return selectLayer(resourceName, this.applicationSelectors, () -> "Resource '" + resourceName + "'");
}
@Override
public Layer getLayer(Library library) {
return selectLayer(library, this.librarySelectors, () -> "Library '" + library.getName() + "'");
}
private <T> Layer selectLayer(T item, List<ContentSelector<T>> selectors, Supplier<String> name) {
for (ContentSelector<T> selector : selectors) {
if (selector.contains(item)) {
return selector.getLayer();
}
}
throw new IllegalStateException(name.get() + " did not match any layer");
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\layer\CustomLayers.java
| 1
|
请完成以下Java代码
|
private void handleSolution(List<DancingNode> answer) {
int[][] result = parseBoard(answer);
printSolution(result);
}
private int size = 9;
private int[][] parseBoard(List<DancingNode> answer) {
int[][] result = new int[size][size];
for (DancingNode n : answer) {
DancingNode rcNode = n;
int min = Integer.parseInt(rcNode.C.name);
for (DancingNode tmp = n.R; tmp != n; tmp = tmp.R) {
int val = Integer.parseInt(tmp.C.name);
if (val < min) {
min = val;
rcNode = tmp;
}
}
int ans1 = Integer.parseInt(rcNode.C.name);
int ans2 = Integer.parseInt(rcNode.R.C.name);
int r = ans1 / size;
int c = ans1 % size;
int num = (ans2 % size) + 1;
result[r][c] = num;
}
|
return result;
}
private static void printSolution(int[][] result) {
int size = result.length;
for (int[] aResult : result) {
StringBuilder ret = new StringBuilder();
for (int j = 0; j < size; j++) {
ret.append(aResult[j]).append(" ");
}
System.out.println(ret);
}
System.out.println();
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\sudoku\DancingLinks.java
| 1
|
请完成以下Java代码
|
public long getCreatedTime() {
return super.getCreatedTime();
}
@Override
public String getName() {
return name;
}
public TenantProfileData getProfileData() {
if (profileData != null) {
return profileData;
} else {
if (profileDataBytes != null) {
try {
profileData = mapper.readValue(new ByteArrayInputStream(profileDataBytes), TenantProfileData.class);
} catch (IOException e) {
log.warn("Can't deserialize tenant profile data: ", e);
return createDefaultTenantProfileData();
}
return profileData;
} else {
return createDefaultTenantProfileData();
}
}
}
@JsonIgnore
public Optional<DefaultTenantProfileConfiguration> getProfileConfiguration() {
return Optional.ofNullable(getProfileData().getConfiguration())
.filter(profileConfiguration -> profileConfiguration instanceof DefaultTenantProfileConfiguration)
.map(profileConfiguration -> (DefaultTenantProfileConfiguration) profileConfiguration);
}
@JsonIgnore
public DefaultTenantProfileConfiguration getDefaultProfileConfiguration() {
return getProfileConfiguration().orElse(null);
}
|
public TenantProfileData createDefaultTenantProfileData() {
TenantProfileData tpd = new TenantProfileData();
tpd.setConfiguration(new DefaultTenantProfileConfiguration());
this.profileData = tpd;
return tpd;
}
public void setProfileData(TenantProfileData data) {
this.profileData = data;
try {
this.profileDataBytes = data != null ? mapper.writeValueAsBytes(data) : null;
} catch (JsonProcessingException e) {
log.warn("Can't serialize tenant profile data: ", e);
}
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\TenantProfile.java
| 1
|
请完成以下Java代码
|
public String getDepPostParentId() {
return depPostParentId;
}
public void setDepPostParentId(String depPostParentId) {
this.depPostParentId = depPostParentId;
}
/**
* 重写equals方法
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SysDepartTreeModel model = (SysDepartTreeModel) o;
return Objects.equals(id, model.id) &&
Objects.equals(parentId, model.parentId) &&
Objects.equals(departName, model.departName) &&
Objects.equals(departNameEn, model.departNameEn) &&
Objects.equals(departNameAbbr, model.departNameAbbr) &&
Objects.equals(departOrder, model.departOrder) &&
Objects.equals(description, model.description) &&
Objects.equals(orgCategory, model.orgCategory) &&
Objects.equals(orgType, model.orgType) &&
Objects.equals(orgCode, model.orgCode) &&
Objects.equals(mobile, model.mobile) &&
Objects.equals(fax, model.fax) &&
Objects.equals(address, model.address) &&
Objects.equals(memo, model.memo) &&
|
Objects.equals(status, model.status) &&
Objects.equals(delFlag, model.delFlag) &&
Objects.equals(qywxIdentifier, model.qywxIdentifier) &&
Objects.equals(createBy, model.createBy) &&
Objects.equals(createTime, model.createTime) &&
Objects.equals(updateBy, model.updateBy) &&
Objects.equals(updateTime, model.updateTime) &&
Objects.equals(directorUserIds, model.directorUserIds) &&
Objects.equals(positionId, model.positionId) &&
Objects.equals(depPostParentId, model.depPostParentId) &&
Objects.equals(children, model.children);
}
/**
* 重写hashCode方法
*/
@Override
public int hashCode() {
return Objects.hash(id, parentId, departName, departNameEn, departNameAbbr,
departOrder, description, orgCategory, orgType, orgCode, mobile, fax, address,
memo, status, delFlag, qywxIdentifier, createBy, createTime, updateBy, updateTime,
children,directorUserIds, positionId, depPostParentId);
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\SysDepartTreeModel.java
| 1
|
请完成以下Java代码
|
public TenantCheck getTenantCheck() {
return tenantCheck;
}
public String getReportPeriodUnitName() {
return durationPeriodUnit.name();
}
protected class ExecuteDurationCmd implements Command<List<DurationReportResult>> {
@Override
public List<DurationReportResult> execute(CommandContext commandContext) {
return executeDuration(commandContext);
}
}
protected class HistoricTaskInstanceCountByNameCmd implements Command<List<HistoricTaskInstanceReportResult>> {
|
@Override
public List<HistoricTaskInstanceReportResult> execute(CommandContext commandContext) {
return executeCountByTaskName(commandContext);
}
}
protected class HistoricTaskInstanceCountByProcessDefinitionKey implements Command<List<HistoricTaskInstanceReportResult>> {
@Override
public List<HistoricTaskInstanceReportResult> execute(CommandContext commandContext) {
return executeCountByProcessDefinitionKey(commandContext);
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricTaskInstanceReportImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String rotatePassword(String name) {
try {
SimpleCredentialName credentialName = new SimpleCredentialName(name);
CredentialDetails<PasswordCredential> oldPassword = credentialOperations.getByName(credentialName, PasswordCredential.class);
CredentialDetails<PasswordCredential> newPassword = credentialOperations.regenerate(credentialName, PasswordCredential.class);
return "Credential:" + credentialName + " re-generated successfully!";
} catch (Exception e) {
return "Error! Unable to re-generate credential";
}
}
public String deletePassword(String name) {
try {
SimpleCredentialName credentialName = new SimpleCredentialName(name);
credentialOperations.deleteByName(credentialName);
return "Credential:" + credentialName + " deleted successfully!";
} catch (Exception e) {
return "Error! Unable to delete credential";
}
}
public String getPassword(String name) {
try {
SimpleCredentialName credentialName = new SimpleCredentialName(name);
return credentialOperations.getByName(credentialName, PasswordCredential.class)
.getValue()
.getPassword();
} catch (Exception e) {
return null;
}
}
public CredentialPermission addCredentialPermission(String name) {
SimpleCredentialName credentialName = new SimpleCredentialName(name);
try {
Permission permission = Permission.builder()
.app(UUID.randomUUID()
.toString())
.operations(Operation.READ, Operation.WRITE)
|
.user("u101")
.build();
CredentialPermission credentialPermission = permissionOperations.addPermissions(credentialName, permission);
return credentialPermission;
} catch (Exception e) {
return null;
}
}
public CredentialPermission getCredentialPermission(String name) {
try {
return permissionOperations.getPermissions(name);
} catch (Exception e) {
return null;
}
}
}
|
repos\tutorials-master\spring-credhub\src\main\java\com\baeldung\service\CredentialService.java
| 2
|
请完成以下Java代码
|
protected String doIt() throws Exception
{
PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null,null);
for (PrintService ps : printServices)
{
addLog("Available service: "+ps.getName()+" - "+ps.toString());
}
if (I_AD_Printer.Table_Name.equals(getTableName()) && getRecord_ID() > 0)
{
int AD_Printer_ID = getRecord_ID();
I_AD_Printer printer = InterfaceWrapperHelper.create(getCtx(), AD_Printer_ID, I_AD_Printer.class, get_TrxName());
String printerName = printer.getPrinterName();
boolean found = false;
for (PrintService ps : printServices)
|
{
if (ps.getName().equals(printerName))
{
addLog("Found service for "+printerName+": "+ps);
found = true;
}
}
if (!found)
{
throw new AdempiereException("No printing services found for "+printerName);
}
}
return "Ok";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\process\AD_Printer_CheckSuggest.java
| 1
|
请完成以下Java代码
|
private Set<PriceListId> retrievePriceLists()
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final String trxName = ITrx.TRXNAME_None;
final IQuery<I_I_Pharma_Product> pharmaPriceListQuery = queryBL.createQueryBuilder(I_I_Pharma_Product.class, trxName)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_I_Pharma_Product.COLUMNNAME_IsPriceCopied, false)
.create();
return queryBL.createQueryBuilder(I_M_PriceList.class, trxName)
.setJoinOr()
.addInSubQueryFilter(I_M_PriceList.COLUMNNAME_M_PriceList_ID, I_I_Pharma_Product.COLUMNNAME_AEP_Price_List_ID, pharmaPriceListQuery)
.addInSubQueryFilter(I_M_PriceList.COLUMNNAME_M_PriceList_ID, I_I_Pharma_Product.COLUMNNAME_APU_Price_List_ID, pharmaPriceListQuery)
.addInSubQueryFilter(I_M_PriceList.COLUMNNAME_M_PriceList_ID, I_I_Pharma_Product.COLUMNNAME_AVP_Price_List_ID, pharmaPriceListQuery)
.addInSubQueryFilter(I_M_PriceList.COLUMNNAME_M_PriceList_ID, I_I_Pharma_Product.COLUMNNAME_KAEP_Price_List_ID, pharmaPriceListQuery)
.addInSubQueryFilter(I_M_PriceList.COLUMNNAME_M_PriceList_ID, I_I_Pharma_Product.COLUMNNAME_UVP_Price_List_ID, pharmaPriceListQuery)
.addInSubQueryFilter(I_M_PriceList.COLUMNNAME_M_PriceList_ID, I_I_Pharma_Product.COLUMNNAME_ZBV_Price_List_ID, pharmaPriceListQuery)
.setOption(IQueryBuilder.OPTION_Explode_OR_Joins_To_SQL_Unions)
|
.create()
.setOption(IQuery.OPTION_IteratorBufferSize, 1000)
.listDistinct(I_M_PriceList.COLUMNNAME_M_PriceList_ID)
.stream()
.map(this::extractPriceListIdorNull)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
}
@Nullable private PriceListId extractPriceListIdorNull(@NonNull final Map<String, Object> map)
{
final int priceListId = NumberUtils.asInt(map.get(I_M_PriceList.COLUMNNAME_M_PriceList_ID), -1);
if (priceListId <= 0)
{
// shall not happen
return null;
}
return PriceListId.ofRepoId(priceListId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\impexp\product\IFAProductImportProcess.java
| 1
|
请完成以下Java代码
|
@Override public String toString() { return ">"; }
};
public static final Operator LE = new SimpleOperator() {
@Override public Object apply(TypeConverter converter, Object o1, Object o2) { return BooleanOperations.le(converter, o1, o2); }
@Override public String toString() { return "<="; }
};
public static final Operator LT = new SimpleOperator() {
@Override public Object apply(TypeConverter converter, Object o1, Object o2) { return BooleanOperations.lt(converter, o1, o2); }
@Override public String toString() { return "<"; }
};
public static final Operator MOD = new SimpleOperator() {
@Override public Object apply(TypeConverter converter, Object o1, Object o2) { return NumberOperations.mod(converter, o1, o2); }
@Override public String toString() { return "%"; }
};
public static final Operator MUL = new SimpleOperator() {
@Override public Object apply(TypeConverter converter, Object o1, Object o2) { return NumberOperations.mul(converter, o1, o2); }
@Override public String toString() { return "*"; }
};
public static final Operator NE = new SimpleOperator() {
@Override public Object apply(TypeConverter converter, Object o1, Object o2) { return BooleanOperations.ne(converter, o1, o2); }
@Override public String toString() { return "!="; }
};
public static final Operator OR = new Operator() {
public Object eval(Bindings bindings, ELContext context, AstNode left, AstNode right) {
Boolean l = bindings.convert(left.eval(bindings, context), Boolean.class);
return Boolean.TRUE.equals(l) ? Boolean.TRUE : bindings.convert(right.eval(bindings, context), Boolean.class);
}
@Override public String toString() { return "||"; }
};
public static final Operator SUB = new SimpleOperator() {
@Override public Object apply(TypeConverter converter, Object o1, Object o2) { return NumberOperations.sub(converter, o1, o2); }
@Override public String toString() { return "-"; }
};
private final Operator operator;
private final AstNode left, right;
public AstBinary(AstNode left, AstNode right, Operator operator) {
this.left = left;
this.right = right;
this.operator = operator;
}
public Operator getOperator() {
return operator;
}
@Override
public Object eval(Bindings bindings, ELContext context) {
|
return operator.eval(bindings, context, left, right);
}
@Override
public String toString() {
return "'" + operator.toString() + "'";
}
@Override
public void appendStructure(StringBuilder b, Bindings bindings) {
left.appendStructure(b, bindings);
b.append(' ');
b.append(operator);
b.append(' ');
right.appendStructure(b, bindings);
}
public int getCardinality() {
return 2;
}
public AstNode getChild(int i) {
return i == 0 ? left : i == 1 ? right : null;
}
}
|
repos\camunda-bpm-platform-master\juel\src\main\java\org\camunda\bpm\impl\juel\AstBinary.java
| 1
|
请完成以下Java代码
|
public GatewayFilter apply(NameConfig config) {
// AbstractChangeRequestUriGatewayFilterFactory.apply() returns
// OrderedGatewayFilter
OrderedGatewayFilter gatewayFilter = (OrderedGatewayFilter) super.apply(config);
return new OrderedGatewayFilter(gatewayFilter, gatewayFilter.getOrder()) {
@Override
public String toString() {
String name = Objects.requireNonNull(config.getName(), "name must not be null");
return filterToStringCreator(RequestHeaderToRequestUriGatewayFilterFactory.this).append("name", name)
.toString();
}
};
}
@Override
protected Optional<URI> determineRequestUri(ServerWebExchange exchange, NameConfig config) {
|
String name = Objects.requireNonNull(config.getName(), "name must not be null");
String requestUrl = exchange.getRequest().getHeaders().getFirst(name);
return Optional.ofNullable(requestUrl).map(url -> {
try {
URI uri = URI.create(url);
uri.toURL(); // validate url
return uri;
}
catch (IllegalArgumentException | MalformedURLException e) {
log.info("Request url is invalid : url={}, error={}", requestUrl, e.getMessage());
return null;
}
});
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RequestHeaderToRequestUriGatewayFilterFactory.java
| 1
|
请完成以下Java代码
|
public class CachingDelegateEncryptablePropertySource<T> extends PropertySource<T> implements EncryptablePropertySource<T> {
private final PropertySource<T> delegate;
private final CachingResolver cachingResolver;
@Setter
private boolean wrapGetSource = false;
/**
* <p>Constructor for CachingDelegateEncryptablePropertySource.</p>
*
* @param delegate a {@link org.springframework.core.env.PropertySource} object
* @param resolver a {@link com.ulisesbocchio.jasyptspringboot.EncryptablePropertyResolver} object
* @param filter a {@link com.ulisesbocchio.jasyptspringboot.EncryptablePropertyFilter} object
*/
public CachingDelegateEncryptablePropertySource(PropertySource<T> delegate, EncryptablePropertyResolver resolver, EncryptablePropertyFilter filter) {
super(delegate.getName(), delegate.getSource());
Assert.notNull(delegate, "PropertySource delegate cannot be null");
Assert.notNull(resolver, "EncryptablePropertyResolver cannot be null");
Assert.notNull(filter, "EncryptablePropertyFilter cannot be null");
this.delegate = delegate;
this.cachingResolver = new CachingResolver(
resolver,
filter,
delegate
);
}
/** {@inheritDoc} */
@Override
public PropertySource<T> getDelegate() {
return delegate;
}
|
/** {@inheritDoc} */
@Override
@NonNull
public Object getProperty(@NonNull String name) {
return cachingResolver.resolveProperty(name);
}
/** {@inheritDoc} */
@Override
public void refresh() {
log.info("Property Source {} refreshed", delegate.getName());
cachingResolver.refresh();
}
/** {@inheritDoc} */
@Override
@NonNull
public T getSource() {
T source = delegate.getSource();
if (this.wrapGetSource && source instanceof java.util.Map) {
@SuppressWarnings("unchecked")
T wrapped = (T) new EncryptableMapWrapper(cachingResolver);
return wrapped;
}
return source;
}
}
|
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\caching\CachingDelegateEncryptablePropertySource.java
| 1
|
请完成以下Java代码
|
public int getAD_User_AuthToken_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_AuthToken_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_User getAD_User() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setAD_User(org.compiere.model.I_AD_User AD_User)
{
set_ValueFromPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class, AD_User);
}
/** Set Ansprechpartner.
@param AD_User_ID
User within the system - Internal or Business Partner Contact
*/
@Override
public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 0)
set_Value (COLUMNNAME_AD_User_ID, null);
else
set_Value (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID));
}
/** Get Ansprechpartner.
@return User within the system - Internal or Business Partner Contact
*/
@Override
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Authentication Token.
@param AuthToken Authentication Token */
@Override
public void setAuthToken (java.lang.String AuthToken)
{
set_Value (COLUMNNAME_AuthToken, AuthToken);
|
}
/** Get Authentication Token.
@return Authentication Token */
@Override
public java.lang.String getAuthToken ()
{
return (java.lang.String)get_Value(COLUMNNAME_AuthToken);
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_AuthToken.java
| 1
|
请完成以下Java代码
|
public static DemandDetail forShipmentScheduleIdAndOrderLineId(
final int shipmentScheduleId,
final int orderLineId,
final int orderId,
@NonNull final BigDecimal qty)
{
return DemandDetail.builder()
.shipmentScheduleId(shipmentScheduleId)
.orderLineId(orderLineId)
.orderId(orderId)
.qty(qty).build();
}
@NonNull
public static DemandDetail forShipmentLineId(
final int inOutLineId,
@NonNull final BigDecimal qty)
{
return DemandDetail.builder()
.inOutLineId(inOutLineId)
.qty(qty)
.build();
}
public static DemandDetail forForecastLineId(
final int forecastLineId,
final int forecastId,
@NonNull final BigDecimal qty)
{
return DemandDetail.builder()
.forecastLineId(forecastLineId)
.forecastId(forecastId)
.qty(qty).build();
}
int forecastId;
int forecastLineId;
int shipmentScheduleId;
int orderId;
int orderLineId;
int subscriptionProgressId;
|
int inOutLineId;
BigDecimal qty;
/**
* Used when a new supply candidate is created, to link it to it's respective demand candidate;
* When a demand detail is loaded from DB, this field is always <= 0.
*/
int demandCandidateId;
/**
* dev-note: it's about an {@link de.metas.material.event.MaterialEvent} traceId, currently used when posting SupplyRequiredEvents
*/
@With
@Nullable
String traceId;
@Override
public CandidateBusinessCase getCandidateBusinessCase()
{
return CandidateBusinessCase.SHIPMENT;
}
public static DemandDetail castOrNull(@Nullable final BusinessCaseDetail businessCaseDetail)
{
return businessCaseDetail instanceof DemandDetail ? cast(businessCaseDetail) : null;
}
public static DemandDetail cast(@NonNull final BusinessCaseDetail businessCaseDetail)
{
return (DemandDetail)businessCaseDetail;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\businesscase\DemandDetail.java
| 1
|
请完成以下Java代码
|
public HttpHeaders getHeaders() {
long contentLength = headers.getContentLength();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.putAll(headers);
if (contentLength > 0) {
httpHeaders.setContentLength(contentLength);
}
else {
// TODO: this causes a 'HTTP/1.1 411 Length Required' // on
// httpbin.org
httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked");
}
return httpHeaders;
}
@Override
public Flux<DataBuffer> getBody() {
return outputMessage.getBody();
}
};
}
public static class Config {
private @Nullable ParameterizedTypeReference inClass;
private @Nullable ParameterizedTypeReference outClass;
private @Nullable String contentType;
private @Nullable RewriteFunction rewriteFunction;
public @Nullable ParameterizedTypeReference getInClass() {
return inClass;
}
public Config setInClass(Class inClass) {
return setInClass(ParameterizedTypeReference.forType(inClass));
}
public Config setInClass(ParameterizedTypeReference inTypeReference) {
this.inClass = inTypeReference;
return this;
}
public @Nullable ParameterizedTypeReference getOutClass() {
return outClass;
}
public Config setOutClass(Class outClass) {
return setOutClass(ParameterizedTypeReference.forType(outClass));
}
public Config setOutClass(ParameterizedTypeReference outClass) {
this.outClass = outClass;
return this;
}
|
public @Nullable RewriteFunction getRewriteFunction() {
return rewriteFunction;
}
public Config setRewriteFunction(RewriteFunction rewriteFunction) {
this.rewriteFunction = rewriteFunction;
return this;
}
public <T, R> Config setRewriteFunction(Class<T> inClass, Class<R> outClass,
RewriteFunction<T, R> rewriteFunction) {
setInClass(inClass);
setOutClass(outClass);
setRewriteFunction(rewriteFunction);
return this;
}
public <T, R> Config setRewriteFunction(ParameterizedTypeReference<T> inClass,
ParameterizedTypeReference<R> outClass, RewriteFunction<T, R> rewriteFunction) {
setInClass(inClass);
setOutClass(outClass);
setRewriteFunction(rewriteFunction);
return this;
}
public @Nullable String getContentType() {
return contentType;
}
public Config setContentType(@Nullable String contentType) {
this.contentType = contentType;
return this;
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\rewrite\ModifyRequestBodyGatewayFilterFactory.java
| 1
|
请完成以下Java代码
|
public int getAD_Tab_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Tab_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_AD_Table getAD_Table() throws RuntimeException
{
return (org.compiere.model.I_AD_Table)MTable.get(getCtx(), org.compiere.model.I_AD_Table.Table_Name)
.getPO(getAD_Table_ID(), get_TrxName()); }
/** Set DB-Tabelle.
@param AD_Table_ID
Database Table information
*/
public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get DB-Tabelle.
@return Database Table information
*/
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set UI Trigger.
@param AD_TriggerUI_ID UI Trigger */
public void setAD_TriggerUI_ID (int AD_TriggerUI_ID)
{
if (AD_TriggerUI_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_TriggerUI_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_TriggerUI_ID, Integer.valueOf(AD_TriggerUI_ID));
}
/** Get UI Trigger.
@return UI Trigger */
public int getAD_TriggerUI_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_TriggerUI_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Optional short description of the record
*/
public String getDescription ()
|
{
return (String)get_Value(COLUMNNAME_Description);
}
/** EntityType AD_Reference_ID=389 */
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entitaets-Art.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
public void setEntityType (String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitaets-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** 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.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_AD_TriggerUI.java
| 1
|
请完成以下Java代码
|
protected Collection<String> getUserRoles(HttpServletRequest request) {
ArrayList<String> j2eeUserRolesList = new ArrayList<>();
for (String role : this.j2eeMappableRoles) {
if (request.isUserInRole(role)) {
j2eeUserRolesList.add(role);
}
}
return j2eeUserRolesList;
}
/**
* Builds the authentication details object.
*
* @see org.springframework.security.authentication.AuthenticationDetailsSource#buildDetails(Object)
*/
@Override
public PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails buildDetails(HttpServletRequest context) {
Collection<String> j2eeUserRoles = getUserRoles(context);
Collection<? extends GrantedAuthority> userGrantedAuthorities = this.j2eeUserRoles2GrantedAuthoritiesMapper
.getGrantedAuthorities(j2eeUserRoles);
if (this.logger.isDebugEnabled()) {
this.logger.debug(LogMessage.format("J2EE roles [%s] mapped to Granted Authorities: [%s]", j2eeUserRoles,
userGrantedAuthorities));
|
}
return new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(context, userGrantedAuthorities);
}
/**
* @param aJ2eeMappableRolesRetriever The MappableAttributesRetriever to use
*/
public void setMappableRolesRetriever(MappableAttributesRetriever aJ2eeMappableRolesRetriever) {
this.j2eeMappableRoles = Collections.unmodifiableSet(aJ2eeMappableRolesRetriever.getMappableAttributes());
}
/**
* @param mapper The Attributes2GrantedAuthoritiesMapper to use
*/
public void setUserRoles2GrantedAuthoritiesMapper(Attributes2GrantedAuthoritiesMapper mapper) {
this.j2eeUserRoles2GrantedAuthoritiesMapper = mapper;
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\preauth\j2ee\J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public final class NewRelicMetricsExportAutoConfiguration {
private final NewRelicProperties properties;
NewRelicMetricsExportAutoConfiguration(NewRelicProperties properties) {
this.properties = properties;
}
@Bean
@ConditionalOnMissingBean
NewRelicConfig newRelicConfig() {
return new NewRelicPropertiesConfigAdapter(this.properties);
}
@Bean
@ConditionalOnMissingBean
NewRelicClientProvider newRelicClientProvider(NewRelicConfig newRelicConfig) {
if (newRelicConfig.clientProviderType() == ClientProviderType.INSIGHTS_AGENT) {
return new NewRelicInsightsAgentClientProvider(newRelicConfig);
}
return new NewRelicInsightsApiClientProvider(newRelicConfig,
|
new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout()));
}
@Bean
@ConditionalOnMissingBean
NewRelicMeterRegistry newRelicMeterRegistry(NewRelicConfig newRelicConfig, Clock clock,
NewRelicClientProvider newRelicClientProvider) {
return NewRelicMeterRegistry.builder(newRelicConfig)
.clock(clock)
.clientProvider(newRelicClientProvider)
.build();
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\newrelic\NewRelicMetricsExportAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setSeqNoGrid (final int SeqNoGrid)
{
set_Value (COLUMNNAME_SeqNoGrid, SeqNoGrid);
}
@Override
public int getSeqNoGrid()
{
return get_ValueAsInt(COLUMNNAME_SeqNoGrid);
}
@Override
public void setSeqNo_SideList (final int SeqNo_SideList)
{
set_Value (COLUMNNAME_SeqNo_SideList, SeqNo_SideList);
}
@Override
public int getSeqNo_SideList()
{
return get_ValueAsInt(COLUMNNAME_SeqNo_SideList);
}
@Override
public void setUIStyle (final @Nullable java.lang.String UIStyle)
{
set_Value (COLUMNNAME_UIStyle, UIStyle);
}
@Override
public java.lang.String getUIStyle()
{
return get_ValueAsString(COLUMNNAME_UIStyle);
}
/**
* ViewEditMode AD_Reference_ID=541263
* Reference name: ViewEditMode
*/
public static final int VIEWEDITMODE_AD_Reference_ID=541263;
/** Never = N */
public static final String VIEWEDITMODE_Never = "N";
/** OnDemand = D */
public static final String VIEWEDITMODE_OnDemand = "D";
/** Always = Y */
public static final String VIEWEDITMODE_Always = "Y";
@Override
public void setViewEditMode (final @Nullable java.lang.String ViewEditMode)
|
{
set_Value (COLUMNNAME_ViewEditMode, ViewEditMode);
}
@Override
public java.lang.String getViewEditMode()
{
return get_ValueAsString(COLUMNNAME_ViewEditMode);
}
/**
* WidgetSize AD_Reference_ID=540724
* Reference name: WidgetSize_WEBUI
*/
public static final int WIDGETSIZE_AD_Reference_ID=540724;
/** Small = S */
public static final String WIDGETSIZE_Small = "S";
/** Medium = M */
public static final String WIDGETSIZE_Medium = "M";
/** Large = L */
public static final String WIDGETSIZE_Large = "L";
/** ExtraLarge = XL */
public static final String WIDGETSIZE_ExtraLarge = "XL";
/** XXL = XXL */
public static final String WIDGETSIZE_XXL = "XXL";
@Override
public void setWidgetSize (final @Nullable java.lang.String WidgetSize)
{
set_Value (COLUMNNAME_WidgetSize, WidgetSize);
}
@Override
public java.lang.String getWidgetSize()
{
return get_ValueAsString(COLUMNNAME_WidgetSize);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UI_Element.java
| 1
|
请完成以下Java代码
|
public void executeCopyPasteAction(final CopyPasteActionType actionType)
{
if (activeCopyPasteSupport == null)
{
return;
}
activeCopyPasteSupport.executeCopyPasteAction(actionType);
}
@Override
public Action getCopyPasteAction(final CopyPasteActionType actionType)
{
return copyPasteActions.get(actionType);
}
@Override
public void putCopyPasteAction(final CopyPasteActionType actionType, final Action action, final KeyStroke keyStroke)
{
// do nothing because we already provided the right action to be used
// comboBoxCopyPasteSupport.putCopyPasteAction(actionType, action, keyStroke);
// textFieldCopyPasteSupport.putCopyPasteAction(actionType, action, keyStroke);
}
@Override
public boolean isCopyPasteActionAllowed(final CopyPasteActionType actionType)
{
if (activeCopyPasteSupport == null)
{
return false;
}
return activeCopyPasteSupport.isCopyPasteActionAllowed(actionType);
}
private class CopyPasteActionProxy extends AbstractAction
{
private static final long serialVersionUID = 1L;
private final CopyPasteActionType actionType;
public CopyPasteActionProxy(final CopyPasteActionType actionType)
{
super();
this.actionType = actionType;
}
@Override
public void actionPerformed(final ActionEvent e)
{
final ICopyPasteSupportEditor copyPasteSupport = getActiveCopyPasteEditor();
if (copyPasteSupport == null)
{
return;
}
copyPasteSupport.executeCopyPasteAction(actionType);
}
private final ICopyPasteSupportEditor getActiveCopyPasteEditor()
{
return activeCopyPasteSupport;
}
}
|
/**
* Action implementation which forwards a given {@link CopyPasteActionType} to {@link ICopyPasteSupportEditor}.
*
* To be used only when the component does not already have a registered handler for this action type.
*
* @author tsa
*
*/
private static class CopyPasteAction extends AbstractAction
{
private static final Action getCreateAction(final ICopyPasteSupportEditor copyPasteSupport, final CopyPasteActionType actionType)
{
Action action = copyPasteSupport.getCopyPasteAction(actionType);
if (action == null)
{
action = new CopyPasteAction(copyPasteSupport, actionType);
}
copyPasteSupport.putCopyPasteAction(actionType, action, actionType.getKeyStroke());
return action;
}
private static final long serialVersionUID = 1L;
private final ICopyPasteSupportEditor copyPasteSupport;
private final CopyPasteActionType actionType;
public CopyPasteAction(final ICopyPasteSupportEditor copyPasteSupport, final CopyPasteActionType actionType)
{
super();
this.copyPasteSupport = copyPasteSupport;
this.actionType = actionType;
}
@Override
public void actionPerformed(final ActionEvent e)
{
copyPasteSupport.executeCopyPasteAction(actionType);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLookupCopyPasteSupportEditor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable ConfigDataLocation getLocation() {
return this.location;
}
@Override
public @Nullable Origin getOrigin() {
return Origin.from(this.location);
}
@Override
public String getReferenceDescription() {
return getReferenceDescription(this.resource, this.location);
}
/**
* Create a new {@link ConfigDataResourceNotFoundException} instance with a location.
* @param location the location to set
* @return a new {@link ConfigDataResourceNotFoundException} instance
*/
ConfigDataResourceNotFoundException withLocation(ConfigDataLocation location) {
return new ConfigDataResourceNotFoundException(this.resource, location, getCause());
}
private static String getMessage(ConfigDataResource resource, @Nullable ConfigDataLocation location) {
return String.format("Config data %s cannot be found", getReferenceDescription(resource, location));
}
private static String getReferenceDescription(ConfigDataResource resource, @Nullable ConfigDataLocation location) {
String description = String.format("resource '%s'", resource);
if (location != null) {
description += String.format(" via location '%s'", location);
}
return description;
}
/**
* Throw a {@link ConfigDataNotFoundException} if the specified {@link Path} does not
* exist.
* @param resource the config data resource
* @param pathToCheck the path to check
*/
public static void throwIfDoesNotExist(ConfigDataResource resource, Path pathToCheck) {
throwIfNot(resource, Files.exists(pathToCheck));
}
/**
|
* Throw a {@link ConfigDataNotFoundException} if the specified {@link File} does not
* exist.
* @param resource the config data resource
* @param fileToCheck the file to check
*/
public static void throwIfDoesNotExist(ConfigDataResource resource, File fileToCheck) {
throwIfNot(resource, fileToCheck.exists());
}
/**
* Throw a {@link ConfigDataNotFoundException} if the specified {@link Resource} does
* not exist.
* @param resource the config data resource
* @param resourceToCheck the resource to check
*/
public static void throwIfDoesNotExist(ConfigDataResource resource, Resource resourceToCheck) {
throwIfNot(resource, resourceToCheck.exists());
}
private static void throwIfNot(ConfigDataResource resource, boolean check) {
if (!check) {
throw new ConfigDataResourceNotFoundException(resource);
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigDataResourceNotFoundException.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public static class ComputeFileNameRequest
{
private static final String DEFAULT_PDF_EXTENSION = ".pdf";
@Nullable
OrgId orgId;
@Nullable
DocTypeId docTypeId;
@NonNull TableRecordReference recordReference;
@Nullable
String documentNo;
@NonNull
String fileExtension;
@Nullable
String suffix;
@Builder
public ComputeFileNameRequest(
@Nullable final OrgId orgId,
|
@Nullable final DocTypeId docTypeId,
@NonNull final TableRecordReference recordReference,
@Nullable final String documentNo,
@Nullable final String fileExtension,
@Nullable final String suffix)
{
this.orgId = orgId;
this.docTypeId = docTypeId;
this.recordReference = recordReference;
this.documentNo = documentNo;
this.fileExtension = CoalesceUtil.coalesceNotNull(fileExtension, DEFAULT_PDF_EXTENSION);
this.suffix = suffix;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\api\ArchiveFileNameService.java
| 2
|
请完成以下Java代码
|
public MDunningRunEntry[] getEntries (boolean requery, boolean onlyInvoices)
{
if (m_entries != null && !requery)
return m_entries;
String sql = "SELECT * FROM C_DunningRunEntry WHERE C_DunningRun_ID=? ORDER BY C_DunningLevel_ID, C_DunningRunEntry_ID";
ArrayList<MDunningRunEntry> list = new ArrayList<>();
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement (sql, get_TrxName());
pstmt.setInt (1, getC_DunningRun_ID());
rs = pstmt.executeQuery ();
while (rs.next ())
{
MDunningRunEntry thisEntry = new MDunningRunEntry(getCtx(), rs, get_TrxName());
if (!(onlyInvoices && thisEntry.hasInvoices()))
list.add (new MDunningRunEntry(getCtx(), rs, get_TrxName()));
}
rs.close ();
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
log.error(sql, e);
}
finally
{
DB.close(rs, pstmt);
rs = null; pstmt = null;
}
m_entries = new MDunningRunEntry[list.size ()];
list.toArray (m_entries);
return m_entries;
} // getEntries
/**
* Delete all Entries
* @param force delete also processed records
* @return true if deleted
*/
public boolean deleteEntries(boolean force)
{
getEntries(true);
for (MDunningRunEntry entry : m_entries) {
|
entry.delete(force);
}
boolean ok = getEntries(true).length == 0;
if (ok)
m_entries = null;
return ok;
} // deleteEntries
/**
* Get/Create Entry for BPartner
* @param C_BPartner_ID business partner
* @param C_Currency_ID currency
* @param SalesRep_ID sales rep
* @param C_DunningLevel_ID dunning level
* @return entry
*/
public MDunningRunEntry getEntry (int C_BPartner_ID, int C_Currency_ID, int SalesRep_ID, int C_DunningLevel_ID)
{
// TODO: Related BP
int C_BPartnerRelated_ID = C_BPartner_ID;
//
getEntries(false);
for (int i = 0; i < m_entries.length; i++)
{
MDunningRunEntry entry = m_entries[i];
if (entry.getC_BPartner_ID() == C_BPartnerRelated_ID && entry.getC_DunningLevel_ID() == C_DunningLevel_ID)
return entry;
}
// New Entry
MDunningRunEntry entry = new MDunningRunEntry (this);
I_C_BPartner bp = Services.get(IBPartnerDAO.class).getById(C_BPartnerRelated_ID);
entry.setBPartner(bp, true); // AR hardcoded
//
if (entry.getSalesRep_ID() == 0)
entry.setSalesRep_ID (SalesRep_ID);
entry.setC_Currency_ID (C_Currency_ID);
entry.setC_DunningLevel_ID(C_DunningLevel_ID);
//
m_entries = null;
return entry;
} // getEntry
} // MDunningRun
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MDunningRun.java
| 1
|
请完成以下Java代码
|
public String processUpdateForm(Owner owner, @Valid Pet pet, BindingResult result,
RedirectAttributes redirectAttributes) {
String petName = pet.getName();
// checking if the pet name already exists for the owner
if (StringUtils.hasText(petName)) {
Pet existingPet = owner.getPet(petName, false);
if (existingPet != null && !Objects.equals(existingPet.getId(), pet.getId())) {
result.rejectValue("name", "duplicate", "already exists");
}
}
LocalDate currentDate = LocalDate.now();
if (pet.getBirthDate() != null && pet.getBirthDate().isAfter(currentDate)) {
result.rejectValue("birthDate", "typeMismatch.birthDate");
}
if (result.hasErrors()) {
return VIEWS_PETS_CREATE_OR_UPDATE_FORM;
}
updatePetDetails(owner, pet);
redirectAttributes.addFlashAttribute("message", "Pet details has been edited");
return "redirect:/owners/{ownerId}";
}
/**
* Updates the pet details if it exists or adds a new pet to the owner.
* @param owner The owner of the pet
* @param pet The pet with updated details
*/
|
private void updatePetDetails(Owner owner, Pet pet) {
Integer id = pet.getId();
Assert.state(id != null, "'pet.getId()' must not be null");
Pet existingPet = owner.getPet(id);
if (existingPet != null) {
// Update existing pet's properties
existingPet.setName(pet.getName());
existingPet.setBirthDate(pet.getBirthDate());
existingPet.setType(pet.getType());
}
else {
owner.addPet(pet);
}
this.owners.save(owner);
}
}
|
repos\spring-petclinic-main\src\main\java\org\springframework\samples\petclinic\owner\PetController.java
| 1
|
请完成以下Java代码
|
public void setM_ReceiptSchedule_ExportAudit_ID (final int M_ReceiptSchedule_ExportAudit_ID)
{
if (M_ReceiptSchedule_ExportAudit_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ReceiptSchedule_ExportAudit_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ReceiptSchedule_ExportAudit_ID, M_ReceiptSchedule_ExportAudit_ID);
}
@Override
public int getM_ReceiptSchedule_ExportAudit_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ReceiptSchedule_ExportAudit_ID);
}
@Override
public de.metas.inoutcandidate.model.I_M_ReceiptSchedule getM_ReceiptSchedule()
{
return get_ValueAsPO(COLUMNNAME_M_ReceiptSchedule_ID, de.metas.inoutcandidate.model.I_M_ReceiptSchedule.class);
}
@Override
public void setM_ReceiptSchedule(final de.metas.inoutcandidate.model.I_M_ReceiptSchedule M_ReceiptSchedule)
{
set_ValueFromPO(COLUMNNAME_M_ReceiptSchedule_ID, de.metas.inoutcandidate.model.I_M_ReceiptSchedule.class, M_ReceiptSchedule);
}
@Override
public void setM_ReceiptSchedule_ID (final int M_ReceiptSchedule_ID)
{
if (M_ReceiptSchedule_ID < 1)
set_Value (COLUMNNAME_M_ReceiptSchedule_ID, null);
|
else
set_Value (COLUMNNAME_M_ReceiptSchedule_ID, M_ReceiptSchedule_ID);
}
@Override
public int getM_ReceiptSchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ReceiptSchedule_ID);
}
@Override
public void setTransactionIdAPI (final @Nullable java.lang.String TransactionIdAPI)
{
set_Value (COLUMNNAME_TransactionIdAPI, TransactionIdAPI);
}
@Override
public java.lang.String getTransactionIdAPI()
{
return get_ValueAsString(COLUMNNAME_TransactionIdAPI);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ReceiptSchedule_ExportAudit.java
| 1
|
请完成以下Java代码
|
public Mono<ProfileView> getProfile(String profileUsername, User viewer) {
return userRepository.findByUsernameOrFail(profileUsername)
.map(user -> ProfileView.toProfileViewForViewer(user, viewer));
}
public Mono<ProfileView> getProfile(String profileUsername) {
return userRepository.findByUsernameOrFail(profileUsername)
.map(ProfileView::toUnfollowedProfileView);
}
public Mono<UserView> signup(UserRegistrationRequest request) {
return credentialsService.signup(request);
}
public Mono<UserView> login(UserAuthenticationRequest request) {
return credentialsService.login(request);
}
public Mono<UserView> updateUser(UpdateUserRequest request, UserSession userSession) {
var user = userSession.user();
var token = userSession.token();
return userUpdater.updateUser(request, user)
.flatMap(userRepository::save)
.map(it -> UserView.fromUserAndToken(it, token));
}
public Mono<ProfileView> follow(String username, User follower) {
|
return userRepository.findByUsernameOrFail(username)
.flatMap(userToFollow -> {
follower.follow(userToFollow);
return userRepository.save(follower).thenReturn(userToFollow);
})
.map(ProfileView::toFollowedProfileView);
}
public Mono<ProfileView> unfollow(String username, User follower) {
return userRepository.findByUsernameOrFail(username)
.flatMap(userToUnfollow -> {
follower.unfollow(userToUnfollow);
return userRepository.save(follower).thenReturn(userToUnfollow);
})
.map(ProfileView::toUnfollowedProfileView);
}
}
|
repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\user\UserFacade.java
| 1
|
请完成以下Java代码
|
public static VariableInstanceDto fromVariableInstance(VariableInstance variableInstance) {
VariableInstanceDto dto = new VariableInstanceDto();
dto.id = variableInstance.getId();
dto.name = variableInstance.getName();
dto.processDefinitionId = variableInstance.getProcessDefinitionId();
dto.processInstanceId = variableInstance.getProcessInstanceId();
dto.executionId = variableInstance.getExecutionId();
dto.caseExecutionId = variableInstance.getCaseExecutionId();
dto.caseInstanceId = variableInstance.getCaseInstanceId();
dto.taskId = variableInstance.getTaskId();
dto.batchId = variableInstance.getBatchId();
dto.activityInstanceId = variableInstance.getActivityInstanceId();
|
dto.tenantId = variableInstance.getTenantId();
if(variableInstance.getErrorMessage() == null) {
VariableValueDto.fromTypedValue(dto, variableInstance.getTypedValue());
}
else {
dto.errorMessage = variableInstance.getErrorMessage();
dto.type = VariableValueDto.toRestApiTypeName(variableInstance.getTypeName());
}
return dto;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\VariableInstanceDto.java
| 1
|
请完成以下Java代码
|
private PayloadMod createPayloadMod(
@NonNull final DunningToExport dunning,
@NonNull final XmlPayload xPayLoad)
{
return PayloadMod.builder()
.type(RequestType.REMINDER.getValue())
.reminder(createReminder(dunning))
.bodyMod(createBodyMod(dunning))
.build();
}
private XmlReminder createReminder(@NonNull final DunningToExport dunning)
{
final XmlReminder createReminder = XmlReminder.builder()
.requestDate(asXmlCalendar(dunning.getDunningDate()))
.requestTimestamp(BigInteger.valueOf(dunning.getDunningTimestamp().getEpochSecond()))
.requestId(dunning.getDocumentNumber())
.reminderText(dunning.getDunningText())
.reminderLevel("1")
.build();
return createReminder;
}
private BodyMod createBodyMod(
@NonNull final DunningToExport dunning)
{
return BodyMod
.builder()
.prologMod(createPrologMod(dunning.getMetasfreshVersion()))
.balanceMod(createBalanceMod(dunning))
.build();
}
private PrologMod createPrologMod(@NonNull final MetasfreshVersion metasfreshVersion)
{
final SoftwareMod softwareMod = createSoftwareMod(metasfreshVersion);
return PrologMod.builder()
.pkgMod(softwareMod)
.generatorMod(createSoftwareMod(metasfreshVersion))
.build();
}
private XMLGregorianCalendar asXmlCalendar(@NonNull final Calendar cal)
{
try
{
final GregorianCalendar gregorianCal = new GregorianCalendar(cal.getTimeZone());
gregorianCal.setTime(cal.getTime());
return DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCal);
|
}
catch (final DatatypeConfigurationException e)
{
throw new AdempiereException(e).appendParametersToMessage()
.setParameter("cal", cal);
}
}
private SoftwareMod createSoftwareMod(@NonNull final MetasfreshVersion metasfreshVersion)
{
final long versionNumber = metasfreshVersion.getMajor() * 100 + metasfreshVersion.getMinor(); // .. as advised in the documentation
return SoftwareMod
.builder()
.name("metasfresh")
.version(versionNumber)
.description(metasfreshVersion.getFullVersion())
.id(0L)
.copyright("Copyright (C) 2018 metas GmbH")
.build();
}
private BalanceMod createBalanceMod(@NonNull final DunningToExport dunning)
{
final Money amount = dunning.getAmount();
final Money alreadyPaidAmount = dunning.getAlreadyPaidAmount();
final BigDecimal amountDue = amount.getAmount().subtract(alreadyPaidAmount.getAmount());
return BalanceMod.builder()
.currency(amount.getCurrency())
.amount(amount.getAmount())
.amountDue(amountDue)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\base\export\dunning\DunningExportClientImpl.java
| 1
|
请完成以下Java代码
|
public void add(String id, ProcessDefinitionInfoCacheObject obj) {
cache.put(id, obj);
}
public void remove(String id) {
cache.remove(id);
}
public void clear() {
cache.clear();
}
// For testing purposes only
public int size() {
return cache.size();
}
protected ProcessDefinitionInfoCacheObject retrieveProcessDefinitionInfoCacheObject(
String processDefinitionId,
CommandContext commandContext
) {
ProcessDefinitionInfoEntityManager infoEntityManager = commandContext.getProcessDefinitionInfoEntityManager();
ObjectMapper objectMapper = commandContext.getProcessEngineConfiguration().getObjectMapper();
ProcessDefinitionInfoCacheObject cacheObject = null;
if (cache.containsKey(processDefinitionId)) {
cacheObject = cache.get(processDefinitionId);
} else {
cacheObject = new ProcessDefinitionInfoCacheObject();
cacheObject.setRevision(0);
cacheObject.setInfoNode(objectMapper.createObjectNode());
}
ProcessDefinitionInfoEntity infoEntity = infoEntityManager.findProcessDefinitionInfoByProcessDefinitionId(
processDefinitionId
|
);
if (infoEntity != null && infoEntity.getRevision() != cacheObject.getRevision()) {
cacheObject.setRevision(infoEntity.getRevision());
if (infoEntity.getInfoJsonId() != null) {
byte[] infoBytes = infoEntityManager.findInfoJsonById(infoEntity.getInfoJsonId());
try {
ObjectNode infoNode = (ObjectNode) objectMapper.readTree(infoBytes);
cacheObject.setInfoNode(infoNode);
} catch (Exception e) {
throw new ActivitiException(
"Error reading json info node for process definition " + processDefinitionId,
e
);
}
}
} else if (infoEntity == null) {
cacheObject.setRevision(0);
cacheObject.setInfoNode(objectMapper.createObjectNode());
}
return cacheObject;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\deploy\ProcessDefinitionInfoCache.java
| 1
|
请完成以下Spring Boot application配置
|
spring.datasource.url=jdbc:mysql://localhost:3306/bookstoredb?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MyS
|
QL8Dialect
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.session.events.log.LOG_QUERIES_SLOWER_THAN_MS=25
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootLogSlowQueries545\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public java.lang.String getDataType ()
{
return (java.lang.String)get_Value(COLUMNNAME_DataType);
}
/** Set Dezimal-Punkt.
@param DecimalPoint
Decimal Point in the data file - if any
*/
@Override
public void setDecimalPoint (java.lang.String DecimalPoint)
{
set_Value (COLUMNNAME_DecimalPoint, DecimalPoint);
}
/** Get Dezimal-Punkt.
@return Decimal Point in the data file - if any
*/
@Override
public java.lang.String getDecimalPoint ()
{
return (java.lang.String)get_Value(COLUMNNAME_DecimalPoint);
}
/** Set Durch 100 teilen.
@param DivideBy100
Divide number by 100 to get correct amount
*/
@Override
public void setDivideBy100 (boolean DivideBy100)
{
set_Value (COLUMNNAME_DivideBy100, Boolean.valueOf(DivideBy100));
}
/** Get Durch 100 teilen.
@return Divide number by 100 to get correct amount
*/
@Override
public boolean isDivideBy100 ()
{
Object oo = get_Value(COLUMNNAME_DivideBy100);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set End-Nr..
@param EndNo End-Nr. */
@Override
public void setEndNo (int EndNo)
{
set_Value (COLUMNNAME_EndNo, Integer.valueOf(EndNo));
}
/** Get End-Nr..
@return End-Nr. */
@Override
public int getEndNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_EndNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name Name */
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Skript.
@param Script
Dynamic Java Language Script to calculate result
*/
@Override
public void setScript (java.lang.String Script)
{
set_Value (COLUMNNAME_Script, Script);
}
/** Get Skript.
@return Dynamic Java Language Script to calculate result
*/
|
@Override
public java.lang.String getScript ()
{
return (java.lang.String)get_Value(COLUMNNAME_Script);
}
/** Set Reihenfolge.
@param SeqNo
Method of ordering records; lowest number comes first
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Method of ordering records; lowest number comes first
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Start No.
@param StartNo
Starting number/position
*/
@Override
public void setStartNo (int StartNo)
{
set_Value (COLUMNNAME_StartNo, Integer.valueOf(StartNo));
}
/** Get Start No.
@return Starting number/position
*/
@Override
public int getStartNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_StartNo);
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_ImpFormat_Row.java
| 1
|
请完成以下Java代码
|
public HUConsolidationJob updateById(@NonNull final HUConsolidationJobId id, @NonNull final UnaryOperator<HUConsolidationJob> mapper)
{
return trxManager.callInThreadInheritedTrx(() -> {
final HUConsolidationJob job = getById(id);
final HUConsolidationJob jobChanged = mapper.apply(job);
if (Objects.equals(job, jobChanged))
{
return job;
}
save(jobChanged);
return jobChanged;
});
}
public void save(final HUConsolidationJob job)
{
jobs.put(job.getId(), job);
}
public List<HUConsolidationJob> getByNotProcessedAndResponsibleId(final @NonNull UserId userId)
{
return jobs.values()
|
.stream()
.filter(job -> UserId.equals(job.getResponsibleId(), userId)
&& !job.getDocStatus().isProcessed())
.collect(ImmutableList.toImmutableList());
}
public ImmutableSet<PickingSlotId> getInUsePickingSlotIds()
{
return jobs.values()
.stream()
.filter(job -> !job.getDocStatus().isProcessed())
.flatMap(job -> job.getPickingSlotIds().stream())
.collect(ImmutableSet.toImmutableSet());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\job\HUConsolidationJobRepository.java
| 1
|
请完成以下Java代码
|
private static void sortStream() {
map.entrySet().stream()
.sorted(Map.Entry.<String, Employee>comparingByKey().reversed())
.forEach(System.out::println);
Map<String, Employee> result = map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
result.entrySet().forEach(System.out::println);
}
private static void treeSetByValue() {
SortedSet<Employee> values = new TreeSet<>(map.values());
System.out.println(values);
}
private static void treeSetByKey() {
SortedSet<String> keysSet = new TreeSet<>(map.keySet());
System.out.println(keysSet);
}
private static void treeMapSortByKey() {
TreeMap<String, Employee> sorted = new TreeMap<>(map);
sorted.putAll(map);
sorted.entrySet().forEach(System.out::println);
}
private static void arrayListSortByValue() {
List<Employee> employeeById = new ArrayList<>(map.values());
Collections.sort(employeeById);
System.out.println(employeeById);
}
private static void arrayListSortByKey() {
List<String> employeeByKey = new ArrayList<>(map.keySet());
Collections.sort(employeeByKey);
System.out.println(employeeByKey);
}
|
private static void initialize() {
Employee employee1 = new Employee(1L, "Mher");
map.put(employee1.getName(), employee1);
Employee employee2 = new Employee(22L, "Annie");
map.put(employee2.getName(), employee2);
Employee employee3 = new Employee(8L, "John");
map.put(employee3.getName(), employee3);
Employee employee4 = new Employee(2L, "George");
map.put(employee4.getName(), employee4);
}
private static void addDuplicates() {
Employee employee5 = new Employee(1L, "Mher");
map.put(employee5.getName(), employee5);
Employee employee6 = new Employee(22L, "Annie");
map.put(employee6.getName(), employee6);
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-maps\src\main\java\com\baeldung\map\sort\SortHashMap.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 8888
spring:
application:
name: demo-config-server
profiles:
active: native # TODO 采用的方案
cloud:
config:
serv
|
er:
native:
search-locations: classpath:/shared
|
repos\SpringBoot-Labs-master\labx-12-spring-cloud-config\labx-12-sc-config-server-demo\src\main\resources\application.yml
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class JksSslBundleProperties extends SslBundleProperties {
/**
* Keystore properties.
*/
private final Store keystore = new Store();
/**
* Truststore properties.
*/
private final Store truststore = new Store();
public Store getKeystore() {
return this.keystore;
}
public Store getTruststore() {
return this.truststore;
}
/**
* Store properties.
*/
public static class Store {
/**
* Type of the store to create, e.g. JKS.
*/
private @Nullable String type;
/**
* Provider for the store.
*/
private @Nullable String provider;
/**
* Location of the resource containing the store content.
*/
private @Nullable String location;
/**
* Password used to access the store.
*/
|
private @Nullable String password;
public @Nullable String getType() {
return this.type;
}
public void setType(@Nullable String type) {
this.type = type;
}
public @Nullable String getProvider() {
return this.provider;
}
public void setProvider(@Nullable String provider) {
this.provider = provider;
}
public @Nullable String getLocation() {
return this.location;
}
public void setLocation(@Nullable String location) {
this.location = location;
}
public @Nullable String getPassword() {
return this.password;
}
public void setPassword(@Nullable String password) {
this.password = password;
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\ssl\JksSslBundleProperties.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void unimportCostsFromRepairOrder(@NonNull final RepairManufacturingOrderInfo repairOrder)
{
final ServiceRepairProjectTaskId taskId = projectTaskRepository
.getTaskIdByRepairOrderId(repairOrder.getProjectId(), repairOrder.getId())
.orElseThrow(() -> new AdempiereException("No task found for " + repairOrder));
final ImmutableList<ServiceRepairProjectCostCollector> costCollectorsToDelete = projectCostCollectorRepository
.getByTaskId(taskId)
.stream()
.filter(ServiceRepairProjectCostCollector::isNotIncludedInCustomerQuotation)
.collect(ImmutableList.toImmutableList());
deleteCostCollectors(costCollectorsToDelete, false);
projectTaskRepository.save(
projectTaskRepository.getById(taskId)
.withRepairOrderNotDone());
}
private void deleteCostCollectors(
@NonNull final Collection<ServiceRepairProjectCostCollector> costCollectors,
final boolean deleteHUReservations)
{
if (costCollectors.isEmpty())
{
return;
}
final HashSet<HuId> reservedVHUIds = new HashSet<>();
final HashSet<ServiceRepairProjectCostCollectorId> costCollectorIdsToDelete = new HashSet<>();
final ArrayList<AddQtyToProjectTaskRequest> addQtyToProjectTaskRequests = new ArrayList<>();
for (final ServiceRepairProjectCostCollector costCollector : costCollectors)
{
if (deleteHUReservations && costCollector.getVhuId() != null)
{
reservedVHUIds.add(costCollector.getVhuId());
}
|
addQtyToProjectTaskRequests.add(extractAddQtyToProjectTaskRequest(costCollector).negate());
costCollectorIdsToDelete.add(costCollector.getId());
}
huReservationService.deleteReservationsByVHUIds(reservedVHUIds);
projectCostCollectorRepository.deleteByIds(costCollectorIdsToDelete);
addQtyToProjectTaskRequests.forEach(this::addQtyToProjectTask);
}
public void unlinkQuotationFromProject(@NonNull final ProjectId projectId, @NonNull final OrderId quotationId)
{
projectCostCollectorRepository.unsetCustomerQuotation(projectId, quotationId);
}
public void unlinkProposalLineFromProject(@NonNull final OrderAndLineId proposalLineId)
{
projectCostCollectorRepository.unsetCustomerQuotationLine(proposalLineId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\service\ServiceRepairProjectService.java
| 2
|
请完成以下Java代码
|
public Map<String, TaskTemplateDefinition> getTasks() {
return tasks;
}
public void setTasks(Map<String, TaskTemplateDefinition> tasks) {
this.tasks = tasks;
}
public TaskTemplateDefinition getDefaultTemplate() {
return defaultTemplate;
}
public void setDefaultTemplate(TaskTemplateDefinition defaultTemplate) {
this.defaultTemplate = defaultTemplate;
}
public Optional<TemplateDefinition> findAssigneeTemplateForTask(String taskUUID) {
TaskTemplateDefinition taskTemplateDefinition = tasks.get(taskUUID);
if (taskTemplateDefinition == null) {
return Optional.empty();
}
return Optional.ofNullable(taskTemplateDefinition.getAssignee());
}
public Optional<TemplateDefinition> findCandidateTemplateForTask(String taskUUID) {
TaskTemplateDefinition taskTemplateDefinition = tasks.get(taskUUID);
if (taskTemplateDefinition == null) {
return Optional.empty();
}
return Optional.ofNullable(taskTemplateDefinition.getCandidate());
}
public boolean isEmailNotificationEnabledForTask(String taskUUID) {
TaskTemplateDefinition taskTemplateDefinition = tasks.get(taskUUID);
if (taskTemplateDefinition == null) {
|
return true;
}
return taskTemplateDefinition.isEmailNotificationEnabled();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TemplatesDefinition that = (TemplatesDefinition) o;
return Objects.equals(tasks, that.tasks) && Objects.equals(defaultTemplate, that.defaultTemplate);
}
@Override
public int hashCode() {
return Objects.hash(tasks, defaultTemplate);
}
}
|
repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\model\TemplatesDefinition.java
| 1
|
请完成以下Java代码
|
private static void failIfInvoiced(@Nullable final I_C_Invoice_Candidate icRecord)
{
if (icRecord != null && icRecord.getQtyInvoiced().signum() != 0)
{
throw new AdempiereException("@" + MSG_DATA_ENTRY_ALREADY_INVOICED_0P + "@");
}
}
private void deleteInvoiceCandidate(@NonNull final I_C_Flatrate_DataEntry dataEntry)
{
final InvoiceCandidateId invoiceCandId = InvoiceCandidateId.ofRepoIdOrNull(dataEntry.getC_Invoice_Candidate_ID());
if (invoiceCandId != null)
{
final I_C_Invoice_Candidate invoiceCandidate = invoiceCandDAO.getById(invoiceCandId);
if (invoiceCandidate != null)
{
dataEntry.setC_Invoice_Candidate_ID(0);
InterfaceWrapperHelper.delete(invoiceCandidate);
}
}
invoiceCandDAO.deleteAllReferencingInvoiceCandidates(dataEntry);
}
private void deleteInvoiceCandidateCorr(@NonNull final I_C_Flatrate_DataEntry dataEntry)
{
final InvoiceCandidateId invoiceCandId = InvoiceCandidateId.ofRepoIdOrNull(dataEntry.getC_Invoice_Candidate_Corr_ID());
if (invoiceCandId != null)
{
final I_C_Invoice_Candidate icCorr = invoiceCandDAO.getById(invoiceCandId);
if (icCorr != null)
{
dataEntry.setC_Invoice_Candidate_Corr_ID(0);
|
InterfaceWrapperHelper.delete(icCorr);
}
}
}
private void afterReactivate(final I_C_Flatrate_DataEntry dataEntry)
{
if (X_C_Flatrate_DataEntry.TYPE_Invoicing_PeriodBased.equals(dataEntry.getType()))
{
final IFlatrateDAO flatrateDB = Services.get(IFlatrateDAO.class);
final List<I_C_Invoice_Clearing_Alloc> allocLines = flatrateDB.retrieveClearingAllocs(dataEntry);
for (final I_C_Invoice_Clearing_Alloc alloc : allocLines)
{
final I_C_Invoice_Candidate candToClear = alloc.getC_Invoice_Cand_ToClear();
candToClear.setQtyInvoiced(BigDecimal.ZERO);
InterfaceWrapperHelper.save(candToClear);
alloc.setC_Invoice_Candidate_ID(0);
InterfaceWrapperHelper.save(alloc);
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\interceptor\C_Flatrate_DataEntry.java
| 1
|
请完成以下Java代码
|
public void afterSave(final I_C_ElementValue elementValue)
{
createValidCombinationIfNeeded(elementValue);
}
@VisibleForTesting
protected void createValidCombinationIfNeeded(final I_C_ElementValue elementValue)
{
if (elementValue.isSummary())
{
return;
}
final AccountDimension.Builder accountDimensionTemplate = AccountDimension.builder()
//.setAcctSchemaId(acctSchema.getId())
.setC_ElementValue_ID(elementValue.getC_ElementValue_ID())
.setAD_Client_ID(elementValue.getAD_Client_ID())
.setAD_Org_ID(OrgId.ANY.getRepoId());
final ChartOfAccountsId chartOfAccountsId = ChartOfAccountsId.ofRepoId(elementValue.getC_Element_ID());
for (final AcctSchema acctSchema : acctSchemasRepo.getByChartOfAccountsId(chartOfAccountsId))
{
|
accountDAO.getOrCreateWithinTrx(accountDimensionTemplate.setAcctSchemaId(acctSchema.getId()).build());
}
}
public static IAutoCloseable temporaryDisableUpdateTreeNode()
{
final boolean wasDisabled = updateTreeNodeDisabled.getAndSet(true);
return () -> updateTreeNodeDisabled.set(wasDisabled);
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = { I_C_ElementValue.COLUMNNAME_Parent_ID, I_C_ElementValue.COLUMNNAME_SeqNo })
public void updateTreeNode(final I_C_ElementValue record)
{
if (updateTreeNodeDisabled.get())
{
return;
}
final ElementValue elementValue = ElementValueRepository.fromRecord(record);
treeNodeService.updateTreeNode(elementValue);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\interceptor\C_ElementValue.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Map<HUQRCodeUniqueId, HuId> getHuIds(@NonNull final Collection<HUQRCode> huQrCodes)
{
return huQRCodesRepository.getHUAssignmentsByQRCode(huQrCodes)
.stream()
.collect(ImmutableMap.toImmutableMap(HUQRCodeAssignment::getId, HUQRCodeAssignment::getSingleHUId));
}
public IHUQRCode parse(@NonNull final String jsonString)
{
return parse(ScannedCode.ofString(jsonString));
}
public IHUQRCode parse(@NonNull final ScannedCode scannedCode)
{
final PickOnTheFlyQRCode pickOnTheFlyQRCode = PickOnTheFlyQRCode.fromScannedCodeOrNullIfNotHandled(scannedCode);
if (pickOnTheFlyQRCode != null)
{
return pickOnTheFlyQRCode;
}
final GlobalQRCode globalQRCode = scannedCode.toGlobalQRCodeIfMatching().orNullIfError();
if (globalQRCode != null)
{
if (HUQRCode.isHandled(globalQRCode))
{
return HUQRCode.fromGlobalQRCode(globalQRCode);
}
else if (LMQRCode.isHandled(globalQRCode))
{
return LMQRCode.fromGlobalQRCode(globalQRCode);
}
}
final CustomHUQRCode customHUQRCode = scannableCodeFormatService.parse(scannedCode)
.map(CustomHUQRCode::ofParsedScannedCode)
.orElse(null);
|
if (customHUQRCode != null)
{
return customHUQRCode;
}
// M_HU.Value / ExternalBarcode attribute
{
final HuId huId = handlingUnitsBL.getHUIdByValueOrExternalBarcode(scannedCode).orElse(null);
if (huId != null)
{
return getFirstQRCodeByHuId(huId);
}
}
final GS1HUQRCode gs1HUQRCode = GS1HUQRCode.fromScannedCodeOrNullIfNotHandled(scannedCode);
if (gs1HUQRCode != null)
{
return gs1HUQRCode;
}
final EAN13HUQRCode ean13HUQRCode = EAN13HUQRCode.fromScannedCodeOrNullIfNotHandled(scannedCode);
if (ean13HUQRCode != null)
{
return ean13HUQRCode;
}
throw new AdempiereException("QR code is not handled: " + scannedCode);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\service\HUQRCodesService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public PageResult<OnlineUser> onlineUser(PageCondition pageCondition) {
PageResult<String> keys = redisUtil.findKeysForPage(Consts.REDIS_JWT_KEY_PREFIX + Consts.SYMBOL_STAR, pageCondition.getCurrentPage(), pageCondition.getPageSize());
List<String> rows = keys.getRows();
Long total = keys.getTotal();
// 根据 redis 中键获取用户名列表
List<String> usernameList = rows.stream().map(s -> StrUtil.subAfter(s, Consts.REDIS_JWT_KEY_PREFIX, true)).collect(Collectors.toList());
// 根据用户名查询用户信息
List<User> userList = userDao.findByUsernameIn(usernameList);
// 封装在线用户信息
List<OnlineUser> onlineUserList = Lists.newArrayList();
userList.forEach(user -> onlineUserList.add(OnlineUser.create(user)));
return new PageResult<>(onlineUserList, total);
}
/**
* 踢出在线用户
|
*
* @param names 用户名列表
*/
public void kickout(List<String> names) {
// 清除 Redis 中的 JWT 信息
List<String> redisKeys = names.parallelStream().map(s -> Consts.REDIS_JWT_KEY_PREFIX + s).collect(Collectors.toList());
redisUtil.delete(redisKeys);
// 获取当前用户名
String currentUsername = SecurityUtil.getCurrentUsername();
names.parallelStream().forEach(name -> {
// TODO: 通知被踢出的用户已被当前登录用户踢出,
// 后期考虑使用 websocket 实现,具体伪代码实现如下。
// String message = "您已被用户【" + currentUsername + "】手动下线!";
log.debug("用户【{}】被用户【{}】手动下线!", name, currentUsername);
});
}
}
|
repos\spring-boot-demo-master\demo-rbac-security\src\main\java\com\xkcoding\rbac\security\service\MonitorService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public PmsMenu getById(Long pid) {
return pmsMenuDao.getById(pid);
}
/**
* 更新菜单.
*
* @param menu
*/
public void update(PmsMenu menu) {
pmsMenuDao.update(menu);
}
/**
* 根据角色查找角色对应的菜单ID集
*
|
* @param roleId
* @return
*/
public String getMenuIdsByRoleId(Long roleId) {
List<PmsMenuRole> menuList = pmsMenuRoleDao.listByRoleId(roleId);
StringBuffer menuIds = new StringBuffer("");
if (menuList != null && !menuList.isEmpty()) {
for (PmsMenuRole rm : menuList) {
menuIds.append(rm.getMenuId()).append(",");
}
}
return menuIds.toString();
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\service\impl\PmsMenuServiceImpl.java
| 2
|
请完成以下Java代码
|
public void addChangedRowIds(@Nullable final DocumentIdsSelection rowIds)
{
// Don't collect rowIds if this was already flagged as fully changed.
if (fullyChanged)
{
return;
}
if (rowIds == null || rowIds.isEmpty())
{
return;
}
else if (rowIds.isAll())
{
fullyChanged = true;
changedRowIds = null;
}
else
{
if (changedRowIds == null)
{
changedRowIds = new HashSet<>();
}
changedRowIds.addAll(rowIds.toSet());
}
}
public void addChangedRowIds(final Collection<DocumentId> rowIds)
{
if (rowIds.isEmpty())
{
return;
}
if (changedRowIds == null)
{
changedRowIds = new HashSet<>();
}
changedRowIds.addAll(rowIds);
}
public void addChangedRowId(@NonNull final DocumentId rowId)
{
if (changedRowIds == null)
|
{
changedRowIds = new HashSet<>();
}
changedRowIds.add(rowId);
}
public DocumentIdsSelection getChangedRowIds()
{
final boolean fullyChanged = this.fullyChanged;
final Set<DocumentId> changedRowIds = this.changedRowIds;
if (fullyChanged)
{
return DocumentIdsSelection.ALL;
}
else if (changedRowIds == null || changedRowIds.isEmpty())
{
return DocumentIdsSelection.EMPTY;
}
else
{
return DocumentIdsSelection.of(changedRowIds);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\event\ViewChanges.java
| 1
|
请完成以下Java代码
|
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append(entry);
sb.append(' ');
sb.append(type);
sb.append(' ');
sb.append(synonymList);
return sb.toString();
}
/**
* 语义距离
*
* @param other
* @return
*/
public long distance(SynonymItem other)
{
|
return entry.distance(other.entry);
}
/**
* 创建一个@类型的词典之外的条目
*
* @param word
* @return
*/
public static SynonymItem createUndefined(String word)
{
SynonymItem item = new SynonymItem(new Synonym(word, word.hashCode() * 1000000 + Long.MAX_VALUE / 3), null, Type.UNDEFINED);
return item;
}
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\common\CommonSynonymDictionary.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class OrderServiceImpl implements OrderService {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private OrderDao orderDao;
@Autowired
private AccountService accountService;
@Autowired
private ProductService productService;
@Override
@DS(value = "order-ds")
@GlobalTransactional
public Integer createOrder(Long userId, Long productId, Integer price) throws Exception {
Integer amount = 1; // 购买数量,暂时设置为 1。
logger.info("[createOrder] 当前 XID: {}", RootContext.getXID());
|
// 扣减库存
productService.reduceStock(productId, amount);
// 扣减余额
accountService.reduceBalance(userId, price);
// 保存订单
OrderDO order = new OrderDO().setUserId(userId).setProductId(productId).setPayAmount(amount * price);
orderDao.saveOrder(order);
logger.info("[createOrder] 保存订单: {}", order.getId());
// 返回订单编号
return order.getId();
}
}
|
repos\SpringBoot-Labs-master\lab-52\lab-52-multiple-datasource\src\main\java\cn\iocoder\springboot\lab52\seatademo\service\impl\OrderServiceImpl.java
| 2
|
请完成以下Java代码
|
public void run(final String localTrxName)
{
final I_C_AllocationHdr allocationHdr = paymentBL.paymentWriteOff(payment, amtToWriteOff, p_AllocDateTrx, writeOffDescription);
// Make sure the payment was fully allocated
InterfaceWrapperHelper.refresh(payment, localTrxName);
Check.errorIf(!payment.isAllocated(), "C_Payment {} still has isAllocated='N' after having created {} with paymentWriteOffAmt={}", payment, allocationHdr, amtToWriteOff);
// Log the success and increase the counter
addLog("@Processed@: @C_Payment_ID@ " + payment.getDocumentNo() + "; @PaymentWriteOffAmt@=" + amtToWriteOff);
counterProcessed.incrementAndGet();
}
@Override
public boolean doCatch(final Throwable e)
{
final String errmsg = "@Error@: @C_Payment_ID@ " + payment.getDocumentNo() + ": " + e.getLocalizedMessage();
addLog(errmsg);
log.error(errmsg, e);
return true; // rollback
}
});
}
private Iterator<I_C_Payment> retrievePayments()
{
final Stopwatch stopwatch = Stopwatch.createStarted();
//
// Create the selection which we might need to update
final IQueryBuilder<I_C_Payment> queryBuilder = queryBL
.createQueryBuilder(I_C_Payment.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Payment.COLUMNNAME_AD_Client_ID, getClientId())
.addEqualsFilter(I_C_Payment.COLUMNNAME_IsAllocated, false);
if (!getProcessInfo().isInvokedByScheduler())
{
// user selection..if any
final IQueryFilter<I_C_Payment> userSelectionFilter = getProcessInfo().getQueryFilterOrElseFalse();
queryBuilder.filter(userSelectionFilter);
}
if (p_SOTrx != null)
{
queryBuilder.addEqualsFilter(I_C_Payment.COLUMNNAME_IsReceipt, p_SOTrx.toBoolean());
}
if (p_PaymentDateFrom != null)
{
queryBuilder.addCompareFilter(I_C_Payment.COLUMNNAME_DateTrx, Operator.GREATER_OR_EQUAL, p_PaymentDateFrom);
}
|
if (p_PaymentDateTo != null)
{
queryBuilder.addCompareFilter(I_C_Payment.COLUMNNAME_DateTrx, Operator.LESS_OR_EQUAL, p_PaymentDateTo);
}
final IQuery<I_C_Payment> query = queryBuilder
.orderBy(I_C_Payment.COLUMNNAME_C_Payment_ID)
.create();
addLog("Using query: " + query);
final int count = query.count();
if (count > 0)
{
final Iterator<I_C_Payment> iterator = query.iterate(I_C_Payment.class);
addLog("Found " + count + " payments to evaluate. Took " + stopwatch);
return iterator;
}
else
{
addLog("No payments found. Took " + stopwatch);
return Collections.emptyIterator();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\payment\process\C_Payment_MassWriteOff.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void onSuccess(ValidationResult result) {
if (result.getResultCode() == ValidationResultCode.OK) {
action.onSuccess(response);
} else {
onFailure(getException(result));
}
}
@Override
public void onFailure(Throwable e) {
action.onFailure(e);
}
public static Exception getException(ValidationResult result) {
ValidationResultCode resultCode = result.getResultCode();
Exception e;
switch (resultCode) {
case ENTITY_NOT_FOUND:
e = new EntityNotFoundException(result.getMessage());
break;
case UNAUTHORIZED:
e = new UnauthorizedException(result.getMessage());
|
break;
case ACCESS_DENIED:
e = new AccessDeniedException(result.getMessage());
break;
case INTERNAL_ERROR:
e = new InternalErrorException(result.getMessage());
break;
default:
e = new UnauthorizedException("Permission denied.");
break;
}
return e;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\ValidationCallback.java
| 2
|
请完成以下Java代码
|
public int getM_SerNoCtlExclude_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_SerNoCtlExclude_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_SerNoCtl getM_SerNoCtl() throws RuntimeException
{
return (I_M_SerNoCtl)MTable.get(getCtx(), I_M_SerNoCtl.Table_Name)
.getPO(getM_SerNoCtl_ID(), get_TrxName()); }
/** Set Serial No Control.
@param M_SerNoCtl_ID
Product Serial Number Control
*/
public void setM_SerNoCtl_ID (int M_SerNoCtl_ID)
{
|
if (M_SerNoCtl_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_SerNoCtl_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_SerNoCtl_ID, Integer.valueOf(M_SerNoCtl_ID));
}
/** Get Serial No Control.
@return Product Serial Number Control
*/
public int getM_SerNoCtl_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_SerNoCtl_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_SerNoCtlExclude.java
| 1
|
请完成以下Java代码
|
public String getRegistrationAttributeDescription()
{
if (m_registrationAttributeDescription == null)
getRegistrationAttribute();
return m_registrationAttributeDescription;
} // getRegistrationAttributeDescription
/**
* Get Attribute SeqNo
* @return seq no
*/
public int getSeqNo()
{
if (m_seqNo == -1)
getRegistrationAttribute();
return m_seqNo;
} // getSeqNo
/**
* Compare To
* @param o the Object to be compared.
* @return a negative integer, zero, or a positive integer as this object
* is less than, equal to, or greater than the specified object.
*/
|
public int compareTo (Object o)
{
if (o == null)
return 0;
MRegistrationValue oo = (MRegistrationValue)o;
int compare = getSeqNo() - oo.getSeqNo();
return compare;
} // compareTo
/**
* String Representation
* @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append(getSeqNo()).append(": ")
.append(getRegistrationAttribute()).append("=").append(getName());
return sb.toString();
} // toString
} // MRegistrationValue
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MRegistrationValue.java
| 1
|
请完成以下Java代码
|
public void setA_Renewal_Date (Timestamp A_Renewal_Date)
{
set_Value (COLUMNNAME_A_Renewal_Date, A_Renewal_Date);
}
/** Get Policy Renewal Date.
@return Policy Renewal Date */
public Timestamp getA_Renewal_Date ()
{
return (Timestamp)get_Value(COLUMNNAME_A_Renewal_Date);
}
/** Set Account State.
@param A_State
State of the Credit Card or Account holder
*/
public void setA_State (String A_State)
{
set_Value (COLUMNNAME_A_State, A_State);
}
/** Get Account State.
@return State of the Credit Card or Account holder
*/
public String getA_State ()
{
return (String)get_Value(COLUMNNAME_A_State);
}
|
/** Set Text.
@param Text Text */
public void setText (String Text)
{
set_Value (COLUMNNAME_Text, Text);
}
/** Get Text.
@return Text */
public String getText ()
{
return (String)get_Value(COLUMNNAME_Text);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Info_Lic.java
| 1
|
请完成以下Java代码
|
private final void destroyEditor()
{
if (editor == null)
{
return;
}
editor.dispose();
editor = null;
}
@Override
public boolean stopCellEditing()
{
if (!super.stopCellEditing())
{
return false;
|
}
destroyEditor();
return true;
}
@Override
public void cancelCellEditing()
{
super.cancelCellEditing();
destroyEditor();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindValueEditor.java
| 1
|
请完成以下Java代码
|
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Parent.
@param Parent_ID
Parent of Entity
*/
@Override
public void setParent_ID (int Parent_ID)
{
if (Parent_ID < 1)
set_Value (COLUMNNAME_Parent_ID, null);
else
set_Value (COLUMNNAME_Parent_ID, Integer.valueOf(Parent_ID));
}
/** Get Parent.
@return Parent of Entity
*/
@Override
public int getParent_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Parent_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Permission Issuer.
@param PermissionIssuer Permission Issuer */
@Override
public void setPermissionIssuer (java.lang.String PermissionIssuer)
{
set_Value (COLUMNNAME_PermissionIssuer, PermissionIssuer);
}
/** Get Permission Issuer.
@return Permission Issuer */
@Override
public java.lang.String getPermissionIssuer ()
{
return (java.lang.String)get_Value(COLUMNNAME_PermissionIssuer);
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Root Entry.
@param Root_ID Root Entry */
@Override
public void setRoot_ID (int Root_ID)
{
if (Root_ID < 1)
set_Value (COLUMNNAME_Root_ID, null);
else
set_Value (COLUMNNAME_Root_ID, Integer.valueOf(Root_ID));
}
/** Get Root Entry.
@return Root Entry */
@Override
public int getRoot_ID ()
{
|
Integer ii = (Integer)get_Value(COLUMNNAME_Root_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Gültig ab.
@param ValidFrom
Gültig ab inklusiv (erster Tag)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Gültig ab inklusiv (erster Tag)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Gültig bis.
@param ValidTo
Gültig bis inklusiv (letzter Tag)
*/
@Override
public void setValidTo (java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Gültig bis.
@return Gültig bis inklusiv (letzter Tag)
*/
@Override
public java.sql.Timestamp getValidTo ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Record_Access.java
| 1
|
请完成以下Java代码
|
public static PlainContextAware newWithThreadInheritedTrx()
{
return new PlainContextAware(Env.getCtx(), ITrx.TRXNAME_ThreadInherited);
}
/**
* @return a {@link IContextAware} for given <code>ctx</code> and <code>trxName</code>.<br>
* Its {@link #isAllowThreadInherited()} will return <code>false</code>.
*/
public static PlainContextAware newWithTrxName(final Properties ctx, @Nullable final String trxName)
{
final boolean allowThreadInherited = false;
return new PlainContextAware(ctx, trxName, allowThreadInherited);
}
public static PlainContextAware newCopy(final IContextAware contextProvider)
{
return new PlainContextAware(contextProvider.getCtx(), contextProvider.getTrxName(), contextProvider.isAllowThreadInherited());
}
private final Properties ctx;
private final String trxName;
private final boolean allowThreadInherited;
/**
* Creates an instance with {@link ITrx#TRXNAME_None} as <code>trxName</code>.
* <p>
* <b>WARNING:</b>
* <li>{@link InterfaceWrapperHelper#newInstance(Class, Object, boolean)
* and maybe other code will still use a thread-inherited trx over the "null" trx if there is any.
* <li>Use {@link #newOutOfTrx(Properties)}
*
* @deprecated please use {@link #newOutOfTrxAllowThreadInherited(Properties)}
* to get a context aware that will use a local trx but can "fall back" to thread-inherited.
*/
@Deprecated
public PlainContextAware(final Properties ctx)
{
this(ctx, ITrx.TRXNAME_None);
}
/**
* @deprecated please use {@link #newWithTrxName(Properties, String)} instead.
*/
@Deprecated
public PlainContextAware(final Properties ctx, @Nullable final String trxName)
{
this(ctx, trxName, true); // allowThreadInherited == true for backward compatibility; also see javadoc of isAllowThreadInherited.
}
private PlainContextAware(@NonNull final Properties ctx, @Nullable final String trxName, final boolean allowThreadInherited)
{
this.ctx = ctx;
this.trxName = trxName;
this.allowThreadInherited = allowThreadInherited;
|
}
@Override
public String toString()
{
return "PlainContextAware["
// +", ctx="+ctx // don't print it... it's fucking too big
+ ", trxName=" + trxName
+ "]";
}
@Override
public int hashCode()
{
return new HashcodeBuilder()
.append(ctx)
.append(trxName)
.toHashcode();
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
final PlainContextAware other = EqualsBuilder.getOther(this, obj);
if (other == null)
{
return false;
}
return new EqualsBuilder()
.appendByRef(ctx, other.ctx)
.append(trxName, other.trxName)
.isEqual();
}
@Override
public Properties getCtx()
{
return ctx;
}
@Override
public String getTrxName()
{
return trxName;
}
@Override
public boolean isAllowThreadInherited()
{
return allowThreadInherited;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\model\PlainContextAware.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setObservationRegistry(ObservationRegistry registry) {
this.observationRegistry = registry;
}
}
public static final class PostAuthorizeAuthorizationMethodInterceptor
implements FactoryBean<AuthorizationManagerAfterMethodInterceptor> {
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private ObservationRegistry observationRegistry = ObservationRegistry.NOOP;
private final PostAuthorizeAuthorizationManager manager = new PostAuthorizeAuthorizationManager();
@Override
public AuthorizationManagerAfterMethodInterceptor getObject() {
AuthorizationManager<MethodInvocationResult> manager = this.manager;
if (!this.observationRegistry.isNoop()) {
manager = new ObservationAuthorizationManager<>(this.observationRegistry, this.manager);
}
AuthorizationManagerAfterMethodInterceptor interceptor = AuthorizationManagerAfterMethodInterceptor
.postAuthorize(manager);
interceptor.setSecurityContextHolderStrategy(this.securityContextHolderStrategy);
return interceptor;
}
@Override
public Class<?> getObjectType() {
return AuthorizationManagerAfterMethodInterceptor.class;
}
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
public void setExpressionHandler(MethodSecurityExpressionHandler expressionHandler) {
this.manager.setExpressionHandler(expressionHandler);
}
public void setObservationRegistry(ObservationRegistry registry) {
this.observationRegistry = registry;
}
}
static class SecurityContextHolderStrategyFactory implements FactoryBean<SecurityContextHolderStrategy> {
@Override
public SecurityContextHolderStrategy getObject() throws Exception {
return SecurityContextHolder.getContextHolderStrategy();
}
|
@Override
public Class<?> getObjectType() {
return SecurityContextHolderStrategy.class;
}
}
static class ObservationRegistryFactory implements FactoryBean<ObservationRegistry> {
@Override
public ObservationRegistry getObject() throws Exception {
return ObservationRegistry.NOOP;
}
@Override
public Class<?> getObjectType() {
return ObservationRegistry.class;
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\method\MethodSecurityBeanDefinitionParser.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Builder setName(final String name)
{
this.name = name;
return this;
}
/**
* Sets the primary key of the {@link I_DLM_Partition_Config} records that already exists for the {@link PartitionConfig} instances that we want to build.
* This information is important when a config is persisted because it determines if a {@link I_DLM_Partition_Config} record shall be loaded and updated rather than inserted.
*
* @param dlm_Partition_Config_ID
* @return
*/
public Builder setDLM_Partition_Config_ID(final int dlm_Partition_Config_ID)
{
DLM_Partition_Config_ID = dlm_Partition_Config_ID;
return this;
}
public Builder setChanged(final boolean changed)
{
this.changed = changed;
return this;
}
private PartitionerConfigLine.LineBuilder newLine()
{
assertLineTableNamesUnique();
final PartitionerConfigLine.LineBuilder lineBuilder = new PartitionerConfigLine.LineBuilder(this);
lineBuilders.add(lineBuilder);
return lineBuilder;
}
/**
*
* @param tableName
* @return the already existing line builder for the given <code>tableName</code>, or a new one, if none existed yet.
*/
public LineBuilder line(final String tableName)
{
final Optional<LineBuilder> existingLineBuilder = lineBuilders
.stream()
.filter(b -> tableName.equals(b.getTableName()))
.findFirst();
if (existingLineBuilder.isPresent())
{
return existingLineBuilder.get();
}
setChanged(true);
|
return newLine().setTableName(tableName);
}
private void assertLineTableNamesUnique()
{
final List<LineBuilder> nonUniqueLines = lineBuilders.stream()
.collect(Collectors.groupingBy(r -> r.getTableName())) // group them by tableName; this returns a map
.entrySet().stream() // now stream the map's entries
.filter(e -> e.getValue().size() > 1) // now remove from the stream those that are OK
.flatMap(e -> e.getValue().stream()) // now get a stream with those that are not OK
.collect(Collectors.toList());
Check.errorUnless(nonUniqueLines.isEmpty(), "Found LineBuilders with duplicate tableNames: {}", nonUniqueLines);
}
public PartitionConfig build()
{
assertLineTableNamesUnique();
final PartitionConfig partitionerConfig = new PartitionConfig(name, changed);
partitionerConfig.setDLM_Partition_Config_ID(DLM_Partition_Config_ID);
// first build the lines
for (final PartitionerConfigLine.LineBuilder lineBuilder : lineBuilders)
{
final PartitionerConfigLine line = lineBuilder.buildLine(partitionerConfig);
partitionerConfig.lines.add(line);
}
for (final PartitionerConfigLine.LineBuilder lineBuilder : lineBuilders)
{
lineBuilder.buildRefs();
}
return partitionerConfig;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\config\PartitionConfig.java
| 2
|
请完成以下Java代码
|
public void setCamundaDecisionBinding(String camundaDecisionBinding) {
camundaDecisionBindingAttribute.setValue(this, camundaDecisionBinding);
}
public String getCamundaDecisionVersion() {
return camundaDecisionVersionAttribute.getValue(this);
}
public void setCamundaDecisionVersion(String camundaDecisionVersion) {
camundaDecisionVersionAttribute.setValue(this, camundaDecisionVersion);
}
public String getCamundaDecisionTenantId() {
return camundaDecisionTenantIdAttribute.getValue(this);
}
public void setCamundaDecisionTenantId(String camundaDecisionTenantId) {
camundaDecisionTenantIdAttribute.setValue(this, camundaDecisionTenantId);
}
@Override
public String getCamundaMapDecisionResult() {
return camundaMapDecisionResultAttribute.getValue(this);
}
@Override
public void setCamundaMapDecisionResult(String camundaMapDecisionResult) {
camundaMapDecisionResultAttribute.setValue(this, camundaMapDecisionResult);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DecisionTask.class, CMMN_ELEMENT_DECISION_TASK)
.namespaceUri(CMMN11_NS)
.extendsType(Task.class)
.instanceProvider(new ModelTypeInstanceProvider<DecisionTask>() {
public DecisionTask newInstance(ModelTypeInstanceContext instanceContext) {
return new DecisionTaskImpl(instanceContext);
}
});
decisionRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_DECISION_REF)
.build();
/** Camunda extensions */
camundaResultVariableAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_RESULT_VARIABLE)
.namespace(CAMUNDA_NS)
.build();
camundaDecisionBindingAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DECISION_BINDING)
.namespace(CAMUNDA_NS)
.build();
|
camundaDecisionVersionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DECISION_VERSION)
.namespace(CAMUNDA_NS)
.build();
camundaDecisionTenantIdAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DECISION_TENANT_ID)
.namespace(CAMUNDA_NS)
.build();
camundaMapDecisionResultAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_MAP_DECISION_RESULT)
.namespace(CAMUNDA_NS)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
parameterMappingCollection = sequenceBuilder.elementCollection(ParameterMapping.class)
.build();
decisionRefExpressionChild = sequenceBuilder.element(DecisionRefExpression.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\DecisionTaskImpl.java
| 1
|
请完成以下Java代码
|
public class SpringBeansResolverFactory implements ResolverFactory, Resolver {
protected static Logger LOG = Logger.getLogger(SpringBeansResolverFactory.class.getName());
protected static String SCOPE_NOT_ACTIVE_EXCEPTION = "org.springframework.beans.factory.support.ScopeNotActiveException";
private ApplicationContext applicationContext;
private Set<String> keySet;
public SpringBeansResolverFactory(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
String[] beannames = applicationContext.getBeanDefinitionNames();
this.keySet = new HashSet<>(Arrays.asList(beannames));
}
@Override
public Resolver createResolver(VariableScope variableScope) {
return this;
}
@Override
public boolean containsKey(Object key) {
if (key instanceof String) {
return keySet.contains((String) key);
} else {
return false;
}
}
@Override
public Object get(Object key) {
if (key instanceof String) {
try {
return applicationContext.getBean((String) key);
} catch (BeanCreationException ex) {
// Only swallow exceptions for beans with inactive scope.
|
// Unfortunately, we cannot use ScopeNotActiveException directly as
// it is only available starting with Spring 5.3, but we still support Spring 4.
if (SCOPE_NOT_ACTIVE_EXCEPTION.equals(ex.getClass().getName())) {
LOG.info("Bean '" + key + "' cannot be accessed since scope is not active. Instead, null is returned. "
+ "Full exception message: " + ex.getMessage());
return null;
} else {
throw ex;
}
}
} else {
return null;
}
}
@Override
public Set<String> keySet() {
return keySet;
}
}
|
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\SpringBeansResolverFactory.java
| 1
|
请完成以下Java代码
|
public Criteria andReadCountNotIn(List<Integer> values) {
addCriterion("read_count not in", values, "readCount");
return (Criteria) this;
}
public Criteria andReadCountBetween(Integer value1, Integer value2) {
addCriterion("read_count between", value1, value2, "readCount");
return (Criteria) this;
}
public Criteria andReadCountNotBetween(Integer value1, Integer value2) {
addCriterion("read_count not between", value1, value2, "readCount");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
|
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsHelpExample.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static ReactiveUserDetailsServiceResourceFactoryBean fromResourceLocation(String resourceLocation) {
ReactiveUserDetailsServiceResourceFactoryBean result = new ReactiveUserDetailsServiceResourceFactoryBean();
result.setResourceLocation(resourceLocation);
return result;
}
/**
* Create a ReactiveUserDetailsServiceResourceFactoryBean with a Resource that is a
* Properties file in the format defined in {@link UserDetailsResourceFactoryBean}.
* @param propertiesResource the Resource that is a properties file that contains the
* users
* @return the ReactiveUserDetailsServiceResourceFactoryBean
*/
public static ReactiveUserDetailsServiceResourceFactoryBean fromResource(Resource propertiesResource) {
ReactiveUserDetailsServiceResourceFactoryBean result = new ReactiveUserDetailsServiceResourceFactoryBean();
result.setResource(propertiesResource);
return result;
|
}
/**
* Create a ReactiveUserDetailsServiceResourceFactoryBean with a String that is in the
* format defined in {@link UserDetailsResourceFactoryBean}.
* @param users the users in the format defined in
* {@link UserDetailsResourceFactoryBean}
* @return the ReactiveUserDetailsServiceResourceFactoryBean
*/
public static ReactiveUserDetailsServiceResourceFactoryBean fromString(String users) {
ReactiveUserDetailsServiceResourceFactoryBean result = new ReactiveUserDetailsServiceResourceFactoryBean();
result.setResource(new InMemoryResource(users));
return result;
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\core\userdetails\ReactiveUserDetailsServiceResourceFactoryBean.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Object getPrincipal() {
return this.delegate.getPrincipal();
}
@Override
public Object getCredentials() {
return this.delegate.getCredentials();
}
@Override
public void eraseCredentials() {
this.delegate.eraseCredentials();
}
@Override
public void setDetails(Object details) {
this.delegate.setDetails(details);
}
@Override
public Object getDetails() {
return this.delegate.getDetails();
}
@Override
public void setAuthenticated(boolean authenticated) {
this.delegate.setAuthenticated(authenticated);
}
@Override
public boolean isAuthenticated() {
return this.delegate.isAuthenticated();
}
@Override
public String getName() {
return this.delegate.getName();
}
@Override
public Collection<GrantedAuthority> getAuthorities() {
return this.delegate.getAuthorities();
}
|
@Override
public Map<String, Object> getTokenAttributes() {
return this.delegate.getTokenAttributes();
}
/**
* Returns a JWT. It usually refers to a token string expressing with 'eyXXX.eyXXX.eyXXX' format.
*
* @return the token value as a String
*/
public String tokenValue() {
return delegate.getToken().getTokenValue();
}
/**
* Extract Subject from JWT. Here, Subject is the user ID in UUID format.
*
* @return the user ID as a UUID
*/
public UUID userId() {
return UUID.fromString(delegate.getName());
}
}
|
repos\realworld-java21-springboot3-main\server\api\src\main\java\io\zhc1\realworld\config\AuthToken.java
| 2
|
请完成以下Java代码
|
public static boolean twoOrMoreAreTrueByLoop(boolean a, boolean b, boolean c) {
int count = 0;
for (boolean i : new Boolean[] { a, b, c }) {
count += i ? 1 : 0;
if (count >= 2)
return true;
}
return false;
}
public static boolean xOrMoreAreTrueByLoop(boolean[] booleans, int x) {
int count = 0;
for (boolean i : booleans) {
count += i ? 1 : 0;
if (count >= x)
return true;
}
return false;
}
public static boolean twoOrMoreAreTrueBySum(boolean a, boolean b, boolean c) {
|
return (a ? 1 : 0) + (b ? 1 : 0) + (c ? 1 : 0) >= 2;
}
public static boolean xOrMoreAreTrueBySum(Boolean[] booleans, int x) {
return Arrays.stream(booleans).mapToInt(b -> Boolean.TRUE.equals(b) ? 1 : 0).sum() >= x;
}
public static boolean twoorMoreAreTrueByKarnaughMap(boolean a, boolean b, boolean c) {
return (c && (a || b)) || (a && b);
}
public static boolean twoOrMoreAreTrueByOperators(boolean a, boolean b, boolean c) {
return (a && b) || (a && c) || (b && c);
}
public static boolean twoOrMoreAreTrueByXor(boolean a, boolean b, boolean c) {
return a ^ b ? c : a;
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-operators-2\src\main\java\com\baeldung\threebool\ThreeBooleans.java
| 1
|
请完成以下Java代码
|
public class OrganisationIdentification8 {
@XmlElement(name = "AnyBIC")
protected String anyBIC;
@XmlElement(name = "Othr")
protected List<GenericOrganisationIdentification1> othr;
/**
* Gets the value of the anyBIC property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAnyBIC() {
return anyBIC;
}
/**
* Sets the value of the anyBIC property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAnyBIC(String value) {
this.anyBIC = value;
}
/**
* Gets the value of the othr property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the othr property.
*
* <p>
* For example, to add a new item, do as follows:
|
* <pre>
* getOthr().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link GenericOrganisationIdentification1 }
*
*
*/
public List<GenericOrganisationIdentification1> getOthr() {
if (othr == null) {
othr = new ArrayList<GenericOrganisationIdentification1>();
}
return this.othr;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\OrganisationIdentification8.java
| 1
|
请完成以下Java代码
|
private void loadPurchaseItem(
@NonNull final PurchaseCandidate purchaseCandidate,
@NonNull final I_C_PurchaseCandidate_Alloc record)
{
final ITableRecordReference transactionReference = TableRecordReference.ofReferencedOrNull(record);
if (record.getAD_Issue_ID() <= 0)
{
final OrderAndLineId purchaseOrderAndLineId = OrderAndLineId.ofRepoIds(record.getC_OrderPO_ID(), record.getC_OrderLinePO_ID());
final Quantity purchasedQty = orderLineBL.getQtyOrdered(purchaseOrderAndLineId);
final PurchaseOrderItem purchaseOrderItem = PurchaseOrderItem.builder()
.purchaseCandidate(purchaseCandidate)
.dimension(purchaseCandidate.getDimension())
.purchaseItemId(PurchaseItemId.ofRepoId(record.getC_PurchaseCandidate_Alloc_ID()))
.datePromised(TimeUtil.asZonedDateTime(record.getDatePromised()))
.dateOrdered(TimeUtil.asZonedDateTime(record.getDateOrdered()))
|
.purchasedQty(purchasedQty)
.remotePurchaseOrderId(record.getRemotePurchaseOrderId())
.transactionReference(transactionReference)
.purchaseOrderAndLineId(purchaseOrderAndLineId)
.build();
purchaseCandidate.addLoadedPurchaseOrderItem(purchaseOrderItem);
}
else
{
purchaseCandidate.createErrorItem()
.purchaseItemId(PurchaseItemId.ofRepoId(record.getC_PurchaseCandidate_Alloc_ID()))
.adIssueId(AdIssueId.ofRepoIdOrNull(record.getAD_Issue_ID()))
.transactionReference(transactionReference)
.buildAndAdd();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\remotepurchaseitem\PurchaseItemRepository.java
| 1
|
请完成以下Java代码
|
private ImmutableSet<AdTableId> retrieveDistinctIds(
@NonNull final String tableName,
@NonNull final String idColumnName)
{
final String sql = "SELECT " + DB_FUNCTION_RETRIEVE_DISTINCT_IDS + "(?,?)";
final Object[] sqlParams = new Object[] { tableName, idColumnName };
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None);
DB.setParameters(pstmt, ImmutableList.of(tableName, idColumnName));
rs = pstmt.executeQuery();
final ImmutableSet.Builder<AdTableId> result = ImmutableSet.builder();
while (rs.next())
{
final AdTableId adTableId = AdTableId.ofRepoIdOrNull(rs.getInt(1));
if (adTableId != null)
{
result.add(adTableId);
}
}
|
return result.build();
}
catch (final SQLException ex)
{
throw DBException.wrapIfNeeded(ex)
.appendParametersToMessage()
.setParameter("sql", sql)
.setParameter("sqlParams", sqlParams);
}
finally
{
DB.close(rs, pstmt);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\api\impl\TableRecordIdDAO.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ShipmentScheduleSubscriptionReferenceProvider implements ShipmentScheduleReferencedLineProvider
{
/**
* @return {@link I_C_SubscriptionProgress#Table_Name}.
*/
@Override
public String getTableName()
{
return I_C_SubscriptionProgress.Table_Name;
}
@Override
public ShipmentScheduleReferencedLine provideFor(@NonNull final I_M_ShipmentSchedule sched)
{
final int subscriptionProgressId = sched.getRecord_ID();
final I_C_SubscriptionProgress subscriptionLine = load(subscriptionProgressId, I_C_SubscriptionProgress.class);
Check.errorIf(subscriptionLine == null,
"Unable to load the referenced C_SubscriptionProgress for M_ShipmentSchedule_ID={}; M_ShipmentSchedule.Record_ID={}",
sched.getM_ShipmentSchedule_ID(), subscriptionProgressId);
final ZoneId timeZone = Services.get(IOrgDAO.class).getTimeZone(OrgId.ofRepoId(sched.getAD_Org_ID()));
final ZonedDateTime eventDate = TimeUtil.asZonedDateTime(subscriptionLine.getEventDate(), timeZone);
return ShipmentScheduleReferencedLine.builder()
.recordRef(TableRecordReference.of(I_C_Flatrate_Term.Table_Name, subscriptionLine.getC_Flatrate_Term_ID()))
.shipperId(ShipperId.optionalOfRepoId(1))
.deliveryDate(eventDate)
.preparationDate(eventDate)
.warehouseId(getWarehouseId(subscriptionLine))
.documentLineDescriptor(createDocumentLineDescriptor(subscriptionLine))
.build();
|
}
public WarehouseId getWarehouseId(@NonNull final I_C_SubscriptionProgress subscriptionLine)
{
return Services.get(IFlatrateBL.class).getWarehouseId(subscriptionLine.getC_Flatrate_Term());
}
private SubscriptionLineDescriptor createDocumentLineDescriptor(
@NonNull final I_C_SubscriptionProgress subscriptionLine)
{
return SubscriptionLineDescriptor.builder()
.flatrateTermId(subscriptionLine.getC_Flatrate_Term_ID())
.subscriptionProgressId(subscriptionLine.getC_SubscriptionProgress_ID())
.subscriptionBillBPartnerId(subscriptionLine.getC_Flatrate_Term().getBill_BPartner_ID())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\inoutcandidate\ShipmentScheduleSubscriptionReferenceProvider.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public R submit(@Valid @RequestBody Code code) {
return R.status(codeService.submit(code));
}
/**
* 删除
*/
@PostMapping("/remove")
@ApiOperationSupport(order = 4)
@Operation(summary = "删除", description = "传入ids")
public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
return R.status(codeService.removeByIds(Func.toLongList(ids)));
}
/**
* 复制
*/
@PostMapping("/copy")
@ApiOperationSupport(order = 5)
@Operation(summary = "复制", description = "传入id")
public R copy(@Parameter(description = "主键", required = true) @RequestParam Long id) {
Code code = codeService.getById(id);
code.setId(null);
code.setCodeName(code.getCodeName() + "-copy");
return R.status(codeService.save(code));
}
/**
* 代码生成
*/
@PostMapping("/gen-code")
@ApiOperationSupport(order = 6)
@Operation(summary = "代码生成", description = "传入ids")
public R genCode(@Parameter(description = "主键集合", required = true) @RequestParam String ids, @RequestParam(defaultValue = "saber3") String system) {
Collection<Code> codes = codeService.listByIds(Func.toLongList(ids));
codes.forEach(code -> {
BladeCodeGenerator generator = new BladeCodeGenerator();
// 设置数据源
Datasource datasource = datasourceService.getById(code.getDatasourceId());
generator.setDriverName(datasource.getDriverClass());
generator.setUrl(datasource.getUrl());
generator.setUsername(datasource.getUsername());
|
generator.setPassword(datasource.getPassword());
// 设置基础配置
generator.setSystemName(system);
generator.setServiceName(code.getServiceName());
generator.setPackageName(code.getPackageName());
generator.setPackageDir(code.getApiPath());
generator.setPackageWebDir(code.getWebPath());
generator.setTablePrefix(Func.toStrArray(code.getTablePrefix()));
generator.setIncludeTables(Func.toStrArray(code.getTableName()));
// 设置是否继承基础业务字段
generator.setHasSuperEntity(code.getBaseMode() == 2);
// 设置是否开启包装器模式
generator.setHasWrapper(code.getWrapMode() == 2);
generator.run();
});
return R.success("代码生成成功");
}
}
|
repos\SpringBlade-master\blade-ops\blade-develop\src\main\java\org\springblade\develop\controller\CodeController.java
| 2
|
请完成以下Java代码
|
public final class QualityInspectionWarehouseDestProvider implements IReceiptScheduleWarehouseDestProvider
{
public static final QualityInspectionWarehouseDestProvider instance = new QualityInspectionWarehouseDestProvider();
private static final String SYSCONFIG_QualityInspectionWarehouseDest_Prefix = "QualityInspectionWarehouseDest";
private QualityInspectionWarehouseDestProvider()
{
super();
}
@Override
public Optional<WarehouseId> getWarehouseDest(final IContext context)
{
final I_M_AttributeSetInstance asi = context.getM_AttributeSetInstance();
if (asi == null || asi.getM_AttributeSetInstance_ID() <= 0)
{
return Optional.empty();
}
final IAttributeDAO attributeDAO = Services.get(IAttributeDAO.class);
final IAttributeSetInstanceBL asiBL = Services.get(IAttributeSetInstanceBL.class);
final AttributeId qualityInspectionCycleAttributeId = attributeDAO.retrieveActiveAttributeIdByValueOrNull(IHUMaterialTrackingBL.ATTRIBUTENAME_QualityInspectionCycle);
if(qualityInspectionCycleAttributeId == null)
{
return Optional.empty();
}
final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoId(asi.getM_AttributeSetInstance_ID());
|
final I_M_AttributeInstance qualityInspectionCycleAttributeInstance = asiBL.getAttributeInstance(asiId, qualityInspectionCycleAttributeId);
if (qualityInspectionCycleAttributeInstance == null)
{
return Optional.empty();
}
final String qualityInspectionCycleValue = qualityInspectionCycleAttributeInstance.getValue();
if (Check.isEmpty(qualityInspectionCycleValue, true))
{
return Optional.empty();
}
final String sysconfigName = SYSCONFIG_QualityInspectionWarehouseDest_Prefix
+ "." + context.getM_Warehouse_ID()
+ "." + qualityInspectionCycleValue;
final int warehouseDestId = Services.get(ISysConfigBL.class).getIntValue(sysconfigName, -1, context.getAD_Client_ID(), context.getAD_Org_ID());
return WarehouseId.optionalOfRepoId(warehouseDestId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\materialtracking\impl\QualityInspectionWarehouseDestProvider.java
| 1
|
请完成以下Java代码
|
public void execute() {
execute(false, false);
}
@Override
public void execute(boolean skipCustomListeners, boolean skipIoMappings) {
execute(true, skipCustomListeners, skipIoMappings);
}
public void execute(boolean writeUserOperationLog, boolean skipCustomListeners, boolean skipIoMappings) {
this.skipCustomListeners = skipCustomListeners;
this.skipIoMappings = skipIoMappings;
ModifyProcessInstanceCmd cmd = new ModifyProcessInstanceCmd(this, writeUserOperationLog);
if (commandExecutor != null) {
commandExecutor.execute(cmd);
} else {
cmd.execute(commandContext);
}
}
@Override
public Batch executeAsync() {
return executeAsync(false, false);
}
@Override
public Batch executeAsync(boolean skipCustomListeners, boolean skipIoMappings) {
this.skipCustomListeners = skipCustomListeners;
this.skipIoMappings = skipIoMappings;
return commandExecutor.execute(new ModifyProcessInstanceAsyncCmd(this));
}
public CommandExecutor getCommandExecutor() {
return commandExecutor;
}
public CommandContext getCommandContext() {
return commandContext;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public List<AbstractProcessInstanceModificationCommand> getModificationOperations() {
return operations;
}
public void setModificationOperations(List<AbstractProcessInstanceModificationCommand> operations) {
this.operations = operations;
}
public boolean isSkipCustomListeners() {
|
return skipCustomListeners;
}
public boolean isSkipIoMappings() {
return skipIoMappings;
}
public boolean isExternallyTerminated() {
return externallyTerminated;
}
public void setSkipCustomListeners(boolean skipCustomListeners) {
this.skipCustomListeners = skipCustomListeners;
}
public void setSkipIoMappings(boolean skipIoMappings) {
this.skipIoMappings = skipIoMappings;
}
public VariableMap getProcessVariables() {
return processVariables;
}
public String getModificationReason() {
return modificationReason;
}
public void setModificationReason(String modificationReason) {
this.modificationReason = modificationReason;
}
public String getAnnotation() {
return annotation;
}
public void setAnnotationInternal(String annotation) {
this.annotation = annotation;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessInstanceModificationBuilderImpl.java
| 1
|
请完成以下Java代码
|
public int getC_HierarchyCommissionSettings_ID()
{
return get_ValueAsInt(COLUMNNAME_C_HierarchyCommissionSettings_ID);
}
@Override
public void setCommission_Product_ID (final int Commission_Product_ID)
{
if (Commission_Product_ID < 1)
set_Value (COLUMNNAME_Commission_Product_ID, null);
else
set_Value (COLUMNNAME_Commission_Product_ID, Commission_Product_ID);
}
@Override
public int getCommission_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_Commission_Product_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setIsCreateShareForOwnRevenue (final boolean IsCreateShareForOwnRevenue)
{
set_Value (COLUMNNAME_IsCreateShareForOwnRevenue, IsCreateShareForOwnRevenue);
}
@Override
public boolean isCreateShareForOwnRevenue()
{
return get_ValueAsBoolean(COLUMNNAME_IsCreateShareForOwnRevenue);
}
@Override
public void setIsSubtractLowerLevelCommissionFromBase (final boolean IsSubtractLowerLevelCommissionFromBase)
|
{
set_Value (COLUMNNAME_IsSubtractLowerLevelCommissionFromBase, IsSubtractLowerLevelCommissionFromBase);
}
@Override
public boolean isSubtractLowerLevelCommissionFromBase()
{
return get_ValueAsBoolean(COLUMNNAME_IsSubtractLowerLevelCommissionFromBase);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setPointsPrecision (final int PointsPrecision)
{
set_Value (COLUMNNAME_PointsPrecision, PointsPrecision);
}
@Override
public int getPointsPrecision()
{
return get_ValueAsInt(COLUMNNAME_PointsPrecision);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_HierarchyCommissionSettings.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.