instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public static Pair<List<Pinyin>, List<Boolean>> convert2Pair(String complexText, boolean removeTone) { List<Pinyin> pinyinList = new LinkedList<Pinyin>(); List<Boolean> booleanList = new LinkedList<Boolean>(); Collection<Token> tokenize = trie.tokenize(complexText); for (Token token : tokenize) { String fragment = token.getFragment(); if (token.isMatch()) { // 是拼音或拼音的一部分,用map转 Pinyin pinyin = convertSingle(fragment); pinyinList.add(pinyin); if (fragment.length() == pinyin.getPinyinWithoutTone().length()) { booleanList.add(true); } else { booleanList.add(false); } } else { List<Pinyin> pinyinListFragment = PinyinDictionary.convertToPinyin(fragment); pinyinList.addAll(pinyinListFragment); for (int i = 0; i < pinyinListFragment.size(); ++i) { booleanList.add(true); } } } makeToneToTheSame(pinyinList); return new Pair<List<Pinyin>, List<Boolean>>(pinyinList, booleanList); } /** * 将单个音节转为拼音 * @param single * @return */ public static Pinyin convertSingle(String single) { Pinyin pinyin = map.get(single); if (pinyin == null) return Pinyin.none5; return pinyin; }
/** * 将拼音的音调统统转为5调或者最大的音调 * @param p * @return */ public static Pinyin convert2Tone5(Pinyin p) { return tone2tone5[p.ordinal()]; } /** * 将所有音调都转为1 * @param pinyinList * @return */ public static List<Pinyin> makeToneToTheSame(List<Pinyin> pinyinList) { ListIterator<Pinyin> listIterator = pinyinList.listIterator(); while (listIterator.hasNext()) { listIterator.set(convert2Tone5(listIterator.next())); } return pinyinList; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\py\String2PinyinConverter.java
1
请完成以下Java代码
public class SamplePoster extends AbstractDefaultPoster { /** * 背景图 */ @PosterBackground(width = 640,height = 990) private BufferedImage backgroundImage; /** * 主图 */ @PosterImageCss(position = {0,0},width = 640,height = 400) private BufferedImage mainImage; /** * 网站站标 */ @PosterImageCss(position = {0,800},width = 640, height = 10) private BufferedImage xuxian; /** * 网站站标 */ @PosterImageCss(position = {10,820},width = 470, height = 130) private BufferedImage siteSlogon; /** * 文章链接二维码 */ @PosterImageCss(position = {520,830},width = 100, height = 100) private BufferedImage postQrcode;
/** * 文章标题 */ @PosterFontCss(position = {20,440}, color = {0,0,0},size = 30,canNewLine={1,600,7}) private String postTitle; /** * 文章日期 */ @PosterFontCss(position = {20,540}, color = {33,33,33},size = 20) private String postDate; /** * 文章简介 */ @PosterFontCss(position = {20,570}, size = 20, color = {0,0,0},canNewLine={1,600,7}) private String posttitleDesc; @Tolerate public SamplePoster() {} }
repos\springboot-demo-master\poster\src\main\java\com\et\poster\service\SamplePoster.java
1
请完成以下Java代码
public void setNumberOfRuns (int NumberOfRuns) { set_Value (COLUMNNAME_NumberOfRuns, Integer.valueOf(NumberOfRuns)); } /** Get Number of runs. @return Frequency of processing Perpetual Inventory */ public int getNumberOfRuns () { Integer ii = (Integer)get_Value(COLUMNNAME_NumberOfRuns); if (ii == null) return 0; return ii.intValue(); } /** 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_M_PerpetualInv.java
1
请完成以下Java代码
protected JobEntity getJob() { return Context .getCommandContext() .getJobManager() .findJobById(jobId); } protected void logException(JobEntity job) { if(exception != null) { job.setExceptionMessage(exception.getMessage()); job.setExceptionStacktrace(getExceptionStacktrace()); } } protected void decrementRetries(JobEntity job) { if (exception == null || shouldDecrementRetriesFor(exception)) { job.setRetries(job.getRetries() - 1); } }
protected String getExceptionStacktrace() { return ExceptionUtil.getExceptionStacktrace(exception); } protected boolean shouldDecrementRetriesFor(Throwable t) { return !(t instanceof OptimisticLockingException); } protected void notifyAcquisition(CommandContext commandContext) { JobExecutor jobExecutor = Context.getProcessEngineConfiguration().getJobExecutor(); MessageAddedNotification messageAddedNotification = new MessageAddedNotification(jobExecutor); TransactionContext transactionContext = commandContext.getTransactionContext(); transactionContext.addTransactionListener(TransactionState.COMMITTED, messageAddedNotification); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\JobRetryCmd.java
1
请在Spring Boot框架中完成以下Java代码
private String appendCharset(MimeType type, String charset) { if (type.getCharset() != null) { return type.toString(); } LinkedHashMap<String, String> parameters = new LinkedHashMap<>(); parameters.put("charset", charset); parameters.putAll(type.getParameters()); return new MimeType(type, parameters).toString(); } } } @Configuration(proxyBeanMethods = false) @ConditionalOnWebApplication(type = Type.REACTIVE) static class ThymeleafWebFluxConfiguration { @Bean @ConditionalOnMissingBean(name = "thymeleafReactiveViewResolver") ThymeleafReactiveViewResolver thymeleafViewResolver(ISpringWebFluxTemplateEngine templateEngine, ThymeleafProperties properties) { ThymeleafReactiveViewResolver resolver = new ThymeleafReactiveViewResolver(); resolver.setTemplateEngine(templateEngine); mapProperties(properties, resolver); mapReactiveProperties(properties.getReactive(), resolver); // This resolver acts as a fallback resolver (e.g. like a // InternalResourceViewResolver) so it needs to have low precedence resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 5); return resolver; } private void mapProperties(ThymeleafProperties properties, ThymeleafReactiveViewResolver resolver) { PropertyMapper map = PropertyMapper.get(); map.from(properties::getEncoding).to(resolver::setDefaultCharset); resolver.setExcludedViewNames(properties.getExcludedViewNames()); resolver.setViewNames(properties.getViewNames()); } private void mapReactiveProperties(Reactive properties, ThymeleafReactiveViewResolver resolver) { PropertyMapper map = PropertyMapper.get(); map.from(properties::getMediaTypes).to(resolver::setSupportedMediaTypes); map.from(properties::getMaxChunkSize) .asInt(DataSize::toBytes) .when((size) -> size > 0) .to(resolver::setResponseMaxChunkSizeBytes); map.from(properties::getFullModeViewNames).to(resolver::setFullModeViewNames); map.from(properties::getChunkedModeViewNames).to(resolver::setChunkedModeViewNames); } } @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(LayoutDialect.class) static class ThymeleafWebLayoutConfiguration { @Bean @ConditionalOnMissingBean LayoutDialect layoutDialect() { return new LayoutDialect(); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(DataAttributeDialect.class) static class DataAttributeDialectConfiguration { @Bean @ConditionalOnMissingBean DataAttributeDialect dialect() { return new DataAttributeDialect(); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ SpringSecurityDialect.class, CsrfToken.class }) static class ThymeleafSecurityDialectConfiguration { @Bean @ConditionalOnMissingBean SpringSecurityDialect securityDialect() { return new SpringSecurityDialect(); } } }
repos\spring-boot-4.0.1\module\spring-boot-thymeleaf\src\main\java\org\springframework\boot\thymeleaf\autoconfigure\ThymeleafAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class TranslationController { /** Window No */ protected int m_WindowNo = Env.WINDOW_None; protected TranslationController() { } protected List<KeyNamePair> getClientList() { final List<KeyNamePair> list = new ArrayList<>(); list.add(new KeyNamePair(-1, "", null/* help */)); Services.get(IClientDAO.class).retrieveAllClients(Env.getCtx()) .stream() .filter(I_AD_Client::isActive) .map(adClient -> KeyNamePair.of(adClient.getAD_Client_ID(), adClient.getName(), adClient.getDescription())) .forEach(list::add); return list; } protected List<ValueNamePair> getLanguageList() { return Services.get(ILanguageDAO.class).retrieveAvailableLanguages().toValueNamePairs(); } protected List<ValueNamePair> getTableList() { final String sql = "SELECT Name, TableName, Description " + " FROM AD_Table " + " WHERE TableName LIKE '%_Trl' AND TableName<>'AD_Column_Trl' " + " ORDER BY Name"; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None); rs = pstmt.executeQuery(); final List<ValueNamePair> list = new ArrayList<>(); list.add(new ValueNamePair("", "", null/* help */));
while (rs.next()) { final ValueNamePair vp = new ValueNamePair( rs.getString("TableName"), rs.getString("Name"), rs.getString("Description")/*help*/); list.add(vp); } return list; } catch (final SQLException e) { throw new DBException(e, sql); } finally { DB.close(rs, pstmt); } } protected void clearStatusBar(final IStatusBar statusBar) { statusBar.setStatusLine(" "); statusBar.setStatusDB(" "); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\i18n\TranslationController.java
2
请完成以下Java代码
public List<I_AD_User_SortPref_Line> retrieveSortPreferenceLines(final I_AD_User user, final String action, final int recordId) { final I_AD_User_SortPref_Hdr hdr = retrieveSortPreferenceHdr(user, action, recordId); return retrieveSortPreferenceLines(hdr); } @Override public List<I_AD_User_SortPref_Line> retrieveConferenceSortPreferenceLines(final Properties ctx, final String action, final int recordId) { final I_AD_User_SortPref_Hdr hdr = retrieveConferenceSortPreferenceHdr(ctx, action, recordId); return retrieveSortPreferenceLines(hdr); } @Override public List<I_AD_User_SortPref_Line_Product> retrieveSortPreferenceLineProducts(final I_AD_User_SortPref_Line sortPreferenceLine) { // // Services final IQueryBL queryBL = Services.get(IQueryBL.class); final Object contextProvider = sortPreferenceLine; final IQueryBuilder<I_AD_User_SortPref_Line_Product> queryBuilder = queryBL.createQueryBuilder(I_AD_User_SortPref_Line_Product.class, contextProvider) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_User_SortPref_Line_Product.COLUMN_AD_User_SortPref_Line_ID, sortPreferenceLine.getAD_User_SortPref_Line_ID()); final IQueryOrderBy orderBy = queryBL.createQueryOrderByBuilder(I_AD_User_SortPref_Line_Product.class) .addColumn(I_AD_User_SortPref_Line_Product.COLUMN_SeqNo) .createQueryOrderBy(); return queryBuilder.create() .setOrderBy(orderBy) .list(I_AD_User_SortPref_Line_Product.class); } @Override public int clearSortPreferenceLines(final I_AD_User_SortPref_Hdr hdr)
{ final IQueryBL queryBL = Services.get(IQueryBL.class); int count = 0; final List<I_AD_User_SortPref_Line> linesToDelete = retrieveSortPreferenceLines(hdr); for (final I_AD_User_SortPref_Line line : linesToDelete) { final int countProductLinesDeleted = queryBL.createQueryBuilder(I_AD_User_SortPref_Line_Product.class, hdr) .addEqualsFilter(I_AD_User_SortPref_Line_Product.COLUMN_AD_User_SortPref_Line_ID, line.getAD_User_SortPref_Line_ID()) .create() .deleteDirectly(); count += countProductLinesDeleted; InterfaceWrapperHelper.delete(line); count++; } logger.info("Deleted {} records in sum", count); return count; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\api\impl\UserSortPrefDAO.java
1
请完成以下Java代码
private Optional<AdArchive> getLastArchive(final I_C_Doc_Outbound_Log log) { return archiveBL.getLastArchive(TableRecordReference.ofReferenced(log)); } private void appendCurrentPdf(final PdfCopy targetPdf, final AdArchive currentLog, final Collection<ArchiveId> printedIds, final AtomicInteger errorCount) { PdfReader pdfReaderToAdd = null; try { pdfReaderToAdd = new PdfReader(currentLog.getArchiveStream()); for (int page = 0; page < pdfReaderToAdd.getNumberOfPages(); ) { targetPdf.addPage(targetPdf.getImportedPage(pdfReaderToAdd, ++page)); } targetPdf.freeReader(pdfReaderToAdd);
} catch (final BadPdfFormatException | IOException e) { errorCount.incrementAndGet(); } finally { if (pdfReaderToAdd != null) { pdfReaderToAdd.close(); } printedIds.add(currentLog.getId()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.webui\src\main\java\de\metas\archive\process\MassConcatenateOutboundPdfs.java
1
请在Spring Boot框架中完成以下Java代码
public BigDecimal getOffsetY() { return offsetY; } /** * Sets the value of the offsetY property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setOffsetY(BigDecimal value) { this.offsetY = value; } /** * Gets the value of the connectionType property. * * @return * possible object is * {@link String } * */ public String getConnectionType() { return connectionType; } /** * Sets the value of the connectionType property. * * @param value * allowed object is * {@link String } * */ public void setConnectionType(String value) { this.connectionType = value;
} /** * Gets the value of the barcodeCapable2D property. * */ public boolean isBarcodeCapable2D() { return barcodeCapable2D; } /** * Sets the value of the barcodeCapable2D property. * */ public void setBarcodeCapable2D(boolean value) { this.barcodeCapable2D = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\Printer.java
2
请完成以下Java代码
public final class SqlViewCustomizerMap { public static SqlViewCustomizerMap ofCollection(final Collection<SqlViewCustomizer> viewCustomizers) { return new SqlViewCustomizerMap(viewCustomizers); } private static final Comparator<SqlViewCustomizer> ORDERED_COMPARATOR = Comparator.comparing(SqlViewCustomizerMap::getOrder); private final ImmutableList<SqlViewCustomizer> viewCustomizers; private ImmutableListMultimap<WindowId, ViewProfile> viewProfilesByWindowId; private final ImmutableMap<WindowId, ImmutableMap<ViewProfileId, SqlViewCustomizer>> map; private SqlViewCustomizerMap(final Collection<SqlViewCustomizer> viewCustomizersCollection) { this.viewCustomizers = viewCustomizersCollection.stream() .sorted(ORDERED_COMPARATOR) .collect(ImmutableList.toImmutableList()); viewProfilesByWindowId = viewCustomizers .stream() .collect(ImmutableListMultimap.toImmutableListMultimap(viewCustomizer -> viewCustomizer.getWindowId(), viewCustomizer -> viewCustomizer.getProfile())); this.map = makeViewCustomizersMap(this.viewCustomizers); } private static ImmutableMap<WindowId, ImmutableMap<ViewProfileId, SqlViewCustomizer>> makeViewCustomizersMap(final ImmutableList<SqlViewCustomizer> viewCustomizers) { final Map<WindowId, ImmutableMap<ViewProfileId, SqlViewCustomizer>> map = viewCustomizers .stream() .sorted(ORDERED_COMPARATOR) .collect(Collectors.groupingBy( SqlViewCustomizer::getWindowId, ImmutableMap.toImmutableMap(viewCustomizer -> viewCustomizer.getProfile().getProfileId(), viewCustomizer -> viewCustomizer))); return ImmutableMap.copyOf(map); } private static int getOrder(@NonNull final SqlViewCustomizer viewCustomizer) { if (viewCustomizer instanceof Ordered) { return ((Ordered)viewCustomizer).getOrder(); } else { return OrderUtils.getOrder(viewCustomizer.getClass(), Ordered.LOWEST_PRECEDENCE); } } public SqlViewCustomizer getOrNull( @NonNull final WindowId windowId, @Nullable final ViewProfileId profileId) { if (ViewProfileId.isNull(profileId)) { return null; }
final ImmutableMap<ViewProfileId, SqlViewCustomizer> viewCustomizersByProfileId = map.get(windowId); if (viewCustomizersByProfileId == null) { return null; } return viewCustomizersByProfileId.get(profileId); } public void forEachWindowIdAndProfileId(@NonNull final BiConsumer<WindowId, ViewProfileId> consumer) { viewCustomizers.forEach(viewCustomizer -> consumer.accept(viewCustomizer.getWindowId(), viewCustomizer.getProfile().getProfileId())); } public ImmutableListMultimap<WindowId, ViewProfile> getViewProfilesIndexedByWindowId() { return viewCustomizers .stream() .collect(ImmutableListMultimap.toImmutableListMultimap(viewCustomizer -> viewCustomizer.getWindowId(), viewCustomizer -> viewCustomizer.getProfile())); } public List<ViewProfile> getViewProfilesByWindowId(WindowId windowId) { return viewProfilesByWindowId.get(windowId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlViewCustomizerMap.java
1
请完成以下Java代码
public void setIsReplicationLookupDefault (final boolean IsReplicationLookupDefault) { set_Value (COLUMNNAME_IsReplicationLookupDefault, IsReplicationLookupDefault); } @Override public boolean isReplicationLookupDefault() { return get_ValueAsBoolean(COLUMNNAME_IsReplicationLookupDefault); } @Override public void setIsShipTo (final boolean IsShipTo) { set_Value (COLUMNNAME_IsShipTo, IsShipTo); } @Override public boolean isShipTo() { return get_ValueAsBoolean(COLUMNNAME_IsShipTo); } @Override public void setIsShipToDefault (final boolean IsShipToDefault) { set_Value (COLUMNNAME_IsShipToDefault, IsShipToDefault); } @Override public boolean isShipToDefault() { return get_ValueAsBoolean(COLUMNNAME_IsShipToDefault); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPhone (final @Nullable java.lang.String Phone) { set_Value (COLUMNNAME_Phone, Phone); } @Override public java.lang.String getPhone() { return get_ValueAsString(COLUMNNAME_Phone); } @Override
public void setPhone2 (final @Nullable java.lang.String Phone2) { set_Value (COLUMNNAME_Phone2, Phone2); } @Override public java.lang.String getPhone2() { return get_ValueAsString(COLUMNNAME_Phone2); } @Override public void setSetup_Place_No (final @Nullable java.lang.String Setup_Place_No) { set_Value (COLUMNNAME_Setup_Place_No, Setup_Place_No); } @Override public java.lang.String getSetup_Place_No() { return get_ValueAsString(COLUMNNAME_Setup_Place_No); } @Override public void setVisitorsAddress (final boolean VisitorsAddress) { set_Value (COLUMNNAME_VisitorsAddress, VisitorsAddress); } @Override public boolean isVisitorsAddress() { return get_ValueAsBoolean(COLUMNNAME_VisitorsAddress); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Location_QuickInput.java
1
请完成以下Java代码
public void stop(Duration timeout) { stop(timeout, Collections.emptyList()); } @Override public void stop(Duration timeout, List<String> arguments) { this.cli.run(new DockerCliCommand.ComposeStop(timeout, arguments)); } @Override public boolean hasDefinedServices() { return !this.cli.run(new DockerCliCommand.ComposeConfig()).services().isEmpty(); } @Override public List<RunningService> getRunningServices() { List<DockerCliComposePsResponse> runningPsResponses = runComposePs().stream().filter(this::isRunning).toList(); if (runningPsResponses.isEmpty()) { return Collections.emptyList(); } DockerComposeFile dockerComposeFile = this.cli.getDockerComposeFile(); List<RunningService> result = new ArrayList<>(); Map<String, DockerCliInspectResponse> inspected = inspect(runningPsResponses); for (DockerCliComposePsResponse psResponse : runningPsResponses) { DockerCliInspectResponse inspectResponse = inspectContainer(psResponse.id(), inspected); Assert.state(inspectResponse != null, () -> "Failed to inspect container '%s'".formatted(psResponse.id())); result.add(new DefaultRunningService(this.hostname, dockerComposeFile, psResponse, inspectResponse)); } return Collections.unmodifiableList(result); } private Map<String, DockerCliInspectResponse> inspect(List<DockerCliComposePsResponse> runningPsResponses) { List<String> ids = runningPsResponses.stream().map(DockerCliComposePsResponse::id).toList();
List<DockerCliInspectResponse> inspectResponses = this.cli.run(new DockerCliCommand.Inspect(ids)); return inspectResponses.stream().collect(Collectors.toMap(DockerCliInspectResponse::id, Function.identity())); } private @Nullable DockerCliInspectResponse inspectContainer(String id, Map<String, DockerCliInspectResponse> inspected) { DockerCliInspectResponse inspect = inspected.get(id); if (inspect != null) { return inspect; } // Docker Compose v2.23.0 returns truncated ids, so we have to do a prefix match for (Entry<String, DockerCliInspectResponse> entry : inspected.entrySet()) { if (entry.getKey().startsWith(id)) { return entry.getValue(); } } return null; } private List<DockerCliComposePsResponse> runComposePs() { return this.cli.run(new DockerCliCommand.ComposePs()); } private boolean isRunning(DockerCliComposePsResponse psResponse) { return !"exited".equals(psResponse.state()); } }
repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\core\DefaultDockerCompose.java
1
请完成以下Java代码
public Authentication convert(HttpServletRequest request) { MultiValueMap<String, String> parameters = OAuth2EndpointUtils.getFormParameters(request); // grant_type (REQUIRED) String grantType = parameters.getFirst(OAuth2ParameterNames.GRANT_TYPE); if (!AuthorizationGrantType.REFRESH_TOKEN.getValue().equals(grantType)) { return null; } Authentication clientPrincipal = SecurityContextHolder.getContext().getAuthentication(); // refresh_token (REQUIRED) String refreshToken = parameters.getFirst(OAuth2ParameterNames.REFRESH_TOKEN); if (!StringUtils.hasText(refreshToken) || parameters.get(OAuth2ParameterNames.REFRESH_TOKEN).size() != 1) { OAuth2EndpointUtils.throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REFRESH_TOKEN, OAuth2EndpointUtils.ACCESS_TOKEN_REQUEST_ERROR_URI); } // scope (OPTIONAL) String scope = parameters.getFirst(OAuth2ParameterNames.SCOPE); if (StringUtils.hasText(scope) && parameters.get(OAuth2ParameterNames.SCOPE).size() != 1) { OAuth2EndpointUtils.throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.SCOPE, OAuth2EndpointUtils.ACCESS_TOKEN_REQUEST_ERROR_URI); } Set<String> requestedScopes = null; if (StringUtils.hasText(scope)) { requestedScopes = new HashSet<>(Arrays.asList(StringUtils.delimitedListToStringArray(scope, " "))); } Map<String, Object> additionalParameters = new HashMap<>();
parameters.forEach((key, value) -> { if (!key.equals(OAuth2ParameterNames.GRANT_TYPE) && !key.equals(OAuth2ParameterNames.REFRESH_TOKEN) && !key.equals(OAuth2ParameterNames.SCOPE)) { additionalParameters.put(key, (value.size() == 1) ? value.get(0) : value.toArray(new String[0])); } }); // Validate DPoP Proof HTTP Header (if available) OAuth2EndpointUtils.validateAndAddDPoPParametersIfAvailable(request, additionalParameters); return new OAuth2RefreshTokenAuthenticationToken(refreshToken, clientPrincipal, requestedScopes, additionalParameters); } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\web\authentication\OAuth2RefreshTokenAuthenticationConverter.java
1
请在Spring Boot框架中完成以下Java代码
public String getCaseDefinitionKey() { return caseDefinitionKey; } public String getCorrelationId() { return correlationId; } public boolean isOnlyTimers() { return onlyTimers; } public boolean isOnlyMessages() { return onlyMessages; } public Date getDuedateHigherThan() { return duedateHigherThan; } public Date getDuedateLowerThan() { return duedateLowerThan; }
public Date getDuedateHigherThanOrEqual() { return duedateHigherThanOrEqual; } public Date getDuedateLowerThanOrEqual() { return duedateLowerThanOrEqual; } public String getLockOwner() { return lockOwner; } public boolean isOnlyLocked() { return onlyLocked; } public boolean isOnlyUnlocked() { return onlyUnlocked; } public boolean isWithoutScopeType() { return withoutScopeType; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\JobQueryImpl.java
2
请在Spring Boot框架中完成以下Java代码
public final class JSONLookupValueValidationInformation { @JsonProperty("title") private final String title; @JsonProperty("question") private final String question; @JsonProperty("answerYes") private final String answerYes; @JsonProperty("answerNo") private final String answerNo; @Builder private JSONLookupValueValidationInformation( @JsonProperty("title") final String title, @JsonProperty("question") final String question, @JsonProperty("answerYes") final String answerYes, @JsonProperty("answerNo") final String answerNo) { this.title = title; this.question = question; this.answerYes = answerYes;
this.answerNo = answerNo; } public static JSONLookupValueValidationInformation ofNullable( @Nullable final ValueNamePairValidationInformation validationInformation, @NonNull final String adLanguage) { if (validationInformation == null) { return null; } final IMsgBL msgBL = Services.get(IMsgBL.class); return JSONLookupValueValidationInformation.builder() .title(msgBL.translate(adLanguage, validationInformation.getTitle().toAD_Message())) .question(msgBL.translate(adLanguage, validationInformation.getQuestion().toAD_Message())) .answerYes(msgBL.translate(adLanguage, validationInformation.getAnswerYes().toAD_Message())) .answerNo(msgBL.translate(adLanguage, validationInformation.getAnswerNo().toAD_Message())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONLookupValueValidationInformation.java
2
请完成以下Java代码
public void setSortNo (final @Nullable BigDecimal SortNo) { set_Value (COLUMNNAME_SortNo, SortNo); } @Override public BigDecimal getSortNo() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SortNo); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSpanX (final int SpanX) { set_Value (COLUMNNAME_SpanX, SpanX); } @Override
public int getSpanX() { return get_ValueAsInt(COLUMNNAME_SpanX); } @Override public void setSpanY (final int SpanY) { set_Value (COLUMNNAME_SpanY, SpanY); } @Override public int getSpanY() { return get_ValueAsInt(COLUMNNAME_SpanY); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Field.java
1
请完成以下Java代码
public int getPMM_Week_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PMM_Week_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override 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 Wochenerster. @param WeekDate Wochenerster */ @Override public void setWeekDate (java.sql.Timestamp WeekDate) { set_ValueNoCheck (COLUMNNAME_WeekDate, WeekDate); } /** Get Wochenerster. @return Wochenerster */ @Override public java.sql.Timestamp getWeekDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_WeekDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_Week.java
1
请完成以下Java代码
public String toString() { //return getDelegate().toString(); return toString(this); } private String toString(PdxInstance pdx) { return toString(pdx, ""); } private String toString(PdxInstance pdx, String indent) { if (Objects.nonNull(pdx)) { StringBuilder buffer = new StringBuilder(OBJECT_BEGIN).append(NEW_LINE); String fieldIndent = indent + INDENT_STRING; buffer.append(fieldIndent).append(formatFieldValue(CLASS_NAME_PROPERTY, pdx.getClassName())); for (String fieldName : nullSafeList(pdx.getFieldNames())) { Object fieldValue = pdx.getField(fieldName); String valueString = toStringObject(fieldValue, fieldIndent); buffer.append(COMMA_NEW_LINE); buffer.append(fieldIndent).append(formatFieldValue(fieldName, valueString)); } buffer.append(NEW_LINE).append(indent).append(OBJECT_END); return buffer.toString(); } else { return null; } } private String toStringArray(Object value, String indent) { Object[] array = (Object[]) value; StringBuilder buffer = new StringBuilder(ARRAY_BEGIN); boolean addComma = false; for (Object element : array) { buffer.append(addComma ? COMMA_SPACE : EMPTY_STRING); buffer.append(toStringObject(element, indent)); addComma = true; } buffer.append(ARRAY_END); return buffer.toString(); } private String toStringObject(Object value, String indent) { return isPdxInstance(value) ? toString((PdxInstance) value, indent)
: isArray(value) ? toStringArray(value, indent) : String.valueOf(value); } private String formatFieldValue(String fieldName, Object fieldValue) { return String.format(FIELD_TYPE_VALUE, fieldName, nullSafeType(fieldValue), fieldValue); } private boolean hasText(String value) { return value != null && !value.trim().isEmpty(); } private boolean isArray(Object value) { return Objects.nonNull(value) && value.getClass().isArray(); } private boolean isPdxInstance(Object value) { return value instanceof PdxInstance; } private <T> List<T> nullSafeList(List<T> list) { return list != null ? list : Collections.emptyList(); } private Class<?> nullSafeType(Object value) { return value != null ? value.getClass() : Object.class; } }
repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\pdx\PdxInstanceWrapper.java
1
请在Spring Boot框架中完成以下Java代码
CompositeHandlerMapping compositeHandlerMapping() { return new CompositeHandlerMapping(); } @Bean(name = DispatcherServlet.HANDLER_ADAPTER_BEAN_NAME) CompositeHandlerAdapter compositeHandlerAdapter(ListableBeanFactory beanFactory) { return new CompositeHandlerAdapter(beanFactory); } @Bean(name = DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME) CompositeHandlerExceptionResolver compositeHandlerExceptionResolver() { return new CompositeHandlerExceptionResolver(); } @Bean @ConditionalOnMissingBean({ RequestContextListener.class, RequestContextFilter.class }) RequestContextFilter requestContextFilter() { return new OrderedRequestContextFilter(); } /** * {@link WebServerFactoryCustomizer} to add an {@link ErrorPage} so that the * {@link ManagementErrorEndpoint} can be used.
*/ static class ManagementErrorPageCustomizer implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>, Ordered { private final WebProperties properties; ManagementErrorPageCustomizer(WebProperties properties) { this.properties = properties; } @Override public void customize(ConfigurableServletWebServerFactory factory) { factory.addErrorPages(new ErrorPage(this.properties.getError().getPath())); } @Override public int getOrder() { return 10; // Run after ManagementWebServerFactoryCustomizer } } }
repos\spring-boot-4.0.1\module\spring-boot-webmvc\src\main\java\org\springframework\boot\webmvc\autoconfigure\actuate\web\WebMvcEndpointChildContextConfiguration.java
2
请完成以下Java代码
protected LinksHandler getLinksHandler() { return new WebFluxLinksHandler(); } /** * Handler for root endpoint providing links. */ class WebFluxLinksHandler implements LinksHandler { @Override @ResponseBody @Reflective public Map<String, Map<String, Link>> links(ServerWebExchange exchange) { String requestUri = UriComponentsBuilder.fromUri(exchange.getRequest().getURI()) .replaceQuery(null) .toUriString(); Map<String, Link> links = WebFluxEndpointHandlerMapping.this.linksResolver.resolveLinks(requestUri); return OperationResponseBody.of(Collections.singletonMap("_links", links)); } @Override public String toString() { return "Actuator root web endpoint";
} } static class WebFluxEndpointHandlerMappingRuntimeHints implements RuntimeHintsRegistrar { private final ReflectiveRuntimeHintsRegistrar reflectiveRegistrar = new ReflectiveRuntimeHintsRegistrar(); private final BindingReflectionHintsRegistrar bindingRegistrar = new BindingReflectionHintsRegistrar(); @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { this.reflectiveRegistrar.registerRuntimeHints(hints, WebFluxLinksHandler.class); this.bindingRegistrar.registerReflectionHints(hints.reflection(), Link.class); } } }
repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\actuate\endpoint\web\WebFluxEndpointHandlerMapping.java
1
请完成以下Java代码
public String getKey() { return key; } public void setKey(String key) { this.key = key; } public Expression getDueDateExpression() { return dueDateExpression; } public void setDueDateExpression(Expression dueDateExpression) { this.dueDateExpression = dueDateExpression; } public Expression getBusinessCalendarNameExpression() { return businessCalendarNameExpression; } public void setBusinessCalendarNameExpression(Expression businessCalendarNameExpression) { this.businessCalendarNameExpression = businessCalendarNameExpression; } public Expression getCategoryExpression() { return categoryExpression; } public void setCategoryExpression(Expression categoryExpression) { this.categoryExpression = categoryExpression; } public Map<String, List<TaskListener>> getTaskListeners() { return taskListeners; } public void setTaskListeners(Map<String, List<TaskListener>> taskListeners) { this.taskListeners = taskListeners; }
public List<TaskListener> getTaskListener(String eventName) { return taskListeners.get(eventName); } public void addTaskListener(String eventName, TaskListener taskListener) { if (TaskListener.EVENTNAME_ALL_EVENTS.equals(eventName)) { // In order to prevent having to merge the "all" tasklisteners with the ones for a specific eventName, // every time "getTaskListener()" is called, we add the listener explicitly to the individual lists this.addTaskListener(TaskListener.EVENTNAME_CREATE, taskListener); this.addTaskListener(TaskListener.EVENTNAME_ASSIGNMENT, taskListener); this.addTaskListener(TaskListener.EVENTNAME_COMPLETE, taskListener); this.addTaskListener(TaskListener.EVENTNAME_DELETE, taskListener); } else { List<TaskListener> taskEventListeners = taskListeners.get(eventName); if (taskEventListeners == null) { taskEventListeners = new ArrayList<>(); taskListeners.put(eventName, taskEventListeners); } taskEventListeners.add(taskListener); } } public Expression getSkipExpression() { return skipExpression; } public void setSkipExpression(Expression skipExpression) { this.skipExpression = skipExpression; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\task\TaskDefinition.java
1
请完成以下Java代码
public class DelegatingFilterProxyRegistrationBean extends AbstractFilterRegistrationBean<DelegatingFilterProxy> implements ApplicationContextAware { @SuppressWarnings("NullAway.Init") private ApplicationContext applicationContext; private final String targetBeanName; /** * Create a new {@link DelegatingFilterProxyRegistrationBean} instance to be * registered with the specified {@link ServletRegistrationBean}s. * @param targetBeanName name of the target filter bean to look up in the Spring * application context (must not be {@code null}). * @param servletRegistrationBeans associate {@link ServletRegistrationBean}s */ public DelegatingFilterProxyRegistrationBean(String targetBeanName, ServletRegistrationBean<?>... servletRegistrationBeans) { super(servletRegistrationBeans); Assert.hasLength(targetBeanName, "'targetBeanName' must not be empty"); this.targetBeanName = targetBeanName; setName(targetBeanName); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } protected String getTargetBeanName() { return this.targetBeanName; }
@Override public DelegatingFilterProxy getFilter() { return new DelegatingFilterProxy(this.targetBeanName, getWebApplicationContext()) { @Override protected void initFilterBean() throws ServletException { // Don't initialize filter bean on init() } }; } private WebApplicationContext getWebApplicationContext() { Assert.state(this.applicationContext != null, "ApplicationContext has not been injected"); Assert.state(this.applicationContext instanceof WebApplicationContext, "Injected ApplicationContext is not a WebApplicationContext"); return (WebApplicationContext) this.applicationContext; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\web\servlet\DelegatingFilterProxyRegistrationBean.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_WF_Next_ID (final int AD_WF_Next_ID) { if (AD_WF_Next_ID < 1) set_Value (COLUMNNAME_AD_WF_Next_ID, null); else set_Value (COLUMNNAME_AD_WF_Next_ID, AD_WF_Next_ID); } @Override public int getAD_WF_Next_ID() { return get_ValueAsInt(COLUMNNAME_AD_WF_Next_ID); } @Override public void setAD_WF_Node_ID (final int AD_WF_Node_ID) { if (AD_WF_Node_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_WF_Node_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_WF_Node_ID, AD_WF_Node_ID); } @Override public int getAD_WF_Node_ID() { return get_ValueAsInt(COLUMNNAME_AD_WF_Node_ID); } @Override public void setAD_WF_NodeNext_ID (final int AD_WF_NodeNext_ID) { if (AD_WF_NodeNext_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_WF_NodeNext_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_WF_NodeNext_ID, AD_WF_NodeNext_ID); } @Override public int getAD_WF_NodeNext_ID() { return get_ValueAsInt(COLUMNNAME_AD_WF_NodeNext_ID); } @Override public void setDescription (final java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); }
/** * EntityType AD_Reference_ID=389 * Reference name: _EntityTypeNew */ public static final int ENTITYTYPE_AD_Reference_ID=389; @Override public void setEntityType (final java.lang.String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } @Override public java.lang.String getEntityType() { return get_ValueAsString(COLUMNNAME_EntityType); } @Override public void setIsStdUserWorkflow (final boolean IsStdUserWorkflow) { set_Value (COLUMNNAME_IsStdUserWorkflow, IsStdUserWorkflow); } @Override public boolean isStdUserWorkflow() { return get_ValueAsBoolean(COLUMNNAME_IsStdUserWorkflow); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setTransitionCode (final java.lang.String TransitionCode) { set_Value (COLUMNNAME_TransitionCode, TransitionCode); } @Override public java.lang.String getTransitionCode() { return get_ValueAsString(COLUMNNAME_TransitionCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_NodeNext.java
1
请完成以下Java代码
public static boolean hasIntersection(Set<String> set1, String[] arr2) { if (set1 == null) { return false; } if(set1.size()>0){ for (String str : arr2) { if (set1.contains(str)) { return true; } } } return false; }
/** * 输出info日志,会捕获异常,防止因为日志问题导致程序异常 * * @param msg * @param objects */ public static void logInfo(String msg, Object... objects) { try { log.info(msg, objects); } catch (Exception e) { log.warn("{} —— {}", msg, e.getMessage()); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\CommonUtils.java
1
请完成以下Java代码
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } public I_C_ValidCombination getHR_Concept_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getHR_Concept_Acct(), get_TrxName()); } /** Set Payroll Concept Account. @param HR_Concept_Acct Payroll Concept Account */ public void setHR_Concept_Acct (int HR_Concept_Acct) { set_Value (COLUMNNAME_HR_Concept_Acct, Integer.valueOf(HR_Concept_Acct)); } /** Get Payroll Concept Account. @return Payroll Concept Account */ public int getHR_Concept_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_Concept_Acct); if (ii == null) return 0; return ii.intValue(); } /** Set Payroll Concept Category. @param HR_Concept_Category_ID Payroll Concept Category */ public void setHR_Concept_Category_ID (int HR_Concept_Category_ID) { if (HR_Concept_Category_ID < 1) set_ValueNoCheck (COLUMNNAME_HR_Concept_Category_ID, null); else set_ValueNoCheck (COLUMNNAME_HR_Concept_Category_ID, Integer.valueOf(HR_Concept_Category_ID)); } /** Get Payroll Concept Category. @return Payroll Concept Category */ public int getHR_Concept_Category_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_Concept_Category_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Default. @param IsDefault Default value */ public void setIsDefault (boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); } /** Get Default. @return Default value */ public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name
Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Concept_Category.java
1
请在Spring Boot框架中完成以下Java代码
GsonHttpConvertersCustomizer gsonHttpMessageConvertersCustomizer(Gson gson) { return new GsonHttpConvertersCustomizer(gson); } } static class GsonHttpConvertersCustomizer implements ClientHttpMessageConvertersCustomizer, ServerHttpMessageConvertersCustomizer { private final GsonHttpMessageConverter converter; GsonHttpConvertersCustomizer(Gson gson) { this.converter = new GsonHttpMessageConverter(gson); } @Override public void customize(ClientBuilder builder) { builder.withJsonConverter(this.converter); } @Override public void customize(ServerBuilder builder) { builder.withJsonConverter(this.converter); } } private static class PreferGsonOrJacksonAndJsonbUnavailableCondition extends AnyNestedCondition { PreferGsonOrJacksonAndJsonbUnavailableCondition() { super(ConfigurationPhase.REGISTER_BEAN); } @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue = "gson") static class GsonPreferred { } @Conditional(JacksonAndJsonbUnavailableCondition.class) static class JacksonJsonbUnavailable { } } private static class JacksonAndJsonbUnavailableCondition extends NoneNestedConditions { JacksonAndJsonbUnavailableCondition() { super(ConfigurationPhase.REGISTER_BEAN);
} @ConditionalOnBean(JacksonHttpMessageConvertersConfiguration.JacksonJsonHttpMessageConvertersCustomizer.class) static class JacksonAvailable { } @SuppressWarnings("removal") @ConditionalOnBean(Jackson2HttpMessageConvertersConfiguration.Jackson2JsonMessageConvertersCustomizer.class) static class Jackson2Available { } @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue = "jsonb") static class JsonbPreferred { } } }
repos\spring-boot-4.0.1\module\spring-boot-http-converter\src\main\java\org\springframework\boot\http\converter\autoconfigure\GsonHttpMessageConvertersConfiguration.java
2
请完成以下Java代码
public int getRfQ_Lost_PrintFormat_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_RfQ_Lost_PrintFormat_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_R_MailText getRfQ_Win_MailText() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_RfQ_Win_MailText_ID, org.compiere.model.I_R_MailText.class); } @Override public void setRfQ_Win_MailText(org.compiere.model.I_R_MailText RfQ_Win_MailText) { set_ValueFromPO(COLUMNNAME_RfQ_Win_MailText_ID, org.compiere.model.I_R_MailText.class, RfQ_Win_MailText); } /** Set RfQ win mail text. @param RfQ_Win_MailText_ID RfQ win mail text */ @Override public void setRfQ_Win_MailText_ID (int RfQ_Win_MailText_ID) { if (RfQ_Win_MailText_ID < 1) set_Value (COLUMNNAME_RfQ_Win_MailText_ID, null); else set_Value (COLUMNNAME_RfQ_Win_MailText_ID, Integer.valueOf(RfQ_Win_MailText_ID)); } /** Get RfQ win mail text. @return RfQ win mail text */ @Override public int getRfQ_Win_MailText_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_RfQ_Win_MailText_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_PrintFormat getRfQ_Win_PrintFormat() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_RfQ_Win_PrintFormat_ID, org.compiere.model.I_AD_PrintFormat.class); } @Override public void setRfQ_Win_PrintFormat(org.compiere.model.I_AD_PrintFormat RfQ_Win_PrintFormat) { set_ValueFromPO(COLUMNNAME_RfQ_Win_PrintFormat_ID, org.compiere.model.I_AD_PrintFormat.class, RfQ_Win_PrintFormat); } /** Set RfQ Won Druck - Format. @param RfQ_Win_PrintFormat_ID RfQ Won Druck - Format */ @Override public void setRfQ_Win_PrintFormat_ID (int RfQ_Win_PrintFormat_ID)
{ if (RfQ_Win_PrintFormat_ID < 1) set_Value (COLUMNNAME_RfQ_Win_PrintFormat_ID, null); else set_Value (COLUMNNAME_RfQ_Win_PrintFormat_ID, Integer.valueOf(RfQ_Win_PrintFormat_ID)); } /** Get RfQ Won Druck - Format. @return RfQ Won Druck - Format */ @Override public int getRfQ_Win_PrintFormat_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_RfQ_Win_PrintFormat_ID); if (ii == null) return 0; return ii.intValue(); } /** * RfQType AD_Reference_ID=540661 * Reference name: RfQType */ public static final int RFQTYPE_AD_Reference_ID=540661; /** Default = D */ public static final String RFQTYPE_Default = "D"; /** Procurement = P */ public static final String RFQTYPE_Procurement = "P"; /** Set Ausschreibung Art. @param RfQType Ausschreibung Art */ @Override public void setRfQType (java.lang.String RfQType) { set_Value (COLUMNNAME_RfQType, RfQType); } /** Get Ausschreibung Art. @return Ausschreibung Art */ @Override public java.lang.String getRfQType () { return (java.lang.String)get_Value(COLUMNNAME_RfQType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQ_Topic.java
1
请完成以下Java代码
public class PharmaModulo11Validator { private static final int PZN_MODULO11 = 11; private static final int PZN7_Length = 7; private static final int PZN7_InitialMultiplier = 2; private static final int PZN8_Length = 8; private static final int PZN8_InitialMultiplier = 1; public static boolean isValid(final String pzn) { if (pzn.length() != PZN7_Length && pzn.length() != PZN8_Length) { return false; } if (!pzn.equals(StringUtils.getDigits(pzn))) { return false; } final int codeLimit = pzn.length() - 1; final int checkDigit = Character.getNumericValue(pzn.charAt(codeLimit)); final String code = pzn.substring(0, codeLimit); final int initialMultiplier; if (pzn.length() == PZN7_Length) { initialMultiplier = PZN7_InitialMultiplier; } else {
initialMultiplier = PZN8_InitialMultiplier; } final int codeModuloResult = calculateModulo11(code, initialMultiplier); return codeModuloResult == checkDigit; } private static int calculateModulo11(final String code, final int initialMultiplier) { int total = 0; int multiplier = initialMultiplier; final int codeLength = code.length(); for (int i = 0; i < codeLength; i++) { int value = Character.getNumericValue(code.charAt(i)); total += value * multiplier; multiplier++; } if (total == 0) { throw new AdempiereException("Invalid code, sum is zero"); } return total % PZN_MODULO11; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\vertical\pharma\PharmaModulo11Validator.java
1
请完成以下Java代码
static WarehouseId extractWarehouseId(final I_M_HU hu) { final WarehouseId warehouseId = extractWarehouseIdOrNull(hu); if (warehouseId == null) { throw new HUException("Warehouse Locator shall be set for: " + hu); } return warehouseId; } static I_M_Warehouse extractWarehouse(final I_M_HU hu) { final I_M_Warehouse warehouse = extractWarehouseOrNull(hu); if (warehouse == null) { throw new HUException("Warehouse Locator shall be set for: " + hu); } return warehouse; } @Nullable static WarehouseId extractWarehouseIdOrNull(final I_M_HU hu) { final int locatorRepoId = hu.getM_Locator_ID(); if (locatorRepoId <= 0) { return null; } return Services.get(IWarehouseDAO.class).getWarehouseIdByLocatorRepoId(locatorRepoId); } @Nullable static I_M_Warehouse extractWarehouseOrNull(final I_M_HU hu) { final WarehouseId warehouseId = extractWarehouseIdOrNull(hu); return warehouseId != null ? InterfaceWrapperHelper.create(Services.get(IWarehouseDAO.class).getById(warehouseId), I_M_Warehouse.class) : null; } @Nullable static I_M_HU_PI_Item_Product extractPIItemProductOrNull(@NonNull final I_M_HU hu) { final HUPIItemProductId piItemProductId = HUPIItemProductId.ofRepoIdOrNull(hu.getM_HU_PI_Item_Product_ID()); return piItemProductId != null
? Services.get(IHUPIItemProductDAO.class).getRecordById(piItemProductId) : null; } AttributesKey getAttributesKeyForInventory(@NonNull I_M_HU hu); AttributesKey getAttributesKeyForInventory(@NonNull IAttributeSet attributeSet); void setHUStatus(@NonNull Collection<I_M_HU> hus, @NonNull String huStatus); void setHUStatus(@NonNull Collection<I_M_HU> hus, @NonNull IHUContext huContext, @NonNull String huStatus); void setHUStatus(I_M_HU hu, IContextAware contextProvider, String huStatus); void setHUStatus(@NonNull I_M_HU hu, @NonNull String huStatus); boolean isEmptyStorage(I_M_HU hu); boolean isDestroyedOrEmptyStorage(I_M_HU hu); void setClearanceStatusRecursively(final HuId huId, final ClearanceStatusInfo statusInfo); boolean isHUHierarchyCleared(@NonNull I_M_HU hu); ITranslatableString getClearanceStatusCaption(ClearanceStatus clearanceStatus); boolean isHUHierarchyCleared(@NonNull final HuId huId); @NonNull ImmutableSet<LocatorId> getLocatorIds(@NonNull Collection<HuId> huIds); Set<HuPackingMaterialId> getHUPackingMaterialIds(HuId huId); }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\IHandlingUnitsBL.java
1
请在Spring Boot框架中完成以下Java代码
class Song { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @ManyToOne private Album album; @ManyToOne private Artist artist; Song(String name, Artist artist) { this.name = name; this.artist = artist; } void assignToAlbum(Album album) { this.album = album; } @Override public boolean equals(Object o) { if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; Song song = (Song) o; return Objects.equals(id, song.id); } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } protected Song() { } }
repos\tutorials-master\persistence-modules\java-jpa-3\src\main\java\com\baeldung\jpa\multiplebagfetchexception\Song.java
2
请完成以下Java代码
public Builder append(@NonNull final CharSequence sql, @Nullable final Object... sqlParams) { final List<Object> sqlParamsList = sqlParams != null && sqlParams.length > 0 ? Arrays.asList(sqlParams) : null; return append(sql, sqlParamsList); } public Builder append(@NonNull final CharSequence sql, @Nullable final List<Object> sqlParams) { if (sql.length() > 0) { if (this.sql == null) { this.sql = new StringBuilder(); } this.sql.append(sql); } if (sqlParams != null && !sqlParams.isEmpty()) { if (this.sqlParams == null) { this.sqlParams = new ArrayList<>(); }
this.sqlParams.addAll(sqlParams); } return this; } public Builder append(@NonNull final SqlAndParams other) { return append(other.sql, other.sqlParams); } public Builder append(@NonNull final SqlAndParams.Builder other) { return append(other.sql, other.sqlParams); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlAndParams.java
1
请完成以下Java代码
public LinkedHashMap<String, Object> getProperties() {return properties;} @JsonAnySetter public void putProperty(final String key, final Object value) {properties.put(key, value);} public Optional<String> getUrl() {return getByPathAsString("page", "url");} public Optional<String> getUsername() {return getByPathAsString("user", "username");} public Optional<String> getCaption() {return getByPathAsString("caption");} public Optional<MobileApplicationId> getApplicationId() {return getByPathAsString("applicationId").map(MobileApplicationId::ofNullableString);} public Optional<String> getDeviceId() {return getByPathAsString("device", "deviceId");} public Optional<String> getTabId() {return getByPathAsString("device", "tabId");} public Optional<String> getUserAgent() {return getByPathAsString("device", "userAgent");} public Optional<String> getByPathAsString(final String... path) { return getByPath(path).map(Object::toString); } public Optional<Object> getByPath(final String... path) { Object currentValue = properties; for (final String pathElement : path) { if (!(currentValue instanceof Map)) { //throw new AdempiereException("Invalid path " + Arrays.asList(path) + " in " + properties); return Optional.empty(); } //noinspection unchecked final Object value = getByKey((Map<String, Object>)currentValue, pathElement).orElse(null);
if (value == null) { return Optional.empty(); } else { currentValue = value; } } return Optional.of(currentValue); } private static Optional<Object> getByKey(final Map<String, Object> map, final String key) { return map.entrySet() .stream() .filter(e -> e.getKey().equalsIgnoreCase(key)) .map(Map.Entry::getValue) .filter(Objects::nonNull) .findFirst(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java\de\metas\server\ui_trace\rest\JsonUITraceEvent.java
1
请完成以下Java代码
public class Employee { private String lastName; private String firstName; private long id; public Employee() { } public Employee(final long id, final String firstName, final String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } public String getLastName() { return lastName; } public String getFirstName() { return firstName; } public long getId() { return id; } public void setLastName(final String lastName) { this.lastName = lastName; } public void setFirstName(final String firstName) { this.firstName = firstName; } public void setId(final long id) { this.id = id; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; }
final Employee employee = (Employee) o; if (id != employee.id) { return false; } if (!Objects.equals(lastName, employee.lastName)) { return false; } return Objects.equals(firstName, employee.firstName); } @Override public int hashCode() { int result = lastName != null ? lastName.hashCode() : 0; result = 31 * result + (firstName != null ? firstName.hashCode() : 0); result = 31 * result + (int) (id ^ (id >>> 32)); return result; } @Override public String toString() { return "User{" + "lastName='" + lastName + '\'' + ", firstName='" + firstName + '\'' + ", id=" + id + '}'; } }
repos\tutorials-master\spring-boot-modules\spring-boot-data-2\src\main\java\com\baeldung\jsonignore\nullfields\Employee.java
1
请完成以下Java代码
private long calculateMaxAgeInSeconds(ServerHttpRequest request, CachedResponse cachedResponse, Duration configuredTimeToLive) { boolean noCache = LocalResponseCacheUtils.isNoCacheRequest(request); long maxAge; if (noCache && ignoreNoCacheUpdate || configuredTimeToLive.getSeconds() < 0) { maxAge = 0; } else { long calculatedMaxAge = configuredTimeToLive.minus(getElapsedTimeInSeconds(cachedResponse)).getSeconds(); maxAge = Math.max(0, calculatedMaxAge); } return maxAge; } private Duration getElapsedTimeInSeconds(CachedResponse cachedResponse) { return Duration.ofMillis(clock.millis() - cachedResponse.timestamp().getTime()); } private static void rewriteCacheControlMaxAge(HttpHeaders headers, long seconds) { boolean isMaxAgePresent = headers.getCacheControl() != null && headers.getCacheControl().contains(MAX_AGE_PREFIX); List<String> newCacheControlDirectives = new ArrayList<>(); if (isMaxAgePresent) { List<String> cacheControlHeaders = headers.get(HttpHeaders.CACHE_CONTROL); cacheControlHeaders = cacheControlHeaders == null ? Collections.emptyList() : cacheControlHeaders;
for (String value : cacheControlHeaders) { if (value.contains(MAX_AGE_PREFIX)) { if (seconds == -1) { List<String> removedMaxAgeList = Arrays.stream(value.split(",")) .filter(i -> !i.trim().startsWith(MAX_AGE_PREFIX)) .collect(Collectors.toList()); value = String.join(",", removedMaxAgeList); } else { value = value.replaceFirst("\\bmax-age=\\d+\\b", MAX_AGE_PREFIX + seconds); } } newCacheControlDirectives.add(value); } } else { List<String> cacheControlHeaders = headers.get(HttpHeaders.CACHE_CONTROL); newCacheControlDirectives = cacheControlHeaders == null ? new ArrayList<>() : new ArrayList<>(cacheControlHeaders); newCacheControlDirectives.add("max-age=" + seconds); } headers.remove(HttpHeaders.CACHE_CONTROL); headers.addAll(HttpHeaders.CACHE_CONTROL, newCacheControlDirectives); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\postprocessor\SetMaxAgeHeaderAfterCacheExchangeMutator.java
1
请完成以下Java代码
public class ReferrerPolicyHeaderWriter implements HeaderWriter { private static final String REFERRER_POLICY_HEADER = "Referrer-Policy"; private ReferrerPolicy policy; /** * Creates a new instance. Default value: no-referrer. */ public ReferrerPolicyHeaderWriter() { this(ReferrerPolicy.NO_REFERRER); } /** * Creates a new instance. * @param policy a referrer policy * @throws IllegalArgumentException if policy is null */ public ReferrerPolicyHeaderWriter(ReferrerPolicy policy) { Assert.notNull(policy, "policy can not be null"); this.policy = policy; } /** * Sets the policy to be used in the response header. * @param policy a referrer policy * @throws IllegalArgumentException if policy is null */ public void setPolicy(ReferrerPolicy policy) { Assert.notNull(policy, "policy can not be null"); this.policy = policy; } /** * @see org.springframework.security.web.header.HeaderWriter#writeHeaders(HttpServletRequest, * HttpServletResponse) */ @Override public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { if (!response.containsHeader(REFERRER_POLICY_HEADER)) { response.setHeader(REFERRER_POLICY_HEADER, this.policy.getPolicy()); } } public enum ReferrerPolicy { NO_REFERRER("no-referrer"), NO_REFERRER_WHEN_DOWNGRADE("no-referrer-when-downgrade"), SAME_ORIGIN("same-origin"), ORIGIN("origin"), STRICT_ORIGIN("strict-origin"), ORIGIN_WHEN_CROSS_ORIGIN("origin-when-cross-origin"),
STRICT_ORIGIN_WHEN_CROSS_ORIGIN("strict-origin-when-cross-origin"), UNSAFE_URL("unsafe-url"); private static final Map<String, ReferrerPolicy> REFERRER_POLICIES; static { Map<String, ReferrerPolicy> referrerPolicies = new HashMap<>(); for (ReferrerPolicy referrerPolicy : values()) { referrerPolicies.put(referrerPolicy.getPolicy(), referrerPolicy); } REFERRER_POLICIES = Collections.unmodifiableMap(referrerPolicies); } private final String policy; ReferrerPolicy(String policy) { this.policy = policy; } public String getPolicy() { return this.policy; } public static @Nullable ReferrerPolicy get(String referrerPolicy) { return REFERRER_POLICIES.get(referrerPolicy); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\writers\ReferrerPolicyHeaderWriter.java
1
请在Spring Boot框架中完成以下Java代码
public class Article { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String name; @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) private Set<Comment> comments = new HashSet<>(); public Set<Comment> getComments() { return comments; } public long getId() { return id; }
public String getName() { return name; } public void setId(long id) { this.id = id; } public void setName(String name) { this.name = name; } public void setComments(Set<Comment> comments) { this.comments = comments; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-4\src\main\java\com\baeldung\spring\data\persistence\unidirectionalcascadingdelete\Article.java
2
请完成以下Java代码
public Timestamp getRRStartDate () { return (Timestamp)get_Value(COLUMNNAME_RRStartDate); } public org.compiere.model.I_C_OrderLine getRef_OrderLine() throws RuntimeException { return (org.compiere.model.I_C_OrderLine)MTable.get(getCtx(), org.compiere.model.I_C_OrderLine.Table_Name) .getPO(getRef_OrderLine_ID(), get_TrxName()); } /** Set Referenced Order Line. @param Ref_OrderLine_ID Reference to corresponding Sales/Purchase Order */ public void setRef_OrderLine_ID (int Ref_OrderLine_ID) { if (Ref_OrderLine_ID < 1) set_Value (COLUMNNAME_Ref_OrderLine_ID, null); else set_Value (COLUMNNAME_Ref_OrderLine_ID, Integer.valueOf(Ref_OrderLine_ID)); } /** Get Referenced Order Line. @return Reference to corresponding Sales/Purchase Order */ public int getRef_OrderLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Ref_OrderLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Ressourcenzuordnung. @param S_ResourceAssignment_ID Ressourcenzuordnung */ public void setS_ResourceAssignment_ID (int S_ResourceAssignment_ID)
{ if (S_ResourceAssignment_ID < 1) set_Value (COLUMNNAME_S_ResourceAssignment_ID, null); else set_Value (COLUMNNAME_S_ResourceAssignment_ID, Integer.valueOf(S_ResourceAssignment_ID)); } /** Get Ressourcenzuordnung. @return Ressourcenzuordnung */ public int getS_ResourceAssignment_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_ResourceAssignment_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_RV_C_OrderLine_Overview.java
1
请完成以下Java代码
public class VariableScopeElResolver extends ELResolver { public static final String EXECUTION_KEY = "execution"; public static final String TASK_KEY = "task"; public static final String LOGGED_IN_USER_KEY = "authenticatedUserId"; protected VariableScope variableScope; public VariableScopeElResolver(VariableScope variableScope) { this.variableScope = variableScope; } @Override public Object getValue(ELContext context, Object base, Object property) { if (base == null) { String variable = (String) property; // according to javadoc, can only be a String if ((EXECUTION_KEY.equals(property) && variableScope instanceof ExecutionEntity) || (TASK_KEY.equals(property) && variableScope instanceof TaskEntity)) { context.setPropertyResolved(true); return variableScope; } else if (EXECUTION_KEY.equals(property) && variableScope instanceof TaskEntity) { context.setPropertyResolved(true); return ((TaskEntity) variableScope).getExecution(); } else if (LOGGED_IN_USER_KEY.equals(property)) { context.setPropertyResolved(true); return Authentication.getAuthenticatedUserId(); } else { if (variableScope.hasVariable(variable)) { context.setPropertyResolved(true); // if not set, the next elResolver in the CompositeElResolver will be called return variableScope.getVariable(variable); } } } // property resolution (eg. bean.value) will be done by the BeanElResolver (part of the CompositeElResolver)
// It will use the bean resolved in this resolver as base. return null; } @Override public boolean isReadOnly(ELContext context, Object base, Object property) { if (base == null) { String variable = (String) property; return !variableScope.hasVariable(variable); } return true; } @Override public void setValue(ELContext context, Object base, Object property, Object value) { if (base == null) { String variable = (String) property; if (variableScope.hasVariable(variable)) { variableScope.setVariable(variable, value); } } } @Override public Class<?> getCommonPropertyType(ELContext arg0, Object arg1) { return Object.class; } @Override public Class<?> getType(ELContext arg0, Object arg1, Object arg2) { return Object.class; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\el\VariableScopeElResolver.java
1
请完成以下Java代码
public static class NullTypeImpl extends PrimitiveValueTypeImpl { private static final long serialVersionUID = 1L; public NullTypeImpl() { super("null", NullType.class); } public TypedValue createValue(Object value, Map<String, Object> valueInfo) { return Variables.untypedNullValue(isTransient(valueInfo)); } } public static class ShortTypeImpl extends PrimitiveValueTypeImpl { private static final long serialVersionUID = 1L; public ShortTypeImpl() { super(Short.class); } public ShortValue createValue(Object value, Map<String, Object> valueInfo) { return Variables.shortValue((Short) value, isTransient(valueInfo)); } @Override public ValueType getParent() { return ValueType.NUMBER; } @Override public ShortValue convertFromTypedValue(TypedValue typedValue) { if (typedValue.getType() != ValueType.NUMBER) { throw unsupportedConversion(typedValue.getType()); } ShortValueImpl shortValue = null; NumberValue numberValue = (NumberValue) typedValue; if (numberValue.getValue() != null) { shortValue = (ShortValueImpl) Variables.shortValue(numberValue.getValue().shortValue()); } else { shortValue = (ShortValueImpl) Variables.shortValue(null); } shortValue.setTransient(numberValue.isTransient()); return shortValue; } @Override public boolean canConvertFromTypedValue(TypedValue typedValue) { if (typedValue.getType() != ValueType.NUMBER) { return false; } if (typedValue.getValue() != null) { NumberValue numberValue = (NumberValue) typedValue; double doubleValue = numberValue.getValue().doubleValue();
// returns false if the value changes due to conversion (e.g. by overflows // or by loss in precision) if (numberValue.getValue().shortValue() != doubleValue) { return false; } } return true; } } public static class StringTypeImpl extends PrimitiveValueTypeImpl { private static final long serialVersionUID = 1L; public StringTypeImpl() { super(String.class); } public StringValue createValue(Object value, Map<String, Object> valueInfo) { return Variables.stringValue((String) value, isTransient(valueInfo)); } } public static class NumberTypeImpl extends PrimitiveValueTypeImpl { private static final long serialVersionUID = 1L; public NumberTypeImpl() { super(Number.class); } public NumberValue createValue(Object value, Map<String, Object> valueInfo) { return Variables.numberValue((Number) value, isTransient(valueInfo)); } @Override public boolean isAbstract() { return true; } } }
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\type\PrimitiveValueTypeImpl.java
1
请完成以下Java代码
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { PropertySource<?> system = environment.getPropertySources() .get(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); Map<String, Object> prefixed = new LinkedHashMap<>(); if (!hasOurPriceProperties(system)) { // Baeldung-internal code so this doesn't break other examples logger.warn("System environment variables [calculation_mode,gross_calculation_tax_rate] not detected, fallback to default value [calcuation_mode={},gross_calcuation_tax_rate={}]", CALCUATION_MODE_DEFAULT_VALUE, GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE); prefixed = names.stream() .collect(Collectors.toMap(this::rename, this::getDefaultValue)); environment.getPropertySources() .addAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, new MapPropertySource("prefixer", prefixed)); return; } prefixed = names.stream() .collect(Collectors.toMap(this::rename, system::getProperty));
environment.getPropertySources() .addAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, new MapPropertySource("prefixer", prefixed)); } private Object getDefaultValue(String key) { return defaults.get(key); } private String rename(String key) { return PREFIX + key.replaceAll("\\_", "."); } private boolean hasOurPriceProperties(PropertySource<?> system) { if (system.containsProperty(CALCUATION_MODE) && system.containsProperty(GROSS_CALCULATION_TAX_RATE)) { return true; } else return false; } }
repos\tutorials-master\spring-boot-modules\spring-boot-environment\src\main\java\com\baeldung\environmentpostprocessor\PriceCalculationEnvironmentPostProcessor.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } } static class UppercasingRequestConverter implements RequestConverterFunction { @Override public Object convertRequest(ServiceRequestContext ctx, AggregatedHttpRequest request, Class<?> expectedResultType, ParameterizedType expectedParameterizedResultType) throws Exception { if (expectedResultType.isAssignableFrom(String.class)) { return request.content(StandardCharsets.UTF_8).toUpperCase(); } return RequestConverterFunction.fallthrough(); } } static class UppercasingResponseConverter implements ResponseConverterFunction {
@Override public HttpResponse convertResponse(ServiceRequestContext ctx, ResponseHeaders headers, @Nullable Object result, HttpHeaders trailers) { if (result instanceof String) { return HttpResponse.of(HttpStatus.OK, MediaType.PLAIN_TEXT_UTF_8, ((String) result).toUpperCase(), trailers); } return ResponseConverterFunction.fallthrough(); } } static class ConflictExceptionHandler implements ExceptionHandlerFunction { @Override public HttpResponse handleException(ServiceRequestContext ctx, HttpRequest req, Throwable cause) { if (cause instanceof IllegalStateException) { return HttpResponse.of(HttpStatus.CONFLICT); } return ExceptionHandlerFunction.fallthrough(); } } } }
repos\tutorials-master\server-modules\armeria\src\main\java\com\baeldung\armeria\AnnotatedServer.java
1
请完成以下Java代码
public class DocSequenceAwareFieldStringExpression implements IStringExpression { private static final String PARAMETER_AD_Client_ID = WindowConstants.FIELDNAME_AD_Client_ID; private static final Set<CtxName> PARAMETERS = ImmutableSet.of(CtxNames.parse(PARAMETER_AD_Client_ID)); @NonNull private final DocSequenceId sequenceId; public DocSequenceAwareFieldStringExpression(@NonNull final DocSequenceId sequenceId) { this.sequenceId = sequenceId; } @Override public String getExpressionString() { return "@CustomSequenceNo@"; } @Override public Set<CtxName> getParameters() { return PARAMETERS; } @Override public String evaluate(final Evaluatee ctx, final IExpressionEvaluator.OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException { final ClientId adClientId = Optional.ofNullable(ctx.get_ValueAsInt(PARAMETER_AD_Client_ID, null)) .map(ClientId::ofRepoId) .orElseGet(() -> ClientId.ofRepoId(Env.getAD_Client_ID(Env.getCtx()))); final IDocumentNoBuilderFactory documentNoFactory = Services.get(IDocumentNoBuilderFactory.class);
final String sequenceNo = documentNoFactory.forSequenceId(sequenceId) .setFailOnError(onVariableNotFound.equals(IExpressionEvaluator.OnVariableNotFound.Fail)) .setClientId(adClientId) .build(); if (sequenceNo == null && onVariableNotFound == IExpressionEvaluator.OnVariableNotFound.Fail) { throw new AdempiereException("Failed to compute sequence!") .appendParametersToMessage() .setParameter("sequenceId", sequenceId); } return sequenceNo; } @NonNull public static DocSequenceAwareFieldStringExpression of(@NonNull final DocSequenceId sequenceId) { return new DocSequenceAwareFieldStringExpression(sequenceId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\DocSequenceAwareFieldStringExpression.java
1
请完成以下Java代码
class LogbackRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { if (!ClassUtils.isPresent("ch.qos.logback.classic.LoggerContext", classLoader)) { return; } ReflectionHints reflection = hints.reflection(); registerHintsForLogbackLoggingSystemTypeChecks(reflection, classLoader); registerHintsForBuiltInLogbackConverters(reflection); registerHintsForSpringBootConverters(reflection); } private void registerHintsForLogbackLoggingSystemTypeChecks(ReflectionHints reflection, @Nullable ClassLoader classLoader) { reflection.registerType(LoggerContext.class); reflection.registerTypeIfPresent(classLoader, "org.slf4j.bridge.SLF4JBridgeHandler", (typeHint) -> { }); } private void registerHintsForBuiltInLogbackConverters(ReflectionHints reflection) {
registerForPublicConstructorInvocation(reflection, DateTokenConverter.class, IntegerTokenConverter.class, SyslogStartConverter.class); } private void registerHintsForSpringBootConverters(ReflectionHints reflection) { registerForPublicConstructorInvocation(reflection, ColorConverter.class, EnclosedInSquareBracketsConverter.class, ExtendedWhitespaceThrowableProxyConverter.class, WhitespaceThrowableProxyConverter.class, CorrelationIdConverter.class); } private void registerForPublicConstructorInvocation(ReflectionHints reflection, Class<?>... classes) { reflection.registerTypes(TypeReference.listOf(classes), (hint) -> hint.withMembers(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\logback\LogbackRuntimeHints.java
1
请在Spring Boot框架中完成以下Java代码
public PmsPermission getByPermissionName(String permissionName) { return this.getSessionTemplate().selectOne(getStatement("getByPermissionName"), permissionName); } /** * 检查权限是否已存在 * * @param permission * @return */ public PmsPermission getByPermission(String permission) { return this.getSessionTemplate().selectOne(getStatement("getByPermission"), permission); } /** * 检查权限名称是否已存在(其他id) * * @param permissionName * @param id * @return */
public PmsPermission getByPermissionNameNotEqId(String permissionName, Long id) { Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("permissionName", permissionName); paramMap.put("id", id); return this.getSessionTemplate().selectOne(getStatement("getByPermissionNameNotEqId"), paramMap); } /** * 获取叶子菜单下所有的功能权限 * * @param valueOf * @return */ public List<PmsPermission> listAllByMenuId(Long menuId) { Map<String, Object> param = new HashMap<String, Object>(); param.put("menuId", menuId); return this.getSessionTemplate().selectList(getStatement("listAllByMenuId"), param); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\dao\impl\PmsPermissionDaoImpl.java
2
请完成以下Java代码
public void findM_HU_PI_Item_ProductForForecast(@NonNull final I_M_Forecast forecast, final ProductId productId, final Consumer<I_M_HU_PI_Item_Product> pipConsumer) { final IHUDocumentHandlerFactory huDocumentHandlerFactory = Services.get(IHUDocumentHandlerFactory.class); final IHUPIItemProductDAO hupiItemProductDAO = Services.get(IHUPIItemProductDAO.class); if (forecast.getC_BPartner_ID() <= 0 || forecast.getDatePromised() == null) { return; } final IHUDocumentHandler handler = huDocumentHandlerFactory.createHandler(I_M_Forecast.Table_Name); if (null != handler && productId != null) { final I_M_HU_PI_Item_Product overridePip = handler.getM_HU_PI_ItemProductFor(forecast, productId); // If we have a default price and it has an M_HU_PI_Item_Product, suggest it in quick entry. if (null != overridePip && overridePip.getM_HU_PI_Item_Product_ID() > 0) { if (overridePip.isAllowAnyProduct()) { pipConsumer.accept(null); } else { pipConsumer.accept(overridePip); } return; } } // // Try fetching best matching PIP
final I_M_HU_PI_Item_Product pip = hupiItemProductDAO.retrieveMaterialItemProduct( productId, BPartnerId.ofRepoIdOrNull(forecast.getC_BPartner_ID()), TimeUtil.asZonedDateTime(forecast.getDatePromised()), X_M_HU_PI_Version.HU_UNITTYPE_TransportUnit, true); // allowInfiniteCapacity = true if (pip == null) { // nothing to do, product is not included in any Transport Units return; } else if (pip.isAllowAnyProduct()) { return; } else { pipConsumer.accept(pip); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\order\api\impl\HUOrderBL.java
1
请完成以下Java代码
public static String random(int length, String chars) { return RandomStringUtils.secure().next(length, chars); } public static String randomAlphanumeric(int count) { return RandomStringUtils.secure().nextAlphanumeric(count); } public static String randomAlphabetic(int count) { return RandomStringUtils.secure().nextAlphabetic(count); } public static String generateSafeToken(int length) { byte[] bytes = new byte[length]; RANDOM.nextBytes(bytes); Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); return encoder.encodeToString(bytes); } public static String generateSafeToken() { return generateSafeToken(DEFAULT_TOKEN_LENGTH); } public static String truncate(String string, int maxLength) { return truncate(string, maxLength, n -> "...[truncated " + n + " symbols]"); } public static String truncate(String string, int maxLength, Function<Integer, String> truncationMarkerFunc) { if (string == null || maxLength <= 0 || string.length() <= maxLength) { return string; } int truncatedSymbols = string.length() - maxLength; return string.substring(0, maxLength) + truncationMarkerFunc.apply(truncatedSymbols); } public static List<String> splitByCommaWithoutQuotes(String value) { List<String> splitValues = List.of(value.trim().split("\\s*,\\s*")); List<String> result = new ArrayList<>(); char lastWayInputValue = '#'; for (String str : splitValues) {
char startWith = str.charAt(0); char endWith = str.charAt(str.length() - 1); // if first value is not quote, so we return values after split if (startWith != '\'' && startWith != '"') return splitValues; // if value is not in quote, so we return values after split if (startWith != endWith) return splitValues; // if different way values, so don't replace quote and return values after split if (lastWayInputValue != '#' && startWith != lastWayInputValue) return splitValues; result.add(str.substring(1, str.length() - 1)); lastWayInputValue = startWith; } return result; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\StringUtils.java
1
请完成以下Java代码
public ITrxConstraints getConstraints() { final Thread callingThread = Thread.currentThread(); return getConstraints(callingThread); } protected boolean isDisabled() { final ISysConfigBL sysconfigBL = Services.get(ISysConfigBL.class); final int adClientId = Env.getAD_Client_ID(Env.getCtx()); final boolean disabled = sysconfigBL.getBooleanValue(SYSCONFIG_TRX_CONSTRAINTS_DISABLED, DEFAULT_TRX_CONSTRAINTS_DISABLED, adClientId); return disabled; } @Override public ITrxConstraints getConstraints(final Thread thread) { if (isDisabled()) { return disabled; } try (final CloseableReentrantLock lock = thread2TrxConstraintLock.open()) { Deque<ITrxConstraints> stack = thread2TrxConstraint.get(thread); if (stack == null) { stack = new ArrayDeque<ITrxConstraints>(); thread2TrxConstraint.put(thread, stack); } if (!stack.isEmpty()) { return stack.getFirst(); } final ITrxConstraints newInstance = new TrxConstraints(); stack.push(newInstance); return newInstance; } } @Override public void saveConstraints() { final Thread callingThread = Thread.currentThread(); try (final CloseableReentrantLock lock = thread2TrxConstraintLock.open())
{ final ITrxConstraints constraints = getConstraints(callingThread); // make sure that there is at least one instance if (isDisabled(constraints)) { return; } final Deque<ITrxConstraints> stack = thread2TrxConstraint.get(callingThread); Check.assume(stack != null, "Stack for thread " + callingThread + " is not null"); Check.assume(!stack.isEmpty(), "Stack for thread " + callingThread + " is not empty"); final TrxConstraints constraintsNew = new TrxConstraints(constraints); stack.push(constraintsNew); } } @Override public void restoreConstraints() { final Thread callingThread = Thread.currentThread(); try (final CloseableReentrantLock lock = thread2TrxConstraintLock.open()) { final Deque<ITrxConstraints> stack = thread2TrxConstraint.get(callingThread); if (stack == null) { // There are no constraints for the calling thread. // In other words, getConstraints() hasn't been called yet. // Consequently there is nothing to restore. return; } Check.assume(!stack.isEmpty(), "Stack for thread " + callingThread + " is not empty"); if (stack.size() <= 1) { // there is only the current constraint instance, but no saved instance. // Consequently there is nothing to restore. return; } stack.pop(); } } @Override public boolean isDisabled(ITrxConstraints constraints) { return constraints instanceof TrxConstraintsDisabled; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\trxConstraints\api\impl\TrxConstraintsBL.java
1
请完成以下Java代码
public void onUserLogin(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID) { if (Ini.isSwingClient()) { final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); final boolean enabled = sysConfigBL.getBooleanValue(SYSCONFIG_Enabled, false, Env.getAD_Client_ID(Env.getCtx())); if (enabled) { try { checkImplementationVersion(); } catch (Exception e) { log.error("Error", e); } } checker = new Checker(); final Thread thread = new Thread(checker, Checker.class.getCanonicalName()); thread.start(); } } /** * */ private final void checkImplementationVersion() { final String clientVersion = Adempiere.getImplementationVersion(); Check.assumeNotNull(clientVersion, "Adempiere.getImplementationVersion() is not null"); if (clientVersion.endsWith(Adempiere.CLIENT_VERSION_UNPROCESSED) || clientVersion.endsWith(Adempiere.CLIENT_VERSION_LOCAL_BUILD)) { log.info("Adempiere ImplementationVersion=" + clientVersion + "! Not checking against DB"); return; } final String newVersion = Services.get(ISystemBL.class).get().getLastBuildInfo(); log.info("Build DB=" + newVersion); log.info("Build Cl=" + clientVersion); // Identical DB version if (clientVersion != null && clientVersion.equals(newVersion)) { return; }
final String title = org.compiere.Adempiere.getName() + " " + Services.get(IMsgBL.class).getMsg(Env.getCtx(), MSG_ErrorMessage, true); // Client version {} is available (current version is {}). String msg = Services.get(IMsgBL.class).getMsg(Env.getCtx(), MSG_ErrorMessage); // complete message msg = MessageFormat.format(msg, new Object[] { clientVersion, newVersion }); JOptionPane.showMessageDialog(null, msg, title, JOptionPane.ERROR_MESSAGE); Env.exitEnv(1); } @Override public void beforeLogout(final MFSession session) { if (checker == null) { return; // nothing to do } // stop the checker checker.stop = true; synchronized (checker) { checker.notify(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\clientupdate\ClientUpdateValidator.java
1
请完成以下Java代码
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } public I_M_DistributionList getM_DistributionList() throws RuntimeException { return (I_M_DistributionList)MTable.get(getCtx(), I_M_DistributionList.Table_Name) .getPO(getM_DistributionList_ID(), get_TrxName()); } /** Set Distribution List. @param M_DistributionList_ID Distribution Lists allow to distribute products to a selected list of partners */ public void setM_DistributionList_ID (int M_DistributionList_ID) { if (M_DistributionList_ID < 1) set_ValueNoCheck (COLUMNNAME_M_DistributionList_ID, null); else set_ValueNoCheck (COLUMNNAME_M_DistributionList_ID, Integer.valueOf(M_DistributionList_ID)); } /** Get Distribution List. @return Distribution Lists allow to distribute products to a selected list of partners */ public int getM_DistributionList_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_DistributionList_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getM_DistributionList_ID())); } /** Set Distribution List Line. @param M_DistributionListLine_ID Distribution List Line with Business Partner and Quantity/Percentage */ public void setM_DistributionListLine_ID (int M_DistributionListLine_ID) { if (M_DistributionListLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_DistributionListLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_DistributionListLine_ID, Integer.valueOf(M_DistributionListLine_ID));
} /** Get Distribution List Line. @return Distribution List Line with Business Partner and Quantity/Percentage */ public int getM_DistributionListLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_DistributionListLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Minimum Quantity. @param MinQty Minimum quantity for the business partner */ public void setMinQty (BigDecimal MinQty) { set_Value (COLUMNNAME_MinQty, MinQty); } /** Get Minimum Quantity. @return Minimum quantity for the business partner */ public BigDecimal getMinQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MinQty); if (bd == null) return Env.ZERO; return bd; } /** Set Ratio. @param Ratio Relative Ratio for Distributions */ public void setRatio (BigDecimal Ratio) { set_Value (COLUMNNAME_Ratio, Ratio); } /** Get Ratio. @return Relative Ratio for Distributions */ public BigDecimal getRatio () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Ratio); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DistributionListLine.java
1
请完成以下Java代码
public Mono<Void> endpointProxy(@PathVariable("instanceId") String instanceId, ServerHttpRequest request, ServerHttpResponse response) { InstanceWebProxy.ForwardRequest fwdRequest = createForwardRequest(request, request.getBody(), this.adminContextPath + INSTANCE_MAPPED_PATH); return this.instanceWebProxy.forward(this.registry.getInstance(InstanceId.of(instanceId)), fwdRequest, (clientResponse) -> { response.setStatusCode(clientResponse.statusCode()); response.getHeaders() .addAll(this.httpHeadersFilter.filterHeaders(clientResponse.headers().asHttpHeaders())); return response.writeAndFlushWith(clientResponse.body(BodyExtractors.toDataBuffers()).window(1)); }); } @ResponseBody @RequestMapping(path = APPLICATION_MAPPED_PATH, method = { RequestMethod.GET, RequestMethod.HEAD, RequestMethod.POST, RequestMethod.PUT, RequestMethod.PATCH, RequestMethod.DELETE, RequestMethod.OPTIONS }) public Flux<InstanceWebProxy.InstanceResponse> endpointProxy( @PathVariable("applicationName") String applicationName, ServerHttpRequest request) { Flux<DataBuffer> cachedBody = request.getBody().map((b) -> { DataBuffer dataBuffer = this.bufferFactory.allocateBuffer(b.readableByteCount()); try (var iterator = b.readableByteBuffers()) { iterator.forEachRemaining(dataBuffer::write); } DataBufferUtils.release(b); return dataBuffer; }).cache(); InstanceWebProxy.ForwardRequest fwdRequest = createForwardRequest(request, cachedBody, this.adminContextPath + APPLICATION_MAPPED_PATH); return this.instanceWebProxy.forward(this.registry.getInstances(applicationName), fwdRequest); } private InstanceWebProxy.ForwardRequest createForwardRequest(ServerHttpRequest request, Flux<DataBuffer> cachedBody,
String pathPattern) { String localPath = this.getLocalPath(pathPattern, request); URI uri = UriComponentsBuilder.fromPath(localPath).query(request.getURI().getRawQuery()).build(true).toUri(); return InstanceWebProxy.ForwardRequest.builder() .uri(uri) .method(request.getMethod()) .headers(this.httpHeadersFilter.filterHeaders(request.getHeaders())) .body(BodyInserters.fromDataBuffers(cachedBody)) .build(); } private String getLocalPath(String pathPattern, ServerHttpRequest request) { String pathWithinApplication = request.getPath().pathWithinApplication().value(); return this.pathMatcher.extractPathWithinPattern(pathPattern, pathWithinApplication); } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\web\reactive\InstancesProxyController.java
1
请完成以下Java代码
public @NotNull Iterator<PickingJobSchedule> iterator() { return list.iterator(); } public boolean isEmpty() { return list.isEmpty(); } public void assertSingleShipmentScheduleId(final @NonNull ShipmentScheduleId expectedShipmentScheduleId) { final ShipmentScheduleId shipmentScheduleId = getSingleShipmentScheduleId(); if (!ShipmentScheduleId.equals(shipmentScheduleId, expectedShipmentScheduleId)) { throw new AdempiereException("Expected shipment schedule " + expectedShipmentScheduleId + " but found " + shipmentScheduleId) .setParameter("list", list); } } public Set<ShipmentScheduleId> getShipmentScheduleIds() { return byShipmentScheduleId.keySet(); } public ShipmentScheduleId getSingleShipmentScheduleId() { final Set<ShipmentScheduleId> shipmentScheduleIds = getShipmentScheduleIds(); if (shipmentScheduleIds.size() != 1) { throw new AdempiereException("Expected only one shipment schedule").setParameter("list", list); } return shipmentScheduleIds.iterator().next(); } public ShipmentScheduleAndJobScheduleIdSet toShipmentScheduleAndJobScheduleIdSet() { return list.stream() .map(PickingJobSchedule::getShipmentScheduleAndJobScheduleId) .collect(ShipmentScheduleAndJobScheduleIdSet.collect()); } public boolean isAllProcessed() { return list.stream().allMatch(PickingJobSchedule::isProcessed); } public Optional<Quantity> getQtyToPick()
{ return list.stream() .map(PickingJobSchedule::getQtyToPick) .reduce(Quantity::add); } public Optional<PickingJobSchedule> getSingleScheduleByShipmentScheduleId(@NonNull ShipmentScheduleId shipmentScheduleId) { final ImmutableList<PickingJobSchedule> schedules = byShipmentScheduleId.get(shipmentScheduleId); if (schedules.isEmpty()) { return Optional.empty(); } else if (schedules.size() == 1) { return Optional.of(schedules.get(0)); } else { throw new AdempiereException("Only one schedule was expected for " + shipmentScheduleId + " but found " + schedules); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\picking\job_schedule\model\PickingJobScheduleCollection.java
1
请在Spring Boot框架中完成以下Java代码
public int updateStatus(Long id, Integer status) { SmsFlashPromotionSession promotionSession = new SmsFlashPromotionSession(); promotionSession.setId(id); promotionSession.setStatus(status); return promotionSessionMapper.updateByPrimaryKeySelective(promotionSession); } @Override public int delete(Long id) { return promotionSessionMapper.deleteByPrimaryKey(id); } @Override public SmsFlashPromotionSession getItem(Long id) { return promotionSessionMapper.selectByPrimaryKey(id); } @Override public List<SmsFlashPromotionSession> list() { SmsFlashPromotionSessionExample example = new SmsFlashPromotionSessionExample(); return promotionSessionMapper.selectByExample(example);
} @Override public List<SmsFlashPromotionSessionDetail> selectList(Long flashPromotionId) { List<SmsFlashPromotionSessionDetail> result = new ArrayList<>(); SmsFlashPromotionSessionExample example = new SmsFlashPromotionSessionExample(); example.createCriteria().andStatusEqualTo(1); List<SmsFlashPromotionSession> list = promotionSessionMapper.selectByExample(example); for (SmsFlashPromotionSession promotionSession : list) { SmsFlashPromotionSessionDetail detail = new SmsFlashPromotionSessionDetail(); BeanUtils.copyProperties(promotionSession, detail); long count = relationService.getCount(flashPromotionId, promotionSession.getId()); detail.setProductCount(count); result.add(detail); } return result; } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\SmsFlashPromotionSessionServiceImpl.java
2
请完成以下Java代码
default void setDocumentRoot(@Nullable File documentRoot) { getSettings().setDocumentRoot(documentRoot); } /** * Sets {@link ServletContextInitializer} that should be applied in addition to * {@link ServletWebServerFactory#getWebServer(ServletContextInitializer...)} * parameters. This method will replace any previously set or added initializers. * @param initializers the initializers to set * @see #addInitializers */ default void setInitializers(List<? extends ServletContextInitializer> initializers) { getSettings().setInitializers(initializers); } /** * Add {@link ServletContextInitializer}s to those that should be applied in addition * to {@link ServletWebServerFactory#getWebServer(ServletContextInitializer...)} * parameters. * @param initializers the initializers to add * @see #setInitializers */ default void addInitializers(ServletContextInitializer... initializers) { getSettings().addInitializers(initializers); } /** * Sets the configuration that will be applied to the server's JSP servlet. * @param jsp the JSP servlet configuration */ default void setJsp(Jsp jsp) { getSettings().setJsp(jsp); } /** * Sets the Locale to Charset mappings. * @param localeCharsetMappings the Locale to Charset mappings */ default void setLocaleCharsetMappings(Map<Locale, Charset> localeCharsetMappings) { getSettings().setLocaleCharsetMappings(localeCharsetMappings); } /** * Sets the init parameters that are applied to the container's * {@link ServletContext}. * @param initParameters the init parameters */ default void setInitParameters(Map<String, String> initParameters) { getSettings().setInitParameters(initParameters); } /**
* Sets {@link CookieSameSiteSupplier CookieSameSiteSuppliers} that should be used to * obtain the {@link SameSite} attribute of any added cookie. This method will replace * any previously set or added suppliers. * @param cookieSameSiteSuppliers the suppliers to add * @see #addCookieSameSiteSuppliers */ default void setCookieSameSiteSuppliers(List<? extends CookieSameSiteSupplier> cookieSameSiteSuppliers) { getSettings().setCookieSameSiteSuppliers(cookieSameSiteSuppliers); } /** * Add {@link CookieSameSiteSupplier CookieSameSiteSuppliers} to those that should be * used to obtain the {@link SameSite} attribute of any added cookie. * @param cookieSameSiteSuppliers the suppliers to add * @see #setCookieSameSiteSuppliers */ default void addCookieSameSiteSuppliers(CookieSameSiteSupplier... cookieSameSiteSuppliers) { getSettings().addCookieSameSiteSuppliers(cookieSameSiteSuppliers); } @Override default void addWebListeners(String... webListenerClassNames) { getSettings().addWebListenerClassNames(webListenerClassNames); } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\ConfigurableServletWebServerFactory.java
1
请完成以下Java代码
public B header(String name, Object value) { Assert.hasText(name, "name cannot be empty"); Assert.notNull(value, "value cannot be null"); this.headers.put(name, value); return getThis(); } /** * A {@code Consumer} to be provided access to the headers allowing the ability to * add, replace, or remove. * @param headersConsumer a {@code Consumer} of the headers * @return the {@link AbstractBuilder} */ public B headers(Consumer<Map<String, Object>> headersConsumer) { headersConsumer.accept(this.headers); return getThis(); }
/** * Builds a new {@link JoseHeader}. * @return a {@link JoseHeader} */ public abstract T build(); private static URL convertAsURL(String header, String value) { URL convertedValue = ClaimConversionService.getSharedInstance().convert(value, URL.class); Assert.notNull(convertedValue, () -> "Unable to convert header '" + header + "' of type '" + value.getClass() + "' to URL."); return convertedValue; } } }
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JoseHeader.java
1
请在Spring Boot框架中完成以下Java代码
public Result<AuthService.AuthUser> login(HttpServletRequest request, String username, String password) { if (StringUtils.isNotBlank(DashboardConfig.getAuthUsername())) { authUsername = DashboardConfig.getAuthUsername(); } if (StringUtils.isNotBlank(DashboardConfig.getAuthPassword())) { authPassword = DashboardConfig.getAuthPassword(); } /* * If auth.username or auth.password is blank(set in application.properties or VM arguments), * auth will pass, as the front side validate the input which can't be blank, * so user can input any username or password(both are not blank) to login in that case. */ if (StringUtils.isNotBlank(authUsername) && !authUsername.equals(username) || StringUtils.isNotBlank(authPassword) && !authPassword.equals(password)) { LOGGER.error("Login failed: Invalid username or password, username=" + username); return Result.ofFail(-1, "Invalid username or password"); } AuthService.AuthUser authUser = new SimpleWebAuthServiceImpl.SimpleWebAuthUserImpl(username);
request.getSession().setAttribute(SimpleWebAuthServiceImpl.WEB_SESSION_KEY, authUser); return Result.ofSuccess(authUser); } @PostMapping(value = "/logout") public Result<?> logout(HttpServletRequest request) { request.getSession().invalidate(); return Result.ofSuccess(null); } @PostMapping(value = "/check") public Result<?> check(HttpServletRequest request) { AuthService.AuthUser authUser = authService.getAuthUser(request); if (authUser == null) { return Result.ofFail(-1, "Not logged in"); } return Result.ofSuccess(authUser); } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\AuthController.java
2
请完成以下Java代码
public class StartEvent extends Event { protected String initiator; protected String formKey; protected boolean sameDeployment = true; protected boolean isInterrupting = true; protected String validateFormFields; protected List<FormProperty> formProperties = new ArrayList<>(); public String getInitiator() { return initiator; } public void setInitiator(String initiator) { this.initiator = initiator; } public boolean isSameDeployment() { return sameDeployment; } public void setSameDeployment(boolean sameDeployment) { this.sameDeployment = sameDeployment; } public String getFormKey() { return formKey; } public void setFormKey(String formKey) { this.formKey = formKey; } public boolean isInterrupting() { return isInterrupting; } public void setInterrupting(boolean isInterrupting) { this.isInterrupting = isInterrupting; } public List<FormProperty> getFormProperties() { return formProperties; } public void setFormProperties(List<FormProperty> formProperties) { this.formProperties = formProperties; } public String getValidateFormFields() { return validateFormFields; } public void setValidateFormFields(String validateFormFields) { this.validateFormFields = validateFormFields;
} @Override public StartEvent clone() { StartEvent clone = new StartEvent(); clone.setValues(this); return clone; } public void setValues(StartEvent otherEvent) { super.setValues(otherEvent); setInitiator(otherEvent.getInitiator()); setFormKey(otherEvent.getFormKey()); setSameDeployment(otherEvent.isInterrupting); setInterrupting(otherEvent.isInterrupting); setValidateFormFields(otherEvent.validateFormFields); formProperties = new ArrayList<>(); if (otherEvent.getFormProperties() != null && !otherEvent.getFormProperties().isEmpty()) { for (FormProperty property : otherEvent.getFormProperties()) { formProperties.add(property.clone()); } } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\StartEvent.java
1
请在Spring Boot框架中完成以下Java代码
public void reportProcessed(HousekeeperTaskType taskType, ToHousekeeperServiceMsg msg, long timing) { HousekeeperStats stats = this.stats.get(taskType); if (msg.getTask().getErrorsCount() == 0) { stats.getProcessedCounter().increment(); } else { stats.getReprocessedCounter().increment(); } stats.getProcessingTimer().record(timing); } public void reportFailure(HousekeeperTaskType taskType, ToHousekeeperServiceMsg msg) { HousekeeperStats stats = this.stats.get(taskType); if (msg.getTask().getErrorsCount() == 0) { stats.getFailedProcessingCounter().increment(); } else { stats.getFailedReprocessingCounter().increment(); } } @Getter static class HousekeeperStats { private final HousekeeperTaskType taskType; private final List<StatsCounter> counters = new ArrayList<>(); private final StatsCounter processedCounter; private final StatsCounter failedProcessingCounter; private final StatsCounter reprocessedCounter; private final StatsCounter failedReprocessingCounter;
private final StatsTimer processingTimer; public HousekeeperStats(HousekeeperTaskType taskType, StatsFactory statsFactory) { this.taskType = taskType; this.processedCounter = register("processed", statsFactory); this.failedProcessingCounter = register("failedProcessing", statsFactory); this.reprocessedCounter = register("reprocessed", statsFactory); this.failedReprocessingCounter = register("failedReprocessing", statsFactory); this.processingTimer = statsFactory.createStatsTimer(StatsType.HOUSEKEEPER.getName(), "processingTime", "taskType", taskType.name()); } private StatsCounter register(String statsName, StatsFactory statsFactory) { StatsCounter counter = statsFactory.createStatsCounter(StatsType.HOUSEKEEPER.getName(), statsName, "taskType", taskType.name()); counters.add(counter); return counter; } public void reset() { counters.forEach(DefaultCounter::clear); processingTimer.reset(); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\housekeeper\stats\HousekeeperStatsService.java
2
请完成以下Java代码
public HUPPOrderIssueProducer targetOrderBOMLine(@NonNull final I_PP_Order_BOMLine targetOrderBOMLine) { return targetOrderBOMLines(ImmutableList.of(targetOrderBOMLine)); } public HUPPOrderIssueProducer targetOrderBOMLine(@NonNull final PPOrderBOMLineId targetOrderBOMLineId) { final I_PP_Order_BOMLine targetOrderBOMLine = ppOrderBOMsRepo.getOrderBOMLineById(targetOrderBOMLineId); return targetOrderBOMLine(targetOrderBOMLine); } public HUPPOrderIssueProducer fixedQtyToIssue(@Nullable final Quantity fixedQtyToIssue) { this.fixedQtyToIssue = fixedQtyToIssue; return this; } public HUPPOrderIssueProducer considerIssueMethodForQtyToIssueCalculation(final boolean considerIssueMethodForQtyToIssueCalculation) { this.considerIssueMethodForQtyToIssueCalculation = considerIssueMethodForQtyToIssueCalculation; return this; } public HUPPOrderIssueProducer processCandidates(@NonNull final ProcessIssueCandidatesPolicy processCandidatesPolicy) { this.processCandidatesPolicy = processCandidatesPolicy; return this; } private boolean isProcessCandidates() { final ProcessIssueCandidatesPolicy processCandidatesPolicy = this.processCandidatesPolicy; if (ProcessIssueCandidatesPolicy.NEVER.equals(processCandidatesPolicy)) { return false; } else if (ProcessIssueCandidatesPolicy.ALWAYS.equals(processCandidatesPolicy)) { return true; } else if (ProcessIssueCandidatesPolicy.IF_ORDER_PLANNING_STATUS_IS_COMPLETE.equals(processCandidatesPolicy)) { final I_PP_Order ppOrder = getPpOrder(); final PPOrderPlanningStatus orderPlanningStatus = PPOrderPlanningStatus.ofCode(ppOrder.getPlanningStatus()); return PPOrderPlanningStatus.COMPLETE.equals(orderPlanningStatus);
} else { throw new AdempiereException("Unknown processCandidatesPolicy: " + processCandidatesPolicy); } } public HUPPOrderIssueProducer changeHUStatusToIssued(final boolean changeHUStatusToIssued) { this.changeHUStatusToIssued = changeHUStatusToIssued; return this; } public HUPPOrderIssueProducer generatedBy(final IssueCandidateGeneratedBy generatedBy) { this.generatedBy = generatedBy; return this; } public HUPPOrderIssueProducer failIfIssueOnlyForReceived(final boolean fail) { this.failIfIssueOnlyForReceived = fail; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\HUPPOrderIssueProducer.java
1
请完成以下Java代码
public class Comment { private String author; private String message; private String timestamp; public Comment(String author, String message, String timestamp) { this.author = author; this.message = message; this.timestamp = timestamp; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message;
} public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } @Override public String toString() { return "Comment{" + "author='" + author + '\'' + ", message='" + message + '\'' + ", timestamp='" + timestamp + '\'' + '}'; } }
repos\spring-boot-master\webflux-thymeleaf-serversentevent\src\main\java\com\mkyong\reactive\model\Comment.java
1
请完成以下Java代码
public Integer getStar() { return star; } public void setStar(Integer star) { this.star = star; } public String getMemberIp() { return memberIp; } public void setMemberIp(String memberIp) { this.memberIp = memberIp; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Integer getShowStatus() { return showStatus; } public void setShowStatus(Integer showStatus) { this.showStatus = showStatus; } public String getProductAttribute() { return productAttribute; } public void setProductAttribute(String productAttribute) { this.productAttribute = productAttribute; } public Integer getCollectCouont() { return collectCouont; } public void setCollectCouont(Integer collectCouont) { this.collectCouont = collectCouont; } public Integer getReadCount() { return readCount; } public void setReadCount(Integer readCount) { this.readCount = readCount; } public String getPics() { return pics; } public void setPics(String pics) { this.pics = pics; }
public String getMemberIcon() { return memberIcon; } public void setMemberIcon(String memberIcon) { this.memberIcon = memberIcon; } public Integer getReplayCount() { return replayCount; } public void setReplayCount(Integer replayCount) { this.replayCount = replayCount; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productId=").append(productId); sb.append(", memberNickName=").append(memberNickName); sb.append(", productName=").append(productName); sb.append(", star=").append(star); sb.append(", memberIp=").append(memberIp); sb.append(", createTime=").append(createTime); sb.append(", showStatus=").append(showStatus); sb.append(", productAttribute=").append(productAttribute); sb.append(", collectCouont=").append(collectCouont); sb.append(", readCount=").append(readCount); sb.append(", pics=").append(pics); sb.append(", memberIcon=").append(memberIcon); sb.append(", replayCount=").append(replayCount); sb.append(", content=").append(content); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsComment.java
1
请完成以下Java代码
public String attribute(String name) { if (attributeMap.containsKey(name)) { return attributeMap.get(name).getValue(); } return null; } public Set<String> attributes() { return attributeMap.keySet(); } public String attributeNS(Namespace namespace, String name) { String attribute = attribute(composeMapKey(namespace.getNamespaceUri(), name)); if (attribute == null && namespace.hasAlternativeUri()) { attribute = attribute(composeMapKey(namespace.getAlternativeUri(), name)); } return attribute; } public String attribute(String name, String defaultValue) { if (attributeMap.containsKey(name)) { return attributeMap.get(name).getValue(); } return defaultValue; } public String attributeNS(Namespace namespace, String name, String defaultValue) { String attribute = attribute(composeMapKey(namespace.getNamespaceUri(), name)); if (attribute == null && namespace.hasAlternativeUri()) { attribute = attribute(composeMapKey(namespace.getAlternativeUri(), name)); } if (attribute == null) { return defaultValue; } return attribute; } protected String composeMapKey(String attributeUri, String attributeName) { StringBuilder strb = new StringBuilder(); if (attributeUri != null && !attributeUri.equals("")) { strb.append(attributeUri); strb.append(":"); } strb.append(attributeName); return strb.toString(); } public List<Element> elements() { return elements; } public String toString() { return "<"+tagName+"..."; } public String getUri() { return uri; } public String getTagName() {
return tagName; } public int getLine() { return line; } public int getColumn() { return column; } /** * Due to the nature of SAX parsing, sometimes the characters of an element * are not processed at once. So instead of a setText operation, we need * to have an appendText operation. */ public void appendText(String text) { this.text.append(text); } public String getText() { return text.toString(); } /** * allows to recursively collect the ids of all elements in the tree. */ public void collectIds(List<String> ids) { ids.add(attribute("id")); for (Element child : elements) { child.collectIds(ids); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\xml\Element.java
1
请完成以下Java代码
public int getC_DataImport_Run_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DataImport_Run_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Beleg fertig stellen. @param IsDocComplete Legt fest, ob ggf erstellte Belege (z.B. Produktionsaufträge) auch direkt automatisch fertig gestellt werden sollen. */ @Override public void setIsDocComplete (boolean IsDocComplete) { set_Value (COLUMNNAME_IsDocComplete, Boolean.valueOf(IsDocComplete)); }
/** Get Beleg fertig stellen. @return Legt fest, ob ggf erstellte Belege (z.B. Produktionsaufträge) auch direkt automatisch fertig gestellt werden sollen. */ @Override public boolean isDocComplete () { Object oo = get_Value(COLUMNNAME_IsDocComplete); 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_C_DataImport_Run.java
1
请在Spring Boot框架中完成以下Java代码
public class CallOrderSummaryData { @NonNull OrderId orderId; @NonNull OrderLineId orderLineId; @NonNull FlatrateTermId flatrateTermId; @NonNull ProductId productId; @NonNull UomId uomId; @NonNull BigDecimal qtyEntered; @With
@NonNull @Builder.Default BigDecimal qtyDelivered = BigDecimal.ZERO; @With @NonNull @Builder.Default BigDecimal qtyInvoiced = BigDecimal.ZERO; @Nullable String poReference; @Nullable AttributeSetInstanceId attributeSetInstanceId; boolean isActive; @NonNull SOTrx soTrx; }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\callorder\summary\model\CallOrderSummaryData.java
2
请完成以下Java代码
public static Builder builder() { return new Builder(); } private static final ImmutableDocumentFilterDescriptorsProvider EMPTY = new ImmutableDocumentFilterDescriptorsProvider(); private final ImmutableMap<String, DocumentFilterDescriptor> descriptorsByFilterId; private ImmutableDocumentFilterDescriptorsProvider(final List<DocumentFilterDescriptor> descriptors) { descriptorsByFilterId = Maps.uniqueIndex(descriptors, DocumentFilterDescriptor::getFilterId); } private ImmutableDocumentFilterDescriptorsProvider() { descriptorsByFilterId = ImmutableMap.of(); } @Override public String toString() { return MoreObjects.toStringHelper(this) .addValue(descriptorsByFilterId.keySet()) .toString(); } @Override public Collection<DocumentFilterDescriptor> getAll() { return descriptorsByFilterId.values(); } @Override public DocumentFilterDescriptor getByFilterIdOrNull(final String filterId) { return descriptorsByFilterId.get(filterId); } // // // // // public static class Builder { private final List<DocumentFilterDescriptor> descriptors = new ArrayList<>(); private Builder() { } public ImmutableDocumentFilterDescriptorsProvider build() { if (descriptors.isEmpty())
{ return EMPTY; } return new ImmutableDocumentFilterDescriptorsProvider(descriptors); } public Builder addDescriptor(@NonNull final DocumentFilterDescriptor descriptor) { descriptors.add(descriptor); return this; } public Builder addDescriptors(@NonNull final Collection<DocumentFilterDescriptor> descriptors) { if (descriptors.isEmpty()) { return this; } this.descriptors.addAll(descriptors); return this; } public Builder addDescriptors(@NonNull final DocumentFilterDescriptorsProvider provider) { addDescriptors(provider.getAll()); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\provider\ImmutableDocumentFilterDescriptorsProvider.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable Saml2MessageBinding getBinding() { return this.binding; } public void setBinding(@Nullable Saml2MessageBinding binding) { this.binding = binding; } public @Nullable Boolean getSignRequest() { return this.signRequest; } public void setSignRequest(@Nullable Boolean signRequest) { this.signRequest = signRequest; } } /** * Verification details for an Identity Provider. */ public static class Verification { /** * Credentials used for verification of incoming SAML messages. */ private List<Credential> credentials = new ArrayList<>(); public List<Credential> getCredentials() { return this.credentials; } public void setCredentials(List<Credential> credentials) { this.credentials = credentials; } public static class Credential { /** * Locations of the X.509 certificate used for verification of incoming * SAML messages. */ private @Nullable Resource certificate; public @Nullable Resource getCertificateLocation() { return this.certificate; } public void setCertificateLocation(@Nullable Resource certificate) { this.certificate = certificate; } } } } /** * Single logout details. */ public static class Singlelogout {
/** * Location where SAML2 LogoutRequest gets sent to. */ private @Nullable String url; /** * Location where SAML2 LogoutResponse gets sent to. */ private @Nullable String responseUrl; /** * Whether to redirect or post logout requests. */ private @Nullable Saml2MessageBinding binding; public @Nullable String getUrl() { return this.url; } public void setUrl(@Nullable String url) { this.url = url; } public @Nullable String getResponseUrl() { return this.responseUrl; } public void setResponseUrl(@Nullable String responseUrl) { this.responseUrl = responseUrl; } public @Nullable Saml2MessageBinding getBinding() { return this.binding; } public void setBinding(@Nullable Saml2MessageBinding binding) { this.binding = binding; } } }
repos\spring-boot-4.0.1\module\spring-boot-security-saml2\src\main\java\org\springframework\boot\security\saml2\autoconfigure\Saml2RelyingPartyProperties.java
2
请完成以下Spring Boot application配置
cloud.aws.credentials.accessKey=YourAccessKey cloud.aws.credentials.secretKey=YourSecretKey cloud.aws.region.static=us-east-1 cloud.aws.rds.spring-cloud-test-db.password=se3retpass # These 3 properties are optional cloud.aws.rds.spring-cloud-test-db.username=testuser cloud.aws.rds.spring-cloud-test-db.re
adReplicaSupport=true cloud.aws.rds.spring-cloud-test-db.databaseName=test # Disable auto cloudformation cloud.aws.stack.auto=false
repos\tutorials-master\spring-cloud-modules\spring-cloud-aws\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public void addArg(String key, String value) { this.args.put(key, value); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PredicateProperties that = (PredicateProperties) o; return Objects.equals(name, that.name) && Objects.equals(args, that.args); }
@Override public int hashCode() { return Objects.hash(name, args); } @Override public String toString() { final StringBuilder sb = new StringBuilder("PredicateDefinition{"); sb.append("name='").append(name).append('\''); sb.append(", args=").append(args); sb.append('}'); return sb.toString(); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\config\PredicateProperties.java
2
请在Spring Boot框架中完成以下Java代码
public class RestTemplateRetryService { private final RestTemplate restTemplate; private int maxRetries = 3; private long retryDelay = 2000; public RestTemplateRetryService(RestTemplate restTemplate) { this.restTemplate = restTemplate; } public String makeRequestWithRetry(String url) { int attempt = 0; while (attempt < maxRetries) { try { return restTemplate.getForObject(url, String.class); } catch (ResourceAccessException e) { attempt++; if (attempt >= maxRetries) { throw new RuntimeException( "Failed after " + maxRetries + " attempts", e); } try {
Thread.sleep(retryDelay); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RuntimeException("Retry interrupted", ie); } } } throw new RuntimeException("Unexpected error in retry logic"); } public void setMaxRetries(int maxRetries) { this.maxRetries = maxRetries; } public void setRetryDelay(long retryDelay) { this.retryDelay = retryDelay; } }
repos\tutorials-master\spring-boot-modules\spring-boot-retries\src\main\java\com\baeldung\retries\service\RestTemplateRetryService.java
2
请完成以下Java代码
public Integer getMinAge() { return minAge; } public void setMinAge(Integer minAge) { this.minAge = minAge; } public Integer getMaxAge() { return maxAge; } public void setMaxAge(Integer maxAge) { this.maxAge = maxAge; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; }
public String getIntroduction() { return introduction; } public void setIntroduction(String introduction) { this.introduction = introduction; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 3-4 课: Spring Data JPA 的基本使用\spring-boot-jpa\src\main\java\com\neo\param\UserDetailParam.java
1
请完成以下Java代码
public PersonIdentificationSchemeName1Choice createPersonIdentificationSchemeName1Choice() { return new PersonIdentificationSchemeName1Choice(); } /** * Create an instance of {@link RestrictedPersonIdentificationSchemeNameSEPA } * */ public RestrictedPersonIdentificationSchemeNameSEPA createRestrictedPersonIdentificationSchemeNameSEPA() { return new RestrictedPersonIdentificationSchemeNameSEPA(); } /** * Create an instance of {@link PostalAddressSEPA } * */ public PostalAddressSEPA createPostalAddressSEPA() { return new PostalAddressSEPA(); } /** * Create an instance of {@link PurposeSEPA } * */ public PurposeSEPA createPurposeSEPA() { return new PurposeSEPA(); } /** * Create an instance of {@link RemittanceInformationSEPA1Choice } * */ public RemittanceInformationSEPA1Choice createRemittanceInformationSEPA1Choice() { return new RemittanceInformationSEPA1Choice(); } /** * Create an instance of {@link ServiceLevelSEPA } * */ public ServiceLevelSEPA createServiceLevelSEPA() { return new ServiceLevelSEPA(); }
/** * Create an instance of {@link StructuredRemittanceInformationSEPA1 } * */ public StructuredRemittanceInformationSEPA1 createStructuredRemittanceInformationSEPA1() { return new StructuredRemittanceInformationSEPA1(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Document }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link Document }{@code >} */ @XmlElementDecl(namespace = "urn:iso:std:iso:20022:tech:xsd:pain.008.003.02", name = "Document") public JAXBElement<Document> createDocument(Document value) { return new JAXBElement<Document>(_Document_QNAME, Document.class, null, value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\ObjectFactory.java
1
请完成以下Java代码
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Budget Control. @param GL_BudgetControl_ID Budget Control */ public void setGL_BudgetControl_ID (int GL_BudgetControl_ID) { if (GL_BudgetControl_ID < 1) set_ValueNoCheck (COLUMNNAME_GL_BudgetControl_ID, null); else set_ValueNoCheck (COLUMNNAME_GL_BudgetControl_ID, Integer.valueOf(GL_BudgetControl_ID)); } /** Get Budget Control. @return Budget Control */ public int getGL_BudgetControl_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_BudgetControl_ID); if (ii == null) return 0; return ii.intValue(); } public I_GL_Budget getGL_Budget() throws RuntimeException { return (I_GL_Budget)MTable.get(getCtx(), I_GL_Budget.Table_Name) .getPO(getGL_Budget_ID(), get_TrxName()); } /** Set Budget. @param GL_Budget_ID General Ledger Budget */ public void setGL_Budget_ID (int GL_Budget_ID) { if (GL_Budget_ID < 1) set_Value (COLUMNNAME_GL_Budget_ID, null); else set_Value (COLUMNNAME_GL_Budget_ID, Integer.valueOf(GL_Budget_ID)); } /** Get Budget. @return General Ledger Budget */ public int getGL_Budget_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_Budget_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); }
/** Set Before Approval. @param IsBeforeApproval The Check is before the (manual) approval */ public void setIsBeforeApproval (boolean IsBeforeApproval) { set_Value (COLUMNNAME_IsBeforeApproval, Boolean.valueOf(IsBeforeApproval)); } /** Get Before Approval. @return The Check is before the (manual) approval */ public boolean isBeforeApproval () { Object oo = get_Value(COLUMNNAME_IsBeforeApproval); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_BudgetControl.java
1
请完成以下Java代码
public static HalVariableValue fromVariableInstance(VariableInstance variableInstance) { HalVariableValue dto = new HalVariableValue(); VariableValueDto variableValueDto = VariableValueDto.fromTypedValue(variableInstance.getTypedValue()); dto.name = variableInstance.getName(); dto.value = variableValueDto.getValue(); dto.type = variableValueDto.getType(); dto.valueInfo = variableValueDto.getValueInfo(); return dto; } public String getName() { return name;
} public Object getValue() { return value; } public String getType() { return type; } public Map<String, Object> getValueInfo() { return valueInfo; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\HalVariableValue.java
1
请完成以下Java代码
public final class WFProcessId { @JsonCreator public static WFProcessId ofString(@NonNull final String string) { final int idx = string.indexOf(SEPARATOR); if (idx <= 0) { throw new AdempiereException("Invalid format: " + string); } final MobileApplicationId applicationId = MobileApplicationId.ofString(string.substring(0, idx)); final String idPart = string.substring(idx + 1); if (idPart.isEmpty()) { throw new AdempiereException("Invalid format: " + string); } return new WFProcessId(applicationId, idPart); } public static WFProcessId ofIdPart(@NonNull final MobileApplicationId applicationId, @NonNull final RepoIdAware idPart) { return new WFProcessId(applicationId, String.valueOf(idPart.getRepoId())); } private static final String SEPARATOR = "-"; @Getter private final MobileApplicationId applicationId; private final String idPart; private transient String stringRepresentation = null; private WFProcessId( @NonNull final MobileApplicationId applicationId, @NonNull final String idPart) { this.applicationId = applicationId; this.idPart = Check.assumeNotEmpty(idPart, "idPart"); } @Override @Deprecated public String toString() { return getAsString(); } @JsonValue public String getAsString() { String stringRepresentation = this.stringRepresentation; if (stringRepresentation == null) { stringRepresentation = this.stringRepresentation = applicationId.getAsString() + SEPARATOR + idPart; } return stringRepresentation; }
@Nullable public static String getAsStringOrNull(@Nullable final WFProcessId id) { return id != null ? id.getAsString() : null; } @NonNull public <ID extends RepoIdAware> ID getRepoId(@NonNull final Function<Integer, ID> idMapper) { try { final int repoIdInt = Integer.parseInt(idPart); return idMapper.apply(repoIdInt); } catch (final Exception ex) { throw new AdempiereException("Failed converting " + this + " to ID", ex); } } @NonNull public <ID extends RepoIdAware> ID getRepoIdAssumingApplicationId(@NonNull MobileApplicationId expectedApplicationId, @NonNull final Function<Integer, ID> idMapper) { assertApplicationId(expectedApplicationId); return getRepoId(idMapper); } public void assertApplicationId(@NonNull final MobileApplicationId expectedApplicationId) { if (!Objects.equals(this.applicationId, expectedApplicationId)) { throw new AdempiereException("Expected applicationId `" + expectedApplicationId + "` but was `" + this.applicationId + "`"); } } public static boolean equals(@Nullable final WFProcessId id1, @Nullable final WFProcessId id2) {return Objects.equals(id1, id2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\model\WFProcessId.java
1
请在Spring Boot框架中完成以下Java代码
public CsrfToken generateToken(HttpServletRequest request) { String id = UUID.randomUUID() .toString() .replace("-", ""); Date now = new Date(); Date exp = new Date(System.currentTimeMillis() + (1000 * 30)); // 30 seconds String token = Jwts.builder() .setId(id) .setIssuedAt(now) .setNotBefore(now) .setExpiration(exp) .signWith(SignatureAlgorithm.HS256, secret) .compact(); return new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", token); } @Override public void saveToken(CsrfToken token, HttpServletRequest request, HttpServletResponse response) { if (token == null) {
HttpSession session = request.getSession(false); if (session != null) { session.removeAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME); } } else { HttpSession session = request.getSession(); session.setAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME, token); } } @Override public CsrfToken loadToken(HttpServletRequest request) { HttpSession session = request.getSession(false); if (session == null || "GET".equals(request.getMethod())) { return null; } return (CsrfToken) session.getAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME); } }
repos\tutorials-master\security-modules\jjwt\src\main\java\io\jsonwebtoken\jjwtfun\config\JWTCsrfTokenRepository.java
2
请在Spring Boot框架中完成以下Java代码
public class OrderingPartyExtensionType { @XmlElement(name = "Department") protected String department; @XmlElement(name = "CostUnit") protected String costUnit; /** * Department of the ordering party. * * @return * possible object is * {@link String } * */ public String getDepartment() { return department; } /** * Sets the value of the department property. * * @param value * allowed object is * {@link String } * */ public void setDepartment(String value) {
this.department = value; } /** * TODO * * @return * possible object is * {@link String } * */ public String getCostUnit() { return costUnit; } /** * Sets the value of the costUnit property. * * @param value * allowed object is * {@link String } * */ public void setCostUnit(String value) { this.costUnit = value; } }
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\OrderingPartyExtensionType.java
2
请完成以下Java代码
/* package */ class FlatrateTermImportFinder { private final transient IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class); public I_AD_User findBillUser(final Properties ctx, final int bpartnerId) { final List<I_AD_User> users = bpartnerDAO.retrieveContacts(ctx, bpartnerId, ITrx.TRXNAME_ThreadInherited); if (users.isEmpty()) { return null; } else if (users.size() == 1) { return users.get(0); } else { final I_AD_User billUser = users.stream() .filter(I_AD_User::isBillToContact_Default) .sorted(Ordering.natural().onResultOf(user -> user.isBillToContact_Default() ? 0 : 1)) .findFirst().get(); if (billUser.isBillToContact_Default()) { return billUser; } else { return null; } } } public I_AD_User findDropShipUser(final Properties ctx, final int bpartnerId) { final List<I_AD_User> users = bpartnerDAO.retrieveContacts(ctx, bpartnerId, ITrx.TRXNAME_ThreadInherited); if (users.isEmpty()) { return null; } else if (users.size() == 1) { return users.get(0); } else { final I_AD_User dropShipUser = users.stream()
.filter(I_AD_User::isShipToContact_Default) .sorted(Ordering.natural().onResultOf(user -> user.isShipToContact_Default() ? 0 : 1)) .findFirst().get(); if (dropShipUser.isShipToContact_Default()) { return dropShipUser; } else { return null; } } } public I_C_BPartner_Location findBPartnerShipToLocation(final Properties ctx, final int bpartnerId) { final I_C_BPartner_Location bpLocation = bpartnerDAO.getDefaultShipToLocation(BPartnerId.ofRepoId(bpartnerId)); if (bpLocation != null && !bpLocation.isShipToDefault()) { return null; } return bpLocation; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\impexp\FlatrateTermImportFinder.java
1
请在Spring Boot框架中完成以下Java代码
public GatewayPathTagsProvider gatewayPathTagsProvider() { return new GatewayPathTagsProvider(); } @Bean public GatewayRouteTagsProvider gatewayRouteTagsProvider() { return new GatewayRouteTagsProvider(); } @Bean public PropertiesTagsProvider propertiesTagsProvider(GatewayMetricsProperties properties) { return new PropertiesTagsProvider(properties.getTags()); } @Bean @ConditionalOnBean(MeterRegistry.class) @ConditionalOnProperty(name = GatewayProperties.PREFIX + ".metrics.enabled", matchIfMissing = true) // don't use @ConditionalOnEnabledGlobalFilter as the above property may // encompass more than just the filter public GatewayMetricsFilter gatewayMetricFilter(MeterRegistry meterRegistry, List<GatewayTagsProvider> tagsProviders, GatewayMetricsProperties properties) { return new GatewayMetricsFilter(meterRegistry, tagsProviders, properties.getPrefix()); } @Bean @ConditionalOnBean(MeterRegistry.class) @ConditionalOnProperty(name = GatewayProperties.PREFIX + ".metrics.enabled", matchIfMissing = true) public RouteDefinitionMetrics routeDefinitionMetrics(MeterRegistry meterRegistry, RouteDefinitionLocator routeDefinitionLocator, GatewayMetricsProperties properties) { return new RouteDefinitionMetrics(meterRegistry, routeDefinitionLocator, properties.getPrefix()); } @Configuration(proxyBeanMethods = false) @ConditionalOnBean(ObservationRegistry.class) @ConditionalOnProperty(name = GatewayProperties.PREFIX + ".observability.enabled", matchIfMissing = true) static class ObservabilityConfiguration { @Bean
@ConditionalOnMissingBean ObservedRequestHttpHeadersFilter observedRequestHttpHeadersFilter(ObservationRegistry observationRegistry, ObjectProvider<GatewayObservationConvention> gatewayObservationConvention) { return new ObservedRequestHttpHeadersFilter(observationRegistry, gatewayObservationConvention.getIfAvailable(() -> null)); } @Bean @ConditionalOnMissingBean ObservedResponseHttpHeadersFilter observedResponseHttpHeadersFilter() { return new ObservedResponseHttpHeadersFilter(); } @Bean @Order(Ordered.HIGHEST_PRECEDENCE) ObservationClosingWebExceptionHandler observationClosingWebExceptionHandler() { return new ObservationClosingWebExceptionHandler(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\GatewayMetricsAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public RSAKey rsaKey(KeyPair keyPair) { return new RSAKey .Builder((RSAPublicKey)keyPair.getPublic()) .privateKey(keyPair.getPrivate()) .keyID(UUID.randomUUID().toString()) .build(); } @Bean public JWKSource<SecurityContext> jwkSource(RSAKey rsaKey) { var jwkSet = new JWKSet(rsaKey); return (jwkSelector, context) -> jwkSelector.select(jwkSet);
} @Bean public JwtDecoder jwtDecoder(RSAKey rsaKey) throws JOSEException { return NimbusJwtDecoder .withPublicKey(rsaKey.toRSAPublicKey()) .build(); } @Bean public JwtEncoder jwtEncoder(JWKSource<SecurityContext> jwkSource) { return new NimbusJwtEncoder(jwkSource); } }
repos\master-spring-and-spring-boot-main\71-spring-security\src\main\java\com\in28minutes\learnspringsecurity\jwt\JwtSecurityConfiguration.java
2
请完成以下Java代码
public void setHelp (final java.lang.String Help) { set_Value (COLUMNNAME_Help, Help); } @Override public java.lang.String getHelp() { return get_ValueAsString(COLUMNNAME_Help); } @Override public void setIsTranslated (final boolean IsTranslated) { set_Value (COLUMNNAME_IsTranslated, IsTranslated); } @Override public boolean isTranslated()
{ return get_ValueAsBoolean(COLUMNNAME_IsTranslated); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Process_Trl.java
1
请完成以下Java代码
private static class AggregationKey { @NonNull LocatorId locatorId; @NonNull HuId topLevelHUId; @NonNull ProductId productId; } } // // // // // private interface LUTUSpec { } @Value private static class HUPIItemProductLUTUSpec implements LUTUSpec { public static final HUPIItemProductLUTUSpec VIRTUAL = new HUPIItemProductLUTUSpec(HUPIItemProductId.VIRTUAL_HU, null); @NonNull HUPIItemProductId tuPIItemProductId;
@Nullable HuPackingInstructionsItemId luPIItemId; public static HUPIItemProductLUTUSpec topLevelTU(@NonNull HUPIItemProductId tuPIItemProductId) { return tuPIItemProductId.isVirtualHU() ? VIRTUAL : new HUPIItemProductLUTUSpec(tuPIItemProductId, null); } public static HUPIItemProductLUTUSpec lu(@NonNull HUPIItemProductId tuPIItemProductId, @NonNull HuPackingInstructionsItemId luPIItemId) { return new HUPIItemProductLUTUSpec(tuPIItemProductId, luPIItemId); } public boolean isTopLevelVHU() { return tuPIItemProductId.isVirtualHU() && luPIItemId == null; } } @Value(staticConstructor = "of") private static class PreciseTUSpec implements LUTUSpec { @NonNull HuPackingInstructionsId tuPackingInstructionsId; @NonNull Quantity qtyCUsPerTU; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\AbstractPPOrderReceiptHUProducer.java
1
请在Spring Boot框架中完成以下Java代码
public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(nullable = false, unique = true) private String username; private String password; public User() { super(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("User [id=").append(id).append(", username=").append(username).append(", password=").append(password).append("]"); return builder.toString(); } }
repos\tutorials-master\spring-security-modules\spring-security-social-login\src\main\java\com\baeldung\persistence\model\User.java
2
请完成以下Java代码
public org.eevolution.model.I_PP_Order_Node getPP_Order_Node() { return get_ValueAsPO(COLUMNNAME_PP_Order_Node_ID, org.eevolution.model.I_PP_Order_Node.class); } @Override public void setPP_Order_Node(final org.eevolution.model.I_PP_Order_Node PP_Order_Node) { set_ValueFromPO(COLUMNNAME_PP_Order_Node_ID, org.eevolution.model.I_PP_Order_Node.class, PP_Order_Node); } @Override public int getPP_Order_Node_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_Node_ID); } @Override public void setPP_Order_Node_ID(final int PP_Order_Node_ID) { if (PP_Order_Node_ID < 1) set_ValueNoCheck(COLUMNNAME_PP_Order_Node_ID, null); else set_ValueNoCheck(COLUMNNAME_PP_Order_Node_ID, PP_Order_Node_ID); } @Override public int getPP_Order_Node_Product_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_Node_Product_ID); } @Override public void setPP_Order_Node_Product_ID(final int PP_Order_Node_Product_ID) { if (PP_Order_Node_Product_ID < 1) set_ValueNoCheck(COLUMNNAME_PP_Order_Node_Product_ID, null); else set_ValueNoCheck(COLUMNNAME_PP_Order_Node_Product_ID, PP_Order_Node_Product_ID); } @Override public org.eevolution.model.I_PP_Order_Workflow getPP_Order_Workflow() { return get_ValueAsPO(COLUMNNAME_PP_Order_Workflow_ID, org.eevolution.model.I_PP_Order_Workflow.class); } @Override public void setPP_Order_Workflow(final org.eevolution.model.I_PP_Order_Workflow PP_Order_Workflow) { set_ValueFromPO(COLUMNNAME_PP_Order_Workflow_ID, org.eevolution.model.I_PP_Order_Workflow.class, PP_Order_Workflow); } @Override public int getPP_Order_Workflow_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_Workflow_ID); } @Override public void setPP_Order_Workflow_ID(final int PP_Order_Workflow_ID) {
if (PP_Order_Workflow_ID < 1) set_ValueNoCheck(COLUMNNAME_PP_Order_Workflow_ID, null); else set_ValueNoCheck(COLUMNNAME_PP_Order_Workflow_ID, PP_Order_Workflow_ID); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQty(final @Nullable BigDecimal Qty) { set_Value(COLUMNNAME_Qty, Qty); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setSeqNo(final int SeqNo) { set_Value(COLUMNNAME_SeqNo, SeqNo); } @Override public java.lang.String getSpecification() { return get_ValueAsString(COLUMNNAME_Specification); } @Override public void setSpecification(final @Nullable java.lang.String Specification) { set_Value(COLUMNNAME_Specification, Specification); } @Override public BigDecimal getYield() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Yield); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setYield(final @Nullable BigDecimal Yield) { set_Value(COLUMNNAME_Yield, Yield); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Node_Product.java
1
请完成以下Spring Boot application配置
#http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#common-application-properties #search multipart spring.servlet.multipart.ma
x-file-size=10MB spring.servlet.multipart.max-request-size=10MB
repos\spring-boot-leaning-master\2.x_42_courses\第 2-6 课:使用 Spring Boot 和 Thymeleaf 演示上传文件\spring-boot-file-upload\src\main\resources\application.properties
2
请完成以下Java代码
class AggregatedTUPackingInfo implements IHUPackingInfo { private static final Logger logger = LogManager.getLogger(AggregatedTUPackingInfo.class); private final I_M_HU aggregatedTU; private final Supplier<IHUProductStorage> huProductStorageSupplier; public AggregatedTUPackingInfo(final I_M_HU aggregatedTU) { this.aggregatedTU = aggregatedTU; huProductStorageSupplier = Suppliers.memoize(() -> { final List<IHUProductStorage> productStorages = Services.get(IHandlingUnitsBL.class) .getStorageFactory() .getStorage(aggregatedTU) .getProductStorages(); if (productStorages.size() == 1) { return productStorages.get(0); } else { return null; } }); } @Override public String toString() { return MoreObjects.toStringHelper(this).addValue(aggregatedTU).toString(); } private IHUProductStorage getHUProductStorage() { return huProductStorageSupplier.get(); } @Override public I_M_HU_PI getM_LU_HU_PI() { return null; // no LU } @Override public I_M_HU_PI getM_TU_HU_PI() { final I_M_HU_PI tuPI = Services.get(IHandlingUnitsBL.class).getEffectivePI(aggregatedTU); if(tuPI == null) { new HUException("Invalid aggregated TU. Effective PI could not be fetched; aggregatedTU=" + aggregatedTU).throwIfDeveloperModeOrLogWarningElse(logger); return null; } return tuPI; } @Override public boolean isInfiniteQtyTUsPerLU() { return false; } @Override public BigDecimal getQtyTUsPerLU() { final I_M_HU_Item parentHUItem = aggregatedTU.getM_HU_Item_Parent(); if (parentHUItem == null) { // note: shall not happen because we assume the aggregatedTU is really an aggregated TU.
new HUException("Invalid aggregated TU. Parent item is null; aggregatedTU=" + aggregatedTU).throwIfDeveloperModeOrLogWarningElse(logger); return null; } return parentHUItem.getQty(); } @Override public boolean isInfiniteQtyCUsPerTU() { return false; } @Override public BigDecimal getQtyCUsPerTU() { final IHUProductStorage huProductStorage = getHUProductStorage(); if (huProductStorage == null) { return null; } final BigDecimal qtyTUsPerLU = getQtyTUsPerLU(); if (qtyTUsPerLU == null || qtyTUsPerLU.signum() == 0) { return null; } final BigDecimal qtyCUTotal = huProductStorage.getQty().toBigDecimal(); final BigDecimal qtyCUsPerTU = qtyCUTotal.divide(qtyTUsPerLU, 0, RoundingMode.HALF_UP); return qtyCUsPerTU; } @Override public I_C_UOM getQtyCUsPerTU_UOM() { final IHUProductStorage huProductStorage = getHUProductStorage(); if (huProductStorage == null) { return null; } return huProductStorage.getC_UOM(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\util\AggregatedTUPackingInfo.java
1
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public Long getMilliseconds() { return milliseconds; } public void setMilliseconds(Long milliseconds) { this.milliseconds = milliseconds; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getValue() { return value; } public void setValue(long value) { this.value = value; }
public String getReporter() { return reporter; } public void setReporter(String reporter) { this.reporter = reporter; } public Object getPersistentState() { // immutable return MeterLogEntity.class; } @Override public Set<String> getReferencedEntityIds() { Set<String> referencedEntityIds = new HashSet<String>(); return referencedEntityIds; } @Override public Map<String, Class> getReferencedEntitiesIdAndClass() { Map<String, Class> referenceIdAndClass = new HashMap<String, Class>(); return referenceIdAndClass; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\MeterLogEntity.java
1
请在Spring Boot框架中完成以下Java代码
public class ScheduledDay { @Id @GeneratedValue private Long id; private Long employeeId; private String dayOfWeek; public ScheduledDay() { } public ScheduledDay(Long id, Long employeeId, String dayofWeek) { this.id = id; this.employeeId = employeeId; this.dayOfWeek = dayofWeek; } public Long getEmployeeId() {
return employeeId; } public void setEmployeeId(Long employeeId) { this.employeeId = employeeId; } public String getDayOfWeek() { return dayOfWeek; } public void setDayOfWeek(String dayOfWeek) { this.dayOfWeek = dayOfWeek; } }
repos\tutorials-master\persistence-modules\java-jpa-4\src\main\java\com\baeldung\jpa\sqlresultsetmapping\ScheduledDay.java
2
请完成以下Java代码
public static String buildStringRestriction(final String columnSQL, final int displayType, final Object value, final Object valueTo, final boolean isRange, final List<Object> params) { final StringBuffer where = new StringBuffer(); if (isRange) { if (value != null || valueTo != null) where.append(" ("); if (value != null) { where.append(columnSQL).append(">?"); params.add(value); } if (valueTo != null) { if (value != null) where.append(" AND "); where.append(columnSQL).append("<?"); params.add(valueTo); } if (value != null || valueTo != null) where.append(") "); } else { where.append(columnSQL).append("=?"); params.add(value); } return where.toString(); } public static String prepareSearchString(final Object value) { return prepareSearchString(value, false); } public static String prepareSearchString(final Object value, final boolean isIdentifier) { if (value == null || value.toString().length() == 0) { return null; } String valueStr; if (isIdentifier) { // metas-2009_0021_AP1_CR064: begin valueStr = ((String)value).trim(); if (!valueStr.startsWith("%")) valueStr = "%" + value;
// metas-2009_0021_AP1_CR064: end if (!valueStr.endsWith("%")) valueStr += "%"; } else { valueStr = (String)value; if (valueStr.startsWith("%")) { ; // nothing } else if (valueStr.endsWith("%")) { ; // nothing } else if (valueStr.indexOf("%") < 0) { valueStr = "%" + valueStr + "%"; } else { ; // nothing } } return valueStr; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\FindHelper.java
1
请完成以下Java代码
public void setPP_MRP_Demand_ID (int PP_MRP_Demand_ID) { if (PP_MRP_Demand_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_MRP_Demand_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_MRP_Demand_ID, Integer.valueOf(PP_MRP_Demand_ID)); } /** Get MRP Demand. @return MRP Demand */ @Override public int getPP_MRP_Demand_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_MRP_Demand_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.eevolution.model.I_PP_MRP getPP_MRP_Supply() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_PP_MRP_Supply_ID, org.eevolution.model.I_PP_MRP.class); } @Override public void setPP_MRP_Supply(org.eevolution.model.I_PP_MRP PP_MRP_Supply) { set_ValueFromPO(COLUMNNAME_PP_MRP_Supply_ID, org.eevolution.model.I_PP_MRP.class, PP_MRP_Supply); } /** Set MRP Supply. @param PP_MRP_Supply_ID MRP Supply */ @Override public void setPP_MRP_Supply_ID (int PP_MRP_Supply_ID) { if (PP_MRP_Supply_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_MRP_Supply_ID, null); else
set_ValueNoCheck (COLUMNNAME_PP_MRP_Supply_ID, Integer.valueOf(PP_MRP_Supply_ID)); } /** Get MRP Supply. @return MRP Supply */ @Override public int getPP_MRP_Supply_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_MRP_Supply_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Zugewiesene Menge. @param QtyAllocated Zugewiesene Menge */ @Override public void setQtyAllocated (java.math.BigDecimal QtyAllocated) { set_Value (COLUMNNAME_QtyAllocated, QtyAllocated); } /** Get Zugewiesene Menge. @return Zugewiesene Menge */ @Override public java.math.BigDecimal getQtyAllocated () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyAllocated); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_MRP_Alloc.java
1
请完成以下Java代码
private static boolean hasJksKeyStoreProperties(Ssl ssl) { return Ssl.isEnabled(ssl) && (ssl.getKeyStore() != null || (ssl.getKeyStoreType() != null && ssl.getKeyStoreType().equals("PKCS11"))); } private static boolean hasJksTrustStoreProperties(Ssl ssl) { return Ssl.isEnabled(ssl) && (ssl.getTrustStore() != null || (ssl.getTrustStoreType() != null && ssl.getTrustStoreType().equals("PKCS11"))); } @Override public String toString() { ToStringCreator creator = new ToStringCreator(this); creator.append("key", this.key); creator.append("protocol", this.protocol); creator.append("stores", this.stores); creator.append("options", this.options); return creator.toString(); } private static final class WebServerSslStoreBundle implements SslStoreBundle { private final @Nullable KeyStore keyStore; private final @Nullable KeyStore trustStore; private final @Nullable String keyStorePassword; private WebServerSslStoreBundle(@Nullable KeyStore keyStore, @Nullable KeyStore trustStore, @Nullable String keyStorePassword) { Assert.state(keyStore != null || trustStore != null, "SSL is enabled but no trust material is configured for the default host"); this.keyStore = keyStore; this.trustStore = trustStore; this.keyStorePassword = keyStorePassword; } @Override public @Nullable KeyStore getKeyStore() {
return this.keyStore; } @Override public @Nullable KeyStore getTrustStore() { return this.trustStore; } @Override public @Nullable String getKeyStorePassword() { return this.keyStorePassword; } @Override public String toString() { ToStringCreator creator = new ToStringCreator(this); creator.append("keyStore.type", (this.keyStore != null) ? this.keyStore.getType() : "none"); creator.append("keyStorePassword", (this.keyStorePassword != null) ? "******" : null); creator.append("trustStore.type", (this.trustStore != null) ? this.trustStore.getType() : "none"); return creator.toString(); } } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\WebServerSslBundle.java
1
请完成以下Java代码
public final class OAuth2RefreshTokenAuthenticationConverter implements AuthenticationConverter { @Nullable @Override public Authentication convert(HttpServletRequest request) { MultiValueMap<String, String> parameters = OAuth2EndpointUtils.getFormParameters(request); // grant_type (REQUIRED) String grantType = parameters.getFirst(OAuth2ParameterNames.GRANT_TYPE); if (!AuthorizationGrantType.REFRESH_TOKEN.getValue().equals(grantType)) { return null; } Authentication clientPrincipal = SecurityContextHolder.getContext().getAuthentication(); // refresh_token (REQUIRED) String refreshToken = parameters.getFirst(OAuth2ParameterNames.REFRESH_TOKEN); if (!StringUtils.hasText(refreshToken) || parameters.get(OAuth2ParameterNames.REFRESH_TOKEN).size() != 1) { OAuth2EndpointUtils.throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REFRESH_TOKEN, OAuth2EndpointUtils.ACCESS_TOKEN_REQUEST_ERROR_URI); } // scope (OPTIONAL) String scope = parameters.getFirst(OAuth2ParameterNames.SCOPE); if (StringUtils.hasText(scope) && parameters.get(OAuth2ParameterNames.SCOPE).size() != 1) { OAuth2EndpointUtils.throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.SCOPE, OAuth2EndpointUtils.ACCESS_TOKEN_REQUEST_ERROR_URI); }
Set<String> requestedScopes = null; if (StringUtils.hasText(scope)) { requestedScopes = new HashSet<>(Arrays.asList(StringUtils.delimitedListToStringArray(scope, " "))); } Map<String, Object> additionalParameters = new HashMap<>(); parameters.forEach((key, value) -> { if (!key.equals(OAuth2ParameterNames.GRANT_TYPE) && !key.equals(OAuth2ParameterNames.REFRESH_TOKEN) && !key.equals(OAuth2ParameterNames.SCOPE)) { additionalParameters.put(key, (value.size() == 1) ? value.get(0) : value.toArray(new String[0])); } }); // Validate DPoP Proof HTTP Header (if available) OAuth2EndpointUtils.validateAndAddDPoPParametersIfAvailable(request, additionalParameters); return new OAuth2RefreshTokenAuthenticationToken(refreshToken, clientPrincipal, requestedScopes, additionalParameters); } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\web\authentication\OAuth2RefreshTokenAuthenticationConverter.java
1
请完成以下Java代码
public boolean isPublic() { if (getAdditionalInfo() != null && getAdditionalInfo().has("isPublic")) { return getAdditionalInfo().get("isPublic").asBoolean(); } return false; } @JsonIgnore public ShortCustomerInfo toShortCustomerInfo() { return new ShortCustomerInfo(id, title, isPublic()); } @Override @JsonProperty(access = Access.READ_ONLY) @Schema(description = "Name of the customer. Read-only, duplicated from title for backward compatibility", example = "Company A", accessMode = Schema.AccessMode.READ_ONLY) public String getName() { return title; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Customer [title="); builder.append(title); builder.append(", tenantId="); builder.append(tenantId); builder.append(", additionalInfo="); builder.append(getAdditionalInfo()); builder.append(", country="); builder.append(country);
builder.append(", state="); builder.append(state); builder.append(", city="); builder.append(city); builder.append(", address="); builder.append(address); builder.append(", address2="); builder.append(address2); builder.append(", zip="); builder.append(zip); builder.append(", phone="); builder.append(phone); builder.append(", email="); builder.append(email); builder.append(", createdTime="); builder.append(createdTime); builder.append(", id="); builder.append(id); builder.append("]"); return builder.toString(); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\Customer.java
1
请完成以下Java代码
public void stateChanged(CallbackData callbackData) { /* * The child case instance has the execution id as callback id stored. * When the child case instance is finished, the execution of the parent process instance needs to be triggered. */ if (CaseInstanceState.TERMINATED.equals(callbackData.getNewState()) || CaseInstanceState.COMPLETED.equals(callbackData.getNewState())) { CommandContext commandContext = CommandContextUtil.getCommandContext(); CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext); CaseInstanceEntity caseInstance = cmmnEngineConfiguration.getCaseInstanceEntityManager().findById(callbackData.getInstanceId()); ProcessInstanceService processInstanceService = cmmnEngineConfiguration.getProcessInstanceService(); Map<String, Object> variables = new HashMap<>(); for (IOParameter outParameter : processInstanceService.getOutputParametersOfCaseTask(callbackData.getCallbackId())) { Object value = null; if (StringUtils.isNotEmpty(outParameter.getSourceExpression())) { Expression expression = cmmnEngineConfiguration.getExpressionManager().createExpression(outParameter.getSourceExpression().trim()); value = expression.getValue(caseInstance); } else { value = caseInstance.getVariable(outParameter.getSource()); }
String variableName = null; if (StringUtils.isNotEmpty(outParameter.getTarget())) { variableName = outParameter.getTarget(); } else if (StringUtils.isNotEmpty(outParameter.getTargetExpression())) { Object variableNameValue = cmmnEngineConfiguration.getExpressionManager().createExpression(outParameter.getTargetExpression()).getValue(caseInstance); if (variableNameValue != null) { variableName = variableNameValue.toString(); } else { LOGGER.warn("Out parameter target expression {} did not resolve to a variable name, this is most likely a programmatic error", outParameter.getTargetExpression()); } } variables.put(variableName, value); } processInstanceService.triggerCaseTask(callbackData.getCallbackId(), variables); } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\callback\ChildBpmnCaseInstanceStateChangeCallback.java
1
请完成以下Java代码
public ProcessDescriptor getProcessDescriptor(@NonNull final ProcessId processId) { final DocumentEntityDescriptor parametersDescriptor = createParametersEntityDescriptor(processId); final ProcessLayout processLayout = ProcessLayout.builder() .setProcessId(processId) .setLayoutType(layoutType) .setCaption(caption) .setDescription(description) .addElements(parametersDescriptor) .build(); return ProcessDescriptor.builder() .setProcessId(processId) .setInternalName(InternalName.ofString(actionId)) .setType(ProcessDescriptorType.Process) // .setLayout(processLayout) // .build(); } public WebuiRelatedProcessDescriptor toWebuiRelatedProcessDescriptor(final ViewAsPreconditionsContext viewContext) { final IView view = viewContext.getView(); final DocumentIdsSelection selectedDocumentIds = viewContext.getSelectedRowIds(); return WebuiRelatedProcessDescriptor.builder() .processId(ViewProcessInstancesRepository.buildProcessId(view.getViewId(), actionId)) .processCaption(caption) .processDescription(description) // .displayPlace(DisplayPlace.ViewQuickActions) .defaultQuickAction(defaultAction) // .preconditionsResolutionSupplier(() -> checkPreconditions(view, selectedDocumentIds)) // .build(); } private ProcessPreconditionsResolution checkPreconditions(final IView view, final DocumentIdsSelection selectedDocumentIds) { try { return getPreconditionsInstance().matches(view, selectedDocumentIds); } catch (final InstantiationException | IllegalAccessException ex) { throw AdempiereException.wrapIfNeeded(ex); }
} private Precondition getPreconditionsInstance() throws InstantiationException, IllegalAccessException { if (preconditionSharedInstance != null) { return preconditionSharedInstance; } return preconditionClass.newInstance(); } @NonNull public Method getViewActionMethod() { return viewActionMethod; } public ProcessInstanceResult.ResultAction convertReturnType(final Object returnValue) { return viewActionReturnTypeConverter.convert(returnValue); } @NonNull public Object[] extractMethodArguments(final IView view, final Document processParameters, final DocumentIdsSelection selectedDocumentIds) { return viewActionParamDescriptors.stream() .map(paramDesc -> paramDesc.extractArgument(view, processParameters, selectedDocumentIds)) .toArray(); } @FunctionalInterface public interface ViewActionMethodReturnTypeConverter { ProcessInstanceResult.ResultAction convert(Object returnValue); } @FunctionalInterface public interface ViewActionMethodArgumentExtractor { Object extractArgument(IView view, Document processParameters, DocumentIdsSelection selectedDocumentIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\view\ViewActionDescriptor.java
1
请完成以下Java代码
public String getCaseInstanceId() { return caseInstanceId; } public PlanItemInstance getStagePlanItemInstance() { return stagePlanItemInstance; } public String getTenantId() { return tenantId; } public Map<String, Object> getLocalVariables() { return localVariables; } public boolean hasLocalVariables() { return localVariables != null && localVariables.size() > 0; } public boolean isAddToParent() { return addToParent; } public boolean isSilentNameExpressionEvaluation() {
return silentNameExpressionEvaluation; } protected void validateData() { if (planItem == null) { throw new FlowableIllegalArgumentException("The plan item must be provided when creating a new plan item instance"); } if (caseDefinitionId == null) { throw new FlowableIllegalArgumentException("The case definition id must be provided when creating a new plan item instance"); } if (caseInstanceId == null) { throw new FlowableIllegalArgumentException("The case instance id must be provided when creating a new plan item instance"); } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\PlanItemInstanceEntityBuilderImpl.java
1
请完成以下Java代码
public int getAD_Client_ID() { return ad_Client_ID; } @Override public final void initialize(final ModelValidationEngine engine, final MClient client) { if (client != null) { ad_Client_ID = client.getAD_Client_ID(); } engine.addModelChange(I_C_OrderLine.Table_Name, this); engine.addModelChange(I_M_Storage.Table_Name, this); } @Override public String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID) { // nothing to do return null; } @Override public String docValidate(final PO po, final int timing) { // nothing to do return null; } @Override public String modelChange(final PO po, int type) { if (type != TYPE_BEFORE_CHANGE && type != TYPE_BEFORE_NEW)
{ return null; } if (!po.is_ValueChanged(I_C_OrderLine.COLUMNNAME_QtyReserved)) { return null; } if (po instanceof MStorage) { final MStorage st = (MStorage)po; if (st.getQtyReserved().signum() < 0) { st.setQtyReserved(BigDecimal.ZERO); // no need for the warning & stacktrace for now. // final AdempiereException ex = new AdempiereException("@" + C_OrderLine.ERR_NEGATIVE_QTY_RESERVED + "@. Setting QtyReserved to ZERO." // + "\nStorage: " + st); // logger.warn(ex.getLocalizedMessage(), ex); logger.info(Services.get(IMsgBL.class).getMsg(po.getCtx(), C_OrderLine.ERR_NEGATIVE_QTY_RESERVED.toAD_MessageWithMarkers() + ". Setting QtyReserved to ZERO." + "\nStorage: " + st)); return null; } } return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\modelvalidator\ProhibitNegativeQtyReserved.java
1
请在Spring Boot框架中完成以下Java代码
public Mono<Void> save(Mono<RouteDefinition> route) { return route.flatMap((r) -> { if (ObjectUtils.isEmpty(r.getId())) { return Mono.error(new IllegalArgumentException("id may not be empty")); } else { this.routes.put(r.getId(), r); return Mono.empty(); } }); } @Override public Mono<Void> delete(Mono<String> routeId) { return routeId.flatMap((id) -> { if (this.routes.containsKey(id)) { this.routes.remove(id); return Mono.empty(); } else {
log.warn("RouteDefinition not found: " + routeId); return Mono.empty(); // return Mono.defer(() -> { // return Mono.error(new NotFoundException("RouteDefinition not found: " + routeId)); // }); } }); } @Override public Flux<RouteDefinition> getRouteDefinitions() { Map<String, RouteDefinition> routesSafeCopy = new LinkedHashMap(this.routes); return Flux.fromIterable(routesSafeCopy.values()); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-cloud-gateway\src\main\java\org\jeecg\loader\repository\MyInMemoryRouteDefinitionRepository.java
2
请完成以下Java代码
public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<String> getTags() { return tags; } public void setTags(List<String> tags) { this.tags.addAll(tags);
} public List<SkillTag> getSkillTags() { return skillTags; } public void setSkillTags(List<SkillTag> skillTags) { this.skillTags.addAll(skillTags); } public List<KVTag> getKVTags() { return this.kvTags; } public void setKVTags(List<KVTag> kvTags) { this.kvTags.addAll(kvTags); } }
repos\tutorials-master\persistence-modules\spring-data-jpa-filtering\src\main\java\com\baeldung\inmemory\persistence\model\Student.java
1
请完成以下Java代码
public int getHR_Contract_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_Contract_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Net Days. @param NetDays Net Days in which payment is due */ public void setNetDays (int NetDays) { set_Value (COLUMNNAME_NetDays, Integer.valueOf(NetDays)); } /** Get Net Days. @return Net Days in which payment is due */ public int getNetDays () { Integer ii = (Integer)get_Value(COLUMNNAME_NetDays); if (ii == null) return 0; return ii.intValue(); } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); }
/** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Contract.java
1
请完成以下Java代码
public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); } public Double getSize() { return sizeAttribute.getValue(this); } public void setSize(Double size) { sizeAttribute.setValue(this, size); } public Boolean isBold() { return isBoldAttribute.getValue(this); } public void setBold(boolean isBold) { isBoldAttribute.setValue(this, isBold); } public Boolean isItalic() { return isItalicAttribute.getValue(this); } public void setItalic(boolean isItalic) { isItalicAttribute.setValue(this, isItalic); }
public Boolean isUnderline() { return isUnderlineAttribute.getValue(this); } public void SetUnderline(boolean isUnderline) { isUnderlineAttribute.setValue(this, isUnderline); } public Boolean isStrikeThrough() { return isStrikeTroughAttribute.getValue(this); } public void setStrikeTrough(boolean isStrikeTrough) { isStrikeTroughAttribute.setValue(this, isStrikeTrough); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\dc\FontImpl.java
1
请完成以下Java代码
private Evaluatee createEvaluationContext(@NonNull final I_C_Doc_Outbound_Log docOutboundLogRecord) { final TableRecordReference modelRef = TableRecordReference.ofOrNull(docOutboundLogRecord.getAD_Table_ID(), docOutboundLogRecord.getRecord_ID()); final Evaluatee modelCtx = modelRef != null ? TableModelLoader.instance.getPO(modelRef) : Evaluatees.empty(); return modelCtx .andComposeWith(InterfaceWrapperHelper.getEvaluatee(docOutboundLogRecord)); } @Value @Builder private static class EmailParams {
String subject; String message; private boolean isHtml() { if (Check.isEmpty(message)) { // no message => no html return false; } return message.toLowerCase().contains("<html>"); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\async\spi\impl\MailWorkpackageProcessor.java
1