instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public String toString() { return "Fact[" + m_doc + "," + getAcctSchema() + ",PostType=" + getPostingType() + "]"; } public boolean isEmpty() { return m_lines.isEmpty(); } public ImmutableList<FactLine> getLines() { return ImmutableList.copyOf(m_lines); } public void mapEachLine(final UnaryOperator<FactLine> mapper) { final ListIterator<FactLine> it = m_lines.listIterator(); while (it.hasNext()) { FactLine line = it.next(); final FactLine changedLine = mapper.apply(line); if (changedLine == null) { it.remove(); } else { it.set(changedLine); } } } @NonNull public FactLine getSingleLineByAccountId(final AccountId accountId) { final MAccount account = services.getAccountById(accountId); FactLine lineFound = null; for (FactLine line : m_lines) { if (ElementValueId.equals(line.getAccountId(), account.getElementValueId())) { if (lineFound == null) { lineFound = line; } else { throw new AdempiereException("More than one fact line found for AccountId: " + accountId.getRepoId() + ": " + lineFound + ", " + line); } } } if (lineFound == null) { throw new AdempiereException("No fact line found for AccountId: " + accountId.getRepoId() + " in " + m_lines); } return lineFound; } public void save() { final FactTrxStrategy factTrxLinesStrategy = getFactTrxLinesStrategyEffective(); if (factTrxLinesStrategy != null) { factTrxLinesStrategy .createFactTrxLines(m_lines) .forEach(this::saveNew); } else { m_lines.forEach(this::saveNew); } } private void saveNew(FactLine line) {services.saveNew(line);} private void saveNew(final FactTrxLines factTrxLines)
{ // // Case: 1 debit line, one or more credit lines if (factTrxLines.getType() == FactTrxLinesType.Debit) { final FactLine drLine = factTrxLines.getDebitLine(); saveNew(drLine); factTrxLines.forEachCreditLine(crLine -> { crLine.setCounterpart_Fact_Acct_ID(drLine.getIdNotNull()); saveNew(crLine); }); } // // Case: 1 credit line, one or more debit lines else if (factTrxLines.getType() == FactTrxLinesType.Credit) { final FactLine crLine = factTrxLines.getCreditLine(); saveNew(crLine); factTrxLines.forEachDebitLine(drLine -> { drLine.setCounterpart_Fact_Acct_ID(crLine.getIdOrNull()); saveNew(drLine); }); } // // Case: no debit lines, no credit lines else if (factTrxLines.getType() == FactTrxLinesType.EmptyOrZero) { // nothing to do } else { throw new AdempiereException("Unknown type: " + factTrxLines.getType()); } // // also save the zero lines, if they are here factTrxLines.forEachZeroLine(this::saveNew); } public void forEach(final Consumer<FactLine> consumer) { m_lines.forEach(consumer); } } // Fact
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Fact.java
1
请完成以下Java代码
public MQuery getZoomQuery() { return null; } // getZoomQuery /** * Get Data Direct from Table. Default implementation - does not requery * * @param evalCtx evaluation context to be used * @param key key * @param saveInCache save in cache for r/w * @param cacheLocal cache locally for r/o * @return value */ public NamePair getDirect(final IValidationContext evalCtx, Object key, boolean saveInCache, boolean cacheLocal) { return get(evalCtx, key); } // getDirect /** * Dispose - clear items w/o firing events */ public void dispose() { if (p_data != null) { p_data.clear(); } p_data = null; m_selectedObject = null; m_tempData = null; m_loaded = false; } // dispose /** * Wait until async Load Complete */ public void loadComplete() { } // loadComplete /** * Set lookup model as mandatory, use in loading data * @param flag */ public void setMandatory(boolean flag) { m_mandatory = flag; } /** * Is lookup model mandatory * @return boolean */ public boolean isMandatory() { return m_mandatory; } /**
* Is this lookup model populated * @return boolean */ public boolean isLoaded() { return m_loaded; } /** * Returns a list of parameters on which this lookup depends. * * Those parameters will be fetched from context on validation time. * * @return list of parameter names */ public Set<String> getParameters() { return ImmutableSet.of(); } /** * * @return evaluation context */ public IValidationContext getValidationContext() { return IValidationContext.NULL; } /** * Suggests a valid value for given value * * @param value * @return equivalent valid value or same this value is valid; if there are no suggestions, null will be returned */ public NamePair suggestValidValue(final NamePair value) { return null; } /** * Returns true if given <code>display</code> value was rendered for a not found item. * To be used together with {@link #getDisplay} methods. * * @param display * @return true if <code>display</code> contains not found markers */ public boolean isNotFoundDisplayValue(String display) { return false; } } // Lookup
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\Lookup.java
1
请在Spring Boot框架中完成以下Java代码
public class YamlFooProperties { private String name; private List<String> aliases; public String getName() { return name; } public void setName(String name) { this.name = name; } public List<String> getAliases() {
return aliases; } public void setAliases(List<String> aliases) { this.aliases = aliases; } @Override public String toString() { return "YamlFooProperties{" + "name='" + name + '\'' + ", aliases=" + aliases + '}'; } }
repos\tutorials-master\spring-boot-modules\spring-boot-properties-2\src\main\java\com\baeldung\properties\yaml\YamlFooProperties.java
2
请完成以下Java代码
static HttpGraphQlClient create(WebClient webClient) { return builder(webClient.mutate()).build(); } /** * Return a builder to initialize an {@link HttpGraphQlClient} with. */ static Builder<?> builder() { return new DefaultHttpGraphQlClientBuilder(); } /** * Variant of {@link #builder()} with a pre-configured {@code WebClient} * to mutate and customize further through the returned builder. * @param webClient the {@code WebClient} to use for sending HTTP requests */ static Builder<?> builder(WebClient webClient) { return builder(webClient.mutate()); } /** * Variant of {@link #builder()} with a pre-configured {@code WebClient} * to mutate and customize further through the returned builder. * @param webClientBuilder the {@code WebClient.Builder} to use for building the HTTP client */ static Builder<?> builder(WebClient.Builder webClientBuilder) { return new DefaultHttpGraphQlClientBuilder(webClientBuilder); } /** * Builder for the GraphQL over HTTP client. * @param <B> the builder type */ interface Builder<B extends Builder<B>> extends WebGraphQlClient.Builder<B> { /** * Customize the {@code WebClient} to use. * <p>Note that some properties of {@code WebClient.Builder} like the
* base URL, headers, and codecs can be customized through this builder. * @param webClient the function for customizing the {@code WebClient.Builder} that's used to build the HTTP client * @see #url(String) * @see #header(String, String...) * @see #codecConfigurer(Consumer) */ B webClient(Consumer<WebClient.Builder> webClient); /** * Build the {@code HttpGraphQlClient} instance. */ @Override HttpGraphQlClient build(); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\HttpGraphQlClient.java
1
请完成以下Java代码
protected Date calculateNextTimer() { BusinessCalendar businessCalendar = Context .getProcessEngineConfiguration() .getBusinessCalendarManager() .getBusinessCalendar(getBusinessCalendarName(TimerEventHandler.geCalendarNameFromConfiguration(jobHandlerConfiguration))); return businessCalendar.resolveDuedate(repeat, maxIterations); } protected String getBusinessCalendarName(String calendarName) { String businessCalendarName = CycleBusinessCalendar.NAME; if (StringUtils.isNotEmpty(calendarName)) { VariableScope execution = NoExecutionVariableScope.getSharedInstance(); if (StringUtils.isNotEmpty(this.executionId)) { execution = Context.getCommandContext().getExecutionEntityManager().findExecutionById(this.executionId); } businessCalendarName = (String) Context.getProcessEngineConfiguration().getExpressionManager().createExpression(calendarName).getValue(execution); } return businessCalendarName; }
public String getLockOwner() { return null; } public void setLockOwner(String lockOwner) { // Nothing to do } public Date getLockExpirationTime() { return null; } public void setLockExpirationTime(Date lockExpirationTime) { // Nothing to do } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TimerJobEntity.java
1
请完成以下Java代码
public void setIsReadOnlyValues (final boolean IsReadOnlyValues) { set_Value (COLUMNNAME_IsReadOnlyValues, IsReadOnlyValues); } @Override public boolean isReadOnlyValues() { return get_ValueAsBoolean(COLUMNNAME_IsReadOnlyValues); } @Override public void setIsStorageRelevant (final boolean IsStorageRelevant) { set_Value (COLUMNNAME_IsStorageRelevant, IsStorageRelevant); } @Override public boolean isStorageRelevant() { return get_ValueAsBoolean(COLUMNNAME_IsStorageRelevant); } @Override public void setM_Attribute_ID (final int M_Attribute_ID) { if (M_Attribute_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Attribute_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Attribute_ID, M_Attribute_ID); } @Override public int getM_Attribute_ID() { return get_ValueAsInt(COLUMNNAME_M_Attribute_ID); } @Override public org.compiere.model.I_M_AttributeSearch getM_AttributeSearch() { return get_ValueAsPO(COLUMNNAME_M_AttributeSearch_ID, org.compiere.model.I_M_AttributeSearch.class); } @Override public void setM_AttributeSearch(final org.compiere.model.I_M_AttributeSearch M_AttributeSearch) { set_ValueFromPO(COLUMNNAME_M_AttributeSearch_ID, org.compiere.model.I_M_AttributeSearch.class, M_AttributeSearch); } @Override public void setM_AttributeSearch_ID (final int M_AttributeSearch_ID) { if (M_AttributeSearch_ID < 1) set_Value (COLUMNNAME_M_AttributeSearch_ID, null); else set_Value (COLUMNNAME_M_AttributeSearch_ID, M_AttributeSearch_ID); } @Override public int getM_AttributeSearch_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSearch_ID); } @Override public void setName (final java.lang.String Name) {
set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPrintValue_Override (final @Nullable java.lang.String PrintValue_Override) { set_Value (COLUMNNAME_PrintValue_Override, PrintValue_Override); } @Override public java.lang.String getPrintValue_Override() { return get_ValueAsString(COLUMNNAME_PrintValue_Override); } @Override public void setValue (final java.lang.String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setValueMax (final @Nullable BigDecimal ValueMax) { set_Value (COLUMNNAME_ValueMax, ValueMax); } @Override public BigDecimal getValueMax() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueMax); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setValueMin (final @Nullable BigDecimal ValueMin) { set_Value (COLUMNNAME_ValueMin, ValueMin); } @Override public BigDecimal getValueMin() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueMin); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Attribute.java
1
请完成以下Java代码
public void setKPI_DataSource_Type (final java.lang.String KPI_DataSource_Type) { set_Value (COLUMNNAME_KPI_DataSource_Type, KPI_DataSource_Type); } @Override public java.lang.String getKPI_DataSource_Type() { return get_ValueAsString(COLUMNNAME_KPI_DataSource_Type); } @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 setSource_Table_ID (final int Source_Table_ID) { if (Source_Table_ID < 1) set_Value (COLUMNNAME_Source_Table_ID, null); else set_Value (COLUMNNAME_Source_Table_ID, Source_Table_ID); } @Override public int getSource_Table_ID() { return get_ValueAsInt(COLUMNNAME_Source_Table_ID); } @Override public void setSQL_Details_WhereClause (final @Nullable java.lang.String SQL_Details_WhereClause) { set_Value (COLUMNNAME_SQL_Details_WhereClause, SQL_Details_WhereClause); } @Override public java.lang.String getSQL_Details_WhereClause() { return get_ValueAsString(COLUMNNAME_SQL_Details_WhereClause); } @Override public void setSQL_From (final @Nullable java.lang.String SQL_From) { set_Value (COLUMNNAME_SQL_From, SQL_From); } @Override public java.lang.String getSQL_From() { return get_ValueAsString(COLUMNNAME_SQL_From); } @Override public void setSQL_GroupAndOrderBy (final @Nullable java.lang.String SQL_GroupAndOrderBy) {
set_Value (COLUMNNAME_SQL_GroupAndOrderBy, SQL_GroupAndOrderBy); } @Override public java.lang.String getSQL_GroupAndOrderBy() { return get_ValueAsString(COLUMNNAME_SQL_GroupAndOrderBy); } @Override public void setSQL_WhereClause (final @Nullable java.lang.String SQL_WhereClause) { set_Value (COLUMNNAME_SQL_WhereClause, SQL_WhereClause); } @Override public java.lang.String getSQL_WhereClause() { return get_ValueAsString(COLUMNNAME_SQL_WhereClause); } @Override public void setWEBUI_KPI_ID (final int WEBUI_KPI_ID) { if (WEBUI_KPI_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, WEBUI_KPI_ID); } @Override public int getWEBUI_KPI_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_KPI_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_KPI.java
1
请完成以下Java代码
private Jwt resolveJwtAssertion(OAuth2AuthorizationContext context) { if (!(context.getPrincipal().getPrincipal() instanceof Jwt)) { return null; } return (Jwt) context.getPrincipal().getPrincipal(); } private OAuth2AccessTokenResponse getTokenResponse(ClientRegistration clientRegistration, JwtBearerGrantRequest jwtBearerGrantRequest) { try { return this.accessTokenResponseClient.getTokenResponse(jwtBearerGrantRequest); } catch (OAuth2AuthorizationException ex) { throw new ClientAuthorizationException(ex.getError(), clientRegistration.getRegistrationId(), ex); } } private boolean hasTokenExpired(OAuth2Token token) { return this.clock.instant().isAfter(token.getExpiresAt().minus(this.clockSkew)); } /** * Sets the client used when requesting an access token credential at the Token * Endpoint for the {@code jwt-bearer} grant. * @param accessTokenResponseClient the client used when requesting an access token * credential at the Token Endpoint for the {@code jwt-bearer} grant */ public void setAccessTokenResponseClient( OAuth2AccessTokenResponseClient<JwtBearerGrantRequest> accessTokenResponseClient) { Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null"); this.accessTokenResponseClient = accessTokenResponseClient; } /** * Sets the resolver used for resolving the {@link Jwt} assertion. * @param jwtAssertionResolver the resolver used for resolving the {@link Jwt} * assertion * @since 5.7 */ public void setJwtAssertionResolver(Function<OAuth2AuthorizationContext, Jwt> jwtAssertionResolver) { Assert.notNull(jwtAssertionResolver, "jwtAssertionResolver cannot be null"); this.jwtAssertionResolver = jwtAssertionResolver; } /** * Sets the maximum acceptable clock skew, which is used when checking the * {@link OAuth2AuthorizedClient#getAccessToken() access token} expiry. The default is * 60 seconds.
* * <p> * An access token is considered expired if * {@code OAuth2AccessToken#getExpiresAt() - clockSkew} is before the current time * {@code clock#instant()}. * @param clockSkew the maximum acceptable clock skew */ public void setClockSkew(Duration clockSkew) { Assert.notNull(clockSkew, "clockSkew cannot be null"); Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0"); this.clockSkew = clockSkew; } /** * Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the access * token expiry. * @param clock the clock */ public void setClock(Clock clock) { Assert.notNull(clock, "clock cannot be null"); this.clock = clock; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\JwtBearerOAuth2AuthorizedClientProvider.java
1
请完成以下Java代码
public class GreedyAlgorithm { int currentLevel = 0; final int maxLevel = 3; SocialConnector sc; FollowersPath fp; public GreedyAlgorithm(SocialConnector sc) { super(); this.sc = sc; this.fp = new FollowersPath(); } public long findMostFollowersPath(String account) { long max = 0; SocialUser toFollow = null; List<SocialUser> followers = sc.getFollowers(account); for (SocialUser el : followers) { long followersCount = el.getFollowersCount();
if (followersCount > max) { toFollow = el; max = followersCount; } } if (currentLevel < maxLevel - 1) { currentLevel++; max += findMostFollowersPath(toFollow.getUsername()); return max; } else { return max; } } public FollowersPath getFollowers() { return fp; } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-6\src\main\java\com\baeldung\algorithms\greedy\GreedyAlgorithm.java
1
请完成以下Java代码
public Boolean isOpen() { return open; } public Boolean isDeleted() { return deleted; } public Boolean isResolved() { return resolved; } public String getAnnotation() { return annotation; } public static HistoricIncidentDto fromHistoricIncident(HistoricIncident historicIncident) { HistoricIncidentDto dto = new HistoricIncidentDto(); dto.id = historicIncident.getId(); dto.processDefinitionKey = historicIncident.getProcessDefinitionKey(); dto.processDefinitionId = historicIncident.getProcessDefinitionId(); dto.processInstanceId = historicIncident.getProcessInstanceId(); dto.executionId = historicIncident.getExecutionId(); dto.createTime = historicIncident.getCreateTime(); dto.endTime = historicIncident.getEndTime();
dto.incidentType = historicIncident.getIncidentType(); dto.failedActivityId = historicIncident.getFailedActivityId(); dto.activityId = historicIncident.getActivityId(); dto.causeIncidentId = historicIncident.getCauseIncidentId(); dto.rootCauseIncidentId = historicIncident.getRootCauseIncidentId(); dto.configuration = historicIncident.getConfiguration(); dto.historyConfiguration = historicIncident.getHistoryConfiguration(); dto.incidentMessage = historicIncident.getIncidentMessage(); dto.open = historicIncident.isOpen(); dto.deleted = historicIncident.isDeleted(); dto.resolved = historicIncident.isResolved(); dto.tenantId = historicIncident.getTenantId(); dto.jobDefinitionId = historicIncident.getJobDefinitionId(); dto.removalTime = historicIncident.getRemovalTime(); dto.rootProcessInstanceId = historicIncident.getRootProcessInstanceId(); dto.annotation = historicIncident.getAnnotation(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricIncidentDto.java
1
请完成以下Java代码
public String getISIN() { return isin; } /** * Sets the value of the isin property. * * @param value * allowed object is * {@link String } * */ public void setISIN(String value) { this.isin = value; } /** * Gets the value of the prtry property. * * @return * possible object is * {@link AlternateSecurityIdentification2 } * */
public AlternateSecurityIdentification2 getPrtry() { return prtry; } /** * Sets the value of the prtry property. * * @param value * allowed object is * {@link AlternateSecurityIdentification2 } * */ public void setPrtry(AlternateSecurityIdentification2 value) { this.prtry = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\SecurityIdentification4Choice.java
1
请在Spring Boot框架中完成以下Java代码
public Result info(@PathVariable("id") Long id) { NewsCategory newsCategory = categoryService.queryById(id); return ResultGenerator.genSuccessResult(newsCategory); } /** * 分类添加 */ @RequestMapping(value = "/categories/save", method = RequestMethod.POST) @ResponseBody public Result save(@RequestParam("categoryName") String categoryName) { if (!StringUtils.hasText(categoryName)) { return ResultGenerator.genFailResult("参数异常!"); } if (categoryService.saveCategory(categoryName)) { return ResultGenerator.genSuccessResult(); } else { return ResultGenerator.genFailResult("分类名称重复"); } } /** * 分类修改 */ @RequestMapping(value = "/categories/update", method = RequestMethod.POST) @ResponseBody public Result update(@RequestParam("categoryId") Long categoryId,
@RequestParam("categoryName") String categoryName) { if (!StringUtils.hasText(categoryName)) { return ResultGenerator.genFailResult("参数异常!"); } if (categoryService.updateCategory(categoryId, categoryName)) { return ResultGenerator.genSuccessResult(); } else { return ResultGenerator.genFailResult("分类名称重复"); } } /** * 分类删除 */ @RequestMapping(value = "/categories/delete", method = RequestMethod.POST) @ResponseBody public Result delete(@RequestBody Integer[] ids) { if (ids.length < 1) { return ResultGenerator.genFailResult("参数异常!"); } if (categoryService.deleteBatchByIds(ids)) { return ResultGenerator.genSuccessResult(); } else { return ResultGenerator.genFailResult("删除失败"); } } }
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\controller\admin\CategoryController.java
2
请完成以下Java代码
public class TablePrinter { @NonNull private final Table table; private int ident = 0; @NonNull private final HashMap<String, Integer> columnWidths = new HashMap<>(); // lazy TablePrinter(@NonNull final Table table) { this.table = table; } public TablePrinter ident(int ident) { this.ident = ident; return this; } @Override public String toString() { final ArrayList<String> header = table.getHeader(); final ArrayList<Row> rowsList = table.getRowsList(); if (header.isEmpty() || rowsList.isEmpty()) { return ""; } final TabularStringWriter writer = TabularStringWriter.builder() .ident(ident) .build(); // // Header { for (final String columnName : header) { writer.appendCell(columnName, getColumnWidth(columnName)); } writer.lineEnd(); } // // Rows { for (final Row row : rowsList) { writer.lineEnd(); for (final String columnName : header) { writer.appendCell(row.getCellValue(columnName), getColumnWidth(columnName)); } writer.lineEnd(); }
} return writer.getAsString(); } int getColumnWidth(final String columnName) { return columnWidths.computeIfAbsent(columnName, this::computeColumnWidth); } private int computeColumnWidth(final String columnName) { int maxWidth = columnName.length(); for (final Row row : table.getRowsList()) { maxWidth = Math.max(maxWidth, row.getColumnWidth(columnName)); } return maxWidth; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\text\tabular\TablePrinter.java
1
请完成以下Java代码
public AppDefinitionEntity findAppDefinitionByDeploymentAndKeyAndTenantId(String deploymentId, String appDefinitionKey, String tenantId) { return dataManager.findAppDefinitionByDeploymentAndKeyAndTenantId(deploymentId, appDefinitionKey, tenantId); } @Override public AppDefinition findAppDefinitionByKeyAndVersionAndTenantId(String appDefinitionKey, Integer appDefinitionVersion, String tenantId) { if (tenantId == null || AppEngineConfiguration.NO_TENANT_ID.equals(tenantId)) { return dataManager.findAppDefinitionByKeyAndVersion(appDefinitionKey, appDefinitionVersion); } else { return dataManager.findAppDefinitionByKeyAndVersionAndTenantId(appDefinitionKey, appDefinitionVersion, tenantId); } } @Override public void deleteAppDefinitionAndRelatedData(String appDefinitionId) { AppDefinitionEntity appDefinitionEntity = findById(appDefinitionId); delete(appDefinitionEntity); }
@Override public AppDefinitionQuery createAppDefinitionQuery() { return new AppDefinitionQueryImpl(engineConfiguration.getCommandExecutor()); } @Override public List<AppDefinition> findAppDefinitionsByQueryCriteria(AppDefinitionQuery appDefinitionQuery) { return dataManager.findAppDefinitionsByQueryCriteria((AppDefinitionQueryImpl) appDefinitionQuery); } @Override public long findAppDefinitionCountByQueryCriteria(AppDefinitionQuery appDefinitionQuery) { return dataManager.findAppDefinitionCountByQueryCriteria((AppDefinitionQueryImpl) appDefinitionQuery); } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\persistence\entity\AppDefinitionEntityManagerImpl.java
1
请完成以下Java代码
protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_M_PackageTree[") .append(get_ID()).append("]"); return sb.toString(); } public org.compiere.model.I_C_BPartner_Location getC_BPartner_Location() throws RuntimeException { return (org.compiere.model.I_C_BPartner_Location)MTable.get(getCtx(), org.compiere.model.I_C_BPartner_Location.Table_Name) .getPO(getC_BPartner_Location_ID(), get_TrxName()); } /** Set Standort. @param C_BPartner_Location_ID Identifiziert die (Liefer-) Adresse des Geschäftspartners */ public void setC_BPartner_Location_ID (int C_BPartner_Location_ID) { if (C_BPartner_Location_ID < 1) set_Value (COLUMNNAME_C_BPartner_Location_ID, null); else set_Value (COLUMNNAME_C_BPartner_Location_ID, Integer.valueOf(C_BPartner_Location_ID)); } /** Get Standort. @return Identifiziert die (Liefer-) Adresse des Geschäftspartners */ public int getC_BPartner_Location_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_Location_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Geschlossen. @param IsClosed The status is closed */ public void setIsClosed (boolean IsClosed) { set_Value (COLUMNNAME_IsClosed, Boolean.valueOf(IsClosed)); } /** Get Geschlossen. @return The status is closed */ public boolean isClosed () { Object oo = get_Value(COLUMNNAME_IsClosed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } public org.compiere.model.I_M_Package getM_Package() throws RuntimeException { return (org.compiere.model.I_M_Package)MTable.get(getCtx(), org.compiere.model.I_M_Package.Table_Name) .getPO(getM_Package_ID(), get_TrxName()); }
/** Set PackstĂĽck. @param M_Package_ID Shipment Package */ public void setM_Package_ID (int M_Package_ID) { if (M_Package_ID < 1) set_Value (COLUMNNAME_M_Package_ID, null); else set_Value (COLUMNNAME_M_Package_ID, Integer.valueOf(M_Package_ID)); } /** Get PackstĂĽck. @return Shipment Package */ public int getM_Package_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Package_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Virtual Package. @param M_PackageTree_ID Virtual Package */ public void setM_PackageTree_ID (int M_PackageTree_ID) { if (M_PackageTree_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PackageTree_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PackageTree_ID, Integer.valueOf(M_PackageTree_ID)); } /** Get Virtual Package. @return Virtual Package */ public int getM_PackageTree_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PackageTree_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\compiere\model\X_M_PackageTree.java
1
请完成以下Java代码
public PlatformTransactionManager getTransactionManager() { return transactionManager; } public void setTransactionManager(PlatformTransactionManager transactionManager) { this.transactionManager = transactionManager; } public String getDeploymentName() { return deploymentName; } public void setDeploymentName(String deploymentName) { this.deploymentName = deploymentName; } public Resource[] getDeploymentResources() { return deploymentResources; } public void setDeploymentResources(Resource[] deploymentResources) { this.deploymentResources = deploymentResources; }
public String getDeploymentTenantId() { return deploymentTenantId; } public void setDeploymentTenantId(String deploymentTenantId) { this.deploymentTenantId = deploymentTenantId; } public boolean isDeployChangedOnly() { return deployChangedOnly; } public void setDeployChangedOnly(boolean deployChangedOnly) { this.deployChangedOnly = deployChangedOnly; } }
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\SpringTransactionsProcessEngineConfiguration.java
1
请在Spring Boot框架中完成以下Java代码
public String getBrandEntityID() { return brandEntityID; } public void setBrandEntityID(String brandEntityID) { this.brandEntityID = brandEntityID; } public Integer getProdState() { return prodState; } public void setProdState(Integer prodState) { this.prodState = prodState; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getCompanyEntityID() { return companyEntityID; } public void setCompanyEntityID(String companyEntityID) { this.companyEntityID = companyEntityID; }
@Override public String toString() { return "ProdInsertReq{" + "id='" + id + '\'' + ", prodName='" + prodName + '\'' + ", marketPrice='" + marketPrice + '\'' + ", shopPrice='" + shopPrice + '\'' + ", stock=" + stock + ", sales=" + sales + ", weight='" + weight + '\'' + ", topCateEntityID='" + topCateEntityID + '\'' + ", subCategEntityID='" + subCategEntityID + '\'' + ", brandEntityID='" + brandEntityID + '\'' + ", prodState=" + prodState + ", content='" + content + '\'' + ", companyEntityID='" + companyEntityID + '\'' + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\product\ProdInsertReq.java
2
请完成以下Java代码
public boolean contains(Object object) { for (Object element : internal) { if (object.equals(element)) { return true; } } return false; } @Override public boolean containsAll(Collection<?> collection) { for (Object element : collection) if (!contains(element)) { return false; } return true; } @SuppressWarnings("unchecked") @Override public E set(int index, E element) { E oldElement = (E) internal[index]; internal[index] = element; return oldElement; } @Override public void clear() { internal = new Object[0]; } @Override public int indexOf(Object object) { for (int i = 0; i < internal.length; i++) { if (object.equals(internal[i])) { return i; } } return -1; } @Override public int lastIndexOf(Object object) { for (int i = internal.length - 1; i >= 0; i--) { if (object.equals(internal[i])) { return i; } } return -1; } @SuppressWarnings("unchecked") @Override public List<E> subList(int fromIndex, int toIndex) { Object[] temp = new Object[toIndex - fromIndex]; System.arraycopy(internal, fromIndex, temp, 0, temp.length); return (List<E>) Arrays.asList(temp); } @Override public Object[] toArray() { return Arrays.copyOf(internal, internal.length); } @SuppressWarnings("unchecked") @Override public <T> T[] toArray(T[] array) { if (array.length < internal.length) { return (T[]) Arrays.copyOf(internal, internal.length, array.getClass());
} System.arraycopy(internal, 0, array, 0, internal.length); if (array.length > internal.length) { array[internal.length] = null; } return array; } @Override public Iterator<E> iterator() { return new CustomIterator(); } @Override public ListIterator<E> listIterator() { return null; } @Override public ListIterator<E> listIterator(int index) { // ignored for brevity return null; } private class CustomIterator implements Iterator<E> { int index; @Override public boolean hasNext() { return index != internal.length; } @SuppressWarnings("unchecked") @Override public E next() { E element = (E) CustomList.this.internal[index]; index++; return element; } } }
repos\tutorials-master\core-java-modules\core-java-collections-list-7\src\main\java\com\baeldung\list\CustomList.java
1
请在Spring Boot框架中完成以下Java代码
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) throws IOException { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Map<String, MultipartFile> fileMap = multipartRequest.getFileMap(); // 错误信息 List<String> errorMessage = new ArrayList<>(); int successLines = 0, errorLines = 0; for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) { // 获取上传文件对象 MultipartFile file = entity.getValue(); ImportParams params = new ImportParams(); params.setTitleRows(2); params.setHeadRows(1); params.setNeedSave(true); try { List<QuartzJob> listQuartzJobs = ExcelImportUtil.importExcel(file.getInputStream(), QuartzJob.class, params); //add-begin-author:taoyan date:20210909 for:导入定时任务,并不会被启动和调度,需要手动点击启动,才会加入调度任务中 #2986 for(QuartzJob job: listQuartzJobs){ job.setStatus(CommonConstant.STATUS_DISABLE); } List<String> list = ImportExcelUtil.importDateSave(listQuartzJobs, IQuartzJobService.class, errorMessage,CommonConstant.SQL_INDEX_UNIQ_JOB_CLASS_NAME); //add-end-author:taoyan date:20210909 for:导入定时任务,并不会被启动和调度,需要手动点击启动,才会加入调度任务中 #2986 errorLines+=list.size(); successLines+=(listQuartzJobs.size()-errorLines); } catch (Exception e) { log.error(e.getMessage(), e); return Result.error("文件导入失败!"); } finally { try { file.getInputStream().close(); } catch (IOException e) { e.printStackTrace(); } } } return ImportExcelUtil.imporReturnRes(errorLines,successLines,errorMessage);
} /** * 立即执行 * @param id * @return */ //@RequiresRoles("admin") @RequiresPermissions("system:quartzJob:execute") @GetMapping("/execute") public Result<?> execute(@RequestParam(name = "id", required = true) String id) { QuartzJob quartzJob = quartzJobService.getById(id); if (quartzJob == null) { return Result.error("未找到对应实体"); } try { quartzJobService.execute(quartzJob); } catch (Exception e) { //e.printStackTrace(); log.info("定时任务 立即执行失败>>"+e.getMessage()); return Result.error("执行失败!"); } return Result.ok("执行成功!"); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\quartz\controller\QuartzJobController.java
2
请完成以下Java代码
public void setDefinitionRef(CaseFileItemDefinition caseFileItemDefinition) { definitionRefAttribute.setReferenceTargetElement(this, caseFileItemDefinition); } public CaseFileItem getSourceRef() { return sourceRefAttribute.getReferenceTargetElement(this); } public void setSourceRef(CaseFileItem sourceRef) { sourceRefAttribute.setReferenceTargetElement(this, sourceRef); } public Collection<CaseFileItem> getSourceRefs() { return sourceRefCollection.getReferenceTargetElements(this); } public Collection<CaseFileItem> getTargetRefs() { return targetRefCollection.getReferenceTargetElements(this); } public Children getChildren() { return childrenChild.getChild(this); } public void setChildren(Children children) { childrenChild.setChild(this, children); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CaseFileItem.class, CMMN_ELEMENT_CASE_FILE_ITEM) .namespaceUri(CMMN11_NS) .extendsType(CmmnElement.class) .instanceProvider(new ModelTypeInstanceProvider<CaseFileItem>() { public CaseFileItem newInstance(ModelTypeInstanceContext instanceContext) { return new CaseFileItemImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); multiplicityAttribute = typeBuilder.enumAttribute(CMMN_ATTRIBUTE_MULTIPLICITY, MultiplicityEnum.class) .defaultValue(MultiplicityEnum.Unspecified) .build();
definitionRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_DEFINITION_REF) .qNameAttributeReference(CaseFileItemDefinition.class) .build(); sourceRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REF) .namespace(CMMN10_NS) .idAttributeReference(CaseFileItem.class) .build(); sourceRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REFS) .idAttributeReferenceCollection(CaseFileItem.class, CmmnAttributeElementReferenceCollection.class) .build(); targetRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_TARGET_REFS) .idAttributeReferenceCollection(CaseFileItem.class, CmmnAttributeElementReferenceCollection.class) .build(); SequenceBuilder sequence = typeBuilder.sequence(); childrenChild = sequence.element(Children.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CaseFileItemImpl.java
1
请完成以下Java代码
private PrinterQueue getOrCreateQueue(final HardwarePrinter printer) { return queuesMap.computeIfAbsent(printer.getId(), k -> new PrinterQueue(printer)); } public void clear() { queuesMap.clear(); } public FrontendPrinterData toFrontendPrinterData() { return queuesMap.values() .stream() .map(PrinterQueue::toFrontendPrinterData) .collect(GuavaCollectors.collectUsingListAccumulator(FrontendPrinterData::of)); } } @RequiredArgsConstructor private static class PrinterQueue { @NonNull private final HardwarePrinter printer; @NonNull private final ArrayList<PrintingDataAndSegment> segments = new ArrayList<>(); public void add( @NonNull PrintingData printingData, @NonNull PrintingSegment segment) { Check.assumeEquals(this.printer, segment.getPrinter(), "Expected segment printer to match: {}, expected={}", segment, printer); segments.add(PrintingDataAndSegment.of(printingData, segment)); } public FrontendPrinterDataItem toFrontendPrinterData() { return FrontendPrinterDataItem.builder() .printer(printer) .filename(suggestFilename()) .data(toByteArray()) .build(); } private byte[] toByteArray() { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (final PrintingDataToPDFWriter pdfWriter = new PrintingDataToPDFWriter(baos)) { for (PrintingDataAndSegment printingDataAndSegment : segments) {
pdfWriter.addArchivePartToPDF(printingDataAndSegment.getPrintingData(), printingDataAndSegment.getSegment()); } } return baos.toByteArray(); } private String suggestFilename() { final ImmutableSet<String> filenames = segments.stream() .map(PrintingDataAndSegment::getDocumentFileName) .collect(ImmutableSet.toImmutableSet()); return filenames.size() == 1 ? filenames.iterator().next() : "report.pdf"; } } @Value(staticConstructor = "of") private static class PrintingDataAndSegment { @NonNull PrintingData printingData; @NonNull PrintingSegment segment; public String getDocumentFileName() { return printingData.getDocumentFileName(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\frontend\FrontendPrinter.java
1
请完成以下Java代码
public String modelChange(final PO po, final int typeInt) { final ModelChangeType type = ModelChangeType.valueOf(typeInt); if (InterfaceWrapperHelper.isInstanceOf(po, I_C_OrderLine.class)) { if (type.isNew() && type.isBefore() && !po.isCopying()) { final I_C_OrderLine orderLine = InterfaceWrapperHelper.create(po, I_C_OrderLine.class); updateOrderLineAddresses(orderLine); } } else if (InterfaceWrapperHelper.isInstanceOf(po, I_C_Order.class)) { final I_C_Order order = InterfaceWrapperHelper.create(po, I_C_Order.class); if (type.isBeforeSaveTrx() || (type.isBefore() && type.isNewOrChange())) { final boolean overridePricingSystem = false; orderBL.setM_PricingSystem_ID(order, overridePricingSystem); } if (type.isAfter() && type.isNewOrChange()) { // If the Price List is Changed (may be because of a PricingSystem change) // the prices in the order lines need to be updated. if (po.is_ValueChanged(I_C_Order.COLUMNNAME_M_PriceList_ID)) { final MOrder mOrder = (MOrder)po; for (final MOrderLine ol : mOrder.getLines()) { ol.setPrice(); ol.saveEx(); } } // // checking if all is okay with this order orderBL.checkForPriceList(order); } else if (type.isBefore() && type.isNewOrChange()) { // // Reset IncotermLocation if Incoterm is empty if (order.getC_Incoterms_ID() <= 0) { order.setIncotermLocation(null); } // // updating the freight cost amount, if necessary final boolean freightCostRuleChanged = po.is_ValueChanged(I_C_Order.COLUMNNAME_FreightCostRule); final FreightCostRule freightCostRule = FreightCostRule.ofCode(order.getFreightCostRule()); if (freightCostRuleChanged && freightCostRule.isNotFixPrice()) { final OrderFreightCostsService orderFreightCostService = Adempiere.getBean(OrderFreightCostsService.class); orderFreightCostService.updateFreightAmt(order); } }
} return null; } private void updateOrderLineAddresses(final I_C_OrderLine orderLine) { // bpartner address if (orderLine.getC_BPartner_Location_ID() > 0) { final String bpartnerAddress = orderLine.getBPartnerAddress(); if (Check.isBlank(bpartnerAddress)) { documentLocationBL.updateRenderedAddressAndCapturedLocation(OrderLineDocumentLocationAdapterFactory.locationAdapter(orderLine)); } } // 01717 final org.compiere.model.I_C_Order order = orderLine.getC_Order(); if (order.isDropShip()) { if (orderLine.getC_BPartner_ID() < 0) { OrderLineDocumentLocationAdapterFactory.locationAdapter(orderLine).setFromOrderHeader(order); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\modelvalidator\Order.java
1
请完成以下Java代码
public static boolean isNotEmpty(@Nullable byte[] array) { return array != null && array.length > 0; } /** * Null-safe operation to determine whether the given {@link Resource} is readable. * * @param resource {@link Resource} to evaluate. * @return a boolean value indicating whether the given {@link Resource} is readable. * @see org.springframework.core.io.Resource#isReadable() * @see org.springframework.core.io.Resource */ public static boolean isReadable(@Nullable Resource resource) { return resource != null && resource.isReadable(); } /** * Null-safe operation to determine whether the given {@link Resource} is writable. * * @param resource {@link Resource} to evaluate. * @return a boolean value indicating whether the given {@link Resource} is writable.
* @see org.springframework.core.io.WritableResource#isWritable() * @see org.springframework.core.io.WritableResource * @see org.springframework.core.io.Resource */ public static boolean isWritable(@Nullable Resource resource) { return resource instanceof WritableResource && ((WritableResource) resource).isWritable(); } /** * Null-safe method to get the {@link Resource#getDescription() description} of the given {@link Resource}. * * @param resource {@link Resource} to describe. * @return a {@link Resource#getDescription() description} of the {@link Resource}, or {@literal null} * if the {@link Resource} handle is {@literal null}. * @see org.springframework.core.io.Resource */ public static @Nullable String nullSafeGetDescription(@Nullable Resource resource) { return resource != null ? resource.getDescription() : null; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\io\support\ResourceUtils.java
1
请完成以下Java代码
public Msv3FaultInfo getAuftragsfehler() { return auftragsfehler; } /** * Sets the value of the auftragsfehler property. * * @param value * allowed object is * {@link Msv3FaultInfo } * */ public void setAuftragsfehler(Msv3FaultInfo value) { this.auftragsfehler = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the auftragsart property. * * @return * possible object is * {@link Auftragsart } * */ public Auftragsart getAuftragsart() { return auftragsart; } /** * Sets the value of the auftragsart property. * * @param value * allowed object is * {@link Auftragsart } * */ public void setAuftragsart(Auftragsart value) { this.auftragsart = value; } /** * Gets the value of the auftragskennung property. * * @return * possible object is * {@link String } * */ public String getAuftragskennung() { return auftragskennung; } /** * Sets the value of the auftragskennung property.
* * @param value * allowed object is * {@link String } * */ public void setAuftragskennung(String value) { this.auftragskennung = value; } /** * Gets the value of the gebindeId property. * * @return * possible object is * {@link String } * */ public String getGebindeId() { return gebindeId; } /** * Sets the value of the gebindeId property. * * @param value * allowed object is * {@link String } * */ public void setGebindeId(String value) { this.gebindeId = value; } /** * Gets the value of the auftragsSupportID property. * */ public int getAuftragsSupportID() { return auftragsSupportID; } /** * Sets the value of the auftragsSupportID property. * */ public void setAuftragsSupportID(int value) { this.auftragsSupportID = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\BestellungAntwortAuftrag.java
1
请完成以下Java代码
public SqlDocumentQueryBuilder setOrderBys(final DocumentQueryOrderByList orderBys) { // Don't throw exception if noSorting is true. Just do nothing. // REASON: it gives us better flexibility when this builder is handled by different methods, each of them adding stuff to it // Check.assume(!noSorting, "sorting enabled for {}", this); if (noSorting) { return this; } this.orderBys = orderBys != null ? orderBys : DocumentQueryOrderByList.EMPTY; return this; } public SqlDocumentQueryBuilder setPage(final int firstRow, final int pageLength) { this.firstRow = firstRow; this.pageLength = pageLength; return this; } private int getFirstRow() { return firstRow; } private int getPageLength() { return pageLength; } public static SqlComposedKey extractComposedKey( final DocumentId recordId, final List<? extends SqlEntityFieldBinding> keyFields) { final int count = keyFields.size(); if (count < 1) { throw new AdempiereException("Invalid composed key: " + keyFields); } final List<Object> composedKeyParts = recordId.toComposedKeyParts(); if (composedKeyParts.size() != count) { throw new AdempiereException("Invalid composed key '" + recordId + "'. Expected " + count + " parts but it has " + composedKeyParts.size());
} final ImmutableSet.Builder<String> keyColumnNames = ImmutableSet.builder(); final ImmutableMap.Builder<String, Object> values = ImmutableMap.builder(); for (int i = 0; i < count; i++) { final SqlEntityFieldBinding keyField = keyFields.get(i); final String keyColumnName = keyField.getColumnName(); keyColumnNames.add(keyColumnName); final Object valueObj = composedKeyParts.get(i); @Nullable final Object valueConv = DataTypes.convertToValueClass( keyColumnName, valueObj, keyField.getWidgetType(), keyField.getSqlValueClass(), null); if (!JSONNullValue.isNull(valueConv)) { values.put(keyColumnName, valueConv); } } return SqlComposedKey.of(keyColumnNames.build(), values.build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\SqlDocumentQueryBuilder.java
1
请完成以下Java代码
private void loadCustomDic(String customPath, boolean isCache) { if (TextUtility.isBlank(customPath)) { return; } logger.info("开始加载自定义词典:" + customPath); DoubleArrayTrie<CoreDictionary.Attribute> dat = new DoubleArrayTrie<CoreDictionary.Attribute>(); String path[] = customPath.split(";"); String mainPath = path[0]; StringBuilder combinePath = new StringBuilder(); for (String aPath : path) { combinePath.append(aPath.trim()); } File file = new File(mainPath); mainPath = file.getParent() + "/" + Math.abs(combinePath.toString().hashCode()); mainPath = mainPath.replace("\\", "/"); DynamicCustomDictionary.loadMainDictionary(mainPath, path, dat, isCache, config.normalization); } /** * 第二次维特比,可以利用前一次的结果,降低复杂度 * * @param wordNet * @return */ // private static List<Vertex> viterbiOptimal(WordNet wordNet) // { // LinkedList<Vertex> nodes[] = wordNet.getVertexes(); // LinkedList<Vertex> vertexList = new LinkedList<Vertex>(); // for (Vertex node : nodes[1]) // { // if (node.isNew) // node.updateFrom(nodes[0].getFirst()); // } // for (int i = 1; i < nodes.length - 1; ++i)
// { // LinkedList<Vertex> nodeArray = nodes[i]; // if (nodeArray == null) continue; // for (Vertex node : nodeArray) // { // if (node.from == null) continue; // if (node.isNew) // { // for (Vertex to : nodes[i + node.realWord.length()]) // { // to.updateFrom(node); // } // } // } // } // Vertex from = nodes[nodes.length - 1].getFirst(); // while (from != null) // { // vertexList.addFirst(from); // from = from.from; // } // return vertexList; // } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\Viterbi\ViterbiSegment.java
1
请完成以下Java代码
public class Source { private final String[] keys; private Source(@NonNull String[] keys) { Assert.notNull(keys, "The String array of keys must not be null"); this.keys = keys; } public void to(String key) { to(key, v -> v); } public void to(@NonNull String key, @NonNull Function<String, Object> function) { String[] keys = this.keys; Assert.state(keys.length == 1, String.format("Source size [%d] cannot be transformed as one argument", keys.length)); Map<String, String> source = getSource();
if (Arrays.stream(keys).allMatch(source::containsKey)) { getTarget().put(key, function.apply(source.get(keys[0]))); } } public void to(String key, TriFunction<String, String, String, Object> function) { String[] keys = this.keys; Assert.state(keys.length == 3, String.format("Source size [%d] cannot be consumed as three arguments", keys.length)); Map<String, String> source = getSource(); if (Arrays.stream(keys).allMatch(source::containsKey)) { getTarget().put(key, function.apply(source.get(keys[0]), source.get(keys[1]), source.get(keys[2]))); } } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-cloud\src\main\java\org\springframework\geode\cloud\bindings\MapMapper.java
1
请在Spring Boot框架中完成以下Java代码
public Channel articleHttpFeed() { List<Article> items = new ArrayList<>(); Article item1 = new Article(); item1.setLink("http://www.baeldung.com/netty-exception-handling"); item1.setTitle("Exceptions in Netty"); item1.setDescription("In this quick article, we’ll be looking at exception handling in Netty."); item1.setPublishedDate(new Date()); item1.setAuthor("Carlos"); Article item2 = new Article(); item2.setLink("http://www.baeldung.com/cockroachdb-java"); item2.setTitle("Guide to CockroachDB in Java"); item2.setDescription("This tutorial is an introductory guide to using CockroachDB with Java."); item2.setPublishedDate(new Date()); item2.setAuthor("Baeldung"); items.add(item1); items.add(item2); Channel channelData = buildChannel(items); return channelData; } private Channel buildChannel(List<Article> articles){ Channel channel = new Channel("rss_2.0"); channel.setLink("http://localhost:8080/spring-mvc-simple/rss"); channel.setTitle("Article Feed"); channel.setDescription("Article Feed Description"); channel.setPubDate(new Date()); List<Item> items = new ArrayList<>(); for (Article article : articles) { Item item = new Item();
item.setLink(article.getLink()); item.setTitle(article.getTitle()); Description description1 = new Description(); description1.setValue(article.getDescription()); item.setDescription(description1); item.setPubDate(article.getPublishedDate()); item.setAuthor(article.getAuthor()); items.add(item); } channel.setItems(items); return channel; } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics-2\src\main\java\com\baeldung\spring\controller\rss\ArticleRssController.java
2
请完成以下Java代码
private Mono<Void> validateToken(ServerWebExchange exchange) { return this.csrfTokenRepository.loadToken(exchange) .switchIfEmpty(Mono.defer(() -> Mono.error(new CsrfException("An expected CSRF token cannot be found")))) .filterWhen((expected) -> containsValidCsrfToken(exchange, expected)) .switchIfEmpty(Mono.defer(() -> Mono.error(new CsrfException("Invalid CSRF Token")))) .then(); } private Mono<Boolean> containsValidCsrfToken(ServerWebExchange exchange, CsrfToken expected) { return this.requestHandler.resolveCsrfTokenValue(exchange, expected) .map((actual) -> equalsConstantTime(actual, expected.getToken())); } private Mono<Void> continueFilterChain(ServerWebExchange exchange, WebFilterChain chain) { return Mono.defer(() -> { Mono<CsrfToken> csrfToken = csrfToken(exchange); this.requestHandler.handle(exchange, csrfToken); return chain.filter(exchange); }); } private Mono<CsrfToken> csrfToken(ServerWebExchange exchange) { return this.csrfTokenRepository.loadToken(exchange).switchIfEmpty(generateToken(exchange)); } /** * Constant time comparison to prevent against timing attacks. * @param expected * @param actual * @return */ private static boolean equalsConstantTime(String expected, String actual) { if (expected == actual) { return true; } if (expected == null || actual == null) { return false; } // Encode after ensure that the string is not null
byte[] expectedBytes = Utf8.encode(expected); byte[] actualBytes = Utf8.encode(actual); return MessageDigest.isEqual(expectedBytes, actualBytes); } private Mono<CsrfToken> generateToken(ServerWebExchange exchange) { return this.csrfTokenRepository.generateToken(exchange) .delayUntil((token) -> this.csrfTokenRepository.saveToken(exchange, token)) .cache(); } private static class DefaultRequireCsrfProtectionMatcher implements ServerWebExchangeMatcher { private static final Set<HttpMethod> ALLOWED_METHODS = new HashSet<>( Arrays.asList(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.TRACE, HttpMethod.OPTIONS)); @Override public Mono<MatchResult> matches(ServerWebExchange exchange) { return Mono.just(exchange.getRequest()) .flatMap((r) -> Mono.justOrEmpty(r.getMethod())) .filter(ALLOWED_METHODS::contains) .flatMap((m) -> MatchResult.notMatch()) .switchIfEmpty(MatchResult.match()); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\csrf\CsrfWebFilter.java
1
请完成以下Java代码
public abstract class CommonDictionaryMaker implements ISaveAble { public boolean verbose = false; /** * 语料库中的单词 */ EasyDictionary dictionary; /** * 输出词典 */ DictionaryMaker dictionaryMaker; /** * 2元文法词典 */ NGramDictionaryMaker nGramDictionaryMaker; public CommonDictionaryMaker(EasyDictionary dictionary) { nGramDictionaryMaker = new NGramDictionaryMaker(); dictionaryMaker = new DictionaryMaker(); this.dictionary = dictionary; } @Override public boolean saveTxtTo(String path) { if (dictionaryMaker.saveTxtTo(path + ".txt")) { if (nGramDictionaryMaker.saveTxtTo(path)) { return true; } } return false; } /** * 处理语料,准备词典 */ public void compute(List<List<IWord>> sentenceList) { roleTag(sentenceList); addToDictionary(sentenceList); } /** * 同compute * @param sentenceList */ public void learn(List<Sentence> sentenceList) { List<List<IWord>> s = new ArrayList<List<IWord>>(sentenceList.size()); for (Sentence sentence : sentenceList) { s.add(sentence.wordList);
} compute(s); } /** * 同compute * @param sentences */ public void learn(Sentence ... sentences) { learn(Arrays.asList(sentences)); } /** * 训练 * @param corpus 语料库路径 */ public void train(String corpus) { CorpusLoader.walk(corpus, new CorpusLoader.Handler() { @Override public void handle(Document document) { List<List<Word>> simpleSentenceList = document.getSimpleSentenceList(); List<List<IWord>> compatibleList = new LinkedList<List<IWord>>(); for (List<Word> wordList : simpleSentenceList) { compatibleList.add(new LinkedList<IWord>(wordList)); } CommonDictionaryMaker.this.compute(compatibleList); } }); } /** * 加入到词典中,允许子类自定义过滤等等,这样比较灵活 * @param sentenceList */ abstract protected void addToDictionary(List<List<IWord>> sentenceList); /** * 角色标注,如果子类要进行label的调整或增加新的首尾等等,可以在此进行 */ abstract protected void roleTag(List<List<IWord>> sentenceList); }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\CommonDictionaryMaker.java
1
请在Spring Boot框架中完成以下Java代码
public String getSpbillCreateIp() { return spbillCreateIp; } public void setSpbillCreateIp(String spbillCreateIp) { this.spbillCreateIp = spbillCreateIp; } public String getTimeStart() { return timeStart; } public void setTimeStart(String timeStart) { this.timeStart = timeStart; } public String getTimeExpire() { return timeExpire; } public void setTimeExpire(String timeExpire) { this.timeExpire = timeExpire; } public String getGoodsTag() { return goodsTag; } public void setGoodsTag(String goodsTag) { this.goodsTag = goodsTag; } public String getNotifyUrl() { return notifyUrl; } public void setNotifyUrl(String notifyUrl) { this.notifyUrl = notifyUrl; } public WeiXinTradeTypeEnum getTradeType() { return tradeType;
} public void setTradeType(WeiXinTradeTypeEnum tradeType) { this.tradeType = tradeType; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public String getLimitPay() { return limitPay; } public void setLimitPay(String limitPay) { this.limitPay = limitPay; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\entity\weixinpay\WeiXinPrePay.java
2
请完成以下Java代码
private void handlerMap() { if (instanceMap.size() <= 0) return; for (Map.Entry<String, Object> entry : instanceMap.entrySet()) { if (entry.getValue().getClass().isAnnotationPresent(Schema.class)) { Schema schema = entry.getValue().getClass().getAnnotation(Schema.class); String schemeName = schema.value(); Method[] methods = entry.getValue().getClass().getMethods(); for (Method method : methods) { if (method.isAnnotationPresent(Table.class)) { Table table = method.getAnnotation(Table.class); String tName = table.value(); CanalEntry.EventType[] events = table.event(); //未标明数据事件类型的方法不做映射 if (events.length < 1) { continue; } //同一个方法可以映射多张表 for (int i = 0; i < events.length; i++) { String path = "/" + schemeName + "/" + tName + "/" + events[i].getNumber(); handlerMap.put(path, method); logger.info("handlerMap [{}:{}]", path, method.getName()); } } else { continue; } } } else { continue; } } } public static void doEvent(String path, Document obj) throws Exception { String[] pathArray = path.split("/"); if (pathArray.length != 4) { logger.info("path 格式不正确: {}", path); return;
} Method method = handlerMap.get(path); Object schema = instanceMap.get(pathArray[1]); //查找不到映射Bean和Method不做处理 if (method == null || schema == null) { return; } try { long begin = System.currentTimeMillis(); logger.info("integrate data: {} , {}", path, obj); method.invoke(schema, new Object[]{obj}); logger.info("integrate data consume: {}ms ", System.currentTimeMillis() - begin); } catch (Exception e) { logger.error("调用组合逻辑异常", e); throw new Exception(e.getCause()); } } //获取applicationContext public static ApplicationContext getApplicationContext() { return applicationContext; } //通过name获取 Bean. public static Object getBean(String name) { return getApplicationContext().getBean(name); } //通过class获取Bean. public static <T> T getBean(Class<T> clazz) { return getApplicationContext().getBean(clazz); } //通过name,以及Clazz返回指定的Bean public static <T> T getBean(String name, Class<T> clazz) { return getApplicationContext().getBean(name, clazz); } }
repos\spring-boot-leaning-master\2.x_data\3-4 解决后期业务变动导致的数据结构不一致的问题\spring-boot-canal-mongodb-cascade\src\main\java\com\neo\util\SpringUtil.java
1
请完成以下Java代码
public class ChangePlanItemStateCmd implements Command<Void> { protected CmmnEngineConfiguration cmmnEngineConfiguration; protected ChangePlanItemStateBuilderImpl changePlanItemStateBuilder; public ChangePlanItemStateCmd(ChangePlanItemStateBuilderImpl changePlanItemStateBuilder, CmmnEngineConfiguration cmmnEngineConfiguration) { this.changePlanItemStateBuilder = changePlanItemStateBuilder; this.cmmnEngineConfiguration = cmmnEngineConfiguration; } @Override public Void execute(CommandContext commandContext) { if (changePlanItemStateBuilder.getActivatePlanItemDefinitions().size() == 0 && changePlanItemStateBuilder.getTerminatePlanItemDefinitions().size() == 0 &&
changePlanItemStateBuilder.getChangeToAvailableStatePlanItemDefinitions().size() == 0 && changePlanItemStateBuilder.getWaitingForRepetitionPlanItemDefinitions().size() == 0 && changePlanItemStateBuilder.getRemoveWaitingForRepetitionPlanItemDefinitions().size() == 0) { throw new FlowableIllegalArgumentException("No move plan item instance or (activate) plan item definition ids provided"); } else if (changePlanItemStateBuilder.getCaseInstanceId() == null) { throw new FlowableIllegalArgumentException("Case instance id is required"); } CmmnDynamicStateManager dynamicStateManager = cmmnEngineConfiguration.getDynamicStateManager(); dynamicStateManager.movePlanItemInstanceState(changePlanItemStateBuilder, commandContext); return null; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\ChangePlanItemStateCmd.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonAlbertaProductInfo { @JsonProperty("albertaProductId") @JsonInclude(JsonInclude.Include.NON_NULL) String albertaProductId; @JsonProperty("productGroupId") @JsonInclude(JsonInclude.Include.NON_NULL) @Nullable String productGroupId; @JsonProperty("additionalDescription") @JsonInclude(JsonInclude.Include.NON_NULL) String additionalDescription; @JsonProperty("size") @JsonInclude(JsonInclude.Include.NON_NULL) String size; @JsonProperty("medicalAidPositionNumber") @JsonInclude(JsonInclude.Include.NON_NULL) String medicalAidPositionNumber; @JsonProperty("inventoryType") @JsonInclude(JsonInclude.Include.NON_NULL) String inventoryType; @JsonProperty("status") @JsonInclude(JsonInclude.Include.NON_NULL) String status; @JsonProperty("assortmentType") @JsonInclude(JsonInclude.Include.NON_NULL) String assortmentType; @JsonProperty("purchaseRating") @JsonInclude(JsonInclude.Include.NON_NULL) String purchaseRating;
@JsonProperty("stars") @JsonInclude(JsonInclude.Include.NON_NULL) BigDecimal stars; @JsonProperty("pharmacyPrice") @JsonInclude(JsonInclude.Include.NON_NULL) BigDecimal pharmacyPrice; @JsonProperty("fixedPrice") @JsonInclude(JsonInclude.Include.NON_NULL) BigDecimal fixedPrice; @JsonProperty("therapyIds") @JsonInclude(JsonInclude.Include.NON_NULL) List<String> therapyIds; @JsonProperty("billableTherapies") @JsonInclude(JsonInclude.Include.NON_NULL) List<String> billableTherapies; @JsonProperty("packagingUnits") @JsonInclude(JsonInclude.Include.NON_NULL) List<JsonAlbertaPackagingUnit> packagingUnits; }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-product\src\main\java\de\metas\common\product\v2\response\alberta\JsonAlbertaProductInfo.java
2
请在Spring Boot框架中完成以下Java代码
public class MultipleCrawlerController { public static void main(String[] args) throws Exception { File crawlStorageBase = new File("src/test/resources/crawler4j"); CrawlConfig htmlConfig = new CrawlConfig(); CrawlConfig imageConfig = new CrawlConfig(); htmlConfig.setCrawlStorageFolder(new File(crawlStorageBase, "html").getAbsolutePath()); imageConfig.setCrawlStorageFolder(new File(crawlStorageBase, "image").getAbsolutePath()); imageConfig.setIncludeBinaryContentInCrawling(true); htmlConfig.setMaxPagesToFetch(500); imageConfig.setMaxPagesToFetch(1000); PageFetcher pageFetcherHtml = new PageFetcher(htmlConfig); PageFetcher pageFetcherImage = new PageFetcher(imageConfig); RobotstxtConfig robotstxtConfig = new RobotstxtConfig(); RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcherHtml); CrawlController htmlController = new CrawlController(htmlConfig, pageFetcherHtml, robotstxtServer); CrawlController imageController = new CrawlController(imageConfig, pageFetcherImage, robotstxtServer); htmlController.addSeed("https://www.baeldung.com/"); imageController.addSeed("https://www.baeldung.com/");
CrawlerStatistics stats = new CrawlerStatistics(); CrawlController.WebCrawlerFactory<HtmlCrawler> htmlFactory = () -> new HtmlCrawler(stats); File saveDir = new File("src/test/resources/crawler4j"); CrawlController.WebCrawlerFactory<ImageCrawler> imageFactory = () -> new ImageCrawler(saveDir); imageController.startNonBlocking(imageFactory, 7); htmlController.startNonBlocking(htmlFactory, 10); htmlController.waitUntilFinish(); System.out.printf("Crawled %d pages %n", stats.getProcessedPageCount()); System.out.printf("Total Number of outbound links = %d %n", stats.getTotalLinksCount()); imageController.waitUntilFinish(); System.out.printf("Image Crawler is finished."); } }
repos\tutorials-master\libraries-4\src\main\java\com\baeldung\crawler4j\MultipleCrawlerController.java
2
请完成以下Java代码
private void setContractStatusForCurrentOrder(@NonNull final I_C_Order contractOrder, @NonNull final I_C_Flatrate_Term term) { // set status for the current order final List<I_C_Flatrate_Term> terms = contractsDAO.retrieveFlatrateTermsForOrderIdLatestFirst(OrderId.ofRepoId(contractOrder.getC_Order_ID())); final boolean anyActiveTerms = terms .stream() .anyMatch(currentTerm -> term.getC_Flatrate_Term_ID() != currentTerm.getC_Flatrate_Term_ID() && subscriptionBL.isActiveTerm(currentTerm)); contractOrderService.setOrderContractStatusAndSave(contractOrder, anyActiveTerms ? I_C_Order.CONTRACTSTATUS_Active : I_C_Order.CONTRACTSTATUS_Cancelled); } private void setContractStatusForParentOrderIfNeeded(final List<I_C_Order> orders) { if (orders.size() == 1) // means that the order does not have parent { return; } final I_C_Order contractOrder = orders.get(0);
final I_C_Order parentOrder = orders.get(1); if (isActiveParentContractOrder(parentOrder, contractOrder)) { contractOrderService.setOrderContractStatusAndSave(parentOrder, I_C_Order.CONTRACTSTATUS_Active); } } private boolean isActiveParentContractOrder(@NonNull final I_C_Order parentOrder, @NonNull final I_C_Order contractOrder) { return parentOrder.getC_Order_ID() != contractOrder.getC_Order_ID() // different order from the current one && !I_C_Order.CONTRACTSTATUS_Cancelled.equals(parentOrder.getContractStatus()) // current order wasn't previously cancelled, although shall not be possible this && I_C_Order.CONTRACTSTATUS_Cancelled.equals(contractOrder.getContractStatus()); // current order was cancelled } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\order\UpdateContractOrderStatus.java
1
请完成以下Java代码
public I_AD_Table getAD_Table() throws RuntimeException { return (I_AD_Table)MTable.get(getCtx(), I_AD_Table.Table_Name) .getPO(getAD_Table_ID(), get_TrxName()); } /** Set Table. @param AD_Table_ID Database Table information */ public void setAD_Table_ID (int AD_Table_ID) { if (AD_Table_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID)); } /** Get Table. @return Database Table information */ public int getAD_Table_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Document No. @param DocumentNo Document sequence number of the document */ public void setDocumentNo (String DocumentNo) { set_ValueNoCheck (COLUMNNAME_DocumentNo, DocumentNo); }
/** Get Document No. @return Document sequence number of the document */ public String getDocumentNo () { return (String)get_Value(COLUMNNAME_DocumentNo); } /** Set Record ID. @param Record_ID Direct internal record ID */ public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Record ID. @return Direct internal record ID */ public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Sequence_Audit.java
1
请完成以下Java代码
protected static TenantId getTenantId(UUID uuid) { if (uuid != null && !uuid.equals(EntityId.NULL_UUID)) { return TenantId.fromUUID(uuid); } else { return TenantId.SYS_TENANT_ID; } } protected JsonNode toJson(Object value) { if (value != null) { return JacksonUtil.valueToTree(value); } else { return null; } } protected <T> T fromJson(JsonNode json, Class<T> type) { return JacksonUtil.convertValue(json, type); } protected String listToString(List<?> list) { if (list != null) { return StringUtils.join(list, ',');
} else { return ""; } } protected <E> List<E> listFromString(String string, Function<String, E> mappingFunction) { if (string != null) { return Arrays.stream(StringUtils.split(string, ',')) .filter(StringUtils::isNotBlank) .map(mappingFunction).collect(Collectors.toList()); } else { return Collections.emptyList(); } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\BaseSqlEntity.java
1
请在Spring Boot框架中完成以下Java代码
public ConcurrencyControlConfigurer maximumSessions(SessionLimit sessionLimit) { SessionManagementConfigurer.this.sessionLimit = sessionLimit; return this; } /** * The URL to redirect to if a user tries to access a resource and their session * has been expired due to too many sessions for the current user. The default is * to write a simple error message to the response. * @param expiredUrl the URL to redirect to * @return the {@link ConcurrencyControlConfigurer} for further customizations */ public ConcurrencyControlConfigurer expiredUrl(String expiredUrl) { SessionManagementConfigurer.this.expiredUrl = expiredUrl; return this; } /** * Determines the behaviour when an expired session is detected. * @param expiredSessionStrategy the {@link SessionInformationExpiredStrategy} to * use when an expired session is detected. * @return the {@link ConcurrencyControlConfigurer} for further customizations */ public ConcurrencyControlConfigurer expiredSessionStrategy( SessionInformationExpiredStrategy expiredSessionStrategy) { SessionManagementConfigurer.this.expiredSessionStrategy = expiredSessionStrategy; return this; } /** * If true, prevents a user from authenticating when the * {@link #maximumSessions(int)} has been reached. Otherwise (default), the user * who authenticates is allowed access and an existing user's session is expired. * The user's who's session is forcibly expired is sent to * {@link #expiredUrl(String)}. The advantage of this approach is if a user * accidentally does not log out, there is no need for an administrator to
* intervene or wait till their session expires. * @param maxSessionsPreventsLogin true to have an error at time of * authentication, else false (default) * @return the {@link ConcurrencyControlConfigurer} for further customizations */ public ConcurrencyControlConfigurer maxSessionsPreventsLogin(boolean maxSessionsPreventsLogin) { SessionManagementConfigurer.this.maxSessionsPreventsLogin = maxSessionsPreventsLogin; return this; } /** * Controls the {@link SessionRegistry} implementation used. The default is * {@link SessionRegistryImpl} which is an in memory implementation. * @param sessionRegistry the {@link SessionRegistry} to use * @return the {@link ConcurrencyControlConfigurer} for further customizations */ public ConcurrencyControlConfigurer sessionRegistry(SessionRegistry sessionRegistry) { SessionManagementConfigurer.this.sessionRegistry = sessionRegistry; return this; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\SessionManagementConfigurer.java
2
请完成以下Java代码
class AnsiString { private final Terminal terminal; private final StringBuilder value = new StringBuilder(); /** * Create a new {@link AnsiString} for the given {@link Terminal}. * @param terminal the terminal used to test if {@link Terminal#isAnsiSupported() ANSI * is supported}. */ AnsiString(Terminal terminal) { this.terminal = terminal; } /** * Append text with the given ANSI codes. * @param text the text to append * @param codes the ANSI codes * @return this string */ AnsiString append(String text, Code... codes) { if (codes.length == 0 || !isAnsiSupported()) { this.value.append(text); return this; } Ansi ansi = Ansi.ansi(); for (Code code : codes) { ansi = applyCode(ansi, code); } this.value.append(ansi.a(text).reset().toString()); return this; } private Ansi applyCode(Ansi ansi, Code code) {
if (code.isColor()) { if (code.isBackground()) { return ansi.bg(code.getColor()); } return ansi.fg(code.getColor()); } return ansi.a(code.getAttribute()); } private boolean isAnsiSupported() { return this.terminal.isAnsiSupported(); } @Override public String toString() { return this.value.toString(); } }
repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\shell\AnsiString.java
1
请在Spring Boot框架中完成以下Java代码
public class Dao<T, ID extends Serializable> implements GenericDao<T, ID> { private static final Logger logger = Logger.getLogger(Dao.class.getName()); private static final int BATCH_SIZE = 30; @PersistenceContext private EntityManager entityManager; @Override public <S extends T> void saveInBatch(Iterable<S> entities) { if(entities == null) { throw new IllegalArgumentException("The given Iterable of entities cannot be null!"); } int i = 0; Session session = entityManager.unwrap(Session.class); session.setJdbcBatchSize(BATCH_SIZE); for (S entity : entities) { entityManager.persist(entity); i++; // Flush a batch of inserts and release memory
if (i % session.getJdbcBatchSize() == 0 && i > 0) { logger.log(Level.INFO, "Flushing the EntityManager containing {0} entities ...", i); entityManager.flush(); entityManager.clear(); i = 0; } } if (i > 0) { logger.log(Level.INFO, "Flushing the remaining {0} entities ...", i); entityManager.flush(); entityManager.clear(); } } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchInsertsViaSession\src\main\java\com\bookstore\dao\Dao.java
2
请完成以下Java代码
public void replayApiRequests(@NonNull final ImmutableList<ApiRequestAudit> apiRequestAuditTimeSortedList) { apiRequestAuditTimeSortedList.forEach(this::replayActionNoFailing); } private void replayActionNoFailing(@NonNull final ApiRequestAudit apiRequestAudit) { final ApiAuditLoggable loggable = apiAuditService.createLogger(apiRequestAudit.getIdNotNull(), apiRequestAudit.getUserId()); try (final IAutoCloseable loggableRestorer = Loggables.temporarySetLoggable(loggable)) { Loggables.addLog("Replaying request!"); replayAction(apiRequestAudit); } catch (final Exception e) { loggable.addLog("Error while trying to replay the request:" + e.getMessage(), e); } finally { loggable.flush(); } } private void replayAction(@NonNull final ApiRequestAudit apiRequestAudit)
{ try { final ApiResponse apiResponse = apiAuditService.executeHttpCall(apiRequestAudit); final ApiAuditConfig apiAuditConfig = apiAuditConfigRepository.getConfigById(apiRequestAudit.getApiAuditConfigId()); apiAuditService.auditResponse(apiAuditConfig, apiResponse, apiRequestAudit); } catch (final Exception e) { apiAuditService.updateRequestStatus(Status.ERROR, apiRequestAudit); throw e; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\audit\ApiRequestReplayService.java
1
请完成以下Java代码
public class DomXmlAttributeIterable implements Iterable<SpinXmlAttribute> { protected final NodeList nodeList; protected final DomXmlDataFormat dataFormat; protected final String namespace; protected final boolean validating; public DomXmlAttributeIterable(NodeList nodeList, DomXmlDataFormat dataFormat) { this.nodeList = nodeList; this.dataFormat = dataFormat; this.namespace = null; validating = false; } public DomXmlAttributeIterable(NodeList nodeList, DomXmlDataFormat dataFormat, String namespace) { this.nodeList = nodeList; this.dataFormat = dataFormat; this.namespace = namespace; validating = true; } public Iterator<SpinXmlAttribute> iterator() { return new DomXmlNodeIterator<SpinXmlAttribute>() { private NodeList attributes = nodeList; protected int getLength() { return attributes.getLength();
} protected SpinXmlAttribute getCurrent() { if (attributes != null) { Attr attribute = (Attr) attributes.item(index); SpinXmlAttribute current = dataFormat.createAttributeWrapper(attribute); if (!validating || (current.hasNamespace(namespace))) { return current; } } return null; } }; } }
repos\camunda-bpm-platform-master\spin\dataformat-xml-dom\src\main\java\org\camunda\spin\impl\xml\dom\DomXmlAttributeIterable.java
1
请完成以下Java代码
public CostingMethod getCostingMethod() { return CostingMethod.LastInvoice; } @Override protected CostDetailCreateResult createCostForMatchInvoice_MaterialCosts(final CostDetailCreateRequest request) { final CurrentCost currentCosts = utils.getCurrentCost(request); final CostDetailPreviousAmounts previousCosts = CostDetailPreviousAmounts.of(currentCosts); final CostDetailCreateResult result = utils.createCostDetailRecordWithChangedCosts(request, previousCosts); final CostAmount amt = request.getAmt(); final Quantity qty = request.getQty(); final boolean isOutboundTrx = qty.signum() < 0; if (!isOutboundTrx) { if (qty.signum() != 0) { final CostAmount price = amt.divide(qty, currentCosts.getPrecision()); currentCosts.setCostPrice(CostPrice.ownCostPrice(price, qty.getUomId())); } else { currentCosts.addToOwnCostPrice(amt); } } currentCosts.addToCurrentQtyAndCumulate(qty, amt, utils.getQuantityUOMConverter()); utils.saveCurrentCost(currentCosts); return result; } @Override protected CostDetailCreateResult createOutboundCostDefaultImpl(final CostDetailCreateRequest request) {
final CurrentCost currentCosts = utils.getCurrentCost(request); final CostDetailPreviousAmounts previousCosts = CostDetailPreviousAmounts.of(currentCosts); final CostDetailCreateResult result = utils.createCostDetailRecordWithChangedCosts(request, previousCosts); currentCosts.addToCurrentQtyAndCumulate(request.getQty(), request.getAmt(), utils.getQuantityUOMConverter()); utils.saveCurrentCost(currentCosts); return result; } @Override public void voidCosts(final CostDetailVoidRequest request) { throw new UnsupportedOperationException(); } @Override public MoveCostsResult createMovementCosts(@NonNull final MoveCostsRequest request) { // TODO Auto-generated method stub throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\methods\LastInvoiceCostingMethodHandler.java
1
请完成以下Java代码
private static long getPartitionEndTime(long startTime, long partitionDurationMs) { return startTime + partitionDurationMs; } public List<Long> fetchPartitions(String table) { List<Long> partitions = new ArrayList<>(); List<String> partitionsTables = getJdbcTemplate().queryForList(SELECT_PARTITIONS_STMT, String.class, table); for (String partitionTableName : partitionsTables) { String partitionTsStr = partitionTableName.substring(table.length() + 1); try { partitions.add(Long.parseLong(partitionTsStr)); } catch (NumberFormatException nfe) { log.debug("Failed to parse table name: {}", partitionTableName); } } return partitions; } public long calculatePartitionStartTime(long ts, long partitionDuration) { return ts - (ts % partitionDuration); } private synchronized int getCurrentServerVersion() { if (currentServerVersion == null) {
try { currentServerVersion = getJdbcTemplate().queryForObject("SELECT current_setting('server_version_num')", Integer.class); } catch (Exception e) { log.warn("Error occurred during fetch of the server version", e); } if (currentServerVersion == null) { currentServerVersion = 0; } } return currentServerVersion; } protected JdbcTemplate getJdbcTemplate() { return jdbcTemplate; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sqlts\insert\sql\SqlPartitioningRepository.java
1
请完成以下Java代码
public void migrateProcessInstance(String processInstanceId, ProcessInstanceMigrationDocument processInstanceMigrationDocument) { commandExecutor.execute(new ProcessInstanceMigrationCmd(processInstanceId, processInstanceMigrationDocument)); } @Override public void migrateProcessInstancesOfProcessDefinition(String processDefinitionId, ProcessInstanceMigrationDocument processInstanceMigrationDocument) { commandExecutor.execute(new ProcessInstanceMigrationCmd(processInstanceMigrationDocument, processDefinitionId)); } @Override public void migrateProcessInstancesOfProcessDefinition(String processDefinitionKey, int processDefinitionVersion, String processDefinitionTenantId, ProcessInstanceMigrationDocument processInstanceMigrationDocument) { commandExecutor.execute(new ProcessInstanceMigrationCmd(processDefinitionKey, processDefinitionVersion, processDefinitionTenantId, processInstanceMigrationDocument)); } @Override
public Batch batchMigrateProcessInstancesOfProcessDefinition(String processDefinitionId, ProcessInstanceMigrationDocument processInstanceMigrationDocument) { return commandExecutor.execute(new ProcessInstanceMigrationBatchCmd(processDefinitionId, processInstanceMigrationDocument)); } @Override public Batch batchMigrateProcessInstancesOfProcessDefinition(String processDefinitionKey, int processDefinitionVersion, String processDefinitionTenantId, ProcessInstanceMigrationDocument processInstanceMigrationDocument) { return commandExecutor.execute(new ProcessInstanceMigrationBatchCmd(processDefinitionKey, processDefinitionVersion, processDefinitionTenantId, processInstanceMigrationDocument)); } @Override public ProcessInstanceBatchMigrationResult getResultsOfBatchProcessInstanceMigration(String migrationBatchId) { return commandExecutor.execute(new GetProcessInstanceMigrationBatchResultCmd(migrationBatchId)); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ProcessMigrationServiceImpl.java
1
请完成以下Java代码
public static DataEntryDetailsView cast(@NonNull final Object viewObj) { return (DataEntryDetailsView)viewObj; } @Override public LookupValuesPage getFieldTypeahead(final RowEditingContext ctx, final String fieldName, final String query) { return null; } @Override public LookupValuesList getFieldDropdown(final RowEditingContext ctx, final String fieldName) { return null;
} @Nullable @Override public String getTableNameOrNull(@Nullable final DocumentId documentId_ignored) { return I_C_Flatrate_DataEntry_Detail.Table_Name; } @Override public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors() { return processes; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\contract\flatrate\view\DataEntryDetailsView.java
1
请完成以下Java代码
default String getZoneInfo() { return this.getClaimAsString(StandardClaimNames.ZONEINFO); } /** * Returns the user's locale {@code (locale)}. * @return the user's locale */ default String getLocale() { return this.getClaimAsString(StandardClaimNames.LOCALE); } /** * Returns the user's preferred phone number {@code (phone_number)}. * @return the user's preferred phone number */ default String getPhoneNumber() { return this.getClaimAsString(StandardClaimNames.PHONE_NUMBER); } /** * Returns {@code true} if the user's phone number has been verified * {@code (phone_number_verified)}, otherwise {@code false}. * @return {@code true} if the user's phone number has been verified, otherwise * {@code false} */
default Boolean getPhoneNumberVerified() { return this.getClaimAsBoolean(StandardClaimNames.PHONE_NUMBER_VERIFIED); } /** * Returns the user's preferred postal address {@code (address)}. * @return the user's preferred postal address */ default AddressStandardClaim getAddress() { Map<String, Object> addressFields = this.getClaimAsMap(StandardClaimNames.ADDRESS); return (!CollectionUtils.isEmpty(addressFields) ? new DefaultAddressStandardClaim.Builder(addressFields).build() : new DefaultAddressStandardClaim.Builder().build()); } /** * Returns the time the user's information was last updated {@code (updated_at)}. * @return the time the user's information was last updated */ default Instant getUpdatedAt() { return this.getClaimAsInstant(StandardClaimNames.UPDATED_AT); } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\StandardClaimAccessor.java
1
请完成以下Java代码
protected void onUpdate() { updatedAt = LocalDateTime.now(); } // Getters and setters 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 LocalDateTime getCreatedAt() { return createdAt;
} public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; } public LocalDateTime getUpdatedAt() { return updatedAt; } public void setUpdatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; } @Override public String toString() { return "Event{" + "id=" + id + ", name='" + name + '\'' + ", createdAt=" + createdAt + ", updatedAt=" + updatedAt + '}'; } }
repos\tutorials-master\persistence-modules\spring-jpa-3\src\main\java\com\baeldung\jpa\localdatetimequery\Event.java
1
请完成以下Java代码
public void setNameLike(String nameLike) { this.nameLike = nameLike; } @CamundaQueryParam("owner") public void setOwner(String owner) { this.owner = owner; } protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } protected FilterQuery createNewQuery(ProcessEngine engine) { return engine.getFilterService().createFilterQuery(); } protected void applyFilters(FilterQuery query) { if (filterId != null) { query.filterId(filterId); } if (resourceType != null) { query.filterResourceType(resourceType); } if (name != null) { query.filterName(name); }
if (nameLike != null) { query.filterNameLike(nameLike); } if (owner != null) { query.filterOwner(owner); } } protected void applySortBy(FilterQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_ID_VALUE)) { query.orderByFilterId(); } else if (sortBy.equals(SORT_BY_RESOURCE_TYPE_VALUE)) { query.orderByFilterResourceType(); } else if (sortBy.equals(SORT_BY_NAME_VALUE)) { query.orderByFilterName(); } else if (sortBy.equals(SORT_BY_OWNER_VALUE)) { query.orderByFilterOwner(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\FilterQueryDto.java
1
请在Spring Boot框架中完成以下Java代码
public class HelloController { // Get the SLF4J logger interface, default Logback, a SLF4J implementation private static final Logger logger = LoggerFactory.getLogger(HelloController.class); @GetMapping("/") public String hello() { logger.debug("Debug level - Hello Logback"); logger.info("Info level - Hello Logback"); logger.error("Error level - Hello Logback"); return "Hello SLF4J"; }
// Log variables @GetMapping("/hello/{name}") String find(@PathVariable String name) { logger.debug("Debug level - Hello Logback {}", name); logger.info("Info level - Hello Logback {}", name); logger.error("Error level - Hello Logback {}", name); return "Hello SLF4J" + name; } }
repos\spring-boot-master\spring-boot-logging-slf4j-logback\src\main\java\com\mkyong\HelloController.java
2
请完成以下Java代码
public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmail() { return email; } public void setEmail(final String email) { this.email = email; } public Set<Role> getRoles() { return roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (email == null ? 0 : email.hashCode()); return result; } @Override public boolean equals(final Object obj) {
if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final User user = (User) obj; if (!email.equals(user.email)) { return false; } return true; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("User [id=").append(id).append(", username=").append(username).append(", email=").append(email).append(", roles=").append(roles).append("]"); return builder.toString(); } }
repos\tutorials-master\spring-katharsis\src\main\java\com\baeldung\persistence\model\User.java
1
请完成以下Java代码
public List<IncludedDetailInfo> getIncludedDetailInfos() { return ImmutableList.copyOf(includedDetailInfos.values()); } /* package */ final IncludedDetailInfo includedDetailInfo(final DetailId detailId) { Check.assumeNotNull(detailId, "Parameter detailId is not null"); return includedDetailInfos.computeIfAbsent(detailId, IncludedDetailInfo::new); } /* package */final Optional<IncludedDetailInfo> includedDetailInfoIfExists(final DetailId detailId) { Check.assumeNotNull(detailId, "Parameter detailId is not null"); return Optional.ofNullable(includedDetailInfos.get(detailId)); } /* package */void collectEvent(final IDocumentFieldChangedEvent event) { final boolean init_isKey = false; final boolean init_publicField = true; final boolean init_advancedField = false; final DocumentFieldWidgetType init_widgetType = event.getWidgetType(); fieldChangesOf(event.getFieldName(), init_isKey, init_publicField, init_advancedField, init_widgetType) .mergeFrom(event); } /* package */ void collectFieldWarning(final IDocumentFieldView documentField, final DocumentFieldWarning fieldWarning) { fieldChangesOf(documentField).setFieldWarning(fieldWarning); } public static final class IncludedDetailInfo { private final DetailId detailId; private boolean stale = false; private LogicExpressionResult allowNew; private LogicExpressionResult allowDelete; private IncludedDetailInfo(final DetailId detailId) { this.detailId = detailId; } public DetailId getDetailId() { return detailId; } IncludedDetailInfo setStale() { stale = true; return this; } public boolean isStale() {
return stale; } public LogicExpressionResult getAllowNew() { return allowNew; } IncludedDetailInfo setAllowNew(final LogicExpressionResult allowNew) { this.allowNew = allowNew; return this; } public LogicExpressionResult getAllowDelete() { return allowDelete; } IncludedDetailInfo setAllowDelete(final LogicExpressionResult allowDelete) { this.allowDelete = allowDelete; return this; } private void collectFrom(final IncludedDetailInfo from) { if (from.stale) { stale = from.stale; } if (from.allowNew != null) { allowNew = from.allowNew; } if (from.allowDelete != null) { allowDelete = from.allowDelete; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentChanges.java
1
请完成以下Java代码
protected String doIt() throws Exception { final I_C_Flatrate_Term term = createTermInOwnTrx(); // TODO check out and cleanup those different methods final int adWindowId = getProcessInfo().getAD_Window_ID(); if (adWindowId > 0 && !Ini.isSwingClient()) { // this works for the webui getResult().setRecordToOpen(TableRecordReference.of(term), adWindowId, OpenTarget.SingleDocument); } else { // this is the old code that works for swing getResult().setRecordToSelectAfterExecution(TableRecordReference.of(term)); } return MSG_OK; } private I_C_Flatrate_Term createTermInOwnTrx() { final TrxCallable<I_C_Flatrate_Term> callable = () -> { final I_C_Flatrate_Term term = PMMContractBuilder.newBuilder() .setCtx(getCtx()) .setFailIfNotCreated(true) .setComplete(true) .setC_Flatrate_Conditions(p_C_Flatrate_Conditions) .setC_BPartner(p_C_BPartner) .setStartDate(p_StartDate) .setEndDate(p_EndDate) .setPMM_Product(p_PMM_Product) .setC_UOM(p_C_UOM) .setAD_User_InCharge(p_AD_User_Incharge) .setCurrencyId(p_CurrencyId) .setComplete(p_isComplete) // complete if flag on true, do not complete otherwise .build(); return term; };
// the default config is fine for us final ITrxRunConfig config = trxManager.newTrxRunConfigBuilder().build(); return trxManager.call(ITrx.TRXNAME_None, config, callable); } /** * If the given <code>parameterName</code> is {@value #PARAM_NAME_AD_USER_IN_CHARGE_ID},<br> * then the method returns the user from {@link IPMMContractsBL#getDefaultContractUserInCharge_ID(Properties)}. */ @Override public Object getParameterDefaultValue(final IProcessDefaultParameter parameter) { final String parameterName = parameter.getColumnName(); if (!PARAM_NAME_AD_USER_IN_CHARGE_ID.equals(parameterName)) { return DEFAULT_VALUE_NOTAVAILABLE; } final int adUserInChargeId = pmmContractsBL.getDefaultContractUserInCharge_ID(getCtx()); if (adUserInChargeId < 0) { return DEFAULT_VALUE_NOTAVAILABLE; } return adUserInChargeId; // we need to return the ID, not the actual record. Otherwise then lookup logic will be confused. } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\process\C_Flatrate_Term_Create_ProcurementContract.java
1
请完成以下Java代码
public void onAfterReverse(final I_C_Payment payment) { // // Auto-reconcile the payment and it's reversal if the payment is not present on bank statements final PaymentId paymentId = PaymentId.ofRepoId(payment.getC_Payment_ID()); if (!bankStatementBL.isPaymentOnBankStatement(paymentId)) { final PaymentId reversalId = PaymentId.ofRepoId(payment.getReversal_ID()); final ImmutableList<PaymentReconcileRequest> requests = ImmutableList.of( PaymentReconcileRequest.of(paymentId, PaymentReconcileReference.reversal(reversalId)), PaymentReconcileRequest.of(reversalId, PaymentReconcileReference.reversal(paymentId))); final Collection<I_C_Payment> preloadedPayments = ImmutableList.of(payment); paymentBL.markReconciled(requests, preloadedPayments); } } @DocValidate(timings = { ModelValidator.TIMING_AFTER_COMPLETE }) public void createCashStatementLineIfNeeded(final I_C_Payment payment) {
if (!paymentBL.isCashTrx(payment)) { return; } if (bankStatementBL.isPaymentOnBankStatement(PaymentId.ofRepoId(payment.getC_Payment_ID()))) { return; } cashStatementBL.createCashStatementLine(payment); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_Payment.COLUMNNAME_DateTrx }) public void onDateChange(final I_C_Payment payment) { paymentBL.updateDiscountAndPayAmtFromInvoiceIfAny(payment); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\modelvalidator\C_Payment.java
1
请在Spring Boot框架中完成以下Java代码
public class DeliveryRecipientType extends BusinessEntityType { @XmlElement(name = "DeliveryRecipientExtension", namespace = "http://erpel.at/schemas/1p0/documents/ext") protected DeliveryRecipientExtensionType deliveryRecipientExtension; /** * Gets the value of the deliveryRecipientExtension property. * * @return * possible object is * {@link DeliveryRecipientExtensionType } * */ public DeliveryRecipientExtensionType getDeliveryRecipientExtension() {
return deliveryRecipientExtension; } /** * Sets the value of the deliveryRecipientExtension property. * * @param value * allowed object is * {@link DeliveryRecipientExtensionType } * */ public void setDeliveryRecipientExtension(DeliveryRecipientExtensionType value) { this.deliveryRecipientExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\DeliveryRecipientType.java
2
请完成以下Java代码
private void add(final int rowProductId, final int rowUomId, final BigDecimal rowQty) { // If this aggregation is no longer valid => do nothing if (!valid) { return; } final boolean isInitialized = product != null; if (!isInitialized) { uomConversionCtx = UOMConversionContext.of(rowProductId); uom = productBL.getStockUOM(rowProductId); qty = BigDecimal.ZERO; } // // Check if it's compatible else if (product.getM_Product_ID() != rowProductId) { valid = false; return; } final I_C_UOM rowUOM = InterfaceWrapperHelper.create(getCtx(), rowUomId, I_C_UOM.class, ITrx.TRXNAME_None); final BigDecimal rowQtyInBaseUOM; try { rowQtyInBaseUOM = uomConversionBL.convertQty(uomConversionCtx, rowQty, rowUOM, uom); } catch (final Exception e) { log.warn(e.getLocalizedMessage()); valid = false; return; } qty = qty.add(rowQtyInBaseUOM); } @Override public Object getAggregatedValue(final RModelCalculationContext calculationCtx, final List<Object> groupRow) { if (!valid) { return null; } if (!isGroupBy(calculationCtx, COLUMNNAME_M_Product_ID)) { return null; } final IRModelMetadata metadata = calculationCtx.getMetadata(); final int groupProductId = getM_Product_ID(metadata, groupRow); if (groupProductId <= 0) { return null; } else if (product == null) { return BigDecimal.ZERO; } else if (product.getM_Product_ID() != groupProductId) { // shall not happen return null; } //
// Update UOM column // FIXME: dirty hack { final KeyNamePair uomKNP = new KeyNamePair(uom.getC_UOM_ID(), uom.getName()); setRowValueOrNull(metadata, groupRow, COLUMNNAME_C_UOM_ID, uomKNP); } return qty; } private final int getM_Product_ID(final IRModelMetadata metadata, final List<Object> row) { final KeyNamePair productKNP = getRowValueOrNull(metadata, row, COLUMNNAME_M_Product_ID, KeyNamePair.class); if (productKNP == null) { return -1; } return productKNP.getKey(); } private final int getC_UOM_ID(final IRModelMetadata metadata, final List<Object> row) { final KeyNamePair uomKNP = getRowValueOrNull(metadata, row, COLUMNNAME_C_UOM_ID, KeyNamePair.class); if (uomKNP == null) { return -1; } return uomKNP.getKey(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\compiere\report\core\ProductQtyRModelAggregatedValue.java
1
请完成以下Java代码
public Map<String, Object> toJson() { return toJson(Function.identity()); } public Map<String, Object> toJson(@NonNull final Function<Object, Object> toJsonConverter) { final LinkedHashMap<String, Object> result = new LinkedHashMap<>(parameterNames.size()); for (final String parameterName : parameterNames) { final Object valueObj = values.get(parameterName); final Object valueJson = toJsonConverter.apply(valueObj); result.put(parameterName, valueJson); } return result; } public static class ParamsBuilder { private final LinkedHashSet<String> parameterNames = new LinkedHashSet<>(); private final HashMap<String, Object> values = new HashMap<>(); private ParamsBuilder() { } private ParamsBuilder(@NonNull final Params from) { parameterNames.addAll(from.parameterNames); values.putAll(from.values); } public Params build() { if (parameterNames.isEmpty()) { return EMPTY; } else { return new Params( ImmutableSet.copyOf(parameterNames), ImmutableMap.copyOf(values)); } } public ParamsBuilder value(@NonNull final String parameterName, @Nullable final String valueStr) { return valueObj(parameterName, valueStr); } public ParamsBuilder value(@NonNull final String parameterName, @Nullable final Integer valueInt) { return valueObj(parameterName, valueInt); }
public <T extends RepoIdAware> ParamsBuilder value(@NonNull final String parameterName, @Nullable final T id) { return valueObj(parameterName, id); } public ParamsBuilder value(@NonNull final String parameterName, final boolean valueBoolean) { return valueObj(parameterName, valueBoolean); } public ParamsBuilder value(@NonNull final String parameterName, @Nullable final BigDecimal valueBD) { return valueObj(parameterName, valueBD); } public ParamsBuilder value(@NonNull final String parameterName, @Nullable final ZonedDateTime valueZDT) { return valueObj(parameterName, valueZDT); } public ParamsBuilder value(@NonNull final String parameterName, @Nullable final LocalDate valueLD) { return valueObj(parameterName, valueLD); } public ParamsBuilder valueObj(@NonNull final String parameterName, @Nullable final Object value) { parameterNames.add(parameterName); if (value != null) { values.put(parameterName, value); } else { values.remove(parameterName); } return this; } public ParamsBuilder valueObj(@NonNull final Object value) { return valueObj(toParameterName(value.getClass()), value); } public ParamsBuilder putAll(@NonNull final IParams params) { for (String parameterName : params.getParameterNames()) { valueObj(parameterName, params.getParameterAsObject(parameterName)); } return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\api\Params.java
1
请完成以下Java代码
public int getId() { return 1; } public String getName() { return ProcessEngineConfiguration.HISTORY_ACTIVITY; } public boolean isHistoryEventProduced(HistoryEventType eventType, Object entity) { return PROCESS_INSTANCE_START == eventType || PROCESS_INSTANCE_UPDATE == eventType || PROCESS_INSTANCE_MIGRATE == eventType || PROCESS_INSTANCE_END == eventType || TASK_INSTANCE_CREATE == eventType || TASK_INSTANCE_UPDATE == eventType || TASK_INSTANCE_MIGRATE == eventType || TASK_INSTANCE_COMPLETE == eventType || TASK_INSTANCE_DELETE == eventType
|| ACTIVITY_INSTANCE_START == eventType || ACTIVITY_INSTANCE_UPDATE == eventType || ACTIVITY_INSTANCE_MIGRATE == eventType || ACTIVITY_INSTANCE_END == eventType || CASE_INSTANCE_CREATE == eventType || CASE_INSTANCE_UPDATE == eventType || CASE_INSTANCE_CLOSE == eventType || CASE_ACTIVITY_INSTANCE_CREATE == eventType || CASE_ACTIVITY_INSTANCE_UPDATE == eventType || CASE_ACTIVITY_INSTANCE_END == eventType ; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\HistoryLevelActivity.java
1
请在Spring Boot框架中完成以下Java代码
class CacheMetricsRegistrarConfiguration { private static final String CACHE_MANAGER_SUFFIX = "cacheManager"; private final MeterRegistry registry; private final CacheMetricsRegistrar cacheMetricsRegistrar; private final Map<String, CacheManager> cacheManagers; CacheMetricsRegistrarConfiguration(MeterRegistry registry, Collection<CacheMeterBinderProvider<?>> binderProviders, ConfigurableListableBeanFactory beanFactory) { this.registry = registry; this.cacheManagers = SimpleAutowireCandidateResolver.resolveAutowireCandidates(beanFactory, CacheManager.class); this.cacheMetricsRegistrar = new CacheMetricsRegistrar(this.registry, binderProviders); bindCachesToRegistry(); } @Bean CacheMetricsRegistrar cacheMetricsRegistrar() { return this.cacheMetricsRegistrar; } private void bindCachesToRegistry() { this.cacheManagers.forEach(this::bindCacheManagerToRegistry); } private void bindCacheManagerToRegistry(String beanName, CacheManager cacheManager) { cacheManager.getCacheNames().forEach((cacheName) -> { Cache cache = cacheManager.getCache(cacheName); Assert.state(cache != null, () -> "'cache' must not be null. 'cacheName' is '%s'".formatted(cacheName)); bindCacheToRegistry(beanName, cache); }); } private void bindCacheToRegistry(String beanName, Cache cache) { Tag cacheManagerTag = Tag.of("cache.manager", getCacheManagerName(beanName));
this.cacheMetricsRegistrar.bindCacheToRegistry(cache, cacheManagerTag); } /** * Get the name of a {@link CacheManager} based on its {@code beanName}. * @param beanName the name of the {@link CacheManager} bean * @return a name for the given cache manager */ private String getCacheManagerName(String beanName) { if (beanName.length() > CACHE_MANAGER_SUFFIX.length() && StringUtils.endsWithIgnoreCase(beanName, CACHE_MANAGER_SUFFIX)) { return beanName.substring(0, beanName.length() - CACHE_MANAGER_SUFFIX.length()); } return beanName; } }
repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\autoconfigure\metrics\CacheMetricsRegistrarConfiguration.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 boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Boolean getCompleted() { return completed; } public void setCompleted(Boolean completed) { this.completed = completed; } }
repos\tutorials-master\spring-quartz\src\main\java\org\baeldung\recovery\custom\ApplicationJob.java
1
请在Spring Boot框架中完成以下Java代码
public EntityMetaData scanClass(Class<?> clazz) { EntityMetaData metaData = new EntityMetaData(); // in case with JPA Enhancement method should iterate over superclasses list // to find @Entity and @Id annotations while (clazz != null && !clazz.equals(Object.class)) { // Class should have @Entity annotation boolean isEntity = isEntityAnnotationPresent(clazz); if (isEntity) { metaData.setEntityClass(clazz); metaData.setJPAEntity(true); // Try to find a field annotated with @Id Field idField = getIdField(clazz); if (idField != null) { metaData.setIdField(idField); } else { // Try to find a method annotated with @Id Method idMethod = getIdMethod(clazz); if (idMethod != null) { metaData.setIdMethod(idMethod); } else { throw new FlowableException("Cannot find field or method with annotation @Id on class '" + clazz.getName() + "', only single-valued primary keys are supported on JPA-entities"); } } break; } clazz = clazz.getSuperclass(); } return metaData; } private Method getIdMethod(Class<?> clazz) { Method idMethod = null; // Get all public declared methods on the class. According to spec, @Id should only be // applied to fields and property get methods Method[] methods = clazz.getMethods(); Id idAnnotation = null; for (Method method : methods) { idAnnotation = method.getAnnotation(Id.class); if (idAnnotation != null && !method.isBridge()) { idMethod = method; break; }
} return idMethod; } private Field getIdField(Class<?> clazz) { Field idField = null; Field[] fields = clazz.getDeclaredFields(); Id idAnnotation = null; for (Field field : fields) { idAnnotation = field.getAnnotation(Id.class); if (idAnnotation != null) { idField = field; break; } } if (idField == null) { // Check superClass for fields with @Id, since getDeclaredFields // does not return superclass-fields. Class<?> superClass = clazz.getSuperclass(); if (superClass != null && !superClass.equals(Object.class)) { // Recursively go up class hierarchy idField = getIdField(superClass); } } return idField; } private boolean isEntityAnnotationPresent(Class<?> clazz) { return (clazz.getAnnotation(Entity.class) != null); } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\JPAEntityScanner.java
2
请完成以下Java代码
public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public void setDescription(String description) { this.description = description; } @Override public String getDescription() { return description; } @Override public String getDeploymentId() { return deploymentId; } @Override public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @Override public int getVersion() { return version; } @Override public void setVersion(int version) { this.version = version; } @Override public String getResourceName() { return resourceName; } @Override public void setResourceName(String resourceName) { this.resourceName = resourceName; } @Override public boolean hasGraphicalNotation() { return isGraphicalNotationDefined; } public boolean isGraphicalNotationDefined() { return hasGraphicalNotation(); } @Override public void setHasGraphicalNotation(boolean hasGraphicalNotation) { this.isGraphicalNotationDefined = hasGraphicalNotation; } @Override public String getDiagramResourceName() { return diagramResourceName; }
@Override public void setDiagramResourceName(String diagramResourceName) { this.diagramResourceName = diagramResourceName; } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String getCategory() { return category; } @Override public void setCategory(String category) { this.category = category; } @Override public String getDecisionType() { return decisionType; } @Override public void setDecisionType(String decisionType) { this.decisionType = decisionType; } @Override public String toString() { return "DecisionEntity[" + id + "]"; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\DecisionEntityImpl.java
1
请完成以下Java代码
private ProductsToPickRow applyFieldChangeRequests(@NonNull final ProductsToPickRow row, final List<JSONDocumentChangedEvent> fieldChangeRequests) { Check.assumeNotEmpty(fieldChangeRequests, "fieldChangeRequests is not empty"); fieldChangeRequests.forEach(JSONDocumentChangedEvent::assertReplaceOperation); ProductsToPickRow changedRow = row; for (final JSONDocumentChangedEvent fieldChangeRequest : fieldChangeRequests) { final String fieldName = fieldChangeRequest.getPath(); if (ProductsToPickRow.FIELD_QtyOverride.equals(fieldName)) { if (!row.isQtyOverrideEditableByUser()) { throw new AdempiereException("QtyOverride is not editable") .setParameter("row", row); } final BigDecimal qtyOverride = fieldChangeRequest.getValueAsBigDecimal(); changedRow = changedRow.withQtyOverride(qtyOverride); } else if (ProductsToPickRow.FIELD_QtyReview.equals(fieldName)) { final BigDecimal qtyReviewed = fieldChangeRequest.getValueAsBigDecimal(); final PickingCandidate pickingCandidate = pickingCandidateService.setQtyReviewed(row.getPickingCandidateId(), qtyReviewed); changedRow = changedRow.withUpdatesFromPickingCandidate(pickingCandidate); } else { throw new AdempiereException("Field " + fieldName + " is not editable"); } } return changedRow; } @Override public DocumentIdsSelection getDocumentIdsToInvalidate(final TableRecordReferenceSet recordRefs) { final Set<PickingCandidateId> pickingCandidateIds = recordRefs .streamIds(I_M_Picking_Candidate.Table_Name, PickingCandidateId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); if (pickingCandidateIds.isEmpty()) {
return DocumentIdsSelection.EMPTY; } return getAllRowsByIdNoUpdate() .values() .stream() .filter(row -> pickingCandidateIds.contains(row.getPickingCandidateId())) .map(ProductsToPickRow::getId) .collect(DocumentIdsSelection.toDocumentIdsSelection()); } @Override public void invalidateAll() { rowIdsInvalid = true; } public void updateViewRowFromPickingCandidate(@NonNull final DocumentId rowId, @NonNull final PickingCandidate pickingCandidate) { changeRow(rowId, row -> row.withUpdatesFromPickingCandidate(pickingCandidate)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\rows\ProductsToPickRowsData.java
1
请完成以下Java代码
public class CopySets { // Copy Constructor public static <T> Set<T> copyByConstructor(Set<T> original) { Set<T> copy = new HashSet<>(original); return copy; } // Set.addAll public static <T> Set<T> copyBySetAddAll(Set<T> original) { Set<T> copy = new HashSet<>(); copy.addAll(original); return copy; } // Set.clone public static <T> Set<T> copyBySetClone(HashSet<T> original) { Set<T> copy = (Set<T>) original.clone(); return copy; } // JSON public static <T> Set<T> copyByJson(Set<T> original) { Gson gson = new Gson(); String jsonStr = gson.toJson(original); Set<T> copy = gson.fromJson(jsonStr, Set.class);
return copy; } // Apache Commons Lang public static <T extends Serializable> Set<T> copyByApacheCommonsLang(Set<T> original) { Set<T> copy = new HashSet<>(); for (T item : original) { copy.add((T) SerializationUtils.clone(item)); } return copy; } // Collectors.toSet public static <T extends Serializable> Set<T> copyByCollectorsToSet(Set<T> original) { Set<T> copy = original.stream() .collect(Collectors.toSet()); return copy; } }
repos\tutorials-master\core-java-modules\core-java-collections-set-2\src\main\java\com\baeldung\set\CopySets.java
1
请完成以下Java代码
public void setQM_SpecificationLine_ID (int QM_SpecificationLine_ID) { if (QM_SpecificationLine_ID < 1) set_ValueNoCheck (COLUMNNAME_QM_SpecificationLine_ID, null); else set_ValueNoCheck (COLUMNNAME_QM_SpecificationLine_ID, Integer.valueOf(QM_SpecificationLine_ID)); } /** Get QM_SpecificationLine_ID. @return QM_SpecificationLine_ID */ public int getQM_SpecificationLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_QM_SpecificationLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (String ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public String getValidFrom () { return (String)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_QM_SpecificationLine.java
1
请完成以下Java代码
public static final class Builder { private static final AtomicInteger nextQuickInputDocumentId = new AtomicInteger(1); private DocumentPath _rootDocumentPath; private QuickInputDescriptor _quickInputDescriptor; private Builder() { super(); } public QuickInput build() { return new QuickInput(this); } public Builder setRootDocumentPath(final DocumentPath rootDocumentPath) { _rootDocumentPath = Preconditions.checkNotNull(rootDocumentPath, "rootDocumentPath"); return this; } private DocumentPath getRootDocumentPath() { Check.assumeNotNull(_rootDocumentPath, "Parameter rootDocumentPath is not null"); return _rootDocumentPath; } public Builder setQuickInputDescriptor(final QuickInputDescriptor quickInputDescriptor) { _quickInputDescriptor = quickInputDescriptor; return this; } private QuickInputDescriptor getQuickInputDescriptor()
{ Check.assumeNotNull(_quickInputDescriptor, "Parameter quickInputDescriptor is not null"); return _quickInputDescriptor; } private DetailId getTargetDetailId() { final DetailId targetDetailId = getQuickInputDescriptor().getDetailId(); Check.assumeNotNull(targetDetailId, "Parameter targetDetailId is not null"); return targetDetailId; } private Document buildQuickInputDocument() { return Document.builder(getQuickInputDescriptor().getEntityDescriptor()) .initializeAsNewDocument(nextQuickInputDocumentId::getAndIncrement, VERSION_DEFAULT); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\QuickInput.java
1
请完成以下Java代码
public static SessionFactory getSessionFactory(Strategy strategy) { return buildSessionFactory(strategy); } private static SessionFactory buildSessionFactory(Strategy strategy) { try { ServiceRegistry serviceRegistry = configureServiceRegistry(); MetadataSources metadataSources = new MetadataSources(serviceRegistry); for (Class<?> entityClass : strategy.getEntityClasses()) { metadataSources.addAnnotatedClass(entityClass); } Metadata metadata = metadataSources.getMetadataBuilder() .build(); return metadata.getSessionFactoryBuilder() .build(); } catch (IOException ex) { throw new ExceptionInInitializerError(ex); } } private static ServiceRegistry configureServiceRegistry() throws IOException { Properties properties = getProperties();
return new StandardServiceRegistryBuilder().applySettings(properties) .build(); } private static Properties getProperties() throws IOException { Properties properties = new Properties(); URL propertiesURL = Thread.currentThread() .getContextClassLoader() .getResource("hibernate.properties"); try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { properties.load(inputStream); } return properties; } }
repos\tutorials-master\persistence-modules\hibernate-jpa\src\main\java\com\baeldung\hibernate\onetoone\HibernateUtil.java
1
请完成以下Java代码
public void addMigratingDependentInstance(MigratingInstance migratingInstance) { migratingDependentInstances.add(migratingInstance); } public List<MigratingInstance> getMigratingDependentInstances() { return migratingDependentInstances; } @Override public void migrateState() { ExecutionEntity representativeExecution = resolveRepresentativeExecution(); representativeExecution.setProcessDefinition(targetScope.getProcessDefinition()); representativeExecution.setActivity((PvmActivity) targetScope); } @Override public void migrateDependentEntities() { jobInstance.migrateState(); jobInstance.migrateDependentEntities(); for (MigratingInstance dependentInstance : migratingDependentInstances) { dependentInstance.migrateState(); dependentInstance.migrateDependentEntities(); } } public TransitionInstance getTransitionInstance() { return transitionInstance; } /** * Else asyncBefore
*/ public boolean isAsyncAfter() { return jobInstance.isAsyncAfter(); } public boolean isAsyncBefore() { return jobInstance.isAsyncBefore(); } public MigratingJobInstance getJobInstance() { return jobInstance; } @Override public void setParent(MigratingScopeInstance parentInstance) { if (parentInstance != null && !(parentInstance instanceof MigratingActivityInstance)) { throw MIGRATION_LOGGER.cannotHandleChild(parentInstance, this); } MigratingActivityInstance parentActivityInstance = (MigratingActivityInstance) parentInstance; if (this.parentInstance != null) { ((MigratingActivityInstance) this.parentInstance).removeChild(this); } this.parentInstance = parentActivityInstance; if (parentInstance != null) { parentActivityInstance.addChild(this); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingTransitionInstance.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isEnabled() { return (this.enabled != null) ? this.enabled : this.bundle != null; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public @Nullable String getBundle() { return this.bundle; } public void setBundle(@Nullable String bundle) { this.bundle = bundle; } } public static class Validation { /** * Whether to enable LDAP schema validation. */ private boolean enabled = true; /** * Path to the custom schema. */ private @Nullable Resource schema; public boolean isEnabled() { return this.enabled;
} public void setEnabled(boolean enabled) { this.enabled = enabled; } public @Nullable Resource getSchema() { return this.schema; } public void setSchema(@Nullable Resource schema) { this.schema = schema; } } }
repos\spring-boot-main\module\spring-boot-ldap\src\main\java\org\springframework\boot\ldap\autoconfigure\embedded\EmbeddedLdapProperties.java
2
请完成以下Java代码
public String getA_Term () { return (String)get_Value(COLUMNNAME_A_Term); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); }
/** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Table_Header.java
1
请完成以下Java代码
public IAutoCloseable switchContext(final Properties ctx) { Check.assumeNotNull(ctx, "ctx not null"); // If we were asked to set the context proxy (the one which we are returning everytime), // then it's better to do nothing because this could end in a StackOverflowException. if (ctx == ctxProxy) { return NullAutoCloseable.instance; } final Properties previousTempCtx = temporaryCtxHolder.get(); temporaryCtxHolder.set(ctx); return new IAutoCloseable() { private boolean closed = false; @Override public void close() { if (closed) { return; } if (previousTempCtx != null) {
temporaryCtxHolder.set(previousTempCtx); } else { temporaryCtxHolder.remove(); } closed = true; } }; } @Override public void reset() { temporaryCtxHolder.remove(); rootCtx.clear(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\context\SwingContextProvider.java
1
请在Spring Boot框架中完成以下Java代码
protected void doInTransactionWithoutResult(TransactionStatus status) { Author authorB = authorRepository.findById(1L).orElseThrow(); authorB.setName("Alicia Tom"); System.out.println("Author B: " + authorB.getName() + "\n"); } }); // Direct fetching via findById(), find() and get() doesn't trigger a SELECT // It loads the author directly from Persistence Context Author authorA2 = authorRepository.findById(1L).orElseThrow(); System.out.println("\nAuthor A2: " + authorA2.getName() + "\n"); // JPQL entity queries take advantage of session-level repeatable reads // The data snapshot returned by the triggered SELECT is ignored Author authorViaJpql = authorRepository.fetchByIdJpql(1L); System.out.println("Author via JPQL: " + authorViaJpql.getName() + "\n");
// SQL entity queries take advantage of session-level repeatable reads // The data snapshot returned by the triggered SELECT is ignored Author authorViaSql = authorRepository.fetchByIdSql(1L); System.out.println("Author via SQL: " + authorViaSql.getName() + "\n"); // JPQL query projections always load the latest database state String nameViaJpql = authorRepository.fetchNameByIdJpql(1L); System.out.println("Author name via JPQL: " + nameViaJpql + "\n"); // SQL query projections always load the latest database state String nameViaSql = authorRepository.fetchNameByIdSql(1L); System.out.println("Author name via SQL: " + nameViaSql + "\n"); } }); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootSessionRepeatableReads\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Spring Boot application配置
#\u8FD9\u91CC\u4EE5qq\u90AE\u7BB1\u4E3A\u4F8B # qq\u90AE\u7BB1\u670D\u52A1\u5668 spring.mail.host=smtp.qq.com # \u4F60\u7684qq\u90AE\u7BB1\u8D26\u6237 spring.mail.username=yourAccount@qq.com # \u4F60\u7684qq\u90AE\u7BB1\u7B2C\u4E09\u65B9\u6388\u6743\u7801 spring.mail.password=
yourPassword # \u7F16\u7801\u7C7B\u578B spring.mail.default-encoding=UTF-8 spring.thymeleaf.prefix=classpath:/template/
repos\springboot-demo-master\mail\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public abstract class AbstractTbRuleEngineSubmitStrategy implements TbRuleEngineSubmitStrategy { protected final String queueName; protected List<IdMsgPair<TransportProtos.ToRuleEngineMsg>> orderedMsgList; private volatile boolean stopped; public AbstractTbRuleEngineSubmitStrategy(String queueName) { this.queueName = queueName; } protected abstract void doOnSuccess(UUID id); @Override public void init(List<TbProtoQueueMsg<TransportProtos.ToRuleEngineMsg>> msgs) { orderedMsgList = msgs.stream().map(msg -> new IdMsgPair<>(UUID.randomUUID(), msg)).collect(Collectors.toList()); } @Override public ConcurrentMap<UUID, TbProtoQueueMsg<TransportProtos.ToRuleEngineMsg>> getPendingMap() { return orderedMsgList.stream().collect(Collectors.toConcurrentMap(pair -> pair.uuid, pair -> pair.msg)); } @Override public void update(ConcurrentMap<UUID, TbProtoQueueMsg<TransportProtos.ToRuleEngineMsg>> reprocessMap) { List<IdMsgPair<TransportProtos.ToRuleEngineMsg>> newOrderedMsgList = new ArrayList<>(reprocessMap.size()); for (IdMsgPair<TransportProtos.ToRuleEngineMsg> pair : orderedMsgList) { if (reprocessMap.containsKey(pair.uuid)) { if (StringUtils.isNotEmpty(pair.getMsg().getValue().getFailureMessage())) { var toRuleEngineMsg = TransportProtos.ToRuleEngineMsg.newBuilder(pair.getMsg().getValue()) .clearFailureMessage() .clearRelationTypes() .build(); var newMsg = new TbProtoQueueMsg<>(pair.getMsg().getKey(), toRuleEngineMsg, pair.getMsg().getHeaders()); newOrderedMsgList.add(new IdMsgPair<>(pair.getUuid(), newMsg)); } else { newOrderedMsgList.add(pair);
} } } orderedMsgList = newOrderedMsgList; } @Override public void onSuccess(UUID id) { if (!stopped) { doOnSuccess(id); } } @Override public void stop() { stopped = true; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\processing\AbstractTbRuleEngineSubmitStrategy.java
2
请完成以下Java代码
public static FAOpenItemKey parse(@NonNull final String string) { final String stringNorm = StringUtils.trimBlankToNull(string); if (stringNorm == null) { throw new AdempiereException("empty/null Open Item Key is not allowed"); } try { final List<String> parts = SPLITTER.splitToList(stringNorm); return builder() .stringRepresentation(stringNorm) .accountConceptualName(!"-".equals(parts.get(0)) ? AccountConceptualName.ofString(parts.get(0)) : null) .tableName(parts.get(1)) .recordId(Math.max(NumberUtils.asInt(parts.get(2)), 0)) .lineId(parts.size() >= 4 ? Math.max(NumberUtils.asInt(parts.get(3)), 0) : 0) .subLineId(parts.size() >= 5 ? Math.max(NumberUtils.asInt(parts.get(4)), 0) : 0) .build(); } catch (Exception ex) { throw new AdempiereException("Invalid open item key: " + stringNorm, ex); } } public static boolean equals(@Nullable FAOpenItemKey o1, @Nullable FAOpenItemKey o2) {return Objects.equals(o1, o2);} @Override public String toString() {return getAsString();} public String getAsString() { String stringRepresentation = this.stringRepresentation; if (stringRepresentation == null) { stringRepresentation = this.stringRepresentation = buildStringRepresentation(); } return stringRepresentation; } @NonNull private String buildStringRepresentation() { final StringBuilder sb = new StringBuilder(); sb.append(accountConceptualName != null ? accountConceptualName.getAsString() : "-"); sb.append("#").append(tableName); sb.append("#").append(Math.max(recordId, 0)); if (lineId > 0) { sb.append("#").append(lineId); } if (subLineId > 0) { sb.append("#").append(subLineId); } return sb.toString(); }
public Optional<InvoiceId> getInvoiceId() { return I_C_Invoice.Table_Name.equals(tableName) ? InvoiceId.optionalOfRepoId(recordId) : Optional.empty(); } public Optional<PaymentId> getPaymentId() { return I_C_Payment.Table_Name.equals(tableName) ? PaymentId.optionalOfRepoId(recordId) : Optional.empty(); } public Optional<BankStatementId> getBankStatementId() { return I_C_BankStatement.Table_Name.equals(tableName) ? BankStatementId.optionalOfRepoId(recordId) : Optional.empty(); } public Optional<BankStatementLineId> getBankStatementLineId() { return I_C_BankStatement.Table_Name.equals(tableName) ? BankStatementLineId.optionalOfRepoId(lineId) : Optional.empty(); } public Optional<BankStatementLineRefId> getBankStatementLineRefId() { return I_C_BankStatement.Table_Name.equals(tableName) ? BankStatementLineRefId.optionalOfRepoId(subLineId) : Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\open_items\FAOpenItemKey.java
1
请完成以下Java代码
public void run() { LOG.info(cacheThreadPool.getActiveCount() + "---------"); tasks.remove(task); task.run(); } }); } } } } catch (Exception e) { LOG.error("系统异常", e); e.printStackTrace(); } } }); } /** * 从数据库中取一次数据用来当系统启动时初始化 */ @SuppressWarnings("unchecked") private static void startInitFromDB() { LOG.info("get data from database"); int pageNum = 1; int numPerPage = 500; PageParam pageParam = new PageParam(pageNum, numPerPage); // 查询状态和通知次数符合以下条件的数据进行通知 String[] status = new String[]{"101", "102", "200", "201"}; Integer[] notifyTime = new Integer[]{0, 1, 2, 3, 4}; // 组装查询条件 Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("statusList", status); paramMap.put("notifyTimeList", notifyTime); PageBean<RpNotifyRecord> pager = cacheRpNotifyService.queryNotifyRecordListPage(pageParam, paramMap); int totalSize = (pager.getNumPerPage() - 1) / numPerPage + 1;//总页数 while (pageNum <= totalSize) { List<RpNotifyRecord> list = pager.getRecordList(); for (int i = 0; i < list.size(); i++) { RpNotifyRecord notifyRecord = list.get(i); notifyRecord.setLastNotifyTime(new Date()); cacheNotifyQueue.addElementToList(notifyRecord); } pageNum++; LOG.info(String.format("调用通知服务.rpNotifyService.queryNotifyRecordListPage(%s, %s, %s)", pageNum, numPerPage, paramMap)); pageParam = new PageParam(pageNum, numPerPage); pager = cacheRpNotifyService.queryNotifyRecordListPage(pageParam, paramMap); } } }
repos\roncoo-pay-master\roncoo-pay-app-notify\src\main\java\com\roncoo\pay\AppNotifyApplication.java
1
请完成以下Java代码
private MInOut getCreateHeader(MInvoice invoice) { if (m_inout != null) { return m_inout; } m_inout = new MInOut(invoice, 0, null, p_M_Warehouse_ID); m_inout.saveEx(); return m_inout; } /** * Create shipment/receipt line * * @return shipment/receipt line */ private MInOutLine createLine(MInvoice invoice, MInvoiceLine invoiceLine) { final IInvoiceBL invoiceBL = Services.get(IInvoiceBL.class); final MatchInvoiceService matchInvoiceService = MatchInvoiceService.get(); final StockQtyAndUOMQty qtyMatched = matchInvoiceService.getMaterialQtyMatched(invoiceLine); final StockQtyAndUOMQty qtyInvoiced = StockQtyAndUOMQtys.create( invoiceLine.getQtyInvoiced(), ProductId.ofRepoId(invoiceLine.getM_Product_ID()), invoiceLine.getQtyEntered(), UomId.ofRepoId(invoiceLine.getC_UOM_ID())); final StockQtyAndUOMQty qtyNotMatched = StockQtyAndUOMQtys.subtract(qtyInvoiced, qtyMatched);
// If is fully matched don't create anything if (qtyNotMatched.signum() == 0) { return null; } MInOut inout = getCreateHeader(invoice); MInOutLine sLine = new MInOutLine(inout); sLine.setInvoiceLine(invoiceLine, 0, // Locator invoice.isSOTrx() ? qtyNotMatched.getStockQty().toBigDecimal() : ZERO); sLine.setQtyEntered(qtyNotMatched.getUOMQtyNotNull().toBigDecimal()); sLine.setMovementQty(qtyNotMatched.getStockQty().toBigDecimal()); if (invoiceBL.isCreditMemo(invoice)) { sLine.setQtyEntered(sLine.getQtyEntered().negate()); sLine.setMovementQty(sLine.getMovementQty().negate()); } sLine.saveEx(); // invoiceLine.setM_InOutLine_ID(sLine.getM_InOutLine_ID()); invoiceLine.saveEx(); // return sLine; } } // InvoiceCreateInOut
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\InvoiceCreateInOut.java
1
请在Spring Boot框架中完成以下Java代码
public void createAlarmSubscriptions() { for (EntityId entityId : entitiesIds) { createAlarmSubscriptionForEntity(entityId); } } private void createAlarmSubscriptionForEntity(EntityId entityId) { int subIdx = sessionRef.getSessionSubIdSeq().incrementAndGet(); subToEntityIdMap.put(subIdx, entityId); log.trace("[{}][{}][{}] Creating alarms subscription for [{}] ", serviceId, cmdId, subIdx, entityId); TbAlarmsSubscription subscription = TbAlarmsSubscription.builder() .serviceId(serviceId) .sessionId(sessionRef.getSessionId()) .subscriptionId(subIdx) .tenantId(sessionRef.getSecurityCtx().getTenantId()) .entityId(entityId)
.updateProcessor((sub, update) -> fetchAlarmCount()) .build(); localSubscriptionService.addSubscription(subscription, sessionRef); } public void clearAlarmSubscriptions() { if (subToEntityIdMap != null) { for (Integer subId : subToEntityIdMap.keySet()) { localSubscriptionService.cancelSubscription(getTenantId(), getSessionId(), subId); } subToEntityIdMap.clear(); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\subscription\TbAlarmCountSubCtx.java
2
请完成以下Java代码
public void timeStamp() { if (inserted == 0) { inserted = System.currentTimeMillis(); } } public Long getId() { return this.id; } public String getName() { return this.name; } public String getDescription() { return this.description; } public LocalDateTime getCreated() { return this.created; } public Long getInserted() { return this.inserted; } public void setName(String name) { this.name = name; }
public void setDescription(String description) { this.description = description; } public void setCreated(LocalDateTime created) { this.created = created; } public void setInserted(Long inserted) { this.inserted = inserted; } public Category withId(Long id) { return this.id == id ? this : new Category(id, this.name, this.description, this.created, this.inserted); } @Override public String toString() { return "Category(id=" + this.getId() + ", name=" + this.getName() + ", description=" + this.getDescription() + ", created=" + this.getCreated() + ", inserted=" + this.getInserted() + ")"; } }
repos\spring-data-examples-main\jdbc\aot-optimization\src\main\java\example\springdata\aot\Category.java
1
请完成以下Java代码
public void setSelectionColumnSeqNo (final @Nullable BigDecimal SelectionColumnSeqNo) { set_Value (COLUMNNAME_SelectionColumnSeqNo, SelectionColumnSeqNo); } @Override public BigDecimal getSelectionColumnSeqNo() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SelectionColumnSeqNo); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setSeqNoGrid (final int SeqNoGrid) { set_Value (COLUMNNAME_SeqNoGrid, SeqNoGrid); } @Override public int getSeqNoGrid() { return get_ValueAsInt(COLUMNNAME_SeqNoGrid); } @Override 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 boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Boolean getGenerateUniqueProcessEngineName() { return generateUniqueProcessEngineName; } public void setGenerateUniqueProcessEngineName(Boolean generateUniqueProcessEngineName) { this.generateUniqueProcessEngineName = generateUniqueProcessEngineName; } public Boolean getGenerateUniqueProcessApplicationName() { return generateUniqueProcessApplicationName; } public void setGenerateUniqueProcessApplicationName(Boolean generateUniqueProcessApplicationName) { this.generateUniqueProcessApplicationName = generateUniqueProcessApplicationName; } @Override public String toString() { return joinOn(this.getClass())
.add("enabled=" + enabled) .add("processEngineName=" + processEngineName) .add("generateUniqueProcessEngineName=" + generateUniqueProcessEngineName) .add("generateUniqueProcessApplicationName=" + generateUniqueProcessApplicationName) .add("historyLevel=" + historyLevel) .add("historyLevelDefault=" + historyLevelDefault) .add("autoDeploymentEnabled=" + autoDeploymentEnabled) .add("deploymentResourcePattern=" + Arrays.toString(deploymentResourcePattern)) .add("defaultSerializationFormat=" + defaultSerializationFormat) .add("licenseFile=" + licenseFile) .add("metrics=" + metrics) .add("database=" + database) .add("jobExecution=" + jobExecution) .add("webapp=" + webapp) .add("restApi=" + restApi) .add("authorization=" + authorization) .add("genericProperties=" + genericProperties) .add("adminUser=" + adminUser) .add("filter=" + filter) .add("idGenerator=" + idGenerator) .add("jobExecutorAcquireByPriority=" + jobExecutorAcquireByPriority) .add("defaultNumberOfRetries" + defaultNumberOfRetries) .toString(); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\CamundaBpmProperties.java
1
请在Spring Boot框架中完成以下Java代码
private static Map<String, Object> doExtraProperties(ConfigurableEnvironment environment) { Map<String, Object> properties = new LinkedHashMap<>(); // orderly Map<String, PropertySource<?>> map = doGetPropertySources(environment); for (PropertySource<?> source : map.values()) { if (source instanceof EnumerablePropertySource) { EnumerablePropertySource propertySource = (EnumerablePropertySource) source; String[] propertyNames = propertySource.getPropertyNames(); if (ObjectUtils.isEmpty(propertyNames)) { continue; } for (String propertyName : propertyNames) { if (!properties.containsKey(propertyName)) { // put If absent properties.put(propertyName, propertySource.getProperty(propertyName)); } } } } return properties; }
private static Map<String, PropertySource<?>> doGetPropertySources(ConfigurableEnvironment environment) { Map<String, PropertySource<?>> map = new LinkedHashMap<String, PropertySource<?>>(); MutablePropertySources sources = environment.getPropertySources(); for (PropertySource<?> source : sources) { extract("", map, source); } return map; } private static void extract(String root, Map<String, PropertySource<?>> map, PropertySource<?> source) { if (source instanceof CompositePropertySource) { for (PropertySource<?> nest : ((CompositePropertySource) source) .getPropertySources()) { extract(source.getName() + ":", map, nest); } } else { map.put(root + source.getName(), source); } } }
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\autoconfigure\src\main\java\org\apache\dubbo\spring\boot\util\EnvironmentUtils.java
2
请在Spring Boot框架中完成以下Java代码
default I_AD_Client getById(int adClientId) { return getById(ClientId.ofRepoId(adClientId)); } List<I_AD_Client> getByIds(@NonNull Set<ClientId> adClientIds); @Deprecated I_AD_Client retriveClient(Properties ctx, int adClientId); /** * Retrieves currently login {@link I_AD_Client}. * * @return context client * @see Env#getAD_Client_ID(Properties) */ I_AD_Client retriveClient(Properties ctx);
List<I_AD_Client> retrieveAllClients(Properties ctx); /** @return client/tenant info for context AD_Client_ID; never returns null */ I_AD_ClientInfo retrieveClientInfo(Properties ctx); /** @return client/tenant info for given AD_Client_ID; never returns null */ I_AD_ClientInfo retrieveClientInfo(Properties ctx, int adClientId); ClientEMailConfig getEMailConfigById(ClientId clientId); ClientMailTemplates getClientMailTemplatesById(ClientId clientId); boolean isMultilingualDocumentsEnabled(ClientId adClientId); String getClientNameById(@NonNull ClientId clientId); }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\IClientDAO.java
2
请完成以下Java代码
public void delete(EntityImpl entity) { delete(entity, true); } @Override public void delete(EntityImpl entity, boolean fireDeleteEvent) { getDataManager().delete(entity); FlowableEventDispatcher eventDispatcher = getEventDispatcher(); if (fireDeleteEvent && eventDispatcher != null && eventDispatcher.isEnabled()) { fireEntityDeletedEvent(entity); } } protected void fireEntityDeletedEvent(Entity entity) { FlowableEventDispatcher eventDispatcher = getEventDispatcher(); if (eventDispatcher != null && eventDispatcher.isEnabled()) { eventDispatcher.dispatchEvent(createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, entity), engineType); } }
protected FlowableEntityEvent createEntityEvent(FlowableEngineEventType eventType, Entity entity) { return new FlowableEntityEventImpl(entity, eventType); } protected DM getDataManager() { return dataManager; } protected void setDataManager(DM dataManager) { this.dataManager = dataManager; } protected abstract FlowableEventDispatcher getEventDispatcher(); }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\persistence\entity\AbstractEntityManager.java
1
请完成以下Java代码
public class RelatedEntitiesParser { private final Map<String, String> allEntityIdsAndTypes = new HashMap<>(); private final Map<String, EntityType> tableNameAndEntityType = Map.ofEntries( Map.entry("COPY public.alarm ", EntityType.ALARM), Map.entry("COPY public.asset ", EntityType.ASSET), Map.entry("COPY public.customer ", EntityType.CUSTOMER), Map.entry("COPY public.dashboard ", EntityType.DASHBOARD), Map.entry("COPY public.device ", EntityType.DEVICE), Map.entry("COPY public.rule_chain ", EntityType.RULE_CHAIN), Map.entry("COPY public.rule_node ", EntityType.RULE_NODE), Map.entry("COPY public.tenant ", EntityType.TENANT), Map.entry("COPY public.tb_user ", EntityType.USER), Map.entry("COPY public.entity_view ", EntityType.ENTITY_VIEW), Map.entry("COPY public.widgets_bundle ", EntityType.WIDGETS_BUNDLE), Map.entry("COPY public.widget_type ", EntityType.WIDGET_TYPE), Map.entry("COPY public.tenant_profile ", EntityType.TENANT_PROFILE), Map.entry("COPY public.device_profile ", EntityType.DEVICE_PROFILE), Map.entry("COPY public.asset_profile ", EntityType.ASSET_PROFILE), Map.entry("COPY public.api_usage_state ", EntityType.API_USAGE_STATE) ); public RelatedEntitiesParser(File source) throws IOException { processAllTables(FileUtils.lineIterator(source)); } public String getEntityType(String uuid) { return this.allEntityIdsAndTypes.get(uuid); } private boolean isBlockFinished(String line) { return StringUtils.isBlank(line) || line.equals("\\."); }
private void processAllTables(LineIterator lineIterator) throws IOException { String currentLine; try { while (lineIterator.hasNext()) { currentLine = lineIterator.nextLine(); for(Map.Entry<String, EntityType> entry : tableNameAndEntityType.entrySet()) { if(currentLine.startsWith(entry.getKey())) { processBlock(lineIterator, entry.getValue()); } } } } finally { lineIterator.close(); } } private void processBlock(LineIterator lineIterator, EntityType entityType) { String currentLine; while(lineIterator.hasNext()) { currentLine = lineIterator.nextLine(); if(isBlockFinished(currentLine)) { return; } allEntityIdsAndTypes.put(currentLine.split("\t")[0], entityType.name()); } } }
repos\thingsboard-master\tools\src\main\java\org\thingsboard\client\tools\migrator\RelatedEntitiesParser.java
1
请完成以下Java代码
public Optional<UserDashboardDataProvider> getData(@NonNull final UserDashboardKey userDashboardKey) { return userDashboardRepository.getUserDashboardId(userDashboardKey) .map(this::getData); } public UserDashboardDataProvider getData(@NonNull final UserDashboardId dashboardId) { return providers.getOrLoad(dashboardId, this::createDashboardDataProvider); } private UserDashboardDataProvider createDashboardDataProvider(@NonNull final UserDashboardId dashboardId) { return UserDashboardDataProvider.builder() .userDashboardRepository(userDashboardRepository) .kpiDataProvider(kpiDataProvider)
.dashboardId(dashboardId) .build(); } public KPIDataResult getKPIData(@NonNull final KPIId kpiId, @NonNull final KPIDataContext kpiDataContext) { return kpiDataProvider.getKPIData(KPIDataRequest.builder() .kpiId(kpiId) .timeRangeDefaults(KPITimeRangeDefaults.DEFAULT) .context(kpiDataContext) .maxStaleAccepted(Duration.ofDays(100)) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\UserDashboardDataService.java
1
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private final BookRepositoryFetchModeJoin bookRepositoryFetchModeJoin; private final BookRepositoryEntityGraph bookRepositoryEntityGraph; private final BookRepositoryJoinFetch bookRepositoryJoinFetch; public BookstoreService(BookRepositoryFetchModeJoin bookRepositoryFetchModeJoin, BookRepositoryEntityGraph bookRepositoryEntityGraph, BookRepositoryJoinFetch bookRepositoryJoinFetch) { this.bookRepositoryFetchModeJoin = bookRepositoryFetchModeJoin; this.bookRepositoryEntityGraph = bookRepositoryEntityGraph; this.bookRepositoryJoinFetch = bookRepositoryJoinFetch; } public void displayBookById() { Book book = bookRepositoryFetchModeJoin.findById(1L).orElseThrow(); // LEFT JOIN displayBook(book); } public void displayBookByIdViaJoinFetch() { Book book = bookRepositoryJoinFetch.findById(1L).orElseThrow(); // LEFT JOIN displayBook(book); } public void displayBookByIdViaEntityGraph() { Book book = bookRepositoryEntityGraph.findById(1L).orElseThrow(); // LEFT JOIN displayBook(book); } public void displayBooksCausingNPlus1() { List<Book> books = bookRepositoryFetchModeJoin.findAll(); // N+1 displayBooks(books); } public void displayBooksByAgeGt45CausingNPlus1() {
List<Book> books = bookRepositoryFetchModeJoin.findAll(isPriceGt35()); // N+1 displayBooks(books); } public void displayBooksViaEntityGraph() { List<Book> books = bookRepositoryEntityGraph.findAll(); // LEFT JOIN displayBooks(books); } public void displayBooksByAgeGt45ViaEntityGraph() { List<Book> books = bookRepositoryEntityGraph.findAll(isPriceGt35()); // LEFT JOIN displayBooks(books); } public void displayBooksViaJoinFetch() { List<Book> books = bookRepositoryJoinFetch.findAll(); // LEFT JOIN displayBooks(books); } private void displayBook(Book book) { System.out.println(book); System.out.println(book.getAuthor()); System.out.println(book.getAuthor().getPublisher() + "\n"); } private void displayBooks(List<Book> books) { for (Book book : books) { System.out.println(book); System.out.println(book.getAuthor()); System.out.println(book.getAuthor().getPublisher() + "\n"); } } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootFetchJoinAndQueries\src\main\java\com\bookstore\service\BookstoreService.java
2
请在Spring Boot框架中完成以下Java代码
public MetricRegistry getMetricRegistry() { return metricRegistry; } @Override @Bean public HealthCheckRegistry getHealthCheckRegistry() { return healthCheckRegistry; } @PostConstruct public void init() { log.debug("Registering JVM gauges"); metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet()); metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet()); metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet()); metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge()); metricRegistry.register(PROP_METRIC_REG_JVM_BUFFERS, new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer())); metricRegistry.register(PROP_METRIC_REG_JVM_ATTRIBUTE_SET, new JvmAttributeGaugeSet()); if (hikariDataSource != null) { log.debug("Monitoring the datasource"); // remove the factory created by HikariDataSourceMetricsPostProcessor until JHipster migrate to Micrometer hikariDataSource.setMetricsTrackerFactory(null); hikariDataSource.setMetricRegistry(metricRegistry); }
if (jHipsterProperties.getMetrics().getJmx().isEnabled()) { log.debug("Initializing Metrics JMX reporting"); JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build(); jmxReporter.start(); } if (jHipsterProperties.getMetrics().getLogs().isEnabled()) { log.info("Initializing Metrics Log reporting"); Marker metricsMarker = MarkerFactory.getMarker("metrics"); final Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry) .outputTo(LoggerFactory.getLogger("metrics")) .markWith(metricsMarker) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build(); reporter.start(jHipsterProperties.getMetrics().getLogs().getReportFrequency(), TimeUnit.SECONDS); } } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\config\MetricsConfiguration.java
2
请完成以下Java代码
public void notify(final DelegateTask delegateTask){ if(delegateTask.getExecution() == null) { LOG.taskNotRelatedToExecution(delegateTask); } else { final DelegateExecution execution = delegateTask.getExecution(); Callable<Void> notification = new Callable<Void>() { public Void call() throws Exception { notifyTaskListener(delegateTask); return null; } }; try { performNotification(execution, notification); } catch(Exception e) { throw LOG.exceptionWhileNotifyingPaTaskListener(e); } } } protected void performNotification(final DelegateExecution execution, Callable<Void> notification) throws Exception { final ProcessApplicationReference processApp = ProcessApplicationContextUtil.getTargetProcessApplication((ExecutionEntity) execution); if (processApp == null) { // ignore silently LOG.noTargetProcessApplicationForExecution(execution); } else { if (ProcessApplicationContextUtil.requiresContextSwitch(processApp)) { // this should not be necessary since context switch is already performed by OperationContext and / or DelegateInterceptor Context.executeWithinProcessApplication(notification, processApp, new InvocationContext(execution)); } else { // context switch already performed notification.call(); } } } protected void notifyExecutionListener(DelegateExecution execution) throws Exception { ProcessApplicationReference processApp = Context.getCurrentProcessApplication(); try { ProcessApplicationInterface processApplication = processApp.getProcessApplication(); ExecutionListener executionListener = processApplication.getExecutionListener(); if(executionListener != null) {
executionListener.notify(execution); } else { LOG.paDoesNotProvideExecutionListener(processApp.getName()); } } catch (ProcessApplicationUnavailableException e) { // Process Application unavailable => ignore silently LOG.cannotInvokeListenerPaUnavailable(processApp.getName(), e); } } protected void notifyTaskListener(DelegateTask task) throws Exception { ProcessApplicationReference processApp = Context.getCurrentProcessApplication(); try { ProcessApplicationInterface processApplication = processApp.getProcessApplication(); TaskListener taskListener = processApplication.getTaskListener(); if(taskListener != null) { taskListener.notify(task); } else { LOG.paDoesNotProvideTaskListener(processApp.getName()); } } catch (ProcessApplicationUnavailableException e) { // Process Application unavailable => ignore silently LOG.cannotInvokeListenerPaUnavailable(processApp.getName(), e); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\event\ProcessApplicationEventListenerDelegate.java
1
请完成以下Java代码
public class JWTUtil { private static Logger log = LoggerFactory.getLogger(JWTUtil.class); private static final long EXPIRE_TIME = SpringContextUtil.getBean(SystemProperties.class).getJwtTimeOut() * 1000; /** * 校验 token是否正确 * * @param token 密钥 * @param secret 用户的密码 * @return 是否正确 */ public static boolean verify(String token, String username, String secret) { try { Algorithm algorithm = Algorithm.HMAC256(secret); JWTVerifier verifier = JWT.require(algorithm) .withClaim("username", username) .build(); verifier.verify(token); log.info("token is valid"); return true; } catch (Exception e) { log.info("token is invalid{}", e.getMessage()); return false; } } /** * 从 token中获取用户名 * * @return token中包含的用户名 */ public static String getUsername(String token) { try {
DecodedJWT jwt = JWT.decode(token); return jwt.getClaim("username").asString(); } catch (JWTDecodeException e) { log.error("error:{}", e.getMessage()); return null; } } /** * 生成 token * * @param username 用户名 * @param secret 用户的密码 * @return token */ public static String sign(String username, String secret) { try { username = StringUtils.lowerCase(username); Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME); Algorithm algorithm = Algorithm.HMAC256(secret); return JWT.create() .withClaim("username", username) .withExpiresAt(date) .sign(algorithm); } catch (Exception e) { log.error("error:{}", e); return null; } } }
repos\SpringAll-master\62.Spring-Boot-Shiro-JWT\src\main\java\com\example\demo\authentication\JWTUtil.java
1
请在Spring Boot框架中完成以下Java代码
public Runnable getExecuteJobsRunnable(List<String> jobIds, ProcessEngineImpl processEngine) { return new ExecuteJobsRunnable(jobIds, processEngine); } public boolean schedule(Runnable runnable, boolean isLongRunning) { if(isLongRunning) { return scheduleLongRunningWork(runnable); } else { return scheduleShortRunningWork(runnable); } } protected boolean scheduleShortRunningWork(Runnable runnable) { ManagedQueueExecutorService managedQueueExecutorService = managedQueueInjector.getValue(); try { managedQueueExecutorService.executeBlocking(runnable); return true; } catch (InterruptedException e) { // the the acquisition thread is interrupted, this probably means the app server is turning the lights off -> ignore } catch (Exception e) { // we must be able to schedule this log.log(Level.WARNING, "Cannot schedule long running work.", e); } return false; } protected boolean scheduleLongRunningWork(Runnable runnable) { final ManagedQueueExecutorService managedQueueExecutorService = managedQueueInjector.getValue();
boolean rejected = false; try { // wait for 2 seconds for the job to be accepted by the pool. managedQueueExecutorService.executeBlocking(runnable, 2, TimeUnit.SECONDS); } catch (InterruptedException e) { // the acquisition thread is interrupted, this probably means the app server is turning the lights off -> ignore } catch (ExecutionTimedOutException e) { rejected = true; } catch (RejectedExecutionException e) { rejected = true; } catch (Exception e) { // if it fails for some other reason, log a warning message long now = System.currentTimeMillis(); // only log every 60 seconds to prevent log flooding if((now-lastWarningLogged) >= (60*1000)) { log.log(Level.WARNING, "Unexpected Exception while submitting job to executor pool.", e); } else { log.log(Level.FINE, "Unexpected Exception while submitting job to executor pool.", e); } } return !rejected; } public InjectedValue<ManagedQueueExecutorService> getManagedQueueInjector() { return managedQueueInjector; } }
repos\camunda-bpm-platform-master\distro\wildfly26\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\MscExecutorService.java
2
请完成以下Java代码
public class ToDoItem { private int userId; private int id; private String title; private boolean completed; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; } public boolean isCompleted() { return completed; } public void setCompleted(boolean completed) { this.completed = completed; } @Override public String toString() { return "ToDoItem{" + "userId=" + userId + ", id=" + id + ", title='" + title + '\'' + ", completed=" + completed + '}'; } }
repos\tutorials-master\aws-modules\aws-lambda-modules\todo-reminder-lambda\ToDoFunction\src\main\java\com\baeldung\lambda\todo\api\ToDoItem.java
1
请完成以下Java代码
public void setName(String name) { this.name = name; } public Optional<String> getGenre() { return Optional.ofNullable(genre); } public void setGenre(String genre) { this.genre = genre; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }
public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } @Override public String toString() { return "Author{" + "id=" + id + ", name=" + name + ", genre=" + genre + ", age=" + age + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootOptional\src\main\java\com\bookstore\entity\Author.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isIgnoreUnreadFields() { return this.ignoreUnreadFields; } public void setIgnoreUnreadFields(boolean ignoreUnreadFields) { this.ignoreUnreadFields = ignoreUnreadFields; } public boolean isPersistent() { return this.persistent; } public void setPersistent(boolean persistent) { this.persistent = persistent; }
public boolean isReadSerialized() { return this.readSerialized; } public void setReadSerialized(boolean readSerialized) { this.readSerialized = readSerialized; } public String getSerializerBeanName() { return this.serializerBeanName; } public void setSerializerBeanName(String serializerBeanName) { this.serializerBeanName = serializerBeanName; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\PdxProperties.java
2
请在Spring Boot框架中完成以下Java代码
public String sleep() throws InterruptedException { Thread.sleep(100L); return "sleep"; } // 测试热点参数限流 @GetMapping("/product_info") @SentinelResource("demo_product_info_hot") public String productInfo(Integer id) { return "商品编号:" + id; } // 手动使用 Sentinel 客户端 API @GetMapping("/entry_demo") public String entryDemo() { Entry entry = null; try { // 访问资源 entry = SphU.entry("entry_demo"); // ... 执行业务逻辑 return "执行成功"; } catch (BlockException ex) { return "被拒绝"; } finally { // 释放资源 if (entry != null) { entry.exit();
} } } // 测试 @SentinelResource 注解 @GetMapping("/annotations_demo") @SentinelResource(value = "annotations_demo_resource", blockHandler = "blockHandler", fallback = "fallback") public String annotationsDemo(@RequestParam(required = false) Integer id) throws InterruptedException { if (id == null) { throw new IllegalArgumentException("id 参数不允许为空"); } return "success..."; } // BlockHandler 处理函数,参数最后多一个 BlockException,其余与原函数一致. public String blockHandler(Integer id, BlockException ex) { return "block:" + ex.getClass().getSimpleName(); } // Fallback 处理函数,函数签名与原函数一致或加一个 Throwable 类型的参数. public String fallback(Integer id, Throwable throwable) { return "fallback:" + throwable.getMessage(); } }
repos\SpringBoot-Labs-master\lab-46\lab-46-sentinel-demo\src\main\java\cn\iocoder\springboot\lab46\sentineldemo\controller\DemoController.java
2
请完成以下Java代码
public int getC_CompensationGroup_SchemaLine_ID() { return get_ValueAsInt(COLUMNNAME_C_CompensationGroup_SchemaLine_ID); } @Override public void setC_Flatrate_Conditions_ID (final int C_Flatrate_Conditions_ID) { if (C_Flatrate_Conditions_ID < 1) set_Value (COLUMNNAME_C_Flatrate_Conditions_ID, null); else set_Value (COLUMNNAME_C_Flatrate_Conditions_ID, C_Flatrate_Conditions_ID); } @Override public int getC_Flatrate_Conditions_ID() { return get_ValueAsInt(COLUMNNAME_C_Flatrate_Conditions_ID); } @Override public void setCompleteOrderDiscount (final @Nullable BigDecimal CompleteOrderDiscount) { set_Value (COLUMNNAME_CompleteOrderDiscount, CompleteOrderDiscount); } @Override public BigDecimal getCompleteOrderDiscount() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_CompleteOrderDiscount); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override
public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } /** * Type AD_Reference_ID=540836 * Reference name: C_CompensationGroup_SchemaLine_Type */ public static final int TYPE_AD_Reference_ID=540836; /** Revenue = R */ public static final String TYPE_Revenue = "R"; /** Flatrate = F */ public static final String TYPE_Flatrate = "F"; @Override public void setType (final @Nullable java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\order\model\X_C_CompensationGroup_SchemaLine.java
1
请完成以下Java代码
public class SuperHero extends Person { /** * The public name of a hero that is common knowledge */ private String heroName; private String uniquePower; private int health; private int defense; /** * <p>This is a simple description of the method. . . * <a href="http://www.supermanisthegreatest.com">Superman!</a> * </p> * @param incomingDamage the amount of incoming damage * @return the amount of health hero has after attack * @see <a href="http://www.link_to_jira/HERO-402">HERO-402</a> * @since 1.0 * @deprecated As of version 1.1, use . . . instead * @version 1.2 * @throws IllegalArgumentException if incomingDamage is negative */ public int successfullyAttacked(int incomingDamage, String damageType) throws Exception { // do things if (incomingDamage < 0) { throw new IllegalArgumentException ("Cannot cause negative damage"); } return 0; } public String getHeroName() { return heroName; } public void setHeroName(String heroName) { this.heroName = heroName; } public String getUniquePower() { return uniquePower; }
public void setUniquePower(String uniquePower) { this.uniquePower = uniquePower; } public int getHealth() { return health; } public void setHealth(int health) { this.health = health; } public int getDefense() { return defense; } public void setDefense(int defense) { this.defense = defense; } }
repos\tutorials-master\core-java-modules\core-java-documentation\src\main\java\com\baeldung\javadoc\SuperHero.java
1
请完成以下Java代码
public void setPassword (java.lang.String Password) { set_Value (COLUMNNAME_Password, Password); } /** Get Kennwort. @return Kennwort */ @Override public java.lang.String getPassword () { return (java.lang.String)get_Value(COLUMNNAME_Password); } /** Set Grund der Anfrage. @param RequestReason Grund der Anfrage */ @Override public void setRequestReason (java.lang.String RequestReason) { set_Value (COLUMNNAME_RequestReason, RequestReason); } /** Get Grund der Anfrage. @return Grund der Anfrage */ @Override public java.lang.String getRequestReason () { return (java.lang.String)get_Value(COLUMNNAME_RequestReason); } /** Set REST API URL. @param RestApiBaseURL REST API URL */ @Override public void setRestApiBaseURL (java.lang.String RestApiBaseURL) { set_Value (COLUMNNAME_RestApiBaseURL, RestApiBaseURL); } /** Get REST API URL. @return REST API URL */ @Override public java.lang.String getRestApiBaseURL () { return (java.lang.String)get_Value(COLUMNNAME_RestApiBaseURL); }
/** Set Creditpass-Prüfung wiederholen . @param RetryAfterDays Creditpass-Prüfung wiederholen */ @Override public void setRetryAfterDays (java.math.BigDecimal RetryAfterDays) { set_Value (COLUMNNAME_RetryAfterDays, RetryAfterDays); } /** Get Creditpass-Prüfung wiederholen . @return Creditpass-Prüfung wiederholen */ @Override public java.math.BigDecimal getRetryAfterDays () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RetryAfterDays); if (bd == null) return BigDecimal.ZERO; return bd; } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java-gen\de\metas\vertical\creditscore\creditpass\model\X_CS_Creditpass_Config.java
1
请完成以下Java代码
public String getReferenceId() { return referenceId; } public String getReferenceType() { return referenceType; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public String getTenantIdLikeIgnoreCase() { return tenantIdLikeIgnoreCase; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getActivePlanItemDefinitionId() { return activePlanItemDefinitionId; } public Set<String> getActivePlanItemDefinitionIds() { return activePlanItemDefinitionIds; } public String getInvolvedUser() { return involvedUser; } public IdentityLinkQueryObject getInvolvedUserIdentityLink() { return involvedUserIdentityLink; } public Set<String> getInvolvedGroups() { return involvedGroups; } public IdentityLinkQueryObject getInvolvedGroupIdentityLink() { return involvedGroupIdentityLink; } public boolean isIncludeCaseVariables() { return includeCaseVariables; } public Collection<String> getVariableNamesToInclude() { return variableNamesToInclude; } public List<HistoricCaseInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; }
public String getDeploymentId() { return deploymentId; } public List<String> getDeploymentIds() { return deploymentIds; } public Set<String> getCaseInstanceIds() { return caseInstanceIds; } public boolean isNeedsCaseDefinitionOuterJoin() { if (isNeedsPaging()) { if (AbstractEngineConfiguration.DATABASE_TYPE_ORACLE.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_DB2.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_MSSQL.equals(databaseType)) { // When using oracle, db2 or mssql we don't need outer join for the process definition join. // It is not needed because the outer join order by is done by the row number instead return false; } } return hasOrderByForColumn(HistoricCaseInstanceQueryProperty.CASE_DEFINITION_KEY.getName()); } public List<List<String>> getSafeCaseInstanceIds() { return safeCaseInstanceIds; } public void setSafeCaseInstanceIds(List<List<String>> safeCaseInstanceIds) { this.safeCaseInstanceIds = safeCaseInstanceIds; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } public String getRootScopeId() { return rootScopeId; } public String getParentScopeId() { return parentScopeId; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\history\HistoricCaseInstanceQueryImpl.java
1