instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private void updatePostProcessor(BeanDefinitionRegistry registry, Set<String> packagesToScan) { ServletComponentRegisteringPostProcessorBeanDefinition definition = (ServletComponentRegisteringPostProcessorBeanDefinition) registry .getBeanDefinition(BEAN_NAME); definition.addPackageNames(packagesToScan); } private void addPostProcessor(BeanDefinitionRegistry registry, Set<String> packagesToScan) { ServletComponentRegisteringPostProcessorBeanDefinition definition = new ServletComponentRegisteringPostProcessorBeanDefinition( packagesToScan); registry.registerBeanDefinition(BEAN_NAME, definition); } private Set<String> getPackagesToScan(AnnotationMetadata metadata) { AnnotationAttributes attributes = AnnotationAttributes .fromMap(metadata.getAnnotationAttributes(ServletComponentScan.class.getName())); Assert.state(attributes != null, "'attributes' must not be null"); String[] basePackages = attributes.getStringArray("basePackages"); Class<?>[] basePackageClasses = attributes.getClassArray("basePackageClasses"); Set<String> packagesToScan = new LinkedHashSet<>(Arrays.asList(basePackages)); for (Class<?> basePackageClass : basePackageClasses) { packagesToScan.add(ClassUtils.getPackageName(basePackageClass)); } if (packagesToScan.isEmpty()) { packagesToScan.add(ClassUtils.getPackageName(metadata.getClassName())); } return packagesToScan; }
static final class ServletComponentRegisteringPostProcessorBeanDefinition extends RootBeanDefinition { private final Set<String> packageNames = new LinkedHashSet<>(); ServletComponentRegisteringPostProcessorBeanDefinition(Collection<String> packageNames) { setBeanClass(ServletComponentRegisteringPostProcessor.class); setRole(BeanDefinition.ROLE_INFRASTRUCTURE); addPackageNames(packageNames); } @Override public Supplier<?> getInstanceSupplier() { return () -> new ServletComponentRegisteringPostProcessor(this.packageNames); } private void addPackageNames(Collection<String> additionalPackageNames) { this.packageNames.addAll(additionalPackageNames); } } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\context\ServletComponentScanRegistrar.java
1
请完成以下Java代码
public long getFinishedCaseInstanceCount() { return finishedCaseInstanceCount; } public void setFinishedCaseInstanceCount(Long finishedCaseInstanceCount) { this.finishedCaseInstanceCount = finishedCaseInstanceCount; } public long getCleanableCaseInstanceCount() { return cleanableCaseInstanceCount; } public void setCleanableCaseInstanceCount(Long cleanableCaseInstanceCount) { this.cleanableCaseInstanceCount = cleanableCaseInstanceCount; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) {
this.tenantId = tenantId; } public String toString() { return this.getClass().getSimpleName() + "[caseDefinitionId = " + caseDefinitionId + ", caseDefinitionKey = " + caseDefinitionKey + ", caseDefinitionName = " + caseDefinitionName + ", caseDefinitionVersion = " + caseDefinitionVersion + ", historyTimeToLive = " + historyTimeToLive + ", finishedCaseInstanceCount = " + finishedCaseInstanceCount + ", cleanableCaseInstanceCount = " + cleanableCaseInstanceCount + ", tenantId = " + tenantId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CleanableHistoricCaseInstanceReportResultEntity.java
1
请完成以下Java代码
public String getJoinAlias() { return m_joinAlias; } // getJoinAlias /** * Is Left Aouter Join * @return true if left outer join */ public boolean isLeft() { return m_left; } // isLeft /** * Get Join condition. * e.g. f.AD_Column_ID = c.AD_Column_ID * @return join condition */ public String getCondition() { return m_condition; } // getCondition /*************************************************************************/ /** * Set Main Table Name. * If table name equals alias, the alias is set to "" * @param mainTable */ public void setMainTable(String mainTable) { if (mainTable == null || mainTable.length() == 0) return; m_mainTable = mainTable; if (m_mainAlias.equals(mainTable)) m_mainAlias = ""; } // setMainTable /** * Get Main Table Name * @return Main Table Name */ public String getMainTable() { return m_mainTable; } // getMainTable /** * Set Main Table Name. * If table name equals alias, the alias is set to "" * @param joinTable */ public void setJoinTable(String joinTable) { if (joinTable == null || joinTable.length() == 0) return; m_joinTable = joinTable; if (m_joinAlias.equals(joinTable)) m_joinAlias = ""; } // setJoinTable /** * Get Join Table Name * @return Join Table Name */ public String getJoinTable() { return m_joinTable; } // getJoinTable
/*************************************************************************/ /** * This Join is a condition of the first Join. * e.g. tb.AD_User_ID(+)=? or tb.AD_User_ID(+)='123' * @param first * @return true if condition */ public boolean isConditionOf (Join first) { if (m_mainTable == null // did not find Table from "Alias" && (first.getJoinTable().equals(m_joinTable) // same join table || first.getMainAlias().equals(m_joinTable))) // same main table return true; return false; } // isConditionOf /** * String representation * @return info */ @Override public String toString() { StringBuffer sb = new StringBuffer ("Join["); sb.append(m_joinClause) .append(" - Main=").append(m_mainTable).append("/").append(m_mainAlias) .append(", Join=").append(m_joinTable).append("/").append(m_joinAlias) .append(", Left=").append(m_left) .append(", Condition=").append(m_condition) .append("]"); return sb.toString(); } // toString } // Join
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\dbPort\Join.java
1
请在Spring Boot框架中完成以下Java代码
private UserDetails getUserDetails(SecurityProperties.User user, String password) { List<String> roles = user.getRoles(); return User.withUsername(user.getName()).password(password).roles(StringUtils.toStringArray(roles)).build(); } private String getOrDeducePassword(SecurityProperties.User user, @Nullable PasswordEncoder encoder) { String password = user.getPassword(); if (user.isPasswordGenerated()) { logger.info(String.format("%n%nUsing generated security password: %s%n", user.getPassword())); } if (encoder != null || PASSWORD_ALGORITHM_PATTERN.matcher(password).matches()) { return password; } return NOOP_PASSWORD_PREFIX + password; } static class RSocketEnabledOrReactiveWebApplication extends AnyNestedCondition {
RSocketEnabledOrReactiveWebApplication() { super(ConfigurationPhase.REGISTER_BEAN); } @ConditionalOnBean(RSocketMessageHandler.class) static class RSocketSecurityEnabledCondition { } @ConditionalOnWebApplication(type = Type.REACTIVE) static class ReactiveWebApplicationCondition { } } }
repos\spring-boot-4.0.1\module\spring-boot-security\src\main\java\org\springframework\boot\security\autoconfigure\ReactiveUserDetailsServiceAutoConfiguration.java
2
请完成以下Java代码
public void updateJobPriorityByDefinitionId(String jobDefinitionId, long priority) { Map<String, Object> parameters = new HashMap<>(); parameters.put("jobDefinitionId", jobDefinitionId); parameters.put("priority", priority); getDbEntityManager().update(JobEntity.class, "updateJobPriorityByDefinitionId", parameters); } protected void configureQuery(JobQueryImpl query) { getAuthorizationManager().configureJobQuery(query); getTenantManager().configureQuery(query); } protected ListQueryParameterObject configureParameterizedQuery(Object parameter) { return getTenantManager().configureQuery(parameter); }
protected boolean isEnsureJobDueDateNotNull() { return Context.getProcessEngineConfiguration().isEnsureJobDueDateNotNull(); } /** * Sometimes we get a notification of a job that is not yet due, so we * should not execute it immediately */ protected boolean isJobDue(JobEntity job) { Date duedate = job.getDuedate(); Date now = ClockUtil.getCurrentTime(); return duedate == null || duedate.getTime() <= now.getTime(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\JobManager.java
1
请完成以下Java代码
public class ImageCode { private BufferedImage image; private String code; private LocalDateTime expireTime; public ImageCode(BufferedImage image, String code, int expireIn) { this.image = image; this.code = code; this.expireTime = LocalDateTime.now().plusSeconds(expireIn); } public ImageCode(BufferedImage image, String code, LocalDateTime expireTime) { this.image = image; this.code = code; this.expireTime = expireTime; } boolean isExpire() { return LocalDateTime.now().isAfter(expireTime); } public BufferedImage getImage() { return image; } public void setImage(BufferedImage image) { this.image = image;
} public String getCode() { return code; } public void setCode(String code) { this.code = code; } public LocalDateTime getExpireTime() { return expireTime; } public void setExpireTime(LocalDateTime expireTime) { this.expireTime = expireTime; } }
repos\SpringAll-master\36.Spring-Security-ValidateCode\src\main\java\cc\mrbird\validate\code\ImageCode.java
1
请完成以下Java代码
public HUEditorView computeIfAbsent(@NonNull final PackingHUsViewKey key, @NonNull final PackingHUsViewSupplier packingHUsViewFactory) { return packingHUsViewsByKey.computeIfAbsent(key, packingHUsViewFactory::createPackingHUsView); } public void put(@NonNull final PackingHUsViewKey key, @NonNull final HUEditorView packingHUsView) { packingHUsViewsByKey.put(key, packingHUsView); } public Optional<HUEditorView> removeIfExists(@NonNull final PackingHUsViewKey key) { final HUEditorView packingHUsViewRemoved = packingHUsViewsByKey.remove(key); return Optional.ofNullable(packingHUsViewRemoved); }
public void handleEvent(@NonNull final HUExtractedFromPickingSlotEvent event) { packingHUsViewsByKey.entrySet() .stream() .filter(entry -> isEventMatchingKey(event, entry.getKey())) .map(entry -> entry.getValue()) .forEach(packingHUsView -> packingHUsView.addHUIdAndInvalidate(HuId.ofRepoId(event.getHuId()))); } private static final boolean isEventMatchingKey(final HUExtractedFromPickingSlotEvent event, final PackingHUsViewKey key) { return key.isBPartnerIdMatching(event.getBpartnerId()) && key.isBPartnerLocationIdMatching(event.getBpartnerLocationId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\PackingHUsViewsCollection.java
1
请在Spring Boot框架中完成以下Java代码
public class WebLogAspect { private Logger logger = Logger.getLogger("mongodb"); @Pointcut("execution(public * com.didispace.web..*.*(..))") public void webLog(){} @Before("webLog()") public void doBefore(JoinPoint joinPoint) throws Throwable { // 获取HttpServletRequest ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 获取要记录的日志内容 BasicDBObject logInfo = getBasicDBObject(request, joinPoint); logger.info(logInfo); } private BasicDBObject getBasicDBObject(HttpServletRequest request, JoinPoint joinPoint) { // 基本信息 BasicDBObject r = new BasicDBObject(); r.append("requestURL", request.getRequestURL().toString()); r.append("requestURI", request.getRequestURI()); r.append("queryString", request.getQueryString()); r.append("remoteAddr", request.getRemoteAddr()); r.append("remoteHost", request.getRemoteHost()); r.append("remotePort", request.getRemotePort()); r.append("localAddr", request.getLocalAddr()); r.append("localName", request.getLocalName()); r.append("method", request.getMethod()); r.append("headers", getHeadersInfo(request)); r.append("parameters", request.getParameterMap()); r.append("classMethod", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
r.append("args", Arrays.toString(joinPoint.getArgs())); return r; } /** * 获取头信息 * * @param request * @return */ private Map<String, String> getHeadersInfo(HttpServletRequest request) { Map<String, String> map = new HashMap<>(); Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String key = (String) headerNames.nextElement(); String value = request.getHeader(key); map.put(key, value); } return map; } }
repos\SpringBoot-Learning-master\1.x\Chapter4-2-5\src\main\java\com\didispace\aspect\WebLogAspect.java
2
请完成以下Java代码
private CustomizedWindowInfoMap retrieveCustomizedWindowIdsMap() { final String sql = "SELECT " + I_AD_Window.COLUMNNAME_AD_Window_ID + "," + I_AD_Window.COLUMNNAME_Overrides_Window_ID + "," + I_AD_Window.COLUMNNAME_IsOverrideInMenu + ", " + I_AD_Window.COLUMNNAME_Name + ", (SELECT array_agg(ARRAY[wtrl.ad_language, wtrl.name]) AS array_agg FROM ad_window_trl wtrl WHERE wtrl.ad_window_id = w.ad_window_id) AS name_trls" + " FROM " + I_AD_Window.Table_Name + " w" + " WHERE IsActive='Y' AND " + I_AD_Window.COLUMNNAME_Overrides_Window_ID + " IS NOT NULL" + " ORDER BY AD_Window_ID"; final List<CustomizedWindowInfo> customizedWindowInfos = DB.retrieveRows( sql, ImmutableList.of(), this::retrieveCustomizedWindowInfo); return CustomizedWindowInfoMap.ofList(customizedWindowInfos); } private CustomizedWindowInfo retrieveCustomizedWindowInfo(final ResultSet rs) throws SQLException { return CustomizedWindowInfo.builder() .customizationWindowId(AdWindowId.ofRepoId(rs.getInt(I_AD_Window.COLUMNNAME_AD_Window_ID))) .customizationWindowCaption(retrieveWindowCaption(rs)) .baseWindowId(AdWindowId.ofRepoId(rs.getInt(I_AD_Window.COLUMNNAME_Overrides_Window_ID))) .overrideInMenu(StringUtils.toBoolean(rs.getString(I_AD_Window.COLUMNNAME_IsOverrideInMenu))) .build(); } private static ImmutableTranslatableString retrieveWindowCaption(final ResultSet rs) throws SQLException { final ImmutableTranslatableString.ImmutableTranslatableStringBuilder result = ImmutableTranslatableString.builder() .defaultValue(rs.getString(I_AD_Window.COLUMNNAME_Name)); final Array sqlArray = rs.getArray("name_trls"); if (sqlArray != null) { final String[][] trls = (String[][])sqlArray.getArray(); for (final String[] languageAndName : trls) { final String adLanguage = languageAndName[0]; final String name = languageAndName[1]; result.trl(adLanguage, name); } } return result.build(); }
@Override public void assertNoCycles(@NonNull final AdWindowId adWindowId) { final LinkedHashSet<AdWindowId> seenWindowIds = new LinkedHashSet<>(); AdWindowId currentWindowId = adWindowId; while (currentWindowId != null) { if (!seenWindowIds.add(currentWindowId)) { throw new AdempiereException("Avoid cycles in customization window chain: " + seenWindowIds); } currentWindowId = retrieveBaseWindowId(currentWindowId); } } @Nullable private AdWindowId retrieveBaseWindowId(@NonNull final AdWindowId customizationWindowId) { final String sql = "SELECT " + I_AD_Window.COLUMNNAME_Overrides_Window_ID + " FROM " + I_AD_Window.Table_Name + " WHERE " + I_AD_Window.COLUMNNAME_AD_Window_ID + "=?"; final int baseWindowRepoId = DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sql, customizationWindowId); return AdWindowId.ofRepoIdOrNull(baseWindowRepoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\zoom_into\SqlCustomizedWindowInfoMapRepository.java
1
请完成以下Java代码
public static byte[] uuidToBytes(UUID uuid) { ByteBuffer buf = ByteBuffer.allocate(16); buf.putLong(uuid.getMostSignificantBits()); buf.putLong(uuid.getLeastSignificantBits()); return buf.array(); } public static UUID bytesToUuid(byte[] bytes) { ByteBuffer bb = ByteBuffer.wrap(bytes); long firstLong = bb.getLong(); long secondLong = bb.getLong(); return new UUID(firstLong, secondLong); } public static byte[] stringToBytes(String string) { return string.getBytes(StandardCharsets.UTF_8);
} public static String bytesToString(byte[] data) { return new String(data, StandardCharsets.UTF_8); } public static byte[] longToBytes(long x) { ByteBuffer longBuffer = ByteBuffer.allocate(Long.BYTES); longBuffer.putLong(0, x); return longBuffer.array(); } public static long bytesToLong(byte[] bytes) { return ByteBuffer.wrap(bytes).getLong(); } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\common\AbstractTbQueueTemplate.java
1
请完成以下Java代码
public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public Date getLastUpdatedTime() { return lastUpdatedTime; } public void setLastUpdatedTime(Date lastUpdatedTime) { this.lastUpdatedTime = lastUpdatedTime; } @Override public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } @Override public Date getTime() { return getCreateTime(); } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("HistoricVariableInstanceEntity["); sb.append("id=").append(id); sb.append(", name=").append(name); sb.append(", revision=").append(revision); sb.append(", type=").append(variableType != null ? variableType.getTypeName() : "null"); if (longValue != null) { sb.append(", longValue=").append(longValue); } if (doubleValue != null) { sb.append(", doubleValue=").append(doubleValue); } if (textValue != null) { sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40)); } if (textValue2 != null) { sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40)); } if (byteArrayRef.getId() != null) {
sb.append(", byteArrayValueId=").append(byteArrayRef.getId()); } sb.append("]"); return sb.toString(); } // non-supported (v6) @Override public String getScopeId() { return null; } @Override public String getSubScopeId() { return null; } @Override public String getScopeType() { return null; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricVariableInstanceEntity.java
1
请完成以下Spring Boot application配置
# -------------------------------------------------------------------------------- # Build info # -------------------------------------------------------------------------------- info.build.ciBuildNo=@env.BUILD_NUMBER@ info.build.ciBuildTag=@env.BUILD_TAG@ info.build.ciBuildUrl=@env.BUILD_URL@ info.build.ciJobName=@env.JOB_NAME@ info.build.ciGitSHA1=@env.BUILD_GIT_SHA1@ info.app.name=metasfresh-report info.app.title=metasfresh report service # # Logging # # nothing right now # logstash; see https://github.com/metasfresh/metasfresh/issues/1504 # This application sends log events to logstash, if enabled via this property. # Not enabled by default, because it needs some infrastruction (i.e. an ELK stack) to work. If that infrastructure is in place, use it to enable this feature via command line param or centralized config. # If you are a dev and need a local ELK stack to benefit from logstash, take a look at https://github.com/metas
fresh/metasfresh-dev/tree/master/vagrant # Note that the application won't hang or crash if logstash is not avaiable or too slow. logstash.enabled=false logstash.host=localhost logstash.port=5000 # # Error handling # # see org.springframework.boot.autoconfigure.web.ErrorProperties.IncludeStacktrace #server.error.include-stacktrace=always # actuator-endpoints management.endpoints.web.exposure.include=*
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service-standalone\src\main\resources\config\application.properties
2
请完成以下Java代码
public boolean is2xxSuccessful() { return HttpStatus.Series.SUCCESSFUL.equals(getSeries()); } /** * Whether this status code is in the HTTP series * {@link org.springframework.http.HttpStatus.Series#REDIRECTION}. * @return <code>true</code> if status code is in the REDIRECTION http series */ public boolean is3xxRedirection() { return HttpStatus.Series.REDIRECTION.equals(getSeries()); } /** * Whether this status code is in the HTTP series * {@link org.springframework.http.HttpStatus.Series#CLIENT_ERROR}. * @return <code>true</code> if status code is in the CLIENT_ERROR http series */ public boolean is4xxClientError() { return HttpStatus.Series.CLIENT_ERROR.equals(getSeries()); } /** * Whether this status code is in the HTTP series * {@link org.springframework.http.HttpStatus.Series#SERVER_ERROR}. * @return <code>true</code> if status code is in the SERVER_ERROR http series */ public boolean is5xxServerError() {
return HttpStatus.Series.SERVER_ERROR.equals(getSeries()); } public HttpStatus.Series getSeries() { if (httpStatus != null) { return httpStatus.series(); } if (status != null) { return HttpStatus.Series.valueOf(status); } return null; } /** * Whether this status code is in the HTTP series * {@link org.springframework.http.HttpStatus.Series#CLIENT_ERROR} or * {@link org.springframework.http.HttpStatus.Series#SERVER_ERROR}. * @return <code>true</code> if is either CLIENT_ERROR or SERVER_ERROR */ public boolean isError() { return is4xxClientError() || is5xxServerError(); } @Override public String toString() { return new ToStringCreator(this).append("httpStatus", httpStatus).append("status", status).toString(); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\support\HttpStatusHolder.java
1
请完成以下Java代码
public class WordIndexer { public List<Integer> findWord(String textString, String word) { int index = 0; List<Integer> indexes = new ArrayList<Integer>(); String lowerCaseTextString = textString.toLowerCase(); String lowerCaseWord = word.toLowerCase(); while(index != -1) { index = lowerCaseTextString.indexOf(lowerCaseWord, index); if (index == -1) { break; } indexes.add(index); index++; } return indexes; } public List<Integer> findWordUpgrade(String textString, String word) {
int index = 0; List<Integer> indexes = new ArrayList<Integer>(); StringBuilder output = new StringBuilder(); String lowerCaseTextString = textString.toLowerCase(); String lowerCaseWord = word.toLowerCase(); int wordLength = 0; while(index != -1){ index = lowerCaseTextString.indexOf(lowerCaseWord, index + wordLength); // Slight improvement if (index != -1) { indexes.add(index); } wordLength = word.length(); } return indexes; } }
repos\tutorials-master\core-java-modules\core-java-string-algorithms-4\src\main\java\com\baeldung\searching\WordIndexer.java
1
请在Spring Boot框架中完成以下Java代码
JvmThreadMetrics jvmThreadMetrics() { return new JvmThreadMetrics(); } @Bean @ConditionalOnMissingBean ClassLoaderMetrics classLoaderMetrics() { return new ClassLoaderMetrics(); } @Bean @ConditionalOnMissingBean JvmInfoMetrics jvmInfoMetrics() { return new JvmInfoMetrics(); } @Bean @ConditionalOnMissingBean JvmCompilationMetrics jvmCompilationMetrics() { return new JvmCompilationMetrics(); } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(name = VIRTUAL_THREAD_METRICS_CLASS) static class VirtualThreadMetricsConfiguration { @Bean @ConditionalOnMissingBean(type = VIRTUAL_THREAD_METRICS_CLASS) @ImportRuntimeHints(VirtualThreadMetricsRuntimeHintsRegistrar.class) MeterBinder virtualThreadMetrics() throws ClassNotFoundException { Class<?> virtualThreadMetricsClass = ClassUtils.forName(VIRTUAL_THREAD_METRICS_CLASS, getClass().getClassLoader());
return (MeterBinder) BeanUtils.instantiateClass(virtualThreadMetricsClass); } } static final class VirtualThreadMetricsRuntimeHintsRegistrar implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { hints.reflection() .registerTypeIfPresent(classLoader, VIRTUAL_THREAD_METRICS_CLASS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS); } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\jvm\JvmMetricsAutoConfiguration.java
2
请完成以下Java代码
public static String setActivityIdToConfiguration(String jobHandlerConfiguration, String activityId) { try { JSONObject cfgJson = new JSONObject(jobHandlerConfiguration); cfgJson.put(PROPERTYNAME_TIMER_ACTIVITY_ID, activityId); return cfgJson.toString(); } catch (JSONException ex) { return jobHandlerConfiguration; } } public static String getActivityIdFromConfiguration(String jobHandlerConfiguration) { try { JSONObject cfgJson = new JSONObject(jobHandlerConfiguration); return cfgJson.get(PROPERTYNAME_TIMER_ACTIVITY_ID).toString(); } catch (JSONException ex) { return jobHandlerConfiguration; } } public static String geCalendarNameFromConfiguration(String jobHandlerConfiguration) { try { JSONObject cfgJson = new JSONObject(jobHandlerConfiguration); return cfgJson.get(PROPERTYNAME_CALENDAR_NAME_EXPRESSION).toString(); } catch (JSONException ex) { // calendar name is not specified return ""; } }
public static String setEndDateToConfiguration(String jobHandlerConfiguration, String endDate) { JSONObject cfgJson = null; try { cfgJson = new JSONObject(jobHandlerConfiguration); } catch (JSONException ex) { // create the json config cfgJson = new JSONObject(); cfgJson.put(PROPERTYNAME_TIMER_ACTIVITY_ID, jobHandlerConfiguration); } if (endDate != null) { cfgJson.put(PROPERTYNAME_END_DATE_EXPRESSION, endDate); } return cfgJson.toString(); } public static String getEndDateFromConfiguration(String jobHandlerConfiguration) { try { JSONObject cfgJson = new JSONObject(jobHandlerConfiguration); return cfgJson.get(PROPERTYNAME_END_DATE_EXPRESSION).toString(); } catch (JSONException ex) { return null; } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\jobexecutor\TimerEventHandler.java
1
请完成以下Java代码
public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public List<Book> getBooks() { return books; }
public void setBooks(List<Book> books) { this.books = books; } public short getVersion() { return version; } @Override public String toString() { return "Author{" + "id=" + id + ", name=" + name + ", genre=" + genre + ", age=" + age + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchDeleteCascadeDelete\src\main\java\com\bookstore\entity\Author.java
1
请完成以下Java代码
public int getExternalSystem_Config_LeichMehl_ProductMapping_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_LeichMehl_ProductMapping_ID); } @Override public I_LeichMehl_PluFile_ConfigGroup getLeichMehl_PluFile_ConfigGroup() { return get_ValueAsPO(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, I_LeichMehl_PluFile_ConfigGroup.class); } @Override public void setLeichMehl_PluFile_ConfigGroup(final I_LeichMehl_PluFile_ConfigGroup LeichMehl_PluFile_ConfigGroup) { set_ValueFromPO(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, I_LeichMehl_PluFile_ConfigGroup.class, LeichMehl_PluFile_ConfigGroup); } @Override public void setLeichMehl_PluFile_ConfigGroup_ID (final int LeichMehl_PluFile_ConfigGroup_ID) { if (LeichMehl_PluFile_ConfigGroup_ID < 1) set_Value (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, null); else set_Value (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, LeichMehl_PluFile_ConfigGroup_ID); } @Override public int getLeichMehl_PluFile_ConfigGroup_ID() { return get_ValueAsInt(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
} @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setPLU_File (final String PLU_File) { set_Value (COLUMNNAME_PLU_File, PLU_File); } @Override public String getPLU_File() { return get_ValueAsString(COLUMNNAME_PLU_File); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_LeichMehl_ProductMapping.java
1
请完成以下Java代码
public static void main(String[] args) throws Exception { ApiClient client = Config.defaultClient(); // Optional, put helpful during tests: disable client timeout and enable // HTTP wire-level logs HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(message -> log.info(message)); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient newClient = client.getHttpClient() .newBuilder() .addInterceptor(interceptor) .readTimeout(0, TimeUnit.SECONDS) .build(); client.setHttpClient(newClient); CoreV1Api api = new CoreV1Api(client); // Create the watch object that monitors pod creation/deletion/update events while (true) { log.info("[I46] Creating watch..."); try (Watch<V1Pod> watch = Watch.createWatch( client, api.listPodForAllNamespacesCall(false, null, null, null, null, "false", null, null, 10, true, null), new TypeToken<Response<V1Pod>>(){}.getType())) { log.info("[I52] Receiving events:"); for (Response<V1Pod> event : watch) { V1Pod pod = event.object; V1ObjectMeta meta = pod.getMetadata(); switch (event.type) {
case "ADDED": case "MODIFIED": case "DELETED": log.info("event.type: {}, namespace={}, name={}", event.type, meta.getNamespace(), meta.getName()); break; default: log.warn("[W66] Unknown event type: {}", event.type); } } } catch (ApiException ex) { log.error("[E70] ApiError", ex); } } } }
repos\tutorials-master\kubernetes-modules\k8s-intro\src\main\java\com\baeldung\kubernetes\intro\WatchPods.java
1
请完成以下Java代码
protected String getExternalCommand() { return EXTERNAL_SYSTEM_COMMAND_EXPORT_BPARTNER; } @Override @NonNull protected Optional<Set<IExternalSystemChildConfigId>> getAdditionalExternalSystemConfigIds(@NonNull final BPartnerId bPartnerId) { final I_C_BPartner bPartner = bPartnerDAO.getById(bPartnerId); final boolean isVendor = bPartner.isVendor(); final boolean isCustomer = bPartner.isCustomer(); if (!isCustomer && !isVendor) { return Optional.empty(); } final ImmutableList<ExternalSystemParentConfig> grsParentConfigs = externalSystemConfigRepo.getActiveByType(ExternalSystemType.GRSSignum); return Optional.of(grsParentConfigs.stream() .filter(ExternalSystemParentConfig::isActive) .map(ExternalSystemParentConfig::getChildConfig) .map(ExternalSystemGRSSignumConfig::cast) .filter(grsConfig -> (grsConfig.isAutoSendVendors() && isVendor) || (grsConfig.isAutoSendCustomers() && isCustomer)) .map(IExternalSystemChildConfig::getId) .collect(ImmutableSet.toImmutableSet())); } @NonNull private static Optional<String> getJsonExportDirectorySettings(@NonNull final ExternalSystemGRSSignumConfig grsSignumConfig) { if (!grsSignumConfig.isCreateBPartnerFolders()) {
return Optional.empty(); } if (Check.isBlank(grsSignumConfig.getBPartnerExportDirectories()) || Check.isBlank(grsSignumConfig.getBasePathForExportDirectories())) { throw new AdempiereException("BPartnerExportDirectories and BasePathForExportDirectories must be set!") .appendParametersToMessage() .setParameter("ExternalSystem_Config_GRSSignum_ID", grsSignumConfig.getId()); } final List<String> directories = Arrays .stream(grsSignumConfig.getBPartnerExportDirectories().split(",")) .filter(Check::isNotBlank) .collect(ImmutableList.toImmutableList()); final JsonExportDirectorySettings exportDirectorySettings = JsonExportDirectorySettings.builder() .basePath(grsSignumConfig.getBasePathForExportDirectories()) .directories(directories) .build(); try { final String serializedExportDirectorySettings = JsonObjectMapperHolder.sharedJsonObjectMapper() .writeValueAsString(exportDirectorySettings); return Optional.of(serializedExportDirectorySettings); } catch (final JsonProcessingException e) { throw AdempiereException.wrapIfNeeded(e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\grssignum\ExportBPartnerToGRSService.java
1
请在Spring Boot框架中完成以下Java代码
public int delete(List<Long> ids) { UmsRoleExample example = new UmsRoleExample(); example.createCriteria().andIdIn(ids); int count = roleMapper.deleteByExample(example); adminCacheService.delResourceListByRoleIds(ids); return count; } @Override public List<UmsRole> list() { return roleMapper.selectByExample(new UmsRoleExample()); } @Override public List<UmsRole> list(String keyword, Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum, pageSize); UmsRoleExample example = new UmsRoleExample(); if (!StrUtil.isEmpty(keyword)) { example.createCriteria().andNameLike("%" + keyword + "%"); } return roleMapper.selectByExample(example); } @Override public List<UmsMenu> getMenuList(Long adminId) { return roleDao.getMenuList(adminId); } @Override public List<UmsMenu> listMenu(Long roleId) { return roleDao.getMenuListByRoleId(roleId); } @Override public List<UmsResource> listResource(Long roleId) { return roleDao.getResourceListByRoleId(roleId); } @Override public int allocMenu(Long roleId, List<Long> menuIds) { //先删除原有关系 UmsRoleMenuRelationExample example=new UmsRoleMenuRelationExample(); example.createCriteria().andRoleIdEqualTo(roleId); roleMenuRelationMapper.deleteByExample(example); //批量插入新关系 for (Long menuId : menuIds) { UmsRoleMenuRelation relation = new UmsRoleMenuRelation(); relation.setRoleId(roleId); relation.setMenuId(menuId);
roleMenuRelationMapper.insert(relation); } return menuIds.size(); } @Override public int allocResource(Long roleId, List<Long> resourceIds) { //先删除原有关系 UmsRoleResourceRelationExample example=new UmsRoleResourceRelationExample(); example.createCriteria().andRoleIdEqualTo(roleId); roleResourceRelationMapper.deleteByExample(example); //批量插入新关系 for (Long resourceId : resourceIds) { UmsRoleResourceRelation relation = new UmsRoleResourceRelation(); relation.setRoleId(roleId); relation.setResourceId(resourceId); roleResourceRelationMapper.insert(relation); } adminCacheService.delResourceListByRole(roleId); return resourceIds.size(); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\UmsRoleServiceImpl.java
2
请完成以下Java代码
public I_A_Asset getA_Start_Asset() throws RuntimeException { return (I_A_Asset)MTable.get(getCtx(), I_A_Asset.Table_Name) .getPO(getA_Start_Asset_ID(), get_TrxName()); } /** Set A_Start_Asset_ID. @param A_Start_Asset_ID A_Start_Asset_ID */ public void setA_Start_Asset_ID (int A_Start_Asset_ID) { if (A_Start_Asset_ID < 1) set_Value (COLUMNNAME_A_Start_Asset_ID, null); else set_Value (COLUMNNAME_A_Start_Asset_ID, Integer.valueOf(A_Start_Asset_ID)); } /** Get A_Start_Asset_ID. @return A_Start_Asset_ID */ public int getA_Start_Asset_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_A_Start_Asset_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Document Date. @param DateDoc Date of the Document */ public void setDateDoc (Timestamp DateDoc) { set_Value (COLUMNNAME_DateDoc, DateDoc); } /** Get Document Date. @return Date of the Document */ public Timestamp getDateDoc () { return (Timestamp)get_Value(COLUMNNAME_DateDoc); } /** PostingType AD_Reference_ID=125 */ public static final int POSTINGTYPE_AD_Reference_ID=125; /** Actual = A */ public static final String POSTINGTYPE_Actual = "A"; /** Budget = B */ public static final String POSTINGTYPE_Budget = "B"; /** Commitment = E */ public static final String POSTINGTYPE_Commitment = "E"; /** Statistical = S */ public static final String POSTINGTYPE_Statistical = "S"; /** Reservation = R */ public static final String POSTINGTYPE_Reservation = "R"; /** Set PostingType. @param PostingType The type of posted amount for the transaction */ public void setPostingType (String PostingType) { set_Value (COLUMNNAME_PostingType, PostingType); } /** Get PostingType. @return The type of posted amount for the transaction */ public String getPostingType () { return (String)get_Value(COLUMNNAME_PostingType); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); }
/** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Forecast.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable Boolean getDisableInnerClassSerialization() { return this.disableInnerClassSerialization; } public void setDisableInnerClassSerialization(@Nullable Boolean disableInnerClassSerialization) { this.disableInnerClassSerialization = disableInnerClassSerialization; } public @Nullable LongSerializationPolicy getLongSerializationPolicy() { return this.longSerializationPolicy; } public void setLongSerializationPolicy(@Nullable LongSerializationPolicy longSerializationPolicy) { this.longSerializationPolicy = longSerializationPolicy; } public @Nullable FieldNamingPolicy getFieldNamingPolicy() { return this.fieldNamingPolicy; } public void setFieldNamingPolicy(@Nullable FieldNamingPolicy fieldNamingPolicy) { this.fieldNamingPolicy = fieldNamingPolicy; } public @Nullable Boolean getPrettyPrinting() { return this.prettyPrinting; } public void setPrettyPrinting(@Nullable Boolean prettyPrinting) { this.prettyPrinting = prettyPrinting; } public @Nullable Strictness getStrictness() { return this.strictness; } public void setStrictness(@Nullable Strictness strictness) { this.strictness = strictness; } public void setLenient(@Nullable Boolean lenient) { setStrictness((lenient != null && lenient) ? Strictness.LENIENT : Strictness.STRICT); } public @Nullable Boolean getDisableHtmlEscaping() { return this.disableHtmlEscaping; } public void setDisableHtmlEscaping(@Nullable Boolean disableHtmlEscaping) { this.disableHtmlEscaping = disableHtmlEscaping; } public @Nullable String getDateFormat() { return this.dateFormat; }
public void setDateFormat(@Nullable String dateFormat) { this.dateFormat = dateFormat; } /** * Enumeration of levels of strictness. Values are the same as those on * {@link com.google.gson.Strictness} that was introduced in Gson 2.11. To maximize * backwards compatibility, the Gson enum is not used directly. */ public enum Strictness { /** * Lenient compliance. */ LENIENT, /** * Strict compliance with some small deviations for legacy reasons. */ LEGACY_STRICT, /** * Strict compliance. */ STRICT } }
repos\spring-boot-4.0.1\module\spring-boot-gson\src\main\java\org\springframework\boot\gson\autoconfigure\GsonProperties.java
2
请完成以下Java代码
public static JsonQRCode toJsonQRCode(final HUInfo pickFromHU) { final HUQRCode qrCode = pickFromHU.getQrCode(); return JsonQRCode.builder() .qrCode(qrCode.toGlobalQRCodeString()) .caption(qrCode.toDisplayableQRCode()) .build(); } @Override public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity wfActivity) { final PickingJob pickingJob = getPickingJob(wfProcess); return computeActivityState(pickingJob); } public static WFActivityStatus computeActivityState(final PickingJob pickingJob) { return pickingJob.getPickFromHU().isPresent() ? WFActivityStatus.COMPLETED : WFActivityStatus.NOT_STARTED; } @Override public WFProcess setScannedBarcode(@NonNull final SetScannedBarcodeRequest request) { final HUQRCode qrCode = parseHUQRCode(request.getScannedBarcode()); final HuId huId = huQRCodesService.getHuIdByQRCode(qrCode); final HUInfo pickFromHU = HUInfo.builder()
.id(huId) .qrCode(qrCode) .build(); return PickingMobileApplication.mapPickingJob( request.getWfProcess(), pickingJob -> pickingJobRestService.setPickFromHU(pickingJob, pickFromHU) ); } private HUQRCode parseHUQRCode(final String scannedCode) { final IHUQRCode huQRCode = huQRCodesService.parse(scannedCode); if (huQRCode instanceof HUQRCode) { return (HUQRCode)huQRCode; } else { throw new AdempiereException("Invalid HU QR code: " + scannedCode); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\handlers\activity_handlers\SetPickFromHUWFActivityHandler.java
1
请完成以下Java代码
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if(!ProcessApplicationAttachments.isProcessApplication(deploymentUnit)) { return; } List<ProcessesXmlWrapper> processesXmls = ProcessApplicationAttachments.getProcessesXmls(deploymentUnit); for (ProcessesXmlWrapper wrapper : processesXmls) { for (ProcessEngineXml processEngineXml : wrapper.getProcessesXml().getProcessEngines()) { startProcessEngine(processEngineXml, phaseContext); } } } protected void startProcessEngine(ProcessEngineXml processEngineXml, DeploymentPhaseContext phaseContext) { final ServiceTarget serviceTarget = phaseContext.getServiceTarget(); // transform configuration ManagedProcessEngineMetadata configuration = transformConfiguration(processEngineXml); // validate the configuration configuration.validate(); // create service instance MscManagedProcessEngineController service = new MscManagedProcessEngineController(configuration); // get the service name for the process engine ServiceName serviceName = ServiceNames.forManagedProcessEngine(processEngineXml.getName()); // get service builder ServiceBuilder<?> serviceBuilder = serviceTarget.addService(serviceName); // make this service depend on the current phase -> makes sure it is removed with the phase service at undeployment
serviceBuilder.requires(phaseContext.getPhaseServiceName()); // add Service dependencies service.initializeServiceBuilder(configuration, serviceBuilder, serviceName, processEngineXml.getJobAcquisitionName()); // install the service serviceBuilder.setInstance(service); serviceBuilder.install(); } /** transforms the configuration as provided via the {@link ProcessEngineXml} * into a {@link ManagedProcessEngineMetadata} */ protected ManagedProcessEngineMetadata transformConfiguration(ProcessEngineXml processEngineXml) { return new ManagedProcessEngineMetadata( processEngineXml.getName().equals("default"), processEngineXml.getName(), processEngineXml.getDatasource(), processEngineXml.getProperties().get("history"), processEngineXml.getConfigurationClass(), processEngineXml.getProperties(), processEngineXml.getPlugins()); } }
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\deployment\processor\ProcessEngineStartProcessor.java
1
请完成以下Java代码
private ImmutableList<String> readOutput(final InputStream is, final int tailSize) { final BufferedReader in = new BufferedReader(new InputStreamReader(is), 10240); try { final List<String> tail = tailSize > 0 ? new ArrayList<>(tailSize + 1) : new ArrayList<>(); int truncatedLines = 0; String line; while ((line = in.readLine()) != null) { if (tailSize > 0 && tail.size() >= tailSize) { tail.remove(0); truncatedLines++; } tail.add(line); } if (truncatedLines > 0) { tail.add(0, "(Truncated " + truncatedLines + " lines. Preserved last " + tail.size() + " lines)"); } return ImmutableList.copyOf(tail); } catch (final IOException e) { throw new ScriptExecutionException("Error while reading process output", e) .setDatabase(database) .setExecutor(this); } } @Override public void executeAfterScripts() { final Set<String> functionNames = sqlHelper.getDBFunctionsMatchingPattern(AFTER_MIGRATION_FUNC_PATTERN) .stream() .sorted() .collect(ImmutableSet.toImmutableSet());
if (functionNames.isEmpty()) { logger.warn("Skip executing after migration scripts because no function matching pattern '{}' was found in {}", AFTER_MIGRATION_FUNC_PATTERN, database); return; } final AnonymousScript script = AnonymousScript.builder() .fileName("after_migration.sql") .scriptContent(functionNames.stream() .map(functionName -> "select " + functionName + "();\n") .collect(Collectors.joining())) .build(); final Stopwatch stopwatch = Stopwatch.createStarted(); final int logTailSize = -1; // full log final ScriptExecutionResult result = executeAndReturnResult(script, logTailSize); stopwatch.stop(); logger.info("Executed {} in {}ms and got following result:\n{}", functionNames, stopwatch, Joiner.on("\n").join(result.getLogTail())); } @Builder @Value private static class ScriptExecutionResult { @NonNull final ImmutableList<String> logTail; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\executor\impl\PostgresqlNativeExecutor.java
1
请完成以下Java代码
public void windowLostFocus(final WindowEvent e) { // nothing } }); if (modalFrame instanceof CFrame) { addToWindowManager(modalFrame); } showCenterWindow(parentFrame, modalFrame); } /** * Create a {@link FormFrame} for the given {@link I_AD_Form}. * * @return formFrame which was created or null
*/ public static FormFrame createForm(final I_AD_Form form) { final FormFrame formFrame = new FormFrame(); if (formFrame.openForm(form)) { formFrame.pack(); return formFrame; } else { formFrame.dispose(); return null; } } } // AEnv
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\AEnv.java
1
请完成以下Java代码
public static final void setupInnerTextComponentUI(final JTextField textField) { VEditorInnerTextComponentUI.instance.installUI(textField); } /** * Class used to configure the UI of the inner text component of a {@link VEditor}. * * Also, this class listens the "UI" property change (fired when the L&F is updated) and sets back the properties it customized. * * @author tsa * */ private static final class VEditorInnerTextComponentUI implements PropertyChangeListener { public static final transient VEditorInnerTextComponentUI instance = new VEditorInnerTextComponentUI(); /** Component's UI property */ private static final String PROPERTY_UI = "UI"; private VEditorInnerTextComponentUI() { super(); } public void installUI(final JComponent comp) { updateUI(comp); comp.addPropertyChangeListener("UI", this); } /** Actually sets the UI properties */ private void updateUI(final JComponent comp) { comp.setBorder(null); comp.setFont(AdempierePLAF.getFont_Field()); comp.setForeground(AdempierePLAF.getTextColor_Normal());
} @Override public void propertyChange(PropertyChangeEvent evt) { if (PROPERTY_UI.equals(evt.getPropertyName())) { final JComponent comp = (JComponent)evt.getSource(); updateUI(comp); } } } private VEditorUtils() { super(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VEditorUtils.java
1
请完成以下Java代码
public class MenuApi extends BaseApi { private static final Logger logger = LoggerFactory.getLogger(MenuApi.class); private ApiConfig apiConfig; public MenuApi(ApiConfig apiConfig) { this.apiConfig = apiConfig; } /** * 创建菜单 * * @param menu * @return */ public ResultType createMenu(Menu menu) { BeanUtil.requireNonNull(menu, "menu is null"); String url = BASE_API_URL; if (BeanUtil.isNull(menu.getMatchrule())) { //普通菜单 logger.info("创建普通菜单....."); url += "cgi-bin/menu/create?access_token=" + apiConfig.getAccessToken(); } else {
//个性化菜单 logger.info("创建个性化菜单....."); url += "cgi-bin/menu/addconditional?access_token=" + apiConfig.getAccessToken(); } BaseResponse baseResponse = executePost(url, menu.toJsonString()); return ResultType.get(baseResponse.getErrcode()); } /** * 删除所有菜单,包括个性化菜单 * * @return 调用结果 */ public ResultType deleteMenu() { logger.debug("删除菜单....."); String url = BASE_API_URL + "cgi-bin/menu/delete?access_token=" + apiConfig.getAccessToken(); BaseResponse response = executeGet(url); return ResultType.get(response.getErrcode()); } }
repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\api\MenuApi.java
1
请在Spring Boot框架中完成以下Java代码
public Date getOccurredBefore() { return occurredBefore; } public void setOccurredBefore(Date occurredBefore) { this.occurredBefore = occurredBefore; } public Date getOccurredAfter() { return occurredAfter; } public void setOccurredAfter(Date occurredAfter) { this.occurredAfter = occurredAfter; } public Date getExitBefore() { return exitBefore; } public void setExitBefore(Date exitBefore) { this.exitBefore = exitBefore; } public Date getExitAfter() { return exitAfter; } public void setExitAfter(Date exitAfter) { this.exitAfter = exitAfter; } public Date getEndedBefore() { return endedBefore; } public void setEndedBefore(Date endedBefore) { this.endedBefore = endedBefore; } public Date getEndedAfter() { return endedAfter; } public void setEndedAfter(Date endedAfter) { this.endedAfter = endedAfter; } public String getStartUserId() { return startUserId; } public void setStartUserId(String startUserId) { this.startUserId = startUserId; } public String getReferenceId() { return referenceId; } public void setReferenceId(String referenceId) { this.referenceId = referenceId; } public String getReferenceType() {
return referenceType; } public void setReferenceType(String referenceType) { this.referenceType = referenceType; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public Boolean getWithoutTenantId() { return withoutTenantId; } public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public Boolean getIncludeLocalVariables() { return includeLocalVariables; } public void setIncludeLocalVariables(Boolean includeLocalVariables) { this.includeLocalVariables = includeLocalVariables; } public Set<String> getCaseInstanceIds() { return caseInstanceIds; } public void setCaseInstanceIds(Set<String> caseInstanceIds) { this.caseInstanceIds = caseInstanceIds; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\planitem\HistoricPlanItemInstanceQueryRequest.java
2
请在Spring Boot框架中完成以下Java代码
public static class ServletRestApiConfiguration { private final AdminServerProperties adminServerProperties; public ServletRestApiConfiguration(AdminServerProperties adminServerProperties) { this.adminServerProperties = adminServerProperties; } @Bean @ConditionalOnMissingBean public de.codecentric.boot.admin.server.web.servlet.InstancesProxyController instancesProxyController( InstanceRegistry instanceRegistry, InstanceWebClient.Builder instanceWebClientBuilder) { return new de.codecentric.boot.admin.server.web.servlet.InstancesProxyController( this.adminServerProperties.getContextPath(), this.adminServerProperties.getInstanceProxy().getIgnoredHeaders(), instanceRegistry, instanceWebClientBuilder.build());
} @Bean public org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping adminHandlerMapping( ContentNegotiationManager contentNegotiationManager) { org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping mapping = new de.codecentric.boot.admin.server.web.servlet.AdminControllerHandlerMapping( this.adminServerProperties.getContextPath()); mapping.setOrder(0); mapping.setContentNegotiationManager(contentNegotiationManager); return mapping; } } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\config\AdminServerWebConfiguration.java
2
请完成以下Java代码
public Stream<TableRecordReference> streamByTableName(@NonNull final String tableName) { return recordRefs.stream().filter(recordRef -> tableName.equals(recordRef.getTableName())); } public ListMultimap<AdTableId, Integer> extractTableId2RecordIds() { final ImmutableListMultimap<AdTableId, TableRecordReference> tableName2References = Multimaps.index(recordRefs, TableRecordReference::getAdTableId); return Multimaps.transformValues(tableName2References, TableRecordReference::getRecord_ID); } public <T extends RepoIdAware> Stream<T> streamIds(@NonNull final String tableName, @NonNull final IntFunction<T> idMapper) { return streamByTableName(tableName) .mapToInt(TableRecordReference::getRecord_ID) .mapToObj(idMapper); } public <T extends RepoIdAware> ImmutableSet<T> getRecordIdsByTableName(@NonNull final String tableName, @NonNull final IntFunction<T> idMapper) { return streamIds(tableName, idMapper).collect(ImmutableSet.toImmutableSet()); } public String getSingleTableName() { final ImmutableSet<String> tableNames = recordRefs.stream() .map(TableRecordReference::getTableName) .collect(ImmutableSet.toImmutableSet()); if (tableNames.isEmpty()) { throw new AdempiereException("No tablename"); } else if (tableNames.size() == 1) { return tableNames.iterator().next(); } else { throw new AdempiereException("More than one tablename found: " + tableNames); } } public Set<TableRecordReference> toSet() {return recordRefs;} public Set<Integer> toIntSet() { // just to make sure that our records are from a single table getSingleTableName(); return recordRefs.stream() .map(TableRecordReference::getRecord_ID) .collect(ImmutableSet.toImmutableSet()); } public int size() { return recordRefs.size(); } @NonNull public AdTableId getSingleTableId() { final ImmutableSet<AdTableId> tableIds = getTableIds(); if (tableIds.isEmpty()) { throw new AdempiereException("No AD_Table_ID"); } else if (tableIds.size() == 1) { return tableIds.iterator().next(); }
else { throw new AdempiereException("More than one AD_Table_ID found: " + tableIds); } } public void assertSingleTableName() { final ImmutableSet<AdTableId> tableIds = getTableIds(); if (tableIds.isEmpty()) { throw new AdempiereException("No AD_Table_ID"); } else if (tableIds.size() != 1) { throw new AdempiereException("More than one AD_Table_ID found: " + tableIds); } } public Stream<TableRecordReference> streamReferences() { return recordRefs.stream(); } @NonNull private ImmutableSet<AdTableId> getTableIds() { return recordRefs.stream() .map(TableRecordReference::getAD_Table_ID) .map(AdTableId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\lang\impl\TableRecordReferenceSet.java
1
请在Spring Boot框架中完成以下Java代码
private static Object convertValue(@Nullable final Object value, @NonNull final Class<?> targetClass) { if (value == null) { // null parameter, no conversion is needed return null; } final Class<?> fromClass = value.getClass(); if (targetClass.isAssignableFrom(fromClass)) { // compatible types, no conversion is needed return value; } // If target class is String, convert it right away if (String.class.equals(targetClass)) { return value.toString(); } // Convert from BigDecimal to other values if (BigDecimal.class.isAssignableFrom(fromClass)) { final BigDecimal bd = (BigDecimal)value; if (Integer.class.equals(targetClass)) { return bd.intValueExact(); } else if (Double.class.equals(targetClass)) { return bd.doubleValue(); } else if (Float.class.equals(targetClass)) { return bd.floatValue(); } } // else if (Integer.class.isAssignableFrom(fromClass)) { final Integer ii = (Integer)value; if (BigDecimal.class.equals(targetClass)) { return BigDecimal.valueOf(ii); } } else if (java.util.Date.class.isAssignableFrom(fromClass)) { final java.util.Date date = (java.util.Date)value; if (java.sql.Timestamp.class.equals(targetClass))
{ return new java.sql.Timestamp(date.getTime()); } } else if (String.class.isAssignableFrom(fromClass)) { final String str = (String)value; if (Integer.class.equals(targetClass)) { return Integer.parseInt(str); } else if (BigDecimal.class.equals(targetClass)) { return new BigDecimal(str); } else if (Boolean.class.equals(targetClass)) { return Boolean.parseBoolean(str) || "Y".equals(str); // ADempiere standard } } // Nothing matched, log warning and return original value logger.warn("Cannot convert value '{}' from {} to {}. Ignore", value, fromClass, targetClass); return value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\JasperReportFiller.java
2
请在Spring Boot框架中完成以下Java代码
public Product getProduct(Integer id) { return PRODUCT_LIST.stream() .filter(product -> product.getId().equals(id)) .findFirst().orElse(null); } @Override public Product save(ProductModel productModel) { Product product = new Product(PRODUCT_LIST.size() + 1, productModel); PRODUCT_LIST.add(product); return product; } @Override public Product update(Integer productId, ProductModel productModel) { Product product = getProduct(productId); if (product != null) { update(product, productModel);
} return product; } private void update(Product product, ProductModel productModel) { if (productModel != null) { System.out.println(productModel); Optional.ofNullable(productModel.getName()).ifPresent(product::setName); Optional.ofNullable(productModel.getDescription()).ifPresent(product::setDescription); Optional.ofNullable(productModel.getCurrency()).ifPresent(product::setCurrency); Optional.ofNullable(productModel.getImageUrls()).ifPresent(product::setImageUrls); Optional.ofNullable(productModel.getStock()).ifPresent(product::setStock); Optional.ofNullable(productModel.getStatus()).ifPresent(product::setStatus); Optional.ofNullable(productModel.getVideoUrls()).ifPresent(product::setVideoUrls); Optional.ofNullable(productModel.getPrice()).ifPresent(product::setPrice); } } }
repos\tutorials-master\spring-boot-modules\spring-boot-graphql-2\src\main\java\com\baeldung\graphqlvsrest\repository\impl\ProductRepositoryImpl.java
2
请在Spring Boot框架中完成以下Java代码
public void setSuperProcessInstanceId(String superProcessInstanceId) { this.superProcessInstanceId = superProcessInstanceId; } public List<RestVariable> getVariables() { return variables; } public void setVariables(List<RestVariable> variables) { this.variables = variables; } public void addVariable(RestVariable variable) { variables.add(variable); } @ApiModelProperty(example = "3") public String getCallbackId() { return callbackId; } public void setCallbackId(String callbackId) { this.callbackId = callbackId; } @ApiModelProperty(example = "cmmn") public String getCallbackType() { return callbackType; } public void setCallbackType(String callbackType) { this.callbackType = callbackType; } @ApiModelProperty(example = "123") public String getReferenceId() { return referenceId; }
public void setReferenceId(String referenceId) { this.referenceId = referenceId; } @ApiModelProperty(example = "event-to-bpmn-2.0-process") public String getReferenceType() { return referenceType; } public void setReferenceType(String referenceType) { this.referenceType = referenceType; } @ApiModelProperty(value = "The stage plan item instance id this process instance belongs to or null, if it is not part of a case at all or is not a child element of a stage") public String getPropagatedStageInstanceId() { return propagatedStageInstanceId; } public void setPropagatedStageInstanceId(String propagatedStageInstanceId) { this.propagatedStageInstanceId = propagatedStageInstanceId; } @ApiModelProperty(example = "someTenantId") public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricProcessInstanceResponse.java
2
请完成以下Java代码
public void query(boolean isReport, int AD_Table_ID, int Record_ID) { log.info("Report=" + isReport + ", AD_Table_ID=" + AD_Table_ID + ",Record_ID=" + Record_ID); reportField.setSelected(isReport); m_AD_Table_ID = AD_Table_ID; m_Record_ID = Record_ID; cmd_query(); } // query /************************************************************************** * Create Query */ private void cmd_query() { boolean reports = reportField.isSelected(); KeyNamePair process = (KeyNamePair)processField.getSelectedItem(); KeyNamePair table = (KeyNamePair)tableField.getSelectedItem();
Integer C_BPartner_ID = (Integer)bPartnerField.getValue(); String name = nameQField.getText(); String description = descriptionQField.getText(); String help = helpQField.getText(); KeyNamePair createdBy = (KeyNamePair)createdByQField.getSelectedItem(); Timestamp createdFrom = createdQFrom.getTimestamp(); Timestamp createdTo = createdQTo.getTimestamp(); cmd_query(reports, process, table, C_BPartner_ID, name, description, help, createdBy, createdFrom, createdTo); // Display panel.setSelectedIndex(1); m_index = 1; updateVDisplay(false); } // cmd_query } // ArchiveViewer
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\ArchiveViewer.java
1
请完成以下Java代码
public int getC_UOM_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_UOM_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Berechnete Menge. @param InvoicedQty The quantity invoiced */ @Override public void setInvoicedQty (java.math.BigDecimal InvoicedQty) { set_Value (COLUMNNAME_InvoicedQty, InvoicedQty); } /** Get Berechnete Menge. @return The quantity invoiced */ @Override public java.math.BigDecimal getInvoicedQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_InvoicedQty); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Zeilennetto. @param LineNetAmt Nettowert Zeile (Menge * Einzelpreis) ohne Fracht und Gebühren */ @Override public void setLineNetAmt (java.math.BigDecimal LineNetAmt) { set_Value (COLUMNNAME_LineNetAmt, LineNetAmt); } /** Get Zeilennetto. @return Nettowert Zeile (Menge * Einzelpreis) ohne Fracht und Gebühren */ @Override public java.math.BigDecimal getLineNetAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_LineNetAmt); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Position. @param LineNo Zeile Nr. */ @Override public void setLineNo (int LineNo) {
set_Value (COLUMNNAME_LineNo, Integer.valueOf(LineNo)); } /** Get Position. @return Zeile Nr. */ @Override public int getLineNo () { Integer ii = (Integer)get_Value(COLUMNNAME_LineNo); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override 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 Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_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_C_Customs_Invoice_Line.java
1
请在Spring Boot框架中完成以下Java代码
ObservationRegistry observationRegistry() { return ObservationRegistry.create(); } @Bean @Order(0) PropertiesObservationFilterPredicate propertiesObservationFilter(ObservationProperties properties) { return new PropertiesObservationFilterPredicate(properties); } @Bean @ConditionalOnMissingBean(ValueExpressionResolver.class) SpelValueExpressionResolver spelValueExpressionResolver() { return new SpelValueExpressionResolver(); } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(Advice.class) @ConditionalOnBooleanProperty("management.observations.annotations.enabled") static class ObservedAspectConfiguration { @Bean @ConditionalOnMissingBean ObservedAspect observedAspect(ObservationRegistry observationRegistry, ObjectProvider<ObservationKeyValueAnnotationHandler> observationKeyValueAnnotationHandler) {
ObservedAspect observedAspect = new ObservedAspect(observationRegistry); observationKeyValueAnnotationHandler.ifAvailable(observedAspect::setObservationKeyValueAnnotationHandler); return observedAspect; } @Bean @ConditionalOnMissingBean ObservationKeyValueAnnotationHandler observationKeyValueAnnotationHandler(BeanFactory beanFactory, ValueExpressionResolver valueExpressionResolver) { return new ObservationKeyValueAnnotationHandler(beanFactory::getBean, (ignored) -> valueExpressionResolver); } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-observation\src\main\java\org\springframework\boot\micrometer\observation\autoconfigure\ObservationAutoConfiguration.java
2
请完成以下Java代码
public static String createConfiguration(String id, String endDate, String calendarName) { JSONObject cfgJson = new JSONObject(); cfgJson.put(PROPERTYNAME_TIMER_ACTIVITY_ID, id); if (endDate != null) { cfgJson.put(PROPERTYNAME_END_DATE_EXPRESSION, endDate); } if (calendarName != null) { cfgJson.put(PROPERTYNAME_CALENDAR_NAME_EXPRESSION, calendarName); } return cfgJson.toString(); } public static String setActivityIdToConfiguration(String jobHandlerConfiguration, String activityId) { try { JSONObject cfgJson = new JSONObject(jobHandlerConfiguration); cfgJson.put(PROPERTYNAME_TIMER_ACTIVITY_ID, activityId); return cfgJson.toString(); } catch (JSONException ex) { return jobHandlerConfiguration; } } public static String getActivityIdFromConfiguration(String jobHandlerConfiguration) { try { JSONObject cfgJson = new JSONObject(jobHandlerConfiguration); return cfgJson.get(PROPERTYNAME_TIMER_ACTIVITY_ID).toString(); } catch (JSONException ex) { return jobHandlerConfiguration; } } public static String geCalendarNameFromConfiguration(String jobHandlerConfiguration) { try { JSONObject cfgJson = new JSONObject(jobHandlerConfiguration); return cfgJson.get(PROPERTYNAME_CALENDAR_NAME_EXPRESSION).toString(); } catch (JSONException ex) { // calendar name is not specified return "";
} } public static String setEndDateToConfiguration(String jobHandlerConfiguration, String endDate) { JSONObject cfgJson = null; try { cfgJson = new JSONObject(jobHandlerConfiguration); } catch (JSONException ex) { // create the json config cfgJson = new JSONObject(); cfgJson.put(PROPERTYNAME_TIMER_ACTIVITY_ID, jobHandlerConfiguration); } if (endDate != null) { cfgJson.put(PROPERTYNAME_END_DATE_EXPRESSION, endDate); } return cfgJson.toString(); } public static String getEndDateFromConfiguration(String jobHandlerConfiguration) { try { JSONObject cfgJson = new JSONObject(jobHandlerConfiguration); return cfgJson.get(PROPERTYNAME_END_DATE_EXPRESSION).toString(); } catch (JSONException ex) { return null; } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\jobexecutor\TimerEventHandler.java
1
请完成以下Java代码
public CreditDebitCode getCdtDbtInd() { return cdtDbtInd; } /** * Sets the value of the cdtDbtInd property. * * @param value * allowed object is * {@link CreditDebitCode } * */ public void setCdtDbtInd(CreditDebitCode value) { this.cdtDbtInd = value; } /** * Gets the value of the tp property. * * @return * possible object is * {@link ChargeType2Choice } * */ public ChargeType2Choice getTp() { return tp; } /** * Sets the value of the tp property. * * @param value * allowed object is * {@link ChargeType2Choice } * */ public void setTp(ChargeType2Choice value) { this.tp = value; } /** * Gets the value of the rate property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getRate() { return rate; } /** * Sets the value of the rate property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setRate(BigDecimal value) { this.rate = value; } /** * Gets the value of the br property. * * @return * possible object is * {@link ChargeBearerType1Code } * */ public ChargeBearerType1Code getBr() { return br; }
/** * Sets the value of the br property. * * @param value * allowed object is * {@link ChargeBearerType1Code } * */ public void setBr(ChargeBearerType1Code value) { this.br = value; } /** * Gets the value of the pty property. * * @return * possible object is * {@link BranchAndFinancialInstitutionIdentification4 } * */ public BranchAndFinancialInstitutionIdentification4 getPty() { return pty; } /** * Sets the value of the pty property. * * @param value * allowed object is * {@link BranchAndFinancialInstitutionIdentification4 } * */ public void setPty(BranchAndFinancialInstitutionIdentification4 value) { this.pty = value; } /** * Gets the value of the tax property. * * @return * possible object is * {@link TaxCharges2 } * */ public TaxCharges2 getTax() { return tax; } /** * Sets the value of the tax property. * * @param value * allowed object is * {@link TaxCharges2 } * */ public void setTax(TaxCharges2 value) { this.tax = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\ChargesInformation6.java
1
请完成以下Java代码
public Mono<Book> applyDiscount(Mono<Book> bookMono) { return bookMono.map(book -> { book.setPrice(book.getPrice() - book.getPrice() * 0.2); return book; }); } public Mono<Book> applyTax(Mono<Book> bookMono) { return bookMono.map(book -> { book.setPrice(book.getPrice() + book.getPrice() * 0.1); return book; }); } public Mono<Book> getFinalPricedBook(String bookId) { return bookService.getBook(bookId) .transform(this::applyTax) .transform(this::applyDiscount);
} public Mono<Book> conditionalDiscount(String userId, String bookId) { return userService.getUser(userId) .filter(User::isActive) .flatMap(user -> bookService.getBook(bookId) .transform(this::applyDiscount)) .switchIfEmpty(bookService.getBook(bookId)) .switchIfEmpty(Mono.error(new RuntimeException("Book not found"))); } public Mono<BookBorrowResponse> handleErrorBookBorrow(String userId, String bookId) { return borrowBook(userId, bookId).onErrorResume(ex -> Mono.just(new BookBorrowResponse(userId, bookId, "Rejected"))); } }
repos\tutorials-master\spring-reactive-modules\spring-webflux\src\main\java\com\baeldung\spring\convertmonoobject\MonoTransformer.java
1
请完成以下Java代码
protected void validateOneSecurityByServer(BootstrapConfig config) throws InvalidConfigurationException { for (Map.Entry<Integer, BootstrapConfig.ServerConfig> e : config.servers.entrySet()) { BootstrapConfig.ServerConfig srvCfg = e.getValue(); // look for security entry BootstrapConfig.ServerSecurity security = getSecurityEntry(config, srvCfg.shortId); if (security == null) { throw new InvalidConfigurationException("no security entry for server instance: " + e.getKey()); } // BS Server if (security.bootstrapServer && srvCfg.shortId != 0) { throw new InvalidConfigurationException("short ID must be 0"); } // LwM2M Server /** * This identifier uniquely identifies each LwM2M Server configured for the LwM2M Client. * This Resource MUST be set when the Bootstrap-Server Resource has false value. * Specific ID:0 and ID:65535 values MUST NOT be used for identifying the LwM2M Server (Section 6.3 of the LwM2M version 1.0 specification).
*/ if (!security.bootstrapServer && isNotLwm2mServer(srvCfg.shortId)) { throw new InvalidConfigurationException("Specific ID:" + NOT_USED_IDENTIFYING_LWM2M_SERVER_MIN.getId() + " and ID:" + NOT_USED_IDENTIFYING_LWM2M_SERVER_MAX.getId() + " values MUST NOT be used for identifying the LwM2M Server"); } } } protected static BootstrapConfig.ServerSecurity getSecurityEntry(BootstrapConfig config, int shortId) { for (Map.Entry<Integer, BootstrapConfig.ServerSecurity> es : config.security.entrySet()) { if ((es.getValue().serverId == null && shortId == 0) || (es.getValue().serverId != null && es.getValue().serverId == shortId)) { return es.getValue(); } } return null; } }
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\bootstrap\store\LwM2MConfigurationChecker.java
1
请完成以下Java代码
public void updateTargetWeightRange() { assertNotProcessed(); final Quantity toleranceQty = targetWeight.multiply(tolerance).abs(); this.targetWeightRange = Range.closed( targetWeight.subtract(toleranceQty), targetWeight.add(toleranceQty) ); updateToleranceExceededFlag(); } public void updateUOMFromHeaderToChecks() { assertNotProcessed(); for (final PPOrderWeightingRunCheck check : checks) { check.setUomId(targetWeight.getUomId()); } }
private void assertNotProcessed() { if (isProcessed) { throw new AdempiereException("Already processed"); } } public I_C_UOM getUOM() { return targetWeight.getUOM(); } public SeqNo getNextLineNo() { final SeqNo lastLineNo = checks.stream() .map(PPOrderWeightingRunCheck::getLineNo) .max(Comparator.naturalOrder()) .orElseGet(() -> SeqNo.ofInt(0)); return lastLineNo.next(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\weighting\run\PPOrderWeightingRun.java
1
请完成以下Java代码
protected CmmnExecution eventNotificationsStarted(CmmnExecution execution) { CmmnActivityBehavior behavior = getActivityBehavior(execution); triggerBehavior(behavior, execution); execution.setCurrentState(COMPLETED); return execution; } protected void postTransitionNotification(CmmnExecution execution) { if (!execution.isCaseInstanceExecution()) { execution.remove(); } else { CmmnExecution superCaseExecution = execution.getSuperCaseExecution(); PvmExecutionImpl superExecution = execution.getSuperExecution(); if (superCaseExecution != null) { TransferVariablesActivityBehavior behavior = (TransferVariablesActivityBehavior) getActivityBehavior(superCaseExecution); behavior.transferVariables(execution, superCaseExecution); superCaseExecution.complete(); } else if (superExecution != null) { SubProcessActivityBehavior behavior = (SubProcessActivityBehavior) getActivityBehavior(superExecution); try { behavior.passOutputVariables(superExecution, execution); } catch (RuntimeException e) { LOG.completingSubCaseError(execution, e); throw e; } catch (Exception e) { LOG.completingSubCaseError(execution, e); throw LOG.completingSubCaseErrorException(execution, e);
} // set sub case instance to null superExecution.setSubCaseInstance(null); try { behavior.completed(superExecution); } catch (RuntimeException e) { LOG.completingSubCaseError(execution, e); throw e; } catch (Exception e) { LOG.completingSubCaseError(execution, e); throw LOG.completingSubCaseErrorException(execution, e); } } execution.setSuperCaseExecution(null); execution.setSuperExecution(null); } CmmnExecution parent = execution.getParent(); if (parent != null) { CmmnActivityBehavior behavior = getActivityBehavior(parent); if (behavior instanceof CmmnCompositeActivityBehavior) { CmmnCompositeActivityBehavior compositeBehavior = (CmmnCompositeActivityBehavior) behavior; compositeBehavior.handleChildCompletion(parent, execution); } } } protected abstract void triggerBehavior(CmmnActivityBehavior behavior, CmmnExecution execution); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\operation\AbstractAtomicOperationCaseExecutionComplete.java
1
请完成以下Java代码
public void onRequestTypeChange(final I_R_Request request) { final I_R_RequestType requestType = request.getR_RequestType(); if (requestType == null) { // in case the request type is deleted, the R_RequestType_InternalName must be set to null request.setR_RequestType_InternalName(null); } else { // set the internal name of the request type request.setR_RequestType_InternalName(requestType.getInternalName()); } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = I_R_Request.COLUMNNAME_M_InOut_ID) @CalloutMethod(columnNames = { I_R_Request.COLUMNNAME_M_InOut_ID }) public void onMInOutSet(final de.metas.request.model.I_R_Request request) { final I_M_InOut inout = InterfaceWrapperHelper.create(request.getM_InOut(), I_M_InOut.class); if (inout == null) { // in case the inout was removed or is not set, the DateDelivered shall also be not set request.setDateDelivered(null); } else { request.setDateDelivered(inout.getMovementDate()); } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = de.metas.request.model.I_R_Request.COLUMNNAME_M_QualityNote_ID) @CalloutMethod(columnNames = { de.metas.request.model.I_R_Request.COLUMNNAME_M_QualityNote_ID }) public void onQualityNoteChanged(final de.metas.request.model.I_R_Request request) { final QualityNoteId qualityNoteId = QualityNoteId.ofRepoIdOrNull(request.getM_QualityNote_ID()); if (qualityNoteId == null) { // nothing to do return;
} final I_M_QualityNote qualityNote = Services.get(IQualityNoteDAO.class).getById(qualityNoteId); if (qualityNote == null) { // nothing to do return; } // set the request's performance type with the value form the quality note entry final String performanceType = qualityNote.getPerformanceType(); request.setPerformanceType(performanceType); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW }) public void setSalesRep(final I_R_Request request) { final Properties ctx = InterfaceWrapperHelper.getCtx(request); final RoleId adRoleId = Env.getLoggedRoleId(ctx); final Role role = Services.get(IRoleDAO.class).getById(adRoleId); // task #577: The SalesRep in R_Request will be Role's supervisor final UserId supervisorId = role.getSupervisorId(); if (supervisorId != null) { request.setSalesRep_ID(supervisorId.getRepoId()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\request\model\validator\R_Request.java
1
请完成以下Java代码
public boolean rejectIt() { return true; } @Override public boolean reverseAccrualIt() { log.info(toString()); // Before reverseAccrual m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_REVERSEACCRUAL); if (m_processMsg != null) return false; // After reverseAccrual m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_REVERSEACCRUAL); if (m_processMsg != null) return false; return true; } // reverseAccrualIt @Override public boolean reverseCorrectIt() { log.info(toString()); // Before reverseCorrect m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_REVERSECORRECT); if (m_processMsg != null) return false; // After reverseCorrect m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_REVERSECORRECT); if (m_processMsg != null) return false; return true; } /**
* Unlock Document. * * @return true if success */ @Override public boolean unlockIt() { log.info(toString()); setProcessing(false); return true; } // unlockIt @Override public boolean voidIt() { return false; } @Override public int getC_Currency_ID() { return 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\model\MCFlatrateConditions.java
1
请完成以下Java代码
public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setFeePercentageOfGrandTotal (final BigDecimal FeePercentageOfGrandTotal) { set_Value (COLUMNNAME_FeePercentageOfGrandTotal, FeePercentageOfGrandTotal); } @Override public BigDecimal getFeePercentageOfGrandTotal() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_FeePercentageOfGrandTotal); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setInvoiceProcessingServiceCompany_BPartnerAssignment_ID (final int InvoiceProcessingServiceCompany_BPartnerAssignment_ID) { if (InvoiceProcessingServiceCompany_BPartnerAssignment_ID < 1) set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_BPartnerAssignment_ID, null); else set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_BPartnerAssignment_ID, InvoiceProcessingServiceCompany_BPartnerAssignment_ID); }
@Override public int getInvoiceProcessingServiceCompany_BPartnerAssignment_ID() { return get_ValueAsInt(COLUMNNAME_InvoiceProcessingServiceCompany_BPartnerAssignment_ID); } @Override public org.compiere.model.I_InvoiceProcessingServiceCompany getInvoiceProcessingServiceCompany() { return get_ValueAsPO(COLUMNNAME_InvoiceProcessingServiceCompany_ID, org.compiere.model.I_InvoiceProcessingServiceCompany.class); } @Override public void setInvoiceProcessingServiceCompany(final org.compiere.model.I_InvoiceProcessingServiceCompany InvoiceProcessingServiceCompany) { set_ValueFromPO(COLUMNNAME_InvoiceProcessingServiceCompany_ID, org.compiere.model.I_InvoiceProcessingServiceCompany.class, InvoiceProcessingServiceCompany); } @Override public void setInvoiceProcessingServiceCompany_ID (final int InvoiceProcessingServiceCompany_ID) { if (InvoiceProcessingServiceCompany_ID < 1) set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_ID, null); else set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_ID, InvoiceProcessingServiceCompany_ID); } @Override public int getInvoiceProcessingServiceCompany_ID() { return get_ValueAsInt(COLUMNNAME_InvoiceProcessingServiceCompany_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_InvoiceProcessingServiceCompany_BPartnerAssignment.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getClan() { return clan; } public void setClan(String clan) { this.clan = clan; } public String getTimes() { return times; } public void setTimes(String times) { this.times = times; } public String getTempleNumber() { return TempleNumber; } public void setTempleNumber(String templeNumber) { TempleNumber = templeNumber; } public String getPosthumousTitle() { return posthumousTitle; } public void setPosthumousTitle(String posthumousTitle) { this.posthumousTitle = posthumousTitle;
} public String getSon() { return son; } public void setSon(String son) { this.son = son; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public King getKing() { return king; } public void setKing(King king) { this.king = king; } }
repos\springBoot-master\springboot-neo4j\src\main\java\cn\abel\neo4j\bean\Queen.java
1
请完成以下Java代码
private I_M_Product getProduct() { if (product == null) { product = Services.get(IQueryBL.class) .createQueryBuilder(I_M_Product.class, getCtx(), get_TrxName()) .addEqualsFilter(I_M_Product.COLUMN_S_ExpenseType_ID, getS_ExpenseType_ID()) .create() .firstOnly(I_M_Product.class); } return product; } @Override protected boolean beforeSave(boolean newRecord) { if (newRecord) { if (getValue() == null || getValue().length() == 0) { setValue(getName()); } product = InterfaceWrapperHelper.newInstance(I_M_Product.class); product.setProductType(X_M_Product.PRODUCTTYPE_ExpenseType); updateProductFromExpenseType(product, this); InterfaceWrapperHelper.save(product); } return true; } // beforeSave @Override protected boolean afterSave(boolean newRecord, boolean success) { if (!success) return success; final I_M_Product product = getProduct(); if(updateProductFromExpenseType(product, this)) { InterfaceWrapperHelper.save(product); } return success; } /** * Set Expense Type * * @param parent expense type * @return true if changed */ private static boolean updateProductFromExpenseType(final I_M_Product product, final I_S_ExpenseType parent) { boolean changed = false; if (!X_M_Product.PRODUCTTYPE_ExpenseType.equals(product.getProductType())) { product.setProductType(X_M_Product.PRODUCTTYPE_ExpenseType); changed = true; } if (parent.getS_ExpenseType_ID() != product.getS_ExpenseType_ID()) { product.setS_ExpenseType_ID(parent.getS_ExpenseType_ID());
changed = true; } if (parent.isActive() != product.isActive()) { product.setIsActive(parent.isActive()); changed = true; } // if (!parent.getValue().equals(product.getValue())) { product.setValue(parent.getValue()); changed = true; } if (!parent.getName().equals(product.getName())) { product.setName(parent.getName()); changed = true; } if ((parent.getDescription() == null && product.getDescription() != null) || (parent.getDescription() != null && !parent.getDescription().equals(product.getDescription()))) { product.setDescription(parent.getDescription()); changed = true; } if (parent.getC_UOM_ID() != product.getC_UOM_ID()) { product.setC_UOM_ID(parent.getC_UOM_ID()); changed = true; } if (parent.getM_Product_Category_ID() != product.getM_Product_Category_ID()) { product.setM_Product_Category_ID(parent.getM_Product_Category_ID()); changed = true; } // metas 05129 end return changed; } } // MExpenseType
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MExpenseType.java
1
请完成以下Java代码
public void recreateGroupOnOrderLineChanged(final I_C_OrderLine orderLine) { if (!isEligible(orderLine)) { return; } final GroupId groupId = OrderGroupRepository.extractGroupId(orderLine); final Group group = groupsRepo.retrieveGroup(groupId); if (group.isBasedOnGroupTemplate()) { recreateGroupFromTemplate(group); } } private void recreateGroupFromTemplate(final Group group) { final GroupTemplate groupTemplate = groupTemplateRepo.getById(group.getGroupTemplateId()); groupsRepo.prepareNewGroup() .groupTemplate(groupTemplate) .recreateGroup(group); final OrderId orderId = OrderGroupRepository.extractOrderIdFromGroup(group); groupsRepo.renumberOrderLinesForOrderId(orderId); } private boolean isEligible(final I_C_OrderLine orderLine) { // Skip if given line is currently changed by the repository (to avoid race conditions) if (OrderGroupRepository.isRepositoryUpdate(orderLine)) { return false; } // Skip if not a group line if (!OrderGroupCompensationUtils.isInGroup(orderLine)) { return false; } // Don't touch processed lines (e.g. completed orders) return !orderLine.isProcessed(); } public void onOrderLineDeleted(final I_C_OrderLine orderLine) { if (!isEligible(orderLine)) { return; } final boolean groupCompensationLine = orderLine.isGroupCompensationLine(); if (groupCompensationLine) { onCompensationLineDeleted(orderLine); } } private void onCompensationLineDeleted(final I_C_OrderLine compensationLine) { final GroupId groupId = OrderGroupRepository.extractGroupId(compensationLine); final Group group = groupsRepo.retrieveGroupIfExists(groupId); // If no group found => nothing to do // Usually this case happens when we delete the order, so all the lines together. if (group == null) { return; } if (!group.hasCompensationLines()) { groupsRepo.destroyGroup(group); }
else { group.updateAllCompensationLines(); groupsRepo.saveGroup(group); } } public void updateCompensationLineNoSave(final I_C_OrderLine orderLine) { final Group group = groupsRepo.createPartialGroupFromCompensationLine(orderLine); group.updateAllCompensationLines(); final OrderLinesStorage orderLinesStorage = groupsRepo.createNotSaveableSingleOrderLineStorage(orderLine); groupsRepo.saveGroup(group, orderLinesStorage); } @Nullable public GroupTemplateId getGroupTemplateId(@NonNull final GroupId groupId) { return groupsRepo.getGroupTemplateId(groupId); } public boolean isProductExcludedFromFlatrateConditions(@Nullable final GroupTemplateId groupTemplateId, @NonNull final ProductId productId) { if (groupTemplateId == null) { return false; } return flatrateConditionsExcludedProductsRepo.isProductExcludedFromFlatrateConditions(groupTemplateId, productId); } public IQueryBuilder<I_C_OrderLine> retrieveGroupOrderLinesQuery(final GroupId groupId) { return groupsRepo.retrieveGroupOrderLinesQuery(groupId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\compensationGroup\OrderGroupCompensationChangesHandler.java
1
请完成以下Java代码
public String getSeparator() { return "/!"; } @Override public Iterable<Path> getRootDirectories() { assertNotClosed(); return Collections.emptySet(); } @Override public Iterable<FileStore> getFileStores() { assertNotClosed(); return Collections.emptySet(); } @Override public Set<String> supportedFileAttributeViews() { assertNotClosed(); return SUPPORTED_FILE_ATTRIBUTE_VIEWS; } @Override public Path getPath(String first, String... more) { assertNotClosed(); if (more.length != 0) { throw new IllegalArgumentException("Nested paths must contain a single element"); } return new NestedPath(this, first); } @Override public PathMatcher getPathMatcher(String syntaxAndPattern) { throw new UnsupportedOperationException("Nested paths do not support path matchers"); } @Override public UserPrincipalLookupService getUserPrincipalLookupService() { throw new UnsupportedOperationException("Nested paths do not have a user principal lookup service"); }
@Override public WatchService newWatchService() throws IOException { throw new UnsupportedOperationException("Nested paths do not support the WatchService"); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } NestedFileSystem other = (NestedFileSystem) obj; return this.jarPath.equals(other.jarPath); } @Override public int hashCode() { return this.jarPath.hashCode(); } @Override public String toString() { return this.jarPath.toAbsolutePath().toString(); } private void assertNotClosed() { if (this.closed) { throw new ClosedFileSystemException(); } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedFileSystem.java
1
请完成以下Java代码
public void setPriority(String externalTaskId, long priority) { commandExecutor.execute(new SetExternalTaskPriorityCmd(externalTaskId, priority)); } public ExternalTaskQuery createExternalTaskQuery() { return new ExternalTaskQueryImpl(commandExecutor); } @Override public List<String> getTopicNames() { return commandExecutor.execute(new GetTopicNamesCmd(false,false,false)); } @Override public List<String> getTopicNames(boolean withLockedTasks, boolean withUnlockedTasks, boolean withRetriesLeft) { return commandExecutor.execute(new GetTopicNamesCmd(withLockedTasks, withUnlockedTasks, withRetriesLeft)); } public String getExternalTaskErrorDetails(String externalTaskId) { return commandExecutor.execute(new GetExternalTaskErrorDetailsCmd(externalTaskId)); } @Override public void setRetries(String externalTaskId, int retries) { setRetries(externalTaskId, retries, true); } @Override public void setRetries(List<String> externalTaskIds, int retries) { updateRetries() .externalTaskIds(externalTaskIds) .set(retries);
} @Override public Batch setRetriesAsync(List<String> externalTaskIds, ExternalTaskQuery externalTaskQuery, int retries) { return updateRetries() .externalTaskIds(externalTaskIds) .externalTaskQuery(externalTaskQuery) .setAsync(retries); } @Override public UpdateExternalTaskRetriesSelectBuilder updateRetries() { return new UpdateExternalTaskRetriesBuilderImpl(commandExecutor); } @Override public void extendLock(String externalTaskId, String workerId, long lockDuration) { commandExecutor.execute(new ExtendLockOnExternalTaskCmd(externalTaskId, workerId, lockDuration)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ExternalTaskServiceImpl.java
1
请完成以下Java代码
public class PotentialStarterParser implements BpmnXMLConstants { public void parse(XMLStreamReader xtr, Process activeProcess) throws Exception { String resourceElement = XMLStreamReaderUtil.moveDown(xtr); if (StringUtils.isNotEmpty(resourceElement) && "resourceAssignmentExpression".equals(resourceElement)) { String expression = XMLStreamReaderUtil.moveDown(xtr); if (StringUtils.isNotEmpty(expression) && "formalExpression".equals(expression)) { List<String> assignmentList = new ArrayList<String>(); String assignmentText = xtr.getElementText(); if (assignmentText.contains(",")) { String[] assignmentArray = assignmentText.split(","); assignmentList = asList(assignmentArray); } else { assignmentList.add(assignmentText); } for (String assignmentValue : assignmentList) { if (assignmentValue == null) continue; assignmentValue = assignmentValue.trim(); if (assignmentValue.length() == 0) continue; String userPrefix = "user("; String groupPrefix = "group(";
if (assignmentValue.startsWith(userPrefix)) { assignmentValue = assignmentValue .substring(userPrefix.length(), assignmentValue.length() - 1) .trim(); activeProcess.getCandidateStarterUsers().add(assignmentValue); } else if (assignmentValue.startsWith(groupPrefix)) { assignmentValue = assignmentValue .substring(groupPrefix.length(), assignmentValue.length() - 1) .trim(); activeProcess.getCandidateStarterGroups().add(assignmentValue); } else { activeProcess.getCandidateStarterGroups().add(assignmentValue); } } } } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\parser\PotentialStarterParser.java
1
请完成以下Java代码
public boolean isRestartInclude(URL url) { return isMatch(url.toString(), this.restartIncludePatterns); } public boolean isRestartExclude(URL url) { return isMatch(url.toString(), this.restartExcludePatterns); } public Map<String, Object> getPropertyDefaults() { return Collections.unmodifiableMap(this.propertyDefaults); } private boolean isMatch(String url, List<Pattern> patterns) { for (Pattern pattern : patterns) { if (pattern.matcher(url).find()) { return true; } } return false; } public static DevToolsSettings get() { if (settings == null) { settings = load(); } return settings;
} static DevToolsSettings load() { return load(SETTINGS_RESOURCE_LOCATION); } static DevToolsSettings load(String location) { try { DevToolsSettings settings = new DevToolsSettings(); Enumeration<URL> urls = Thread.currentThread().getContextClassLoader().getResources(location); while (urls.hasMoreElements()) { settings.add(PropertiesLoaderUtils.loadProperties(new UrlResource(urls.nextElement()))); } if (logger.isDebugEnabled()) { logger.debug("Included patterns for restart : " + settings.restartIncludePatterns); logger.debug("Excluded patterns for restart : " + settings.restartExcludePatterns); } return settings; } catch (Exception ex) { throw new IllegalStateException("Unable to load devtools settings from location [" + location + "]", ex); } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\settings\DevToolsSettings.java
1
请在Spring Boot框架中完成以下Java代码
public User getUser(String username) { return userRepository.findByUsername(username).orElseThrow(() -> new NoSuchElementException("user not found.")); } /** * Register a new user in the system. * * @param registry User registration information * @return Returns the registered user */ @SuppressWarnings("UnusedReturnValue") public User signup(UserRegistry registry) { if (userRepository.existsBy(registry.email(), registry.username())) { throw new IllegalArgumentException("email or username is already exists."); } var requester = new User(registry); requester.encryptPassword(passwordEncoder, registry.password()); return userRepository.save(requester); } /** * Login to the system. * * @param email users email * @param password users password * @return Returns the logged-in user */ public User login(String email, String password) { if (email == null || email.isBlank()) { throw new IllegalArgumentException("email is required."); } if (password == null || password.isBlank()) { throw new IllegalArgumentException("password is required."); } return userRepository .findByEmail(email) .filter(user -> passwordEncoder.matches(password, user.getPassword())) .orElseThrow(() -> new IllegalArgumentException("invalid email or password.")); } /**
* Update user information. * * @param userId The user who requested the update * @param email users email * @param username users username * @param password users password * @param bio users bio * @param imageUrl users imageUrl * @return Returns the updated user */ public User updateUserDetails( UUID userId, String email, String username, String password, String bio, String imageUrl) { if (userId == null) { throw new IllegalArgumentException("user id is required."); } return userRepository.updateUserDetails(userId, passwordEncoder, email, username, password, bio, imageUrl); } }
repos\realworld-java21-springboot3-main\module\core\src\main\java\io\zhc1\realworld\service\UserService.java
2
请完成以下Java代码
protected List<Section> resolveSubSections(List<Section> sections) { List<Section> allSections = new ArrayList<>(); allSections.add(this.referenceDocs); allSections.add(this.guides); allSections.add(this.additionalLinks); allSections.addAll(sections); return allSections; } public GettingStartedSection addReferenceDocLink(String href, String description) { this.referenceDocs.addItem(new Link(href, description)); return this; } public BulletedSection<Link> referenceDocs() { return this.referenceDocs; } public GettingStartedSection addGuideLink(String href, String description) { this.guides.addItem(new Link(href, description)); return this; } public BulletedSection<Link> guides() { return this.guides; } public GettingStartedSection addAdditionalLink(String href, String description) { this.additionalLinks.addItem(new Link(href, description)); return this; } public BulletedSection<Link> additionalLinks() { return this.additionalLinks; }
/** * Internal representation of a link. */ public static class Link { private final String href; private final String description; Link(String href, String description) { this.href = href; this.description = description; } public String getHref() { return this.href; } public String getDescription() { return this.description; } } }
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\documentation\GettingStartedSection.java
1
请完成以下Java代码
public List<Object> toComposedKeyParts() { return ImmutableList.of(idInt); } } private static final class StringDocumentId extends DocumentId { private final String idStr; private StringDocumentId(final String idStr) { Check.assumeNotEmpty(idStr, "idStr is not empty"); this.idStr = idStr; } @Override public String toJson() { return idStr; } @Override public int hashCode() { return Objects.hash(idStr); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof StringDocumentId)) { return false; } final StringDocumentId other = (StringDocumentId)obj;
return Objects.equals(idStr, other.idStr); } @Override public boolean isInt() { return false; } @Override public int toInt() { if (isComposedKey()) { throw new AdempiereException("Composed keys cannot be converted to int: " + this); } else { throw new AdempiereException("String document IDs cannot be converted to int: " + this); } } @Override public boolean isNew() { return false; } @Override public boolean isComposedKey() { return idStr.contains(COMPOSED_KEY_SEPARATOR); } @Override public List<Object> toComposedKeyParts() { final ImmutableList.Builder<Object> composedKeyParts = ImmutableList.builder(); COMPOSED_KEY_SPLITTER.split(idStr).forEach(composedKeyParts::add); return composedKeyParts.build(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DocumentId.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isUseInsecureTrustManager() { return useInsecureTrustManager; } public void setUseInsecureTrustManager(boolean useInsecureTrustManager) { this.useInsecureTrustManager = useInsecureTrustManager; } public Duration getHandshakeTimeout() { return handshakeTimeout; } public void setHandshakeTimeout(Duration handshakeTimeout) { this.handshakeTimeout = handshakeTimeout; } public Duration getCloseNotifyFlushTimeout() { return closeNotifyFlushTimeout; } public void setCloseNotifyFlushTimeout(Duration closeNotifyFlushTimeout) { this.closeNotifyFlushTimeout = closeNotifyFlushTimeout; } public Duration getCloseNotifyReadTimeout() { return closeNotifyReadTimeout; } public void setCloseNotifyReadTimeout(Duration closeNotifyReadTimeout) { this.closeNotifyReadTimeout = closeNotifyReadTimeout; } public String getSslBundle() { return sslBundle; } public void setSslBundle(String sslBundle) { this.sslBundle = sslBundle; } @Override public String toString() { return new ToStringCreator(this).append("useInsecureTrustManager", useInsecureTrustManager) .append("trustedX509Certificates", trustedX509Certificates) .append("handshakeTimeout", handshakeTimeout) .append("closeNotifyFlushTimeout", closeNotifyFlushTimeout) .append("closeNotifyReadTimeout", closeNotifyReadTimeout) .toString(); } } public static class Websocket { /** Max frame payload length. */ private Integer maxFramePayloadLength;
/** Proxy ping frames to downstream services, defaults to true. */ private boolean proxyPing = true; public Integer getMaxFramePayloadLength() { return this.maxFramePayloadLength; } public void setMaxFramePayloadLength(Integer maxFramePayloadLength) { this.maxFramePayloadLength = maxFramePayloadLength; } public boolean isProxyPing() { return proxyPing; } public void setProxyPing(boolean proxyPing) { this.proxyPing = proxyPing; } @Override public String toString() { return new ToStringCreator(this).append("maxFramePayloadLength", maxFramePayloadLength) .append("proxyPing", proxyPing) .toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\HttpClientProperties.java
2
请完成以下Java代码
private void register() { for (int tableId : instance.getAssignedTableIds()) { final String tableName = adTableDAO.retrieveTableName(tableId); if (documentBL.isDocumentTable(tableName)) { engine.addDocValidate(tableName, this); logger.debug("Registered docValidate " + this); } else { engine.addModelChange(tableName, this); logger.debug("Registered modelChange " + this); } } } public void unregister() { for (int tableId : instance.getAssignedTableIds()) { final String tableName = adTableDAO.retrieveTableName(tableId); engine.removeModelChange(tableName, this);
engine.removeDocValidate(tableName, this); } logger.debug("Unregistered " + this); } public IReferenceNoGeneratorInstance getInstance() { return instance; } @Override public String toString() { return "ReferenceNoGeneratorInstanceValidator [instance=" + instance + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java\de\metas\document\refid\modelvalidator\ReferenceNoGeneratorInstanceValidator.java
1
请完成以下Java代码
protected boolean afterSave (boolean newRecord, boolean success) { /* v_Description := :new.Name; IF (:new.Description IS NOT NULL AND LENGTH(:new.Description) > 0) THEN v_Description := v_Description || ' (' || :new.Description || ')'; END IF; -- Update Expense Line UPDATE S_TimeExpenseLine SET Description = v_Description, Qty = :new.Qty WHERE S_ResourceAssignment_ID = :new.S_ResourceAssignment_ID AND (Description <> v_Description OR Qty <> :new.Qty); -- Update Order Line UPDATE C_OrderLine SET Description = v_Description, QtyOrdered = :new.Qty WHERE S_ResourceAssignment_ID = :new.S_ResourceAssignment_ID AND (Description <> v_Description OR QtyOrdered <> :new.Qty); -- Update Invoice Line UPDATE C_InvoiceLine SET Description = v_Description, QtyInvoiced = :new.Qty WHERE S_ResourceAssignment_ID = :new.S_ResourceAssignment_ID AND (Description <> v_Description OR QtyInvoiced <> :new.Qty); */ return success; } // afterSave /** * String Representation * @return string */ @Override public String toString() { StringBuffer sb = new StringBuffer ("MResourceAssignment[ID="); sb.append(get_ID()) .append(",S_Resource_ID=").append(getS_Resource_ID()) .append(",From=").append(getAssignDateFrom()) .append(",To=").append(getAssignDateTo())
.append(",Qty=").append(getQty()) .append("]"); return sb.toString(); } // toString /** * Before Delete * @return true if not confirmed */ @Override protected boolean beforeDelete () { // allow to delete, when not confirmed if (isConfirmed()) return false; return true; } // beforeDelete } // MResourceAssignment
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MResourceAssignment.java
1
请完成以下Java代码
private static ExchangeFilterFunction setInstance(Mono<Instance> instance) { return (request, next) -> instance .map((i) -> ClientRequest.from(request).attribute(ATTRIBUTE_INSTANCE, i).build()) .switchIfEmpty(Mono.error(() -> new ResolveInstanceException("Could not resolve Instance"))) .flatMap(next::exchange); } private static ExchangeFilterFunction toExchangeFilterFunction(InstanceExchangeFilterFunction filter) { return (request, next) -> request.attribute(ATTRIBUTE_INSTANCE) .filter(Instance.class::isInstance) .map(Instance.class::cast) .map((instance) -> filter.filter(instance, request, next)) .orElseGet(() -> next.exchange(request)); } public static class Builder { private List<InstanceExchangeFilterFunction> filters = new ArrayList<>(); private WebClient.Builder webClientBuilder; public Builder() { this(WebClient.builder()); } public Builder(WebClient.Builder webClientBuilder) { this.webClientBuilder = webClientBuilder; } protected Builder(Builder other) { this.filters = new ArrayList<>(other.filters); this.webClientBuilder = other.webClientBuilder.clone(); } public Builder filter(InstanceExchangeFilterFunction filter) {
this.filters.add(filter); return this; } public Builder filters(Consumer<List<InstanceExchangeFilterFunction>> filtersConsumer) { filtersConsumer.accept(this.filters); return this; } public Builder webClient(WebClient.Builder builder) { this.webClientBuilder = builder; return this; } public Builder clone() { return new Builder(this); } public InstanceWebClient build() { this.filters.stream() .map(InstanceWebClient::toExchangeFilterFunction) .forEach(this.webClientBuilder::filter); return new InstanceWebClient(this.webClientBuilder.build()); } } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\web\client\InstanceWebClient.java
1
请在Spring Boot框架中完成以下Java代码
public class EmployeeServiceImpl implements EmployeeService { @Inject private EmployeeRepository employeeRepositoryImpl; @WebMethod public Employee getEmployee(int id) throws EmployeeNotFound { return employeeRepositoryImpl.getEmployee(id); } @WebMethod public Employee updateEmployee(int id, String name) throws EmployeeNotFound { return employeeRepositoryImpl.updateEmployee(id, name); } @WebMethod public boolean deleteEmployee(int id) throws EmployeeNotFound {
return employeeRepositoryImpl.deleteEmployee(id); } @WebMethod public Employee addEmployee(int id, String name) throws EmployeeAlreadyExists { return employeeRepositoryImpl.addEmployee(id, name); } @WebMethod public int countEmployees() { return employeeRepositoryImpl.count(); } @WebMethod public List<Employee> getAllEmployees() { return employeeRepositoryImpl.getAllEmployees(); } }
repos\tutorials-master\web-modules\jee-7\src\main\java\com\baeldung\jaxws\server\bottomup\EmployeeServiceImpl.java
2
请完成以下Java代码
public List<MapExceptionEntry> getMapExceptions() { return mapExceptions; } public void setMapExceptions(List<MapExceptionEntry> mapExceptions) { this.mapExceptions = mapExceptions; } public void setValues(Activity otherActivity) { super.setValues(otherActivity); setFailedJobRetryTimeCycleValue(otherActivity.getFailedJobRetryTimeCycleValue()); setDefaultFlow(otherActivity.getDefaultFlow()); setForCompensation(otherActivity.isForCompensation()); if (otherActivity.getLoopCharacteristics() != null) { setLoopCharacteristics(otherActivity.getLoopCharacteristics().clone()); } if (otherActivity.getIoSpecification() != null) { setIoSpecification(otherActivity.getIoSpecification().clone()); } dataInputAssociations = new ArrayList<DataAssociation>(); if (otherActivity.getDataInputAssociations() != null && !otherActivity.getDataInputAssociations().isEmpty()) { for (DataAssociation association : otherActivity.getDataInputAssociations()) { dataInputAssociations.add(association.clone());
} } dataOutputAssociations = new ArrayList<DataAssociation>(); if (otherActivity.getDataOutputAssociations() != null && !otherActivity.getDataOutputAssociations().isEmpty()) { for (DataAssociation association : otherActivity.getDataOutputAssociations()) { dataOutputAssociations.add(association.clone()); } } boundaryEvents.clear(); for (BoundaryEvent event : otherActivity.getBoundaryEvents()) { boundaryEvents.add(event); } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\Activity.java
1
请在Spring Boot框架中完成以下Java代码
public class CostAmountAndQty { @NonNull CostAmount amt; @NonNull Quantity qty; public static CostAmountAndQty zero(@NonNull final CurrencyId currencyId, @NonNull final UomId uomId) { return of(CostAmount.zero(currencyId), Quantitys.zero(uomId)); } public static CurrencyId getCommonCurrencyIdOfAll(@Nullable final CostAmountAndQty... values) { return CurrencyId.getCommonCurrencyIdOfAll(CostAmountAndQty::getCurrencyId, "amount", values); } public static UomId getCommonUomIdOfAll(@Nullable final CostAmountAndQty... values) { return UomId.getCommonUomIdOfAll(CostAmountAndQty::getUomId, "quantity", values); } public CurrencyId getCurrencyId() {return amt.getCurrencyId();} public UomId getUomId() {return qty.getUomId();} public boolean isZero() {return amt.isZero() && qty.isZero();} public CostAmountAndQty toZero() {return isZero() ? this : of(amt.toZero(), qty.toZero());} public CostAmountAndQty negate() {return isZero() ? this : of(amt.negate(), qty.negate());} public CostAmountAndQty mapQty(@NonNull final UnaryOperator<Quantity> qtyMapper) { if (qty.isZero()) { return this; } final Quantity newQty = qtyMapper.apply(qty); if (Objects.equals(qty, newQty)) {
return this; } return of(amt, newQty); } public CostAmountAndQty add(@NonNull final CostAmountAndQty other) { if (other.isZero()) { return this; } else if (this.isZero()) { return other; } else { return of(this.amt.add(other.amt), this.qty.add(other.qty)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostAmountAndQty.java
2
请完成以下Java代码
public String getExtraValue() { return extraValue; } public String getInvolvedUser() { return involvedUser; } public Collection<String> getInvolvedGroups() { return involvedGroups; } public boolean isOnlyStages() { return onlyStages; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public boolean isIncludeLocalVariables() {
return includeLocalVariables; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } public List<List<String>> getSafeCaseInstanceIds() { return safeCaseInstanceIds; } public void setSafeCaseInstanceIds(List<List<String>> safeProcessInstanceIds) { this.safeCaseInstanceIds = safeProcessInstanceIds; } public Collection<String> getCaseInstanceIds() { return caseInstanceIds; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\history\HistoricPlanItemInstanceQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public Map<Integer, Integer> getNotifyRuleMap(){ return (Map) JSONObject.parseObject(getNotifyRule()); } /** 最后一次通知时间 **/ public Date getLastNotifyTime() { return lastNotifyTime; } /** 最后一次通知时间 **/ public void setLastNotifyTime(Date lastNotifyTime) { this.lastNotifyTime = lastNotifyTime; } /** 通知次数 **/ public Integer getNotifyTimes() { return notifyTimes; } /** 通知次数 **/ public void setNotifyTimes(Integer notifyTimes) { this.notifyTimes = notifyTimes; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; }
/** 限制通知次数 **/ public Integer getLimitNotifyTimes() { return limitNotifyTimes; } /** 限制通知次数 **/ public void setLimitNotifyTimes(Integer limitNotifyTimes) { this.limitNotifyTimes = limitNotifyTimes; } public String getBankOrderNo() { return bankOrderNo; } public void setBankOrderNo(String bankOrderNo) { this.bankOrderNo = bankOrderNo; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\notify\entity\RpOrderResultQueryVo.java
2
请完成以下Java代码
private void setAuthenticator(LdapAuthenticator authenticator) { Assert.notNull(authenticator, "An LdapAuthenticator must be supplied"); this.authenticator = authenticator; } private LdapAuthenticator getAuthenticator() { return this.authenticator; } private void setAuthoritiesPopulator(LdapAuthoritiesPopulator authoritiesPopulator) { Assert.notNull(authoritiesPopulator, "An LdapAuthoritiesPopulator must be supplied"); this.authoritiesPopulator = authoritiesPopulator; } protected LdapAuthoritiesPopulator getAuthoritiesPopulator() { return this.authoritiesPopulator; } public void setHideUserNotFoundExceptions(boolean hideUserNotFoundExceptions) { this.hideUserNotFoundExceptions = hideUserNotFoundExceptions; } @Override protected DirContextOperations doAuthentication(UsernamePasswordAuthenticationToken authentication) { try { return getAuthenticator().authenticate(authentication); } catch (PasswordPolicyException ex) { // The only reason a ppolicy exception can occur during a bind is that the // account is locked. throw new LockedException( this.messages.getMessage(ex.getStatus().getErrorCode(), ex.getStatus().getDefaultMessage())); }
catch (UsernameNotFoundException ex) { if (this.hideUserNotFoundExceptions) { throw new BadCredentialsException( this.messages.getMessage("LdapAuthenticationProvider.badCredentials", "Bad credentials")); } throw ex; } catch (NamingException ex) { throw new InternalAuthenticationServiceException(ex.getMessage(), ex); } } @Override protected Collection<? extends GrantedAuthority> loadUserAuthorities(DirContextOperations userData, String username, String password) { return getAuthoritiesPopulator().getGrantedAuthorities(userData, username); } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\authentication\LdapAuthenticationProvider.java
1
请完成以下Java代码
private void unclose(final I_PP_Order ppOrder) { ModelValidationEngine.get().fireDocValidate(ppOrder, ModelValidator.TIMING_BEFORE_UNCLOSE); // // Unclose PP_Order's Qty ppOrderBL.uncloseQtyOrdered(ppOrder); ppOrdersRepo.save(ppOrder); // // Unclose PP_Order BOM Line's quantities final List<I_PP_Order_BOMLine> lines = ppOrderBOMDAO.retrieveOrderBOMLines(ppOrder); for (final I_PP_Order_BOMLine line : lines) { ppOrderBOMBL.unclose(line); } // // Unclose activities final PPOrderId ppOrderId = PPOrderId.ofRepoId(ppOrder.getPP_Order_ID()); ppOrderBL.uncloseActivities(ppOrderId); // firing this before having updated the docstatus. This is how the *real* DocActions like MInvoice do it too. ModelValidationEngine.get().fireDocValidate(ppOrder, ModelValidator.TIMING_AFTER_UNCLOSE); // // Update DocStatus ppOrder.setDocStatus(IDocument.STATUS_Completed); ppOrder.setDocAction(IDocument.ACTION_Close); ppOrdersRepo.save(ppOrder); // // Reverse ALL cost collectors reverseCostCollectorsGeneratedOnClose(ppOrderId); }
private void reverseCostCollectorsGeneratedOnClose(final PPOrderId ppOrderId) { final ArrayList<I_PP_Cost_Collector> costCollectors = new ArrayList<>(ppCostCollectorDAO.getByOrderId(ppOrderId)); // Sort the cost collectors in reverse order of their creation, // just to make sure we are reversing the effect from last one to first one. costCollectors.sort(ModelByIdComparator.getInstance().reversed()); for (final I_PP_Cost_Collector cc : costCollectors) { final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(cc.getDocStatus()); if (docStatus.isReversedOrVoided()) { continue; } final CostCollectorType costCollectorType = CostCollectorType.ofCode(cc.getCostCollectorType()); if (costCollectorType == CostCollectorType.UsageVariance) { if (docStatus.isClosed()) { cc.setDocStatus(DocStatus.Completed.getCode()); ppCostCollectorDAO.save(cc); } docActionBL.processEx(cc, IDocument.ACTION_Reverse_Correct, DocStatus.Reversed.getCode()); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\PP_Order_UnClose.java
1
请完成以下Java代码
public void setC_Async_Batch_ID (final int C_Async_Batch_ID) { if (C_Async_Batch_ID < 1) set_Value (COLUMNNAME_C_Async_Batch_ID, null); else set_Value (COLUMNNAME_C_Async_Batch_ID, C_Async_Batch_ID); } @Override public int getC_Async_Batch_ID() { return get_ValueAsInt(COLUMNNAME_C_Async_Batch_ID); } @Override public void setChunkUUID (final @Nullable java.lang.String ChunkUUID) { set_Value (COLUMNNAME_ChunkUUID, ChunkUUID); } @Override public java.lang.String getChunkUUID() { return get_ValueAsString(COLUMNNAME_ChunkUUID); }
@Override public de.metas.inoutcandidate.model.I_M_ShipmentSchedule getM_ShipmentSchedule() { return get_ValueAsPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class); } @Override public void setM_ShipmentSchedule(final de.metas.inoutcandidate.model.I_M_ShipmentSchedule M_ShipmentSchedule) { set_ValueFromPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class, M_ShipmentSchedule); } @Override public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_Value (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID); } @Override public int getM_ShipmentSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule_Recompute.java
1
请完成以下Java代码
private void putToken(Map<String, Object> attributes, @Nullable CsrfToken token) { if (token == null) { attributes.remove(this.sessionAttributeName); } else { attributes.put(this.sessionAttributeName, token); } } @Override @SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290 public Mono<CsrfToken> loadToken(ServerWebExchange exchange) { return exchange.getSession() .filter((session) -> session.getAttributes().containsKey(this.sessionAttributeName)) .mapNotNull((session) -> session.getAttribute(this.sessionAttributeName)); } /** * Sets the {@link ServerWebExchange} parameter name that the {@link CsrfToken} is * expected to appear on * @param parameterName the new parameter name to use */ public void setParameterName(String parameterName) { Assert.hasLength(parameterName, "parameterName cannot be null or empty"); this.parameterName = parameterName; } /** * Sets the header name that the {@link CsrfToken} is expected to appear on and the * header that the response will contain the {@link CsrfToken}. * @param headerName the new header name to use */
public void setHeaderName(String headerName) { Assert.hasLength(headerName, "headerName cannot be null or empty"); this.headerName = headerName; } /** * Sets the {@link WebSession} attribute name that the {@link CsrfToken} is stored in * @param sessionAttributeName the new attribute name to use */ public void setSessionAttributeName(String sessionAttributeName) { Assert.hasLength(sessionAttributeName, "sessionAttributeName cannot be null or empty"); this.sessionAttributeName = sessionAttributeName; } private CsrfToken createCsrfToken() { return new DefaultCsrfToken(this.headerName, this.parameterName, createNewToken()); } private String createNewToken() { return UUID.randomUUID().toString(); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\csrf\WebSessionServerCsrfTokenRepository.java
1
请完成以下Spring Boot application配置
# # Copyright 2015-2022 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND
, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # logging.level.root=WARN logging.level.sample.mybatis.kotlin.mapper=TRACE
repos\spring-boot-starter-master\mybatis-spring-boot-samples\mybatis-spring-boot-sample-kotlin\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public static void createWorkpackage(final List<Integer> inOutLineIds) { if (inOutLineIds == null || inOutLineIds.isEmpty()) { // no lines to process return; } for (final Integer inOutLineId : inOutLineIds) { if (inOutLineId == null || inOutLineId <= 0) { // should not happen continue; } // Schedule the request creation based on the given inoutline ids SCHEDULER.schedule(InOutLineWithQualityIssues.of(inOutLineId)); } } /** * Class to keep information about the inout lines with quality issues (Quality Discount Percent). * This model will be used ion the * * @author metas-dev <dev@metasfresh.com> */ private static final class InOutLineWithQualityIssues { public static InOutLineWithQualityIssues of(int inOutLineId) { return new InOutLineWithQualityIssues(inOutLineId); } private final int inOutLineId; private InOutLineWithQualityIssues(int inOutLineId) { super(); this.inOutLineId = inOutLineId; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("inOutLineId", inOutLineId) .toString(); } public int getM_InOutLine_ID() { return inOutLineId; } } private static final WorkpackagesOnCommitSchedulerTemplate<InOutLineWithQualityIssues> SCHEDULER = new WorkpackagesOnCommitSchedulerTemplate<InOutLineWithQualityIssues>(C_Request_CreateFromInout_Async.class) {
@Override protected boolean isEligibleForScheduling(final InOutLineWithQualityIssues model) { return model != null && model.getM_InOutLine_ID() > 0; } ; @Override protected Properties extractCtxFromItem(final InOutLineWithQualityIssues item) { return Env.getCtx(); } @Override protected String extractTrxNameFromItem(final InOutLineWithQualityIssues item) { return ITrx.TRXNAME_ThreadInherited; } @Override protected Object extractModelToEnqueueFromItem(final Collector collector, final InOutLineWithQualityIssues item) { return TableRecordReference.of(I_M_InOutLine.Table_Name, item.getM_InOutLine_ID()); } }; @Override public Result processWorkPackage(final I_C_Queue_WorkPackage workPackage, final String localTrxName) { // Services final IQueueDAO queueDAO = Services.get(IQueueDAO.class); final IRequestBL requestBL = Services.get(IRequestBL.class); // retrieve the items (inout lines) that were enqueued and put them in a list final List<I_M_InOutLine> lines = queueDAO.retrieveAllItems(workPackage, I_M_InOutLine.class); // for each line that was enqueued, create a R_Request containing the information from the inout line and inout for (final I_M_InOutLine line : lines) { requestBL.createRequestFromInOutLineWithQualityIssues(line); } return Result.SUCCESS; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\request\service\async\spi\impl\C_Request_CreateFromInout_Async.java
2
请在Spring Boot框架中完成以下Java代码
public BigDecimal getPercentage() { return percentage; } /** * Sets the value of the percentage property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setPercentage(BigDecimal value) { this.percentage = value; } /** * Gets the value of the amount property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getAmount() { return amount; } /** * Sets the value of the amount property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setAmount(BigDecimal value) { this.amount = value; } /** * Gets the value of the calcuationCode property. * * @return * possible object is * {@link String } * */ public String getCalcuationCode() { return calcuationCode; } /** * Sets the value of the calcuationCode property. * * @param value * allowed object is * {@link String } * */ public void setCalcuationCode(String value) { this.calcuationCode = value; } /** * Gets the value of the vatRate property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getVATRate() {
return vatRate; } /** * Sets the value of the vatRate property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setVATRate(BigDecimal value) { this.vatRate = value; } /** * Gets the value of the allowanceOrChargeQualifier property. * * @return * possible object is * {@link String } * */ public String getAllowanceOrChargeQualifier() { return allowanceOrChargeQualifier; } /** * Sets the value of the allowanceOrChargeQualifier property. * * @param value * allowed object is * {@link String } * */ public void setAllowanceOrChargeQualifier(String value) { this.allowanceOrChargeQualifier = value; } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\AdditionalChargesAndReductionsType.java
2
请完成以下Java代码
public void setAllowedOrigins(String allowedOrigins) { this.allowedOrigins = allowedOrigins; } public boolean getAllowCredentials() { return allowCredentials; } public void setAllowCredentials(boolean allowCredentials) { this.allowCredentials = allowCredentials; } public String getAllowedHeaders() { return allowedHeaders; } public void setAllowedHeaders(String allowedHeaders) { this.allowedHeaders = allowedHeaders; } public String getExposedHeaders() { return exposedHeaders; } public void setExposedHeaders(String exposedHeaders) { this.exposedHeaders = exposedHeaders; } public String getPreflightMaxAge() { return preflightMaxAge; }
public void setPreflightMaxAge(String preflightMaxAge) { this.preflightMaxAge = preflightMaxAge; } @Override public String toString() { return "CamundaBpmRunCorsProperty [" + "enabled=" + enabled + ", allowCredentials=" + allowCredentials + ", allowedOrigins=" + allowedOrigins + ", allowedHeaders=" + allowedHeaders + ", exposedHeaders=" + exposedHeaders + ", preflightMaxAge=" + preflightMaxAge + ']'; } }
repos\camunda-bpm-platform-master\distro\run\core\src\main\java\org\camunda\bpm\run\property\CamundaBpmRunCorsProperty.java
1
请完成以下Java代码
protected void suspendJobs(List<Job> jobs) { for (Job job: jobs) { JobEntity jobInstance = (JobEntity) job; jobInstance.setSuspensionState(SuspensionState.SUSPENDED.getStateCode()); jobInstance.setDuedate(null); } } @SuppressWarnings("unchecked") protected JobEntity createJob(int[] minuteChunk, int maxRetries) { HistoryCleanupContext context = createCleanupContext(minuteChunk, maxRetries); return HISTORY_CLEANUP_JOB_DECLARATION.createJobInstance(context); } protected HistoryCleanupContext createCleanupContext(int[] minuteChunk, int maxRetries) { int minuteFrom = minuteChunk[0]; int minuteTo = minuteChunk[1]; return new HistoryCleanupContext(immediatelyDue, minuteFrom, minuteTo, maxRetries); } protected void writeUserOperationLog(CommandContext commandContext) { PropertyChange propertyChange = new PropertyChange("immediatelyDue", null, immediatelyDue);
commandContext.getOperationLogManager() .logJobOperation(UserOperationLogEntry.OPERATION_TYPE_CREATE_HISTORY_CLEANUP_JOB, null, null, null, null, null, propertyChange); } protected void acquireExclusiveLock(CommandContext commandContext) { PropertyManager propertyManager = commandContext.getPropertyManager(); //exclusive lock propertyManager.acquireExclusiveLockForHistoryCleanupJob(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\HistoryCleanupCmd.java
1
请完成以下Java代码
public static ObjectMapper enhancedObjectMapper() { ObjectMapper objectMapper = JsonMapper.builder() .configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .build(); registerWellKnownModulesIfAvailable(objectMapper); return objectMapper; } private static void registerWellKnownModulesIfAvailable(ObjectMapper objectMapper) { if (JDK8_MODULE_PRESENT) { objectMapper.registerModule(Jdk8ModuleProvider.MODULE); } if (PARAMETER_NAMES_MODULE_PRESENT) { objectMapper.registerModule(ParameterNamesProvider.MODULE); } if (JAVA_TIME_MODULE_PRESENT) { objectMapper.registerModule(JavaTimeModuleProvider.MODULE); } if (JODA_MODULE_PRESENT) { objectMapper.registerModule(JodaModuleProvider.MODULE); } if (KOTLIN_MODULE_PRESENT) { objectMapper.registerModule(KotlinModuleProvider.MODULE); } } private JacksonUtils() { } private static final class Jdk8ModuleProvider { static final com.fasterxml.jackson.databind.Module MODULE = new com.fasterxml.jackson.datatype.jdk8.Jdk8Module(); } private static final class ParameterNamesProvider { static final com.fasterxml.jackson.databind.Module MODULE =
new com.fasterxml.jackson.module.paramnames.ParameterNamesModule(); } private static final class JavaTimeModuleProvider { static final com.fasterxml.jackson.databind.Module MODULE = new com.fasterxml.jackson.datatype.jsr310.JavaTimeModule(); } private static final class JodaModuleProvider { static final com.fasterxml.jackson.databind.Module MODULE = new com.fasterxml.jackson.datatype.joda.JodaModule(); } private static final class KotlinModuleProvider { static final com.fasterxml.jackson.databind.Module MODULE = new com.fasterxml.jackson.module.kotlin.KotlinModule.Builder().build(); } }
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\support\converter\JacksonUtils.java
1
请完成以下Java代码
public String getCurrencyUnit() { return currencyUnit; } public BigDecimal getPrice() { return price; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((currencyUnit == null) ? 0 : currencyUnit.hashCode()); result = prime * result + ((price == null) ? 0 : price.hashCode()); return result;
} public void setCurrencyUnit(String currencyUnit) { this.currencyUnit = currencyUnit; } public void setPrice(BigDecimal price) { this.price = price; } @Override public String toString() { return "JpaProduct [currencyUnit=" + currencyUnit + ", price=" + price + "]"; } }
repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\ddd\order\jpa\JpaProduct.java
1
请在Spring Boot框架中完成以下Java代码
public @ResponseBody User getUserById(@PathVariable(value = "id") Long id) { User user = new User(); user.setId(id); user.setName("mrbird"); user.setAge(25); return user; } @ApiOperation(value = "获取用户列表", notes = "获取用户列表") @GetMapping("/list") public @ResponseBody List<User> getUserList() { List<User> list = new ArrayList<>(); User user1 = new User(); user1.setId(1l); user1.setName("mrbird"); user1.setAge(25); list.add(user1); User user2 = new User(); user2.setId(2l); user2.setName("scott"); user2.setAge(29); list.add(user2); return list; } @ApiOperation(value = "新增用户", notes = "根据用户实体创建用户") @ApiImplicitParam(name = "user", value = "用户实体", required = true, dataType = "User") @PostMapping("/add") public @ResponseBody Map<String, Object> addUser(@RequestBody User user) { Map<String, Object> map = new HashMap<>(); map.put("result", "success"); return map; } @ApiOperation(value = "删除用户", notes = "根据用户id删除用户") @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Long", paramType = "path")
@DeleteMapping("/{id}") public @ResponseBody Map<String, Object> deleteUser(@PathVariable(value = "id") Long id) { Map<String, Object> map = new HashMap<>(); map.put("result", "success"); return map; } @ApiOperation(value = "更新用户", notes = "根据用户id更新用户") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Long", paramType = "path"), @ApiImplicitParam(name = "user", value = "用户实体", required = true, dataType = "User") }) @PutMapping("/{id}") public @ResponseBody Map<String, Object> updateUser(@PathVariable(value = "id") Long id, @RequestBody User user) { Map<String, Object> map = new HashMap<>(); map.put("result", "success"); return map; } }
repos\SpringAll-master\20.Spring-Boot-Swagger2\src\main\java\com\example\demo\controller\UserController.java
2
请完成以下Java代码
public Receive createReceive() { return receiveBuilder() .match(ReadLines.class, r -> { log.info("Received ReadLines message from " + getSender()); String[] lines = text.split("\n"); List<CompletableFuture> futures = new ArrayList<>(); for (int i = 0; i < lines.length; i++) { String line = lines[i]; ActorRef wordCounterActorRef = getContext().actorOf(Props.create(WordCounterActor.class), "word-counter-" + i); CompletableFuture<Object> future = ask(wordCounterActorRef, new WordCounterActor.CountWords(line), 1000).toCompletableFuture(); futures.add(future);
} Integer totalNumberOfWords = futures.stream() .map(CompletableFuture::join) .mapToInt(n -> (Integer) n) .sum(); ActorRef printerActorRef = getContext().actorOf(Props.create(PrinterActor.class), "Printer-Actor"); printerActorRef.forward(new PrinterActor.PrintFinalResult(totalNumberOfWords), getContext()); // printerActorRef.tell(new PrinterActor.PrintFinalResult(totalNumberOfWords), getSelf()); }) .build(); } }
repos\tutorials-master\akka-modules\akka-actors\src\main\java\com\baeldung\akkaactors\ReadingActor.java
1
请完成以下Java代码
public static int getFrequency(String word) { CoreDictionary.Attribute attribute = getAttribute(word); if (attribute == null) return 0; return attribute.totalFrequency; } /** * 设置某个单词的属性 * @param word * @param attribute * @return */ public static boolean setAttribute(String word, CoreDictionary.Attribute attribute) { if (attribute == null) return false; if (CoreDictionary.trie.set(word, attribute)) return true; if (CustomDictionary.DEFAULT.dat.set(word, attribute)) return true; if (CustomDictionary.DEFAULT.trie == null) { CustomDictionary.add(word); } CustomDictionary.DEFAULT.trie.put(word, attribute); return true; } /** * 设置某个单词的属性 * @param word * @param natures * @return */ public static boolean setAttribute(String word, Nature... natures) { if (natures == null) return false; CoreDictionary.Attribute attribute = new CoreDictionary.Attribute(natures, new int[natures.length]); Arrays.fill(attribute.frequency, 1); return setAttribute(word, attribute); } /** * 设置某个单词的属性 * @param word * @param natures * @return */ public static boolean setAttribute(String word, String... natures) { if (natures == null) return false; Nature[] natureArray = new Nature[natures.length]; for (int i = 0; i < natureArray.length; i++) { natureArray[i] = Nature.create(natures[i]); } return setAttribute(word, natureArray); } /** * 设置某个单词的属性
* @param word * @param natureWithFrequency * @return */ public static boolean setAttribute(String word, String natureWithFrequency) { CoreDictionary.Attribute attribute = CoreDictionary.Attribute.create(natureWithFrequency); return setAttribute(word, attribute); } /** * 将字符串词性转为Enum词性 * @param name 词性名称 * @param customNatureCollector 一个收集集合 * @return 转换结果 */ public static Nature convertStringToNature(String name, LinkedHashSet<Nature> customNatureCollector) { Nature nature = Nature.fromString(name); if (nature == null) { nature = Nature.create(name); if (customNatureCollector != null) customNatureCollector.add(nature); } return nature; } /** * 将字符串词性转为Enum词性 * @param name 词性名称 * @return 转换结果 */ public static Nature convertStringToNature(String name) { return convertStringToNature(name, null); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\utility\LexiconUtility.java
1
请完成以下Java代码
public class PalindromIterator implements Iterator<String> { private final List<String> list; private int currentIndex; public PalindromIterator(List<String> list) { this.list = list; this.currentIndex = 0; } @Override public boolean hasNext() { while (currentIndex < list.size()) { String currString = list.get(currentIndex); if (isPalindrome(currString)) { return true; } currentIndex++; } return false;
} @Override public String next() { if (!hasNext()) { throw new NoSuchElementException(); } return list.get(currentIndex++); } private boolean isPalindrome(String input) { for (int i = 0; i < input.length() / 2; i++) { if (input.charAt(i) != input.charAt(input.length() - i - 1)) { return false; } } return true; } }
repos\tutorials-master\core-java-modules\core-java-collections-5\src\main\java\com\baeldung\customiterators\PalindromIterator.java
1
请在Spring Boot框架中完成以下Java代码
private static class SequenceChangeLog { private boolean newSequence = false; private String sequenceName; private String sequenceNameNew; private int currentNext; private int currentNextNew; private int currentNextSys; private int currentNextSysNew; private boolean newValuesSet = false; public SequenceChangeLog(final I_AD_Sequence sequence) { Check.assumeNotNull(sequence, "sequence not null"); this.newSequence = sequence.getAD_Sequence_ID() <= 0; this.sequenceName = sequence.getName(); this.currentNext = sequence.getCurrentNext(); this.currentNextSys = sequence.getCurrentNextSys(); } public void setNewValues(final I_AD_Sequence sequence) { Check.assumeNotNull(sequence, "sequence not null"); this.sequenceNameNew = sequence.getName(); this.currentNextNew = sequence.getCurrentNext(); this.currentNextSysNew = sequence.getCurrentNextSys(); this.newValuesSet = true; } public boolean isChange() { if (!newValuesSet) { return false; } if (newSequence) { return true; } if (!Objects.equals(this.sequenceName, this.sequenceNameNew)) { return true; } if (currentNext != currentNextNew) { return true; } if (currentNextSys != currentNextSysNew) { return true; } return false; } @Override public String toString() { final StringBuilder changes = new StringBuilder(); if (newValuesSet && !Objects.equals(sequenceName, sequenceNameNew)) { if (changes.length() > 0) { changes.append(", ");
} changes.append("Name(new)=").append(sequenceNameNew); } if (newValuesSet && currentNext != currentNextNew) { if (changes.length() > 0) { changes.append(", "); } changes.append("CurrentNext=").append(currentNext).append("->").append(currentNextNew); } if (newValuesSet && currentNextSys != currentNextSysNew) { if (changes.length() > 0) { changes.append(", "); } changes.append("CurrentNextSys=").append(currentNextSys).append("->").append(currentNextSysNew); } final StringBuilder sb = new StringBuilder(); sb.append("Sequence ").append(sequenceName); if (newSequence) { sb.append(" (new)"); } sb.append(": "); if (changes.length() > 0) { sb.append(changes); } else if (newSequence) { sb.append("just created"); } else { sb.append("no changes"); } return sb.toString(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\service\impl\TableSequenceChecker.java
2
请完成以下Java代码
public Mono<Payload> requestResponse(Payload payload) { try { return Mono.just(payload); // reflect the payload back to the sender } catch (Exception x) { return Mono.error(x); } } /** * Handle Fire-and-Forget messages * * @param payload Message payload * @return nothing */ @Override public Mono<Void> fireAndForget(Payload payload) { try { dataPublisher.publish(payload); // forward the payload return Mono.empty(); } catch (Exception x) { return Mono.error(x); } } /** * Handle Request/Stream messages. Each request returns a new stream. * * @param payload Payload that can be used to determine which stream to return * @return Flux stream containing simulated measurement data */ @Override public Flux<Payload> requestStream(Payload payload) { String streamName = payload.getDataUtf8();
if (DATA_STREAM_NAME.equals(streamName)) { return Flux.from(dataPublisher); } return Flux.error(new IllegalArgumentException(streamName)); } /** * Handle request for bidirectional channel * * @param payloads Stream of payloads delivered from the client * @return */ @Override public Flux<Payload> requestChannel(Publisher<Payload> payloads) { Flux.from(payloads) .subscribe(gameController::processPayload); Flux<Payload> channel = Flux.from(gameController); return channel; } } }
repos\tutorials-master\spring-reactive-modules\rsocket\src\main\java\com\baeldung\rsocket\Server.java
1
请完成以下Java代码
public class SentryExport implements CmmnXmlConstants { public static void writeSentry(CmmnModel model, Sentry sentry, XMLStreamWriter xtw) throws Exception { // start sentry element xtw.writeStartElement(ELEMENT_SENTRY); xtw.writeAttribute(ATTRIBUTE_ID, sentry.getId()); if (StringUtils.isNotEmpty(sentry.getName())) { xtw.writeAttribute(ATTRIBUTE_NAME, sentry.getName()); } if (StringUtils.isNotEmpty(sentry.getTriggerMode()) && !Sentry.TRIGGER_MODE_DEFAULT.equals(sentry.getTriggerMode())) { // default is not exported. If missing, default is assumed xtw.writeAttribute(FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_TRIGGER_MODE, sentry.getTriggerMode()); } if (StringUtils.isNotEmpty(sentry.getDocumentation())) { xtw.writeStartElement(ELEMENT_DOCUMENTATION); xtw.writeCharacters(sentry.getDocumentation()); xtw.writeEndElement(); } boolean didWriteExtensionElement = CmmnXmlUtil.writeExtensionElements(sentry, false, model.getNamespaces(), xtw); if (didWriteExtensionElement) { xtw.writeEndElement(); } for (SentryOnPart sentryOnPart : sentry.getOnParts()) { // start sentry on part element xtw.writeStartElement(ELEMENT_PLAN_ITEM_ON_PART); xtw.writeAttribute(ATTRIBUTE_ID, sentryOnPart.getId());
xtw.writeAttribute(ATTRIBUTE_SOURCE_REF, sentryOnPart.getSourceRef()); // start standard event element xtw.writeStartElement(ELEMENT_STANDARD_EVENT); xtw.writeCharacters(sentryOnPart.getStandardEvent()); xtw.writeEndElement(); // end sentry on part element xtw.writeEndElement(); } // If part SentryIfPart sentryIfPart = sentry.getSentryIfPart(); if (sentryIfPart != null) { xtw.writeStartElement(ELEMENT_IF_PART); if (StringUtils.isNotEmpty(sentryIfPart.getId())) { xtw.writeAttribute(ATTRIBUTE_ID, sentryIfPart.getId()); } xtw.writeStartElement(ELEMENT_CONDITION); xtw.writeCData(sentryIfPart.getCondition()); xtw.writeEndElement(); xtw.writeEndElement(); } // end plan item element xtw.writeEndElement(); } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\export\SentryExport.java
1
请完成以下Java代码
/* package */class ReceiptScheduleProductStorage extends AbstractProductStorage { private final transient IReceiptScheduleBL receiptScheduleBL = Services.get(IReceiptScheduleBL.class); private final I_M_ReceiptSchedule schedule; private final Capacity capacityTotal; private boolean staled = false; public ReceiptScheduleProductStorage(final de.metas.inoutcandidate.model.I_M_ReceiptSchedule schedule, final boolean enforceCapacity) { super(); this.schedule = InterfaceWrapperHelper.create(schedule, I_M_ReceiptSchedule.class); final boolean allowNegativeCapacity = !enforceCapacity; // true because we want to over/under allocate on this receipt schedule capacityTotal = Capacity.createCapacity( receiptScheduleBL.getQtyOrdered(schedule), // qty ProductId.ofRepoId(schedule.getM_Product_ID()), // product Services.get(IUOMDAO.class).getById(schedule.getC_UOM_ID()), // uom allowNegativeCapacity ); } @Override protected BigDecimal retrieveQtyInitial() { checkStaled(); // // Capacity is the total Qty required on receipt schedule final BigDecimal qtyCapacity = getTotalCapacity().toBigDecimal(); final BigDecimal qtyMoved = receiptScheduleBL.getQtyMoved(schedule); // final BigDecimal qtyAllocatedOnHUs = Services.get(IHUReceiptScheduleDAO.class).getQtyAllocatedOnHUs(schedule); final BigDecimal qtyAllocatedOnHUs = BigDecimal.ZERO; final BigDecimal qtyToMove = qtyCapacity.subtract(qtyMoved).subtract(qtyAllocatedOnHUs);
// NOTE: Qty to Move is the actual storage qty // because this is an inbound transaction // and storage qty means qty which is available to take out return qtyToMove; } @Override protected Capacity retrieveTotalCapacity() { return capacityTotal; } @Override protected void beforeMarkingStalled() { staled = true; } private final void checkStaled() { if (!staled) { return; } InterfaceWrapperHelper.refresh(schedule); staled = false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\receiptschedule\impl\ReceiptScheduleProductStorage.java
1
请完成以下Java代码
public void setIsEMUMember (boolean IsEMUMember) { set_Value (COLUMNNAME_IsEMUMember, Boolean.valueOf(IsEMUMember)); } /** Get EMU Member. @return This currency is member if the European Monetary Union */ @Override public boolean isEMUMember () { Object oo = get_Value(COLUMNNAME_IsEMUMember); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set The Euro Currency. @param IsEuro This currency is the Euro */ @Override public void setIsEuro (boolean IsEuro) { set_Value (COLUMNNAME_IsEuro, Boolean.valueOf(IsEuro)); } /** Get The Euro Currency. @return This currency is the Euro */ @Override public boolean isEuro () { Object oo = get_Value(COLUMNNAME_IsEuro); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set ISO Währungscode. @param ISO_Code Three letter ISO 4217 Code of the Currency */ @Override public void setISO_Code (java.lang.String ISO_Code) { set_Value (COLUMNNAME_ISO_Code, ISO_Code);
} /** Get ISO Währungscode. @return Three letter ISO 4217 Code of the Currency */ @Override public java.lang.String getISO_Code () { return (java.lang.String)get_Value(COLUMNNAME_ISO_Code); } /** Set Round Off Factor. @param RoundOffFactor Used to Round Off Payment Amount */ @Override public void setRoundOffFactor (java.math.BigDecimal RoundOffFactor) { set_Value (COLUMNNAME_RoundOffFactor, RoundOffFactor); } /** Get Round Off Factor. @return Used to Round Off Payment Amount */ @Override public java.math.BigDecimal getRoundOffFactor () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RoundOffFactor); if (bd == null) return Env.ZERO; return bd; } /** Set Standardgenauigkeit. @param StdPrecision Rule for rounding calculated amounts */ @Override public void setStdPrecision (int StdPrecision) { set_Value (COLUMNNAME_StdPrecision, Integer.valueOf(StdPrecision)); } /** Get Standardgenauigkeit. @return Rule for rounding calculated amounts */ @Override public int getStdPrecision () { Integer ii = (Integer)get_Value(COLUMNNAME_StdPrecision); 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_C_Currency.java
1
请在Spring Boot框架中完成以下Java代码
static class SecurityContextHolderAwareRequestFilterBeanFactory extends GrantedAuthorityDefaultsParserUtils.AbstractGrantedAuthorityDefaultsBeanFactory { private SecurityContextHolderAwareRequestFilter filter = new SecurityContextHolderAwareRequestFilter(); private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder .getContextHolderStrategy(); @Override public SecurityContextHolderAwareRequestFilter getBean() { this.filter.setSecurityContextHolderStrategy(this.securityContextHolderStrategy); this.filter.setRolePrefix(this.rolePrefix); return this.filter; } void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { this.securityContextHolderStrategy = securityContextHolderStrategy; } } 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\http\HttpConfigurationBuilder.java
2
请完成以下Java代码
public class I18nUtil { private static Logger logger = LoggerFactory.getLogger(I18nUtil.class); private static Properties prop = null; public static Properties loadI18nProp(){ if (prop != null) { return prop; } try { // build i18n prop String i18n = XxlJobAdminConfig.getAdminConfig().getI18n(); String i18nFile = MessageFormat.format("i18n/message_{0}.properties", i18n); // load prop Resource resource = new ClassPathResource(i18nFile); EncodedResource encodedResource = new EncodedResource(resource,"UTF-8"); prop = PropertiesLoaderUtils.loadProperties(encodedResource); } catch (IOException e) { logger.error(e.getMessage(), e); } return prop; } /** * get val of i18n key * * @param key * @return */ public static String getString(String key) { return loadI18nProp().getProperty(key); }
/** * get mult val of i18n mult key, as json * * @param keys * @return */ public static String getMultString(String... keys) { Map<String, String> map = new HashMap<String, String>(); Properties prop = loadI18nProp(); if (keys!=null && keys.length>0) { for (String key: keys) { map.put(key, prop.getProperty(key)); } } else { for (String key: prop.stringPropertyNames()) { map.put(key, prop.getProperty(key)); } } String json = JacksonUtil.writeValueAsString(map); return json; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\util\I18nUtil.java
1
请在Spring Boot框架中完成以下Java代码
public Language getReportLanguageEffective() { final Object languageObj = get(PARAM_REPORT_LANGUAGE); Language currLang = null; if (languageObj instanceof String) { currLang = Language.getLanguage((String)languageObj); } else if (languageObj instanceof Language) { currLang = (Language)languageObj; } if (currLang == null) { currLang = Env.getLanguage(Env.getCtx()); } return currLang; } public void putLocale(@Nullable final Locale locale) { put(JRParameter.REPORT_LOCALE, locale); } @Nullable public Locale getLocale() { return (Locale)get(JRParameter.REPORT_LOCALE); } public void putRecordId(final int recordId) { put(PARAM_RECORD_ID, recordId);
} public void putTableId(final int tableId) { put(PARAM_AD_Table_ID, tableId); } public void putBarcodeURL(final String barcodeURL) { put(PARAM_BARCODE_URL, barcodeURL); } @Nullable public String getBarcodeUrl() { final Object barcodeUrl = get(PARAM_BARCODE_URL); return barcodeUrl != null ? barcodeUrl.toString() : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\JRParametersCollector.java
2
请在Spring Boot框架中完成以下Java代码
public class GatewayDiscoveryClientAutoConfiguration { public static List<PredicateDefinition> initPredicates() { ArrayList<PredicateDefinition> definitions = new ArrayList<>(); // TODO: add a predicate that matches the url at /serviceId? // add a predicate that matches the url at /serviceId/** PredicateDefinition predicate = new PredicateDefinition(); predicate.setName(normalizeRoutePredicateName(PathRoutePredicateFactory.class)); predicate.addArg(PATTERN_KEY, "'/'+serviceId+'/**'"); definitions.add(predicate); return definitions; } public static List<FilterDefinition> initFilters() { ArrayList<FilterDefinition> definitions = new ArrayList<>(); // add a filter that removes /serviceId by default FilterDefinition filter = new FilterDefinition(); filter.setName(normalizeFilterFactoryName(RewritePathGatewayFilterFactory.class)); String regex = "'/' + serviceId + '/?(?<remaining>.*)'"; String replacement = "'/${remaining}'"; filter.addArg(REGEXP_KEY, regex); filter.addArg(REPLACEMENT_KEY, replacement); definitions.add(filter);
return definitions; } @Bean public DiscoveryLocatorProperties discoveryLocatorProperties() { DiscoveryLocatorProperties properties = new DiscoveryLocatorProperties(); properties.setPredicates(initPredicates()); properties.setFilters(initFilters()); return properties; } @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(value = "spring.cloud.discovery.reactive.enabled", matchIfMissing = true) public static class ReactiveDiscoveryClientRouteDefinitionLocatorConfiguration { @Bean @ConditionalOnProperty(name = "spring.cloud.gateway.server.webflux.discovery.locator.enabled") public DiscoveryClientRouteDefinitionLocator discoveryClientRouteDefinitionLocator( ReactiveDiscoveryClient discoveryClient, DiscoveryLocatorProperties properties) { return new DiscoveryClientRouteDefinitionLocator(discoveryClient, properties); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\discovery\GatewayDiscoveryClientAutoConfiguration.java
2
请完成以下Java代码
private ImmutableMap<HuId, ImmutableSet<OrderId>> getHUId2OpenPickingOrderIds() { final ImmutableSet<HuId> allHuIds = huEditorRows.values() .stream() .map(HUEditorRow::getAllHuIds) .flatMap(Set::stream) .collect(ImmutableSet.toImmutableSet()); return pickingCandidateService.getOpenPickingOrderIdsByHuId(allHuIds); } @NonNull private static ImmutableMap<HuId, Boolean> getHUId2ProcessedFlag(@NonNull final ImmutableList<PickingCandidate> pickingCandidates) { final HashMap<HuId, Boolean> huId2ProcessedFlag = new HashMap<>(); pickingCandidates.stream() .filter(pickingCandidate -> pickingCandidate.getPickingSlotId() != null) .filter(pickingCandidate -> !pickingCandidate.isRejectedToPick()) .filter(pickingCandidate -> pickingCandidate.getPickFrom().getHuId() != null) .forEach(pickingCandidate -> huId2ProcessedFlag.merge(pickingCandidate.getPickFrom().getHuId(), PickingCandidateHURowsProvider.isPickingCandidateProcessed(pickingCandidate), (oldValue, newValue) -> oldValue || newValue)); return ImmutableMap.copyOf(huId2ProcessedFlag); } private static boolean isPickingCandidateProcessed(@NonNull final PickingCandidate pc)
{ final PickingCandidateStatus status = pc.getProcessingStatus(); if (PickingCandidateStatus.Closed.equals(status)) { return true; } else if (PickingCandidateStatus.Processed.equals(status)) { return true; } else if (PickingCandidateStatus.Draft.equals(status)) { return false; } else { throw new AdempiereException("Unexpected M_Picking_Candidate.Status=" + status).setParameter("pc", pc); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingCandidateHURowsProvider.java
1
请完成以下Java代码
public class BPMNSignalImpl extends BPMNElementImpl implements BPMNSignal { private SignalPayload signalPayload; public BPMNSignalImpl() {} public BPMNSignalImpl(String elementId) { this.setElementId(elementId); } public SignalPayload getSignalPayload() { return signalPayload; } public void setSignalPayload(SignalPayload signalPayload) { this.signalPayload = signalPayload; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BPMNSignalImpl that = (BPMNSignalImpl) o; return ( Objects.equals(getElementId(), that.getElementId()) && Objects.equals(signalPayload, that.getSignalPayload())
); } @Override public int hashCode() { return Objects.hash( getElementId(), signalPayload != null ? signalPayload.getId() : null, signalPayload != null ? signalPayload.getName() : null ); } @Override public String toString() { return ( "BPMNActivityImpl{" + ", elementId='" + getElementId() + '\'' + ", signalPayload='" + (signalPayload != null ? signalPayload.toString() : null) + '\'' + '}' ); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\BPMNSignalImpl.java
1
请完成以下Java代码
private ReactiveSession session() { return this.driver.session(ReactiveSession.class, Neo4jHealthIndicator.DEFAULT_SESSION_CONFIG); } private Mono<Neo4jHealthDetails> healthDetails(ReactiveSession session) { return Mono.from(session.run(Neo4jHealthIndicator.CYPHER)).flatMap(this::healthDetails); } private Mono<? extends Neo4jHealthDetails> healthDetails(ReactiveResult result) { Flux<Record> records = Flux.from(result.records()); Mono<ResultSummary> summary = Mono.from(result.consume()); Neo4jHealthDetailsBuilder builder = new Neo4jHealthDetailsBuilder(); return records.single().doOnNext(builder::record).then(summary).map(builder::build); } /** * Builder used to create a {@link Neo4jHealthDetails} from a {@link Record} and a * {@link ResultSummary}. */ private static final class Neo4jHealthDetailsBuilder {
private @Nullable Record record; void record(Record record) { this.record = record; } private Neo4jHealthDetails build(ResultSummary summary) { Assert.state(this.record != null, "'record' must not be null"); return new Neo4jHealthDetails(this.record, summary); } } }
repos\spring-boot-4.0.1\module\spring-boot-neo4j\src\main\java\org\springframework\boot\neo4j\health\Neo4jReactiveHealthIndicator.java
1
请在Spring Boot框架中完成以下Java代码
public abstract class HealthProperties { @NestedConfigurationProperty private final Status status = new Status(); /** * When to show components. If not specified the 'show-details' setting will be used. */ private @Nullable Show showComponents; /** * Roles used to determine whether a user is authorized to be shown details. When * empty, all authenticated users are authorized. */ private Set<String> roles = new HashSet<>(); public Status getStatus() { return this.status; } public @Nullable Show getShowComponents() { return this.showComponents; } public void setShowComponents(@Nullable Show showComponents) { this.showComponents = showComponents; } public abstract @Nullable Show getShowDetails(); public Set<String> getRoles() { return this.roles; } public void setRoles(Set<String> roles) { this.roles = roles; } /** * Status properties for the group. */ public static class Status { /**
* List of health statuses in order of severity. */ private List<String> order = new ArrayList<>(); /** * Mapping of health statuses to HTTP status codes. By default, registered health * statuses map to sensible defaults (for example, UP maps to 200). */ private final Map<String, Integer> httpMapping = new HashMap<>(); public List<String> getOrder() { return this.order; } public void setOrder(List<String> statusOrder) { if (!CollectionUtils.isEmpty(statusOrder)) { this.order = statusOrder; } } public Map<String, Integer> getHttpMapping() { return this.httpMapping; } } }
repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\autoconfigure\actuate\endpoint\HealthProperties.java
2
请完成以下Java代码
public void setPP_Cost_Collector_ImportAudit_ID (int PP_Cost_Collector_ImportAudit_ID) { if (PP_Cost_Collector_ImportAudit_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Cost_Collector_ImportAudit_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Cost_Collector_ImportAudit_ID, Integer.valueOf(PP_Cost_Collector_ImportAudit_ID)); } @Override public int getPP_Cost_Collector_ImportAudit_ID() { return get_ValueAsInt(COLUMNNAME_PP_Cost_Collector_ImportAudit_ID); } @Override public void setPP_Cost_Collector_ImportAuditItem_ID (int PP_Cost_Collector_ImportAuditItem_ID) { if (PP_Cost_Collector_ImportAuditItem_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Cost_Collector_ImportAuditItem_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Cost_Collector_ImportAuditItem_ID, Integer.valueOf(PP_Cost_Collector_ImportAuditItem_ID)); } @Override public int getPP_Cost_Collector_ImportAuditItem_ID() { return get_ValueAsInt(COLUMNNAME_PP_Cost_Collector_ImportAuditItem_ID); } @Override public org.eevolution.model.I_PP_Order getPP_Order() { return get_ValueAsPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class); } @Override
public void setPP_Order(org.eevolution.model.I_PP_Order PP_Order) { set_ValueFromPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class, PP_Order); } @Override public void setPP_Order_ID (int PP_Order_ID) { if (PP_Order_ID < 1) set_Value (COLUMNNAME_PP_Order_ID, null); else set_Value (COLUMNNAME_PP_Order_ID, Integer.valueOf(PP_Order_ID)); } @Override public int getPP_Order_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Cost_Collector_ImportAuditItem.java
1
请完成以下Java代码
public static void saveWarning(final Logger logger, final String AD_Message, final String message) { final ValueNamePair lastWarning = ValueNamePair.of(AD_Message, message); getLastErrorsInstance().setLastWarning(lastWarning); // print it if (true) { logger.warn(AD_Message + " - " + message); } } // saveWarning /** * Get Warning from Stack * * @return AD_Message as Value and Message as String */ public static ValueNamePair retrieveWarning() { final ValueNamePair lastWarning = getLastErrorsInstance().getLastWarningAndReset(); return lastWarning; } // retrieveWarning /** * Reset Saved Messages/Errors/Info */ public static void resetLast() { getLastErrorsInstance().reset(); } private final static LastErrorsInstance getLastErrorsInstance() { final Properties ctx = Env.getCtx(); return Env.get(ctx, LASTERRORINSTANCE_CTXKEY, LastErrorsInstance::new); } /** * Holds last error/exception, warning and info. * * @author tsa */ @ThreadSafe @SuppressWarnings("serial") private static class LastErrorsInstance implements Serializable { private ValueNamePair lastError; private Throwable lastException; private ValueNamePair lastWarning; private LastErrorsInstance() { super(); } @Override public synchronized String toString() { final StringBuilder sb = new StringBuilder(getClass().getSimpleName()).append("["); sb.append("lastError=").append(lastError); sb.append(", lastException=").append(lastException); sb.append(", lastWarning=").append(lastWarning); sb.append("]"); return sb.toString(); } public synchronized ValueNamePair getLastErrorAndReset() { final ValueNamePair lastErrorToReturn = lastError; lastError = null; return lastErrorToReturn; } public synchronized void setLastError(final ValueNamePair lastError) { this.lastError = lastError; }
public synchronized Throwable getLastExceptionAndReset() { final Throwable lastExceptionAndClear = lastException; lastException = null; return lastExceptionAndClear; } public synchronized void setLastException(final Throwable lastException) { this.lastException = lastException; } public synchronized ValueNamePair getLastWarningAndReset() { final ValueNamePair lastWarningToReturn = lastWarning; lastWarning = null; return lastWarningToReturn; } public synchronized void setLastWarning(final ValueNamePair lastWarning) { this.lastWarning = lastWarning; } public synchronized void reset() { lastError = null; lastException = null; lastWarning = null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\logging\MetasfreshLastError.java
1
请完成以下Java代码
public String getAmtInWords (String amount) throws Exception { if (amount == null) return amount; Language lang = Env.getLanguage(Env.getCtx()); // StringBuffer sb = new StringBuffer (); int pos = 0; if(lang.isDecimalPoint()) pos = amount.lastIndexOf ('.'); // Old else pos = amount.lastIndexOf (','); int pos2 = 0; if(lang.isDecimalPoint()) pos2 = amount.lastIndexOf (','); // Old else pos2 = amount.lastIndexOf ('.'); if (pos2 > pos) pos = pos2; String oldamt = amount; if(lang.isDecimalPoint()) amount = amount.replaceAll (",", ""); // Old else amount = amount.replaceAll( "\\.",""); int newpos = 0; if(lang.isDecimalPoint()) newpos = amount.lastIndexOf ('.'); // Old else newpos = amount.lastIndexOf (',');
long pesos = Long.parseLong(amount.substring (0, newpos)); sb.append (convert (pesos)); for (int i = 0; i < oldamt.length (); i++) { if (pos == i) // we are done { String cents = oldamt.substring (i + 1); sb.append (' ') .append (cents) .append ("/100"); // .append ("/100 PESOS"); break; } } return sb.toString (); } // getAmtInWords public static void main(String[] args) throws Exception { AmtInWords_ES aiw = new AmtInWords_ES(); // for (int i=0; i<=2147000000; i++) // System.out.println(aiw.getAmtInWords(i+",00")); System.out.println(aiw.getAmtInWords("9223372036854775807.99")); } } // AmtInWords_ES
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\AmtInWords_ES.java
1
请在Spring Boot框架中完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (cInvoiceID == null ? 0 : cInvoiceID.hashCode()); result = prime * result + (isoCode == null ? 0 : isoCode.hashCode()); result = prime * result + (netDays == null ? 0 : netDays.hashCode()); result = prime * result + (netdate == null ? 0 : netdate.hashCode()); result = prime * result + (singlevat == null ? 0 : singlevat.hashCode()); result = prime * result + (taxfree == null ? 0 : taxfree.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Cctop120V other = (Cctop120V)obj; if (cInvoiceID == null) { if (other.cInvoiceID != null) { return false; } } else if (!cInvoiceID.equals(other.cInvoiceID)) { return false; } if (isoCode == null) { if (other.isoCode != null) { return false; } } else if (!isoCode.equals(other.isoCode)) { return false; } if (netDays == null) { if (other.netDays != null) { return false; } } else if (!netDays.equals(other.netDays)) { return false; }
if (netdate == null) { if (other.netdate != null) { return false; } } else if (!netdate.equals(other.netdate)) { return false; } if (singlevat == null) { if (other.singlevat != null) { return false; } } else if (!singlevat.equals(other.singlevat)) { return false; } if (taxfree == null) { if (other.taxfree != null) { return false; } } else if (!taxfree.equals(other.taxfree)) { return false; } return true; } @Override public String toString() { return "Cctop120V [cInvoiceID=" + cInvoiceID + ", isoCode=" + isoCode + ", netdate=" + netdate + ", netDays=" + netDays + ", singlevat=" + singlevat + ", taxfree=" + taxfree + "]"; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\invoicexport\compudata\Cctop120V.java
2
请完成以下Java代码
public class CompositeDunningAggregator { private final List<IDunningAggregator> dunningAggregators = new ArrayList<IDunningAggregator>(); private final IDunningAggregator defaultDunningAggregator = new DefaultDunningAggregator(); public void addAggregator(IDunningAggregator aggregator) { dunningAggregators.add(aggregator); } public boolean isNewDunningDoc(I_C_Dunning_Candidate candidate) { Result finalResult = null; for (IDunningAggregator agg : dunningAggregators) { final Result result = agg.isNewDunningDoc(candidate); if (result == Result.I_FUCKING_DONT_CARE) { continue; } if (result == null) { finalResult = result; } if (!Util.same(result, finalResult)) { throw new DunningException("Confusing verdict for aggregators: " + dunningAggregators); } } if (finalResult == null) { finalResult = defaultDunningAggregator.isNewDunningDoc(candidate); } return toBoolean(finalResult); } public boolean isNewDunningDocLine(I_C_Dunning_Candidate candidate) { if (dunningAggregators.isEmpty()) { throw new DunningException("No child " + IDunningAggregator.class + " registered"); } Result finalResult = null; for (IDunningAggregator agg : dunningAggregators) { final Result result = agg.isNewDunningDocLine(candidate);
if (result == Result.I_FUCKING_DONT_CARE) { continue; } if (result == null) { finalResult = result; } if (!Util.same(result, finalResult)) { throw new DunningException("Confusing verdict for aggregators: " + dunningAggregators); } } if (finalResult == null) { finalResult = defaultDunningAggregator.isNewDunningDocLine(candidate); } return toBoolean(finalResult); } private static final boolean toBoolean(final Result result) { if (result == Result.YES) { return true; } else if (result == Result.NO) { return false; } else { throw new IllegalArgumentException("Result shall be YES or NO: " + result); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\CompositeDunningAggregator.java
1
请完成以下Java代码
private static void assertValidName(@Nullable final String name) { if (name == null || name.isEmpty()) { throw new AdempiereException("Empty name is not a valid name"); } if (!NAME_PATTERN.matcher(name).matches()) { throw new AdempiereException("Invalid name '" + name + "'. It shall match '" + NAME_PATTERN + "'"); } } @Nullable private static String extractDefaultValue(final ArrayList<String> modifiers) { final String defaultValue; if (!modifiers.isEmpty() && !isModifier(modifiers.get(modifiers.size() - 1))) { defaultValue = modifiers.remove(modifiers.size() - 1); } else { defaultValue = VALUE_NULL; } return defaultValue; } /** * Parse a given name, surrounded by {@value #NAME_Marker} */ @Nullable public static CtxName parseWithMarkers(@Nullable final String contextWithMarkers) { if (contextWithMarkers == null) { return null; } String contextWithoutMarkers = contextWithMarkers.trim(); if (contextWithoutMarkers.startsWith(NAME_Marker)) { contextWithoutMarkers = contextWithoutMarkers.substring(1); } if (contextWithoutMarkers.endsWith(NAME_Marker)) { contextWithoutMarkers = contextWithoutMarkers.substring(0, contextWithoutMarkers.length() - 1); } return parse(contextWithoutMarkers); } /** * @param expression expression with context variables (e.g. sql where clause) * @return true if expression contains given name */ @VisibleForTesting static boolean containsName(@Nullable final String name, @Nullable final String expression)
{ // FIXME: replace it with StringExpression if (name == null || name.isEmpty()) { return false; } if (expression == null || expression.isEmpty()) { return false; } final int idx = expression.indexOf(NAME_Marker + name); if (idx < 0) { return false; } final int idx2 = expression.indexOf(NAME_Marker, idx + 1); if (idx2 < 0) { return false; } final String nameStr = expression.substring(idx + 1, idx2); return name.equals(parse(nameStr).getName()); } /** * @return true if given string is a registered modifier */ private static boolean isModifier(final String modifier) { if (Check.isEmpty(modifier)) { return false; } return MODIFIERS.contains(modifier); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\util\CtxNames.java
1