instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class BeamElement implements Comparable<BeamElement> { public float score; public int index; public int action; public int label; public BeamElement(float score, int index, int action, int label) { this.score = score; this.index = index; this.action = action; this.label = label; } @Override public int compareTo(BeamElement beamElement)
{ float diff = score - beamElement.score; if (diff > 0) return 2; if (diff < 0) return -2; if (index != beamElement.index) return beamElement.index - index; return beamElement.action - action; } @Override public boolean equals(Object o) { return false; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\perceptron\transition\configuration\BeamElement.java
2
请在Spring Boot框架中完成以下Java代码
public static class Shutdown { /** * Whether to accept further tasks after the application context close phase * has begun. */ private boolean acceptTasksAfterContextClose; public boolean isAcceptTasksAfterContextClose() { return this.acceptTasksAfterContextClose; } public void setAcceptTasksAfterContextClose(boolean acceptTasksAfterContextClose) { this.acceptTasksAfterContextClose = acceptTasksAfterContextClose; } } } public static class Shutdown { /** * Whether the executor should wait for scheduled tasks to complete on shutdown. */ private boolean awaitTermination; /** * Maximum time the executor should wait for remaining tasks to complete. */ private @Nullable Duration awaitTerminationPeriod; public boolean isAwaitTermination() { return this.awaitTermination; } public void setAwaitTermination(boolean awaitTermination) { this.awaitTermination = awaitTermination; }
public @Nullable Duration getAwaitTerminationPeriod() { return this.awaitTerminationPeriod; } public void setAwaitTerminationPeriod(@Nullable Duration awaitTerminationPeriod) { this.awaitTerminationPeriod = awaitTerminationPeriod; } } /** * Determine when the task executor is to be created. * * @since 3.5.0 */ public enum Mode { /** * Create the task executor if no user-defined executor is present. */ AUTO, /** * Create the task executor even if a user-defined executor is present. */ FORCE } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\task\TaskExecutionProperties.java
2
请完成以下Java代码
public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product. @return Product, Service, Item */ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo);
} return false; } /** Set Quantity Invoiced. @param ServiceLevelInvoiced Quantity of product or service invoiced */ public void setServiceLevelInvoiced (BigDecimal ServiceLevelInvoiced) { set_ValueNoCheck (COLUMNNAME_ServiceLevelInvoiced, ServiceLevelInvoiced); } /** Get Quantity Invoiced. @return Quantity of product or service invoiced */ public BigDecimal getServiceLevelInvoiced () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ServiceLevelInvoiced); if (bd == null) return Env.ZERO; return bd; } /** Set Quantity Provided. @param ServiceLevelProvided Quantity of service or product provided */ public void setServiceLevelProvided (BigDecimal ServiceLevelProvided) { set_ValueNoCheck (COLUMNNAME_ServiceLevelProvided, ServiceLevelProvided); } /** Get Quantity Provided. @return Quantity of service or product provided */ public BigDecimal getServiceLevelProvided () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ServiceLevelProvided); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ServiceLevel.java
1
请在Spring Boot框架中完成以下Java代码
public class Saml2PostAuthenticationRequest extends AbstractSaml2AuthenticationRequest { @Serial private static final long serialVersionUID = -6412064305715642123L; Saml2PostAuthenticationRequest(String samlRequest, String relayState, String authenticationRequestUri, String relyingPartyRegistrationId, String id) { super(samlRequest, relayState, authenticationRequestUri, relyingPartyRegistrationId, id); } /** * @return {@link Saml2MessageBinding#POST} */ @Override public Saml2MessageBinding getBinding() { return Saml2MessageBinding.POST; } /** * Constructs a {@link Builder} from a {@link RelyingPartyRegistration} object. * @param registration a relying party registration * @return a modifiable builder object * @since 5.7 */ public static Builder withRelyingPartyRegistration(RelyingPartyRegistration registration) { String location = registration.getAssertingPartyMetadata().getSingleSignOnServiceLocation(); return new Builder(registration).authenticationRequestUri(location); } /** * Builder class for a {@link Saml2PostAuthenticationRequest} object. */ public static final class Builder extends AbstractSaml2AuthenticationRequest.Builder<Builder> {
private Builder(RelyingPartyRegistration registration) { super(registration); } /** * Constructs an immutable {@link Saml2PostAuthenticationRequest} object. * @return an immutable {@link Saml2PostAuthenticationRequest} object. */ public Saml2PostAuthenticationRequest build() { return new Saml2PostAuthenticationRequest(this.samlRequest, this.relayState, this.authenticationRequestUri, this.relyingPartyRegistrationId, this.id); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\Saml2PostAuthenticationRequest.java
2
请在Spring Boot框架中完成以下Java代码
public void setC_Currency_ID (final int C_Currency_ID) { if (C_Currency_ID < 1) set_Value (COLUMNNAME_C_Currency_ID, null); else set_Value (COLUMNNAME_C_Currency_ID, C_Currency_ID); } @Override public int getC_Currency_ID() { return get_ValueAsInt(COLUMNNAME_C_Currency_ID); } @Override public void setClosingNote (final @Nullable java.lang.String ClosingNote) { set_Value (COLUMNNAME_ClosingNote, ClosingNote); } @Override public java.lang.String getClosingNote() { return get_ValueAsString(COLUMNNAME_ClosingNote); } @Override public org.compiere.model.I_C_POS getC_POS() { return get_ValueAsPO(COLUMNNAME_C_POS_ID, org.compiere.model.I_C_POS.class); } @Override public void setC_POS(final org.compiere.model.I_C_POS C_POS) { set_ValueFromPO(COLUMNNAME_C_POS_ID, org.compiere.model.I_C_POS.class, C_POS); } @Override public void setC_POS_ID (final int C_POS_ID) { if (C_POS_ID < 1) set_Value (COLUMNNAME_C_POS_ID, null); else set_Value (COLUMNNAME_C_POS_ID, C_POS_ID); } @Override public int getC_POS_ID() { return get_ValueAsInt(COLUMNNAME_C_POS_ID); } @Override public void setC_POS_Journal_ID (final int C_POS_Journal_ID) { if (C_POS_Journal_ID < 1) set_ValueNoCheck (COLUMNNAME_C_POS_Journal_ID, null); else set_ValueNoCheck (COLUMNNAME_C_POS_Journal_ID, C_POS_Journal_ID); } @Override public int getC_POS_Journal_ID() { return get_ValueAsInt(COLUMNNAME_C_POS_Journal_ID);
} @Override public void setDateTrx (final java.sql.Timestamp DateTrx) { set_Value (COLUMNNAME_DateTrx, DateTrx); } @Override public java.sql.Timestamp getDateTrx() { return get_ValueAsTimestamp(COLUMNNAME_DateTrx); } @Override public void setDocumentNo (final java.lang.String DocumentNo) { set_Value (COLUMNNAME_DocumentNo, DocumentNo); } @Override public java.lang.String getDocumentNo() { return get_ValueAsString(COLUMNNAME_DocumentNo); } @Override public void setIsClosed (final boolean IsClosed) { set_Value (COLUMNNAME_IsClosed, IsClosed); } @Override public boolean isClosed() { return get_ValueAsBoolean(COLUMNNAME_IsClosed); } @Override public void setOpeningNote (final @Nullable java.lang.String OpeningNote) { set_Value (COLUMNNAME_OpeningNote, OpeningNote); } @Override public java.lang.String getOpeningNote() { return get_ValueAsString(COLUMNNAME_OpeningNote); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_Journal.java
2
请完成以下Java代码
public Builder setDocumentDecorators(final ImmutableList<IDocumentDecorator> documentDecorators) { this.documentDecorators = documentDecorators; return this; } @Nullable public ImmutableList<IDocumentDecorator> getDocumentDecorators() { return this.documentDecorators; } public Builder setRefreshViewOnChangeEvents(final boolean refreshViewOnChangeEvents) { this._refreshViewOnChangeEvents = refreshViewOnChangeEvents; return this; } private boolean isRefreshViewOnChangeEvents() { return _refreshViewOnChangeEvents; } public Builder setPrintProcessId(final AdProcessId printProcessId) { _printProcessId = printProcessId; return this; } private AdProcessId getPrintProcessId() { return _printProcessId; } private boolean isCloneEnabled() { return isCloneEnabled(_tableName); } private static boolean isCloneEnabled(@Nullable final Optional<String> tableName) { if (tableName == null || !tableName.isPresent())
{ return false; } return CopyRecordFactory.isEnabledForTableName(tableName.get()); } public DocumentQueryOrderByList getDefaultOrderBys() { return getFieldBuilders() .stream() .filter(DocumentFieldDescriptor.Builder::isDefaultOrderBy) .sorted(Ordering.natural().onResultOf(DocumentFieldDescriptor.Builder::getDefaultOrderByPriority)) .map(field -> DocumentQueryOrderBy.byFieldName(field.getFieldName(), field.isDefaultOrderByAscending())) .collect(DocumentQueryOrderByList.toDocumentQueryOrderByList()); } public Builder queryIfNoFilters(final boolean queryIfNoFilters) { this.queryIfNoFilters = queryIfNoFilters; return this; } public Builder notFoundMessages(@Nullable final NotFoundMessages notFoundMessages) { this.notFoundMessages = notFoundMessages; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentEntityDescriptor.java
1
请在Spring Boot框架中完成以下Java代码
public Builder location(String location) { this.location = location; return this; } /** * Use this value for the relay state when sending the Logout Request to the * asserting party * * It should not be URL-encoded as this will be done when the response is sent * @param relayState the relay state * @return the {@link Builder} for further configurations */ public Builder relayState(String relayState) { this.parameters.put(Saml2ParameterNames.RELAY_STATE, relayState); return this; } /** * Use this {@link Consumer} to modify the set of query parameters * * No parameter should be URL-encoded as this will be done when the response is * sent, though any signature specified should be Base64-encoded * @param parametersConsumer the {@link Consumer} * @return the {@link Builder} for further configurations */ public Builder parameters(Consumer<Map<String, String>> parametersConsumer) { parametersConsumer.accept(this.parameters); return this; }
/** * Use this strategy for converting parameters into an encoded query string. The * resulting query does not contain a leading question mark. * * In the event that you already have an encoded version that you want to use, you * can call this by doing {@code parameterEncoder((params) -> encodedValue)}. * @param encoder the strategy to use * @return the {@link Saml2LogoutRequest.Builder} for further configurations * @since 5.8 */ public Builder parametersQuery(Function<Map<String, String>, String> encoder) { this.encoder = encoder; return this; } /** * Build the {@link Saml2LogoutResponse} * @return a constructed {@link Saml2LogoutResponse} */ public Saml2LogoutResponse build() { return new Saml2LogoutResponse(this.location, this.binding, this.parameters, this.encoder); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\logout\Saml2LogoutResponse.java
2
请完成以下Java代码
private void createRecord(String text) { MADBoilerPlate.createSpoolRecord(getCtx(), getAD_Client_ID(), getPinstanceId(), text, get_TrxName()); } private boolean isJasperReport() { final String whereClause = I_AD_Process.COLUMNNAME_AD_Process_ID + "=?" + " AND " + I_AD_Process.COLUMNNAME_JasperReport + " IS NOT NULL"; return new Query(getCtx(), I_AD_Process.Table_Name, whereClause, get_TrxName()) .setParameters(getProcessInfo().getAdProcessId()) .anyMatch(); } private void startJasper()
{ ProcessInfo.builder() .setCtx(getCtx()) .setProcessCalledFrom(getProcessInfo().getProcessCalledFrom()) .setAD_Client_ID(getAD_Client_ID()) .setAD_User_ID(getAD_User_ID()) .setPInstanceId(getPinstanceId()) .setAD_Process_ID(0) .setTableName(I_T_BoilerPlate_Spool.Table_Name) // .buildAndPrepareExecution() .onErrorThrowException() .executeSync(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\letters\report\AD_BoilerPlate_Report.java
1
请完成以下Java代码
private StagingData retrieveStagingData(@NonNull final String transactionId) { return cache.getOrLoad(transactionId, this::retrieveStagingData0); } @NonNull private StagingData retrieveStagingData0(@NonNull final String transactionId) { final I_M_ShipmentSchedule_ExportAudit exportAuditRecord = queryBL.createQueryBuilder(I_M_ShipmentSchedule_ExportAudit.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_M_ShipmentSchedule_ExportAudit.COLUMN_TransactionIdAPI, transactionId) .create() .firstOnly(I_M_ShipmentSchedule_ExportAudit.class); // we have a UC on TransactionIdAPI if (exportAuditRecord == null) { return new StagingData(ImmutableMap.of(), null, ImmutableList.of()); } final ImmutableList<I_M_ShipmentSchedule_ExportAudit_Item> exportAuditItemRecords = queryBL.createQueryBuilder(I_M_ShipmentSchedule_ExportAudit_Item.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_M_ShipmentSchedule_ExportAudit_Item.COLUMN_M_ShipmentSchedule_ExportAudit_ID, exportAuditRecord.getM_ShipmentSchedule_ExportAudit_ID()) .create() .listImmutable(I_M_ShipmentSchedule_ExportAudit_Item.class);
return new StagingData( Maps.uniqueIndex(exportAuditItemRecords, I_M_ShipmentSchedule_ExportAudit_Item::getM_ShipmentSchedule_ID), exportAuditRecord, exportAuditItemRecords); } @Value private static class StagingData { @NonNull ImmutableMap<Integer, I_M_ShipmentSchedule_ExportAudit_Item> schedIdToRecords; @Nullable I_M_ShipmentSchedule_ExportAudit record; @NonNull ImmutableList<I_M_ShipmentSchedule_ExportAudit_Item> itemRecords; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\exportaudit\ShipmentScheduleAuditRepository.java
1
请完成以下Java代码
public final class Threads { private Threads() { } /** * Attempt to stop given thread. * * @param thread thread to be stopped. * @param timeoutMillis how many millis (maximum) to try stopping the thread; if ZERO it will try to stop infinitelly * @throws TimeoutException if thread could not be stopped in given time frame. */ public static final void stop(final Thread thread, final long timeoutMillis) throws TimeoutException { Check.assumeNotNull(thread, "thread not null"); Check.assume(timeoutMillis >= 0, "timeoutMillis >= 0"); long timeoutRemaining = timeoutMillis <= 0 ? Long.MAX_VALUE : timeoutMillis; final long periodMillis = Math.min(100, timeoutRemaining); // // As long as the thread is not dead and we did not exceed our timeout, hit the tread unil it dies. while (thread.isAlive() && timeoutRemaining > 0) { thread.interrupt(); // Wait for the thread to die try { thread.join(periodMillis); } catch (InterruptedException e) { // Thread was interrupted. // We don't fucking care, we continue to hit it until it's dead or until the timeout is exceeded. } timeoutRemaining -= periodMillis; }
// // If the thread is still alive we throw an timeout exception if (thread.isAlive()) { throw new TimeoutException("Failed to kill thread " + thread.getName() + " in " + timeoutMillis + "ms"); } } /** * Convenient method to set a thread name and also get the previous name. * * @param thread * @param name * @return previous thread name */ public static String setThreadName(final Thread thread, final String name) { final String nameOld = thread.getName(); thread.setName(name); return nameOld; } /** * Convenient method to set a current thread's name and also get the previous name. * * @param thread * @param name * @return previous thread name */ public static String setThreadName(final String name) { return setThreadName(Thread.currentThread(), name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\concurrent\Threads.java
1
请在Spring Boot框架中完成以下Java代码
public class ViewRowIdsOrderedSelection { ViewId viewId; long size; DocumentQueryOrderByList orderBys; QueryLimit queryLimit; boolean queryLimitHit; @Nullable EmptyReason emptyReason; @Builder(toBuilder = true) private ViewRowIdsOrderedSelection( @NonNull final ViewId viewId, final long size, @Nullable final DocumentQueryOrderByList orderBys, @Nullable final QueryLimit queryLimit, @Nullable final EmptyReason emptyReason) { this.viewId = viewId; this.size = size; this.orderBys = orderBys != null ? orderBys : DocumentQueryOrderByList.EMPTY; this.queryLimit = queryLimit != null ? queryLimit : QueryLimit.NO_LIMIT; this.emptyReason = emptyReason; this.queryLimitHit = this.queryLimit.isLimited()
&& size > 0 && size >= this.queryLimit.toInt(); } public static boolean equals(@Nullable final ViewRowIdsOrderedSelection s1, @Nullable final ViewRowIdsOrderedSelection s2) { return Objects.equals(s1, s2); } public WindowId getWindowId() { return getViewId().getWindowId(); } public String getSelectionId() { return getViewId().getViewId(); } public ViewRowIdsOrderedSelection withSize(final int size) { return this.size == size ? this : toBuilder().size(size).build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRowIdsOrderedSelection.java
2
请在Spring Boot框架中完成以下Java代码
public List<AppDefinition> executeList(CommandContext commandContext) { return CommandContextUtil.getAppDefinitionEntityManager(commandContext).findAppDefinitionsByQueryCriteria(this); } // getters //////////////////////////////////////////// public String getDeploymentId() { return deploymentId; } public Set<String> getDeploymentIds() { return deploymentIds; } public String getId() { return id; } public Set<String> getIds() { return ids; } public String getName() { return name; } public String getNameLike() { return nameLike; } public String getKey() { return key; } public String getKeyLike() { return keyLike; } public Integer getVersion() { return version; } public Integer getVersionGt() { return versionGt; } public Integer getVersionGte() { return versionGte; } public Integer getVersionLt() { return versionLt; } public Integer getVersionLte() { return versionLte; } public boolean isLatest() { return latest; } public String getCategory() { return category; }
public String getCategoryLike() { return categoryLike; } public String getResourceName() { return resourceName; } public String getResourceNameLike() { return resourceNameLike; } public String getCategoryNotEquals() { return categoryNotEquals; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\repository\AppDefinitionQueryImpl.java
2
请完成以下Java代码
public DocumentZoomIntoInfo getDocumentZoomInto(final int id) { final String tableName = fetcher.getLookupTableName() .orElseThrow(() -> new IllegalStateException("Failed converting id=" + id + " to " + DocumentZoomIntoInfo.class + " because the fetcher returned null tablename: " + fetcher)); return DocumentZoomIntoInfo.of(tableName, id); } @Override public final LookupValuesPage findEntities(final Evaluatee ctx, final int pageLength) { return findEntities(ctx, LookupDataSourceContext.FILTER_Any, FIRST_ROW, pageLength); } @Override public final LookupValuesPage findEntities(final Evaluatee ctx, final String filter, final int firstRow, final int pageLength) { final String filterEffective; if (Check.isBlank(filter)) { filterEffective = LookupDataSourceContext.FILTER_Any; } else { filterEffective = filter.trim(); } final LookupDataSourceContext evalCtx = fetcher.newContextForFetchingList() .setParentEvaluatee(ctx) .putFilter(filterEffective, firstRow, pageLength) .requiresFilterAndLimit() // make sure the filter, limit and offset will be kept on build .build(); return fetcher.retrieveEntities(evalCtx); } @Override public LookupValue findById(final Object idObj) { if (idObj == null) { return null; } // // Normalize the ID to Integer/String final Object idNormalized = LookupValue.normalizeId(idObj, fetcher.isNumericKey()); if (idNormalized == null) { return null; } //
// Build the validation context final LookupDataSourceContext evalCtx = fetcher.newContextForFetchingById(idNormalized) .putFilterById(IdsToFilter.ofSingleValue(idNormalized)) .putShowInactive(true) .build(); // // Get the lookup value final LookupValue lookupValue = fetcher.retrieveLookupValueById(evalCtx); if (lookupValue == LookupDataSourceFetcher.LOOKUPVALUE_NULL) { return null; } return lookupValue; } @Override public @NonNull LookupValuesList findByIdsOrdered(final @NonNull Collection<?> ids) { final LookupDataSourceContext evalCtx = fetcher.newContextForFetchingByIds(ids) .putShowInactive(true) .build(); return fetcher.retrieveLookupValueByIdsInOrder(evalCtx); } @Override public List<CCacheStats> getCacheStats() { return fetcher.getCacheStats(); } @Override public void cacheInvalidate() { fetcher.cacheInvalidate(); } @Override public Optional<WindowId> getZoomIntoWindowId() { return fetcher.getZoomIntoWindowId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\LookupDataSourceAdapter.java
1
请完成以下Java代码
public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } /** * Gender AD_Reference_ID=541317 * Reference name: Gender_List */ public static final int GENDER_AD_Reference_ID=541317; /** Unbekannt = 0 */ public static final String GENDER_Unbekannt = "0"; /** Weiblich = 1 */ public static final String GENDER_Weiblich = "1"; /** Männlich = 2 */ public static final String GENDER_Maennlich = "2"; /** Divers = 3 */ public static final String GENDER_Divers = "3"; @Override public void setGender (final @Nullable java.lang.String Gender) { set_Value (COLUMNNAME_Gender, Gender); } @Override public java.lang.String getGender() { return get_ValueAsString(COLUMNNAME_Gender); } @Override public void setTimestamp (final @Nullable java.sql.Timestamp Timestamp) { set_Value (COLUMNNAME_Timestamp, Timestamp); } @Override public java.sql.Timestamp getTimestamp() { return get_ValueAsTimestamp(COLUMNNAME_Timestamp); } /** * Title AD_Reference_ID=541318 * Reference name: Title_List */ public static final int TITLE_AD_Reference_ID=541318; /** Unbekannt = 0 */ public static final String TITLE_Unbekannt = "0"; /** Dr. = 1 */ public static final String TITLE_Dr = "1"; /** Prof. Dr. = 2 */ public static final String TITLE_ProfDr = "2"; /** Dipl. Ing. = 3 */ public static final String TITLE_DiplIng = "3"; /** Dipl. Med. = 4 */ public static final String TITLE_DiplMed = "4";
/** Dipl. Psych. = 5 */ public static final String TITLE_DiplPsych = "5"; /** Dr. Dr. = 6 */ public static final String TITLE_DrDr = "6"; /** Dr. med. = 7 */ public static final String TITLE_DrMed = "7"; /** Prof. Dr. Dr. = 8 */ public static final String TITLE_ProfDrDr = "8"; /** Prof. = 9 */ public static final String TITLE_Prof = "9"; /** Prof. Dr. med. = 10 */ public static final String TITLE_ProfDrMed = "10"; /** Rechtsanwalt = 11 */ public static final String TITLE_Rechtsanwalt = "11"; /** Rechtsanwältin = 12 */ public static final String TITLE_Rechtsanwaeltin = "12"; /** Schwester (Orden) = 13 */ public static final String TITLE_SchwesterOrden = "13"; @Override public void setTitle (final @Nullable java.lang.String Title) { set_Value (COLUMNNAME_Title, Title); } @Override public java.lang.String getTitle() { return get_ValueAsString(COLUMNNAME_Title); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_AD_User_Alberta.java
1
请在Spring Boot框架中完成以下Java代码
public class Client { @Id @Column(name = "client_id") private String clientId; @Column(name = "client_secret") private String clientSecret; @Column(name = "redirect_uri") private String redirectUri; @Column(name = "scope") private String scope; @Column(name = "authorized_grant_types") private String authorizedGrantTypes; public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getClientSecret() { return clientSecret; } public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret; } public String getRedirectUri() { return redirectUri; } public void setRedirectUri(String redirectUri) { this.redirectUri = redirectUri; } public String getScope() { return scope; } public void setScope(String scope) { this.scope = scope; } public String getAuthorizedGrantTypes() { return authorizedGrantTypes; } public void setAuthorizedGrantTypes(String authorizedGrantTypes) { this.authorizedGrantTypes = authorizedGrantTypes; } }
repos\tutorials-master\security-modules\oauth2-framework-impl\oauth2-authorization-server\src\main\java\com\baeldung\oauth2\authorization\server\model\Client.java
2
请在Spring Boot框架中完成以下Java代码
public LocalContainerEntityManagerFactoryBean productEntityManager() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(productDataSource()); em.setPackagesToScan("com.baeldung.multipledb.model.product"); final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); final HashMap<String, Object> properties = new HashMap<String, Object>(); properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); em.setJpaPropertyMap(properties); return em; } @Bean public DataSource productDataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("product.jdbc.url"))); dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); return dataSource; } @Bean public PlatformTransactionManager productTransactionManager() { final JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(productEntityManager().getObject()); return transactionManager; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\multipledb\PersistenceProductConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public static BankCodeEnum getEnum(String enumName) { BankCodeEnum resultEnum = null; BankCodeEnum[] enumAry = BankCodeEnum.values(); for (int i = 0; i < enumAry.length; i++) { if (enumAry[i].name().equals(enumName)) { resultEnum = enumAry[i]; break; } } return resultEnum; } public static Map<String, Map<String, Object>> toMap() { BankCodeEnum[] ary = BankCodeEnum.values(); Map<String, Map<String, Object>> enumMap = new HashMap<String, Map<String, Object>>(); for (int num = 0; num < ary.length; num++) { Map<String, Object> map = new HashMap<String, Object>(); String key = ary[num].name(); map.put("desc", ary[num].getDesc()); enumMap.put(key, map); } return enumMap; } @SuppressWarnings({ "rawtypes", "unchecked" }) public static List toList() { BankCodeEnum[] ary = BankCodeEnum.values(); List list = new ArrayList(); for (int i = 0; i < ary.length; i++) { Map<String, String> map = new HashMap<String, String>(); map.put("name", ary[i].name()); map.put("desc", ary[i].getDesc()); list.add(map); }
return list; } /** * 取枚举的json字符串 * * @return */ public static String getJsonStr() { BankCodeEnum[] enums = BankCodeEnum.values(); StringBuffer jsonStr = new StringBuffer("["); for (BankCodeEnum senum : enums) { if (!"[".equals(jsonStr.toString())) { jsonStr.append(","); } jsonStr.append("{id:'").append(senum).append("',desc:'").append(senum.getDesc()).append("'}"); } jsonStr.append("]"); return jsonStr.toString(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\enums\BankCodeEnum.java
2
请完成以下Java代码
public List<I_M_HU> retrieveAvailableSourceHUs(@NonNull final PickingHUsQuery query) { final SourceHUsService sourceHuService = SourceHUsService.get(); return RetrieveAvailableHUsToPick.retrieveAvailableHUsToPick(query, sourceHuService::retrieveParentHusThatAreSourceHUs); } @Override @NonNull public List<I_M_HU> retrieveAvailableHUsToPick(@NonNull final PickingHUsQuery query) { return RetrieveAvailableHUsToPick.retrieveAvailableHUsToPick(query, RetrieveAvailableHUsToPickFilters::retrieveFullTreeAndExcludePickingHUs); } @Override public ImmutableList<HuId> retrieveAvailableHUIdsToPick(@NonNull final PickingHUsQuery query) { return retrieveAvailableHUsToPick(query) .stream() .map(I_M_HU::getM_HU_ID) .map(HuId::ofRepoId) .collect(ImmutableList.toImmutableList()); } @Override public ImmutableList<HuId> retrieveAvailableHUIdsToPickForShipmentSchedule(@NonNull final RetrieveAvailableHUIdsToPickRequest request) { final I_M_ShipmentSchedule schedule = loadOutOfTrx(request.getScheduleId(), I_M_ShipmentSchedule.class);
final PickingHUsQuery query = PickingHUsQuery .builder() .onlyTopLevelHUs(request.isOnlyTopLevel()) .shipmentSchedule(schedule) .onlyIfAttributesMatchWithShipmentSchedules(request.isConsiderAttributes()) .build(); return retrieveAvailableHUIdsToPick(query); } public boolean clearPickingSlotQueue(@NonNull final PickingSlotId pickingSlotId, final boolean removeQueuedHUsFromSlot) { final I_M_PickingSlot slot = pickingSlotDAO.getById(pickingSlotId, I_M_PickingSlot.class); if (removeQueuedHUsFromSlot) { huPickingSlotDAO.retrieveAllHUs(slot) .stream() .map(hu -> HuId.ofRepoId(hu.getM_HU_ID())) .forEach(queuedHU -> removeFromPickingSlotQueue(slot, queuedHU)); } return huPickingSlotDAO.isEmpty(slot); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\slot\impl\HUPickingSlotBL.java
1
请完成以下Java代码
public class NotificationBL implements INotificationBL { private static final Logger logger = LogManager.getLogger(NotificationBL.class); private final CompositeRecordTextProvider ctxProviders = new CompositeRecordTextProvider(); private NotificationSenderTemplate newNotificationSender() { final NotificationSenderTemplate sender = new NotificationSenderTemplate(); sender.setRecordTextProvider(ctxProviders); return sender; } @Override public void sendAfterCommit(@NonNull final UserNotificationRequest request) { try { newNotificationSender().sendAfterCommit(request); } catch (final Exception ex) { logger.warn("Failed sending notification: {}", request, ex); } } @Override public void sendAfterCommit(@NonNull final List<UserNotificationRequest> requests) { try { if (requests.isEmpty()) { return; } newNotificationSender().sendAfterCommit(requests); } catch (final Exception ex) { logger.warn("Failed sending notifications: {}", requests, ex); } } @Override public void send(@NonNull final UserNotificationRequest request) { try { newNotificationSender().sendNow(request);
} catch (final Exception ex) { logger.warn("Failed sending notification: {}", request, ex); } } @Override public void addCtxProvider(final IRecordTextProvider ctxProvider) { ctxProviders.addCtxProvider(ctxProvider); } @Override public void setDefaultCtxProvider(final IRecordTextProvider defaultCtxProvider) { ctxProviders.setDefaultCtxProvider(defaultCtxProvider); } @Override public @NonNull UserNotificationsConfig getUserNotificationsConfig(final UserId adUserId) { return Services.get(IUserNotificationsConfigRepository.class).getByUserId(adUserId); } @Override public RoleNotificationsConfig getRoleNotificationsConfig(final RoleId adRoleId) { return Services.get(IRoleNotificationsConfigRepository.class).getByRoleId(adRoleId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\impl\NotificationBL.java
1
请完成以下Java代码
public ProductsToPickRow withQtyOverride(@Nullable final BigDecimal qtyOverrideBD) { final Quantity qtyOverride = qtyOverrideBD != null ? Quantity.of(qtyOverrideBD, qty.getUOM()) : null; return withQtyOverride(qtyOverride); } private ProductsToPickRow withQtyOverride(@Nullable final Quantity qtyOverride) { return Objects.equals(this.qtyOverride, qtyOverride) ? this : toBuilder().qtyOverride(qtyOverride).build(); } private ProductsToPickRow withFinishedGoodsQtyOverride( @NonNull final Quantity finishedGoodsQty, @Nullable final Quantity finishedGoodsQtyOverride) { if (finishedGoodsQtyOverride != null) { Quantity.getCommonUomIdOfAll(finishedGoodsQty, finishedGoodsQtyOverride); // just to make sure // qty ............... finishedGoodsQty // qtyOverride ....... finishedGoodsQtyOverride // => qtyOverride = qty * (finishedGoodsQtyOverride / finishedGoodsQty) final BigDecimal multiplier = finishedGoodsQtyOverride.toBigDecimal() .divide(finishedGoodsQty.toBigDecimal(), 12, RoundingMode.HALF_UP); final Quantity qtyOverride = qty.multiply(multiplier).roundToUOMPrecision(); return withQtyOverride(qtyOverride); } else { return withQtyOverride((Quantity)null); } } public boolean isQtyOverrideEditableByUser() { return isFieldEditable(FIELD_QtyOverride); } @SuppressWarnings("SameParameterValue") private boolean isFieldEditable(final String fieldName) { final ViewEditorRenderMode renderMode = getViewEditorRenderModeByFieldName().get(fieldName); return renderMode != null && renderMode.isEditable(); } public boolean isApproved() { return approvalStatus != null && approvalStatus.isApproved(); } private boolean isEligibleForChangingPickStatus() { return !isProcessed() && getType().isPickable();
} public boolean isEligibleForPicking() { return isEligibleForChangingPickStatus() && !isApproved() && pickStatus != null && pickStatus.isEligibleForPicking(); } public boolean isEligibleForRejectPicking() { return isEligibleForChangingPickStatus() && !isApproved() && pickStatus != null && pickStatus.isEligibleForRejectPicking(); } public boolean isEligibleForPacking() { return isEligibleForChangingPickStatus() && isApproved() && pickStatus != null && pickStatus.isEligibleForPacking(); } public boolean isEligibleForReview() { return isEligibleForChangingPickStatus() && pickStatus != null && pickStatus.isEligibleForReview(); } public boolean isEligibleForProcessing() { return isEligibleForChangingPickStatus() && pickStatus != null && pickStatus.isEligibleForProcessing(); } public String getLocatorName() { return locator != null ? locator.getDisplayName() : ""; } @Override public List<ProductsToPickRow> getIncludedRows() { return includedRows; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\rows\ProductsToPickRow.java
1
请完成以下Java代码
abstract class M_CostRevaluation_ProcessTemplate extends JavaProcess implements IProcessPrecondition { protected final CostRevaluationService costRevaluationService = SpringContextHolder.instance.getBean(CostRevaluationService.class); protected final ProcessPreconditionsResolution acceptIfDraft(final @NonNull IProcessPreconditionsContext context) { final CostRevaluationId costRevaluationId = getCostRevaluationId(context); return costRevaluationService.isDraftedDocument(costRevaluationId) ? ProcessPreconditionsResolution.accept() : ProcessPreconditionsResolution.rejectWithInternalReason("Already in progress/finished."); } protected final ProcessPreconditionsResolution acceptIfHasActiveLines(final @NonNull IProcessPreconditionsContext context) { final CostRevaluationId costRevaluationId = getCostRevaluationId(context); return costRevaluationService.hasActiveLines(costRevaluationId) ? ProcessPreconditionsResolution.accept() : ProcessPreconditionsResolution.rejectWithInternalReason("No active lines found"); } protected final ProcessPreconditionsResolution acceptIfDoesNotHaveActiveLines(final @NonNull IProcessPreconditionsContext context)
{ final CostRevaluationId costRevaluationId = getCostRevaluationId(context); return !costRevaluationService.hasActiveLines(costRevaluationId) ? ProcessPreconditionsResolution.accept() : ProcessPreconditionsResolution.rejectWithInternalReason("Active lines found"); } protected final CostRevaluationId getCostRevaluationId() { return CostRevaluationId.ofRepoId(getRecord_ID()); } @NonNull private static CostRevaluationId getCostRevaluationId(final @NonNull IProcessPreconditionsContext context) { return CostRevaluationId.ofRepoId(context.getSingleSelectedRecordId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costrevaluation\process\M_CostRevaluation_ProcessTemplate.java
1
请完成以下Java代码
public void setActionCommand (String actionCommand) { super.setActionCommand (actionCommand); if (getName() == null && actionCommand != null && actionCommand.length() > 0) setName(actionCommand); } // setActionCommand public boolean isSelectionNone() { final Object selectedItem = getSelectedItem(); if (selectedItem == null) { return true; } else { return Check.isEmpty(selectedItem.toString(), true); } } @Override public E getSelectedItem() { final Object selectedItemObj = super.getSelectedItem(); @SuppressWarnings("unchecked") final E selectedItem = (E)selectedItemObj; return selectedItem; } /** * Enables auto completion (while user writes) on this combobox. * * @return combobox's auto-completion instance for further configurations */
public final ComboBoxAutoCompletion<E> enableAutoCompletion() { return ComboBoxAutoCompletion.enable(this); } /** * Disable autocompletion on this combobox. * * If the autocompletion was not enabled, this method does nothing. */ public final void disableAutoCompletion() { ComboBoxAutoCompletion.disable(this); } @Override public ICopyPasteSupportEditor getCopyPasteSupport() { return JComboBoxCopyPasteSupportEditor.ofComponent(this); } } // CComboBox
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CComboBox.java
1
请完成以下Java代码
private @NonNull Set<DDOrderCandidateId> getDDOrderCandidateIds(final @NonNull SupplyRequiredDecreasedEvent event) { final Candidate demandCandidate = candidateRepositoryRetrieval.retrieveById(CandidateId.ofRepoId(event.getSupplyRequiredDescriptor().getDemandCandidateId())); return candidateRepositoryWriteService.getSupplyCandidatesForDemand(demandCandidate, CandidateBusinessCase.DISTRIBUTION) .stream() .map(DDOrderCandidateAdvisedEventCreator::getDDOrderCandidateIdOrNull) .filter(Objects::nonNull) .collect(Collectors.toSet()); } @Nullable private static DDOrderCandidateId getDDOrderCandidateIdOrNull(@NonNull final Candidate candidate) { final DistributionDetail distributionDetail = DistributionDetail.castOrNull(candidate.getBusinessCaseDetail()); if (distributionDetail == null) { return null; } final DDOrderRef ddOrderRef = distributionDetail.getDdOrderRef(); if (ddOrderRef == null) { return null; } return DDOrderCandidateId.ofRepoId(ddOrderRef.getDdOrderCandidateId());
} private Quantity doDecreaseQty(final DDOrderCandidate ddOrderCandidate, final Quantity remainingQtyToDistribute) { if (isCandidateEligibleForBeingDecreased(ddOrderCandidate)) { final Quantity qtyToDecrease = remainingQtyToDistribute.min(ddOrderCandidate.getQtyToProcess()); ddOrderCandidate.setQtyEntered(ddOrderCandidate.getQtyEntered().subtract(qtyToDecrease)); ddOrderCandidateService.save(ddOrderCandidate); return remainingQtyToDistribute.subtract(qtyToDecrease); } return remainingQtyToDistribute; } private static boolean isCandidateEligibleForBeingDecreased(final DDOrderCandidate ddOrderCandidate) { return !ddOrderCandidate.isProcessed() && ddOrderCandidate.getQtyToProcess().signum() > 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddordercandidate\material_dispo\DDOrderCandidateAdvisedEventCreator.java
1
请完成以下Java代码
public Long getId() { return this.id; } public String getName() { return this.name; } public List<User> getMembers() { return this.members; } public void setId(Long id) { this.id = id; } public void setName(String name) { this.name = name; } public void setMembers(List<User> members) { this.members = members; } @Override public boolean equals(Object o) { if (this == o) {
return true; } if (o == null || getClass() != o.getClass()) { return false; } Group group = (Group) o; return Objects.equals(id, group.id); } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } public String toString() { return "Group(id=" + this.getId() + ", name=" + this.getName() + ", members=" + this.getMembers() + ")"; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-2\src\main\java\com\baeldung\listvsset\eager\list\moderatedomain\Group.java
1
请完成以下Java代码
public class AnimalSolution { private final Object objLock1 = new Object(); private final Object objLock2 = new Object(); private String name; private String owner; public String getName() { return name; } public String getOwner() { return owner; } public void setName(String name) { synchronized(objLock1) { this.name = name; } }
public void setOwner(String owner) { synchronized(objLock2) { this.owner = owner; } } public AnimalSolution() { } public AnimalSolution(String name, String owner) { this.name = name; this.owner = owner; } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-4\src\main\java\com\baeldung\synchronizationbadpractices\AnimalSolution.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (sysConfigBL.getBooleanValue(EDIWorkpackageProcessor.SYS_CONFIG_OneDesadvPerShipment, false)) { return ProcessPreconditionsResolution.reject(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { // Enqueue selected desadvs as workpackages final EnqueueDesadvRequest enqueueDesadvRequest = EnqueueDesadvRequest.builder() .pInstanceId(getPinstanceId()) .ctx(getCtx()) .desadvIterator(createIterator()) .build(); final EnqueueDesadvResult result = desadvEnqueuer.enqueue(enqueueDesadvRequest); final List<I_EDI_Desadv> skippedDesadvList = result.getSkippedDesadvList(); // display the desadvs that didn't meet the sum percentage requirement if (!skippedDesadvList.isEmpty()) { desadvBL.createMsgsForDesadvsBelowMinimumFulfilment(ImmutableList.copyOf(skippedDesadvList)); } return MSG_OK; } private IQueryBuilder<I_EDI_Desadv> createEDIDesadvQueryBuilder() { final IQueryFilter<I_EDI_Desadv> processQueryFilter = getProcessInfo().getQueryFilterOrElseFalse();
final IQueryBuilder<I_EDI_Desadv> queryBuilder = queryBL.createQueryBuilder(I_EDI_Desadv.class, getCtx(), get_TrxName()) .addOnlyActiveRecordsFilter() .addInArrayOrAllFilter(I_EDI_Desadv.COLUMNNAME_EDI_ExportStatus, X_EDI_Desadv.EDI_EXPORTSTATUS_Error, X_EDI_Desadv.EDI_EXPORTSTATUS_Pending) .filter(processQueryFilter); queryBuilder.orderBy() .addColumn(I_EDI_Desadv.COLUMNNAME_POReference) .addColumn(I_EDI_Desadv.COLUMNNAME_EDI_Desadv_ID); return queryBuilder; } private Iterator<I_EDI_Desadv> createIterator() { final IQueryBuilder<I_EDI_Desadv> queryBuilder = createEDIDesadvQueryBuilder(); final Iterator<I_EDI_Desadv> iterator = queryBuilder .create() .iterate(I_EDI_Desadv.class); if(!iterator.hasNext()) { addLog("Found no EDI_Desadvs to enqueue within the current selection"); } return iterator; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\EDI_Desadv_EnqueueForExport.java
1
请完成以下Java代码
public BigDecimal getOutcome() { return outcome; } /** 平台账户出款金额 **/ public void setOutcome(BigDecimal outcome) { this.outcome = outcome; } /** 商户订单号 **/ public String getMerchantOrderNo() { return merchantOrderNo; } /** 商户订单号 **/ public void setMerchantOrderNo(String merchantOrderNo) { this.merchantOrderNo = merchantOrderNo; } /** 银行费率 **/ public BigDecimal getBankRate() { return bankRate; } /** 银行费率 **/ public void setBankRate(BigDecimal bankRate) { this.bankRate = bankRate; } /** 订单金额 **/ public BigDecimal getTotalFee() { return totalFee; } /** 订单金额 **/ public void setTotalFee(BigDecimal totalFee) { this.totalFee = totalFee; } /** 银行流水 **/ public String getTradeNo() { return tradeNo; } /** 银行流水 **/ public void setTradeNo(String tradeNo) { this.tradeNo = tradeNo; } /** 交易类型 **/
public String getTransType() { return transType; } /** 交易类型 **/ public void setTransType(String transType) { this.transType = transType; } /** 交易时间 **/ public Date getTransDate() { return transDate; } /** 交易时间 **/ public void setTransDate(Date transDate) { this.transDate = transDate; } /** 银行(支付宝)该笔订单收取的手续费 **/ public BigDecimal getBankFee() { return bankFee; } /** 银行(支付宝)该笔订单收取的手续费 **/ public void setBankFee(BigDecimal bankFee) { this.bankFee = bankFee; } }
repos\roncoo-pay-master\roncoo-pay-app-reconciliation\src\main\java\com\roncoo\pay\app\reconciliation\vo\AlipayAccountLogVO.java
1
请完成以下Java代码
public double getTopSpeed() { return topSpeed; } public void setTopSpeed(double topSpeed) { this.topSpeed = topSpeed; } } public static class Truck extends Vehicle { @JsonIgnore private double payloadCapacity; public Truck() { }
public Truck(String make, String model, double payloadCapacity) { super(make, model); this.payloadCapacity = payloadCapacity; } public double getPayloadCapacity() { return payloadCapacity; } public void setPayloadCapacity(double payloadCapacity) { this.payloadCapacity = payloadCapacity; } } }
repos\tutorials-master\jackson-modules\jackson-core\src\main\java\com\baeldung\jackson\inheritance\SubTypeConversionStructure.java
1
请完成以下Java代码
public void initialize(final ModelValidationEngine engine, final MClient client) { this.engine = engine; if (client != null) { m_AD_Client_ID = client.getAD_Client_ID(); } engine.addModelValidator(new C_ReferenceNo_Type(this), client); engine.addModelValidator(new C_ReferenceNo_Type_Table(this), client); engine.addModelValidator(new C_ReferenceNo(), client); // // Register all referenceNo generator instance interceptors final List<I_C_ReferenceNo_Type> typeRecords = Services.get(IReferenceNoDAO.class).retrieveReferenceNoTypes(); for (final I_C_ReferenceNo_Type typeRecord : typeRecords) { registerInstanceValidator(typeRecord); } // // Register Workflow execution/identification tracker Services.get(IWFExecutionFactory.class).registerListener(new TrackingWFExecutionListener()); } @Override public int getAD_Client_ID() { return m_AD_Client_ID; } @Override public String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID) { // nothing return null; } @Override public String modelChange(final PO po, final int type) throws Exception { // nothing return null; } @Override public String docValidate(final PO po, final int timing) { // nothing return null; } private void registerInstanceValidator(final I_C_ReferenceNo_Type type) {
final Properties ctx = InterfaceWrapperHelper.getCtx(type); final IReferenceNoGeneratorInstance instance = Services.get(IReferenceNoBL.class).getReferenceNoGeneratorInstance(ctx, type); if (instance == null) { return; } final ReferenceNoGeneratorInstanceValidator validator = new ReferenceNoGeneratorInstanceValidator(instance); engine.addModelValidator(validator); docValidators.add(validator); } private void unregisterInstanceValidator(final I_C_ReferenceNo_Type type) { final Iterator<ReferenceNoGeneratorInstanceValidator> it = docValidators.iterator(); while (it.hasNext()) { final ReferenceNoGeneratorInstanceValidator validator = it.next(); if (validator.getInstance().getType().getC_ReferenceNo_Type_ID() == type.getC_ReferenceNo_Type_ID()) { validator.unregister(); it.remove(); } } } public void updateInstanceValidator(final I_C_ReferenceNo_Type type) { unregisterInstanceValidator(type); registerInstanceValidator(type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java\de\metas\document\refid\modelvalidator\Main.java
1
请完成以下Java代码
private static int readInBuffer(DataBlock dataBlock, long pos, ByteBuffer buffer, int maxLen, int minLen) throws IOException { buffer.clear(); if (buffer.remaining() > maxLen) { buffer.limit(maxLen); } int result = 0; while (result < minLen) { int count = dataBlock.read(buffer, pos); if (count <= 0) { throw new EOFException(); } result += count; pos += count; } return result; } private static int getCodePointSize(byte[] bytes, int i) { int b = Byte.toUnsignedInt(bytes[i]); if ((b & 0b1_0000000) == 0b0_0000000) { return 1; } if ((b & 0b111_00000) == 0b110_00000) { return 2; } if ((b & 0b1111_0000) == 0b1110_0000) { return 3; } return 4; } private static int getCodePoint(byte[] bytes, int i, int codePointSize) { int codePoint = Byte.toUnsignedInt(bytes[i]);
codePoint &= INITIAL_BYTE_BITMASK[codePointSize - 1]; for (int j = 1; j < codePointSize; j++) { codePoint = (codePoint << 6) + (bytes[i + j] & SUBSEQUENT_BYTE_BITMASK); } return codePoint; } /** * Supported compare types. */ private enum CompareType { MATCHES, MATCHES_ADDING_SLASH, STARTS_WITH } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\zip\ZipString.java
1
请在Spring Boot框架中完成以下Java代码
public class PickingSlotQRCode { @NonNull PickingSlotId pickingSlotId; @NonNull String caption; public static boolean equals(@Nullable final PickingSlotQRCode o1, @Nullable final PickingSlotQRCode o2) { return Objects.equals(o1, o2); } @Override @Deprecated public String toString() {return toGlobalQRCodeJsonString();} public String toGlobalQRCodeJsonString() {return PickingSlotQRCodeJsonConverter.toGlobalQRCodeJsonString(this);} public static PickingSlotQRCode ofGlobalQRCodeJsonString(@NonNull final String json) {return PickingSlotQRCodeJsonConverter.fromGlobalQRCodeJsonString(json);} public static PickingSlotQRCode ofGlobalQRCode(@NonNull final GlobalQRCode globalQRCode) {return PickingSlotQRCodeJsonConverter.fromGlobalQRCode(globalQRCode);} public static PickingSlotQRCode ofPickingSlotIdAndCaption(@NonNull final PickingSlotIdAndCaption pickingSlotIdAndCaption) { return builder() .pickingSlotId(pickingSlotIdAndCaption.getPickingSlotId())
.caption(pickingSlotIdAndCaption.getCaption()) .build(); } public PrintableQRCode toPrintableQRCode() { return PrintableQRCode.builder() .qrCode(toGlobalQRCodeJsonString()) .bottomText(caption) .build(); } public JsonDisplayableQRCode toJsonDisplayableQRCode() { return toPrintableQRCode().toJsonDisplayableQRCode(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\picking\qrcode\PickingSlotQRCode.java
2
请完成以下Java代码
private List<Map<String, Object>> extractSearchResults(SearchResponse<ObjectNode> response) { List<Map<String, Object>> results = new ArrayList<>(); logger.info("Search completed. Total hits: {}", response.hits() .total() .value()); for (Hit<ObjectNode> hit : response.hits() .hits()) { Map<String, Object> sourceMap = new HashMap<>(); if (hit.source() != null) { hit.source() .fields() .forEachRemaining(entry -> { // Extract the actual value from JsonNode Object value = extractJsonNodeValue(entry.getValue()); sourceMap.put(entry.getKey(), value); }); } results.add(sourceMap); } return results; } /** * Helper method to extract actual values from JsonNode objects */ private Object extractJsonNodeValue(com.fasterxml.jackson.databind.JsonNode jsonNode) { if (jsonNode == null || jsonNode.isNull()) { return null; } else if (jsonNode.isTextual()) {
return jsonNode.asText(); } else if (jsonNode.isInt()) { return jsonNode.asInt(); } else if (jsonNode.isLong()) { return jsonNode.asLong(); } else if (jsonNode.isDouble() || jsonNode.isFloat()) { return jsonNode.asDouble(); } else if (jsonNode.isBoolean()) { return jsonNode.asBoolean(); } else if (jsonNode.isArray()) { List<Object> list = new ArrayList<>(); jsonNode.elements() .forEachRemaining(element -> list.add(extractJsonNodeValue(element))); return list; } else if (jsonNode.isObject()) { Map<String, Object> map = new HashMap<>(); jsonNode.fields() .forEachRemaining(entry -> map.put(entry.getKey(), extractJsonNodeValue(entry.getValue()))); return map; } else { return jsonNode.asText(); } } }
repos\tutorials-master\persistence-modules\spring-data-elasticsearch-2\src\main\java\com\baeldung\wildcardsearch\ElasticsearchWildcardService.java
1
请在Spring Boot框架中完成以下Java代码
public class AdminServiceImpl implements AdminService { private static final Logger LOG = LoggerFactory.getLogger(AdminServiceImpl.class); private static final String SERVICE_PREFIX = "/services/admin"; private final HttpClient httpClient; private final ObjectMapper mapper; private String baseUri; public AdminServiceImpl(HttpClient httpClient, String baseUri, ObjectMapper mapper) { this.httpClient = httpClient; this.baseUri = baseUri + SERVICE_PREFIX; this.mapper = mapper; } @Override public ClientId createClient(CreateClientRequest createClientRequest) throws ServiceException { try { HttpRequest request = HttpRequest.newBuilder() .POST(HttpRequest.BodyPublishers.ofString(mapper.writeValueAsString(createClientRequest))) .uri(URI.create(baseUri + "/client")) .header("Content-Type", "application/json") .build(); HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() != 200) { throw new ServiceException("Http status: " + response.statusCode()); } return mapper.readValue(response.body(), ClientId.class); } catch (Exception e) { LOG.error("ERROR: ", e); throw new ServiceException(e); } } @Override public Collection<Client> getClients() throws ServiceException { try { HttpRequest request = HttpRequest.newBuilder() .GET() .uri(URI.create(baseUri + "/clients"))
.build(); HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() != 200) { throw new ServiceException("Http status: " + response.statusCode()); } return mapper.readValue(response.body(), new TypeReference<List<Client>>(){}); } catch (Exception e) { LOG.error("ERROR: ", e); throw new ServiceException(e); } } @Override public void deleteClient(ClientId id) throws ServiceException { try { HttpRequest request = HttpRequest.newBuilder() .DELETE() .uri(URI.create(baseUri + "/client/" + id.getId())) .build(); HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() != 200) { throw new ServiceException("Http status: " + response.statusCode()); } } catch (Exception e) { LOG.error("ERROR: ", e); throw new ServiceException(e); } } }
repos\spring-examples-java-17\spring-bank\bank-client\src\main\java\itx\examples\springbank\client\service\AdminServiceImpl.java
2
请完成以下Java代码
public Collection<I_C_Recurring> retrieveForToday(final int adClientId, final String trxName) { final List<MRecurring> recurrings = retrieveList(SQL_TODAY, new Object[] { adClientId }, MRecurring.class, trxName); return new ArrayList<>(recurrings); } /** * Executes the given sql (prepared) statement and returns the result as a * list of {@link PO}s. * * @param sql * the sql statement to execute * @param params * prepared statement parameters (its length must correspond to * the number of '?'s in the sql) * @param clazz * the class of the returned list elements needs to have a * constructor with three parameters: * <li>{@link Properties}, * <li>{@link ResultSet}, * <li>{@link String} * @param trxName */ private <T extends PO> List<T> retrieveList(final String sql, final Object[] params, final Class<T> clazz, final String trxName) { PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, trxName); DB.setParameters(pstmt, params); rs = pstmt.executeQuery(); final Properties ctx = Env.getCtx(); final String tableName = InterfaceWrapperHelper.getTableName(clazz); final List<T> result = new ArrayList<>();
while (rs.next()) { final T newPO = TableModelLoader.instance.retrieveModel(ctx, tableName, clazz, rs, trxName); result.add(newPO); } return result; } catch (SQLException e) { throw new DBException(e, sql, params); } finally { DB.close(rs, pstmt); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\document\impl\RecurringPA.java
1
请完成以下Java代码
public boolean addAll(int index, Collection<? extends E> c) { return false; } @Override public boolean removeAll(Collection<?> c) { return false; } @Override public boolean retainAll(Collection<?> c) { return false; } @Override public void clear() { } @Override public E get(int index) { return null; } @Override public E set(int index, E element) { return null; } @Override public void add(int index, E element) { }
@Override public E remove(int index) { return null; } @Override public int indexOf(Object o) { return 0; } @Override public int lastIndexOf(Object o) { return 0; } @Override public ListIterator<E> listIterator() { return null; } @Override public ListIterator<E> listIterator(int index) { return null; } @Override public List<E> subList(int fromIndex, int toIndex) { return null; } }
repos\tutorials-master\core-java-modules\core-java-collections-5\src\main\java\com\baeldung\customiterators\MyList.java
1
请完成以下Java代码
public void setLabel(String label) { labelAttribute.setValue(this, label); } public Description getDescription() { return descriptionChild.getChild(this); } public void setDescription(Description description) { descriptionChild.setChild(this, description); } public ExtensionElements getExtensionElements() { return extensionElementsChild.getChild(this); } public void setExtensionElements(ExtensionElements extensionElements) { extensionElementsChild.setChild(this, extensionElements); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DmnElement.class, DMN_ELEMENT) .namespaceUri(LATEST_DMN_NS) .abstractType(); idAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_ID)
.idAttribute() .build(); labelAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_LABEL) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); descriptionChild = sequenceBuilder.element(Description.class) .build(); extensionElementsChild = sequenceBuilder.element(ExtensionElements.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\DmnElementImpl.java
1
请完成以下Java代码
public void setEsrAttributes(Long value) { this.esrAttributes = value; } /** * Gets the value of the postAccount property. * * @return * possible object is * {@link String } * */ public String getPostAccount() { return postAccount; } /** * Sets the value of the postAccount property. * * @param value * allowed object is * {@link String } * */ public void setPostAccount(String value) { this.postAccount = value; } /** * Gets the value of the iban property. * * @return * possible object is * {@link String } * */ public String getIban() { return iban; } /** * Sets the value of the iban property. * * @param value * allowed object is * {@link String } * */ public void setIban(String value) { this.iban = value; } /** * Gets the value of the referenceNumber property. * * @return * possible object is * {@link String } * */ public String getReferenceNumber() { return referenceNumber; } /** * Sets the value of the referenceNumber property. * * @param value * allowed object is * {@link String } * */ public void setReferenceNumber(String value) {
this.referenceNumber = value; } /** * Gets the value of the codingLine1 property. * * @return * possible object is * {@link String } * */ public String getCodingLine1() { return codingLine1; } /** * Sets the value of the codingLine1 property. * * @param value * allowed object is * {@link String } * */ public void setCodingLine1(String value) { this.codingLine1 = value; } /** * Gets the value of the codingLine2 property. * * @return * possible object is * {@link String } * */ public String getCodingLine2() { return codingLine2; } /** * Sets the value of the codingLine2 property. * * @param value * allowed object is * {@link String } * */ public void setCodingLine2(String value) { this.codingLine2 = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\EsrRedType.java
1
请完成以下Java代码
public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Merkmals-Wert. @param M_AttributeValue_ID Product Attribute Value */ @Override public void setM_AttributeValue_ID (int M_AttributeValue_ID) { if (M_AttributeValue_ID < 1) set_Value (COLUMNNAME_M_AttributeValue_ID, null); else set_Value (COLUMNNAME_M_AttributeValue_ID, Integer.valueOf(M_AttributeValue_ID)); } /** Get Merkmals-Wert. @return Product Attribute Value */ @Override public int getM_AttributeValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeValue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Attribut substitute. @param M_AttributeValue_Mapping_ID Attribut substitute */ @Override public void setM_AttributeValue_Mapping_ID (int M_AttributeValue_Mapping_ID) { if (M_AttributeValue_Mapping_ID < 1) set_ValueNoCheck (COLUMNNAME_M_AttributeValue_Mapping_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeValue_Mapping_ID, Integer.valueOf(M_AttributeValue_Mapping_ID)); } /** Get Attribut substitute. @return Attribut substitute */ @Override public int getM_AttributeValue_Mapping_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeValue_Mapping_ID); if (ii == null) return 0;
return ii.intValue(); } /** Set Merkmals-Wert Nach. @param M_AttributeValue_To_ID Product Attribute Value To */ @Override public void setM_AttributeValue_To_ID (int M_AttributeValue_To_ID) { if (M_AttributeValue_To_ID < 1) set_Value (COLUMNNAME_M_AttributeValue_To_ID, null); else set_Value (COLUMNNAME_M_AttributeValue_To_ID, Integer.valueOf(M_AttributeValue_To_ID)); } /** Get Merkmals-Wert Nach. @return Product Attribute Value To */ @Override public int getM_AttributeValue_To_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeValue_To_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeValue_Mapping.java
1
请完成以下Java代码
public class User { private String userId; private String name; private String email; private boolean active; public User(String userId, String name, String email) { this.userId = userId; this.name = name; this.email = email; } public User(String userId, String name, String email, boolean active) { this.userId = userId; this.name = name; this.email = email; this.active = active; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getName() { return name; }
public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } }
repos\tutorials-master\spring-reactive-modules\spring-webflux\src\main\java\com\baeldung\spring\convertmonoobject\User.java
1
请完成以下Java代码
public String read(OAuth2AuthenticationToken authenticationToken) { String url = remoteResourceServer + "/read"; return callResourceServer(authenticationToken, url); } @RequestMapping("/write") public String write(OAuth2AuthenticationToken authenticationToken) { String url = remoteResourceServer + "/write"; return callResourceServer(authenticationToken, url); } private String callResourceServer(OAuth2AuthenticationToken authenticationToken, String url) { OAuth2AuthorizedClient oAuth2AuthorizedClient = this.authorizedClientService.loadAuthorizedClient(authenticationToken.getAuthorizedClientRegistrationId(), authenticationToken.getName()); OAuth2AccessToken oAuth2AccessToken = oAuth2AuthorizedClient.getAccessToken();
HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", "Bearer " + oAuth2AccessToken.getTokenValue()); HttpEntity<String> entity = new HttpEntity<>("parameters", headers); ResponseEntity<String> responseEntity = null; String response = null; try { responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, String.class); response = responseEntity.getBody(); } catch (HttpClientErrorException e) { response = e.getMessage(); } return response; } }
repos\tutorials-master\security-modules\cloud-foundry-uaa\cf-uaa-oauth2-client\src\main\java\com\baeldung\cfuaa\oauth2\client\CFUAAOAuth2ClientController.java
1
请在Spring Boot框架中完成以下Java代码
public LineBuilder line(final String tableName) { final Optional<LineBuilder> existingLineBuilder = lineBuilders .stream() .filter(b -> tableName.equals(b.getTableName())) .findFirst(); if (existingLineBuilder.isPresent()) { return existingLineBuilder.get(); } setChanged(true); return newLine().setTableName(tableName); } private void assertLineTableNamesUnique() { final List<LineBuilder> nonUniqueLines = lineBuilders.stream() .collect(Collectors.groupingBy(r -> r.getTableName())) // group them by tableName; this returns a map .entrySet().stream() // now stream the map's entries .filter(e -> e.getValue().size() > 1) // now remove from the stream those that are OK .flatMap(e -> e.getValue().stream()) // now get a stream with those that are not OK .collect(Collectors.toList()); Check.errorUnless(nonUniqueLines.isEmpty(), "Found LineBuilders with duplicate tableNames: {}", nonUniqueLines); } public PartitionConfig build()
{ assertLineTableNamesUnique(); final PartitionConfig partitionerConfig = new PartitionConfig(name, changed); partitionerConfig.setDLM_Partition_Config_ID(DLM_Partition_Config_ID); // first build the lines for (final PartitionerConfigLine.LineBuilder lineBuilder : lineBuilders) { final PartitionerConfigLine line = lineBuilder.buildLine(partitionerConfig); partitionerConfig.lines.add(line); } for (final PartitionerConfigLine.LineBuilder lineBuilder : lineBuilders) { lineBuilder.buildRefs(); } return partitionerConfig; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\config\PartitionConfig.java
2
请完成以下Java代码
private ListMultimap<PickingSlotId, PickedHUEditorRow> retrievePickedHUsIndexedByPickingSlotId(@NonNull final List<PickingCandidate> pickingCandidates) { final ImmutableList<PickingCandidate> pickingCandidateToTakeIntoAccount = pickingCandidates.stream() .filter(pickingCandidate -> !pickingCandidate.isRejectedToPick()) .filter(pickingCandidate -> pickingCandidate.getPickFrom().getHuId() != null) .filter(pickingCandidate -> pickingCandidate.getPickingSlotId() != null) .collect(ImmutableList.toImmutableList()); final PickingCandidateHURowsProvider huRowsProvider = PickingCandidateHURowsProvider.builder() .huEditorViewRepository(getHUEditorViewRepository()) .pickingCandidatesRepo(pickingCandidatesRepo) .pickingCandidateService(pickingCandidateService) .pickingCandidates(pickingCandidateToTakeIntoAccount) .build(); final ImmutableMap<HuId, PickedHUEditorRow> huId2EditorRow = huRowsProvider.getForPickingCandidates(); final HashSet<HuId> seenHUIds = new HashSet<>(); final ImmutableListMultimap.Builder<PickingSlotId, PickedHUEditorRow> builder = ImmutableListMultimap.builder(); for (final PickingCandidate pickingCandidate : pickingCandidateToTakeIntoAccount) { final HuId huId = pickingCandidate.getPickFrom().getHuId(); if (seenHUIds.contains(huId)) { continue; } final PickedHUEditorRow huEditorRow = huId2EditorRow.get(pickingCandidate.getPickFrom().getHuId()); if (huEditorRow == null) { continue; } seenHUIds.addAll(huEditorRow.getHuEditorRow().getAllHuIds()); builder.put(pickingCandidate.getPickingSlotId(), huEditorRow); } return builder.build(); } public ListMultimap<PickingSlotId, PickedHUEditorRow> // retrieveAllPickedHUsIndexedByPickingSlotId(@NonNull final List<I_M_PickingSlot> pickingSlots) { final SetMultimap<PickingSlotId, HuId> //
huIdsByPickingSlotId = Services.get(IHUPickingSlotDAO.class).retrieveAllHUIdsIndexedByPickingSlotId(pickingSlots); final HUEditorViewRepository huEditorRepo = getHUEditorViewRepository(); huEditorRepo.warmUp(ImmutableSet.copyOf(huIdsByPickingSlotId.values())); return huIdsByPickingSlotId .entries() .stream() .map(pickingSlotAndHU -> { final PickingSlotId pickingSlotId = pickingSlotAndHU.getKey(); final HuId huId = pickingSlotAndHU.getValue(); final HUEditorRow huEditorRow = huEditorRepo.retrieveForHUId(huId); Check.assumeNotNull(huEditorRow, "HUEditorRow cannot be null if huId is provided!"); return GuavaCollectors.entry(pickingSlotId, PickedHUEditorRow.ofProcessedRow(huEditorRow)); }) .collect(GuavaCollectors.toImmutableListMultimap()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingHURowsRepository.java
1
请完成以下Java代码
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 tp property. * * @return * possible object is * {@link PartyType3Code } * */ public PartyType3Code getTp() { return tp; } /** * Sets the value of the tp property. * * @param value * allowed object is * {@link PartyType3Code } * */ public void setTp(PartyType3Code value) { this.tp = value; } /** * Gets the value of the issr property. * * @return * possible object is * {@link PartyType4Code } * */ public PartyType4Code getIssr() { return issr;
} /** * Sets the value of the issr property. * * @param value * allowed object is * {@link PartyType4Code } * */ public void setIssr(PartyType4Code value) { this.issr = value; } /** * Gets the value of the shrtNm property. * * @return * possible object is * {@link String } * */ public String getShrtNm() { return shrtNm; } /** * Sets the value of the shrtNm property. * * @param value * allowed object is * {@link String } * */ public void setShrtNm(String value) { this.shrtNm = 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_04\GenericIdentification32.java
1
请在Spring Boot框架中完成以下Java代码
public Discovery getDiscovery() { return this.discovery; } public static class Exposure { /** * Endpoint IDs that should be included or '*' for all. */ private Set<String> include = new LinkedHashSet<>(); /** * Endpoint IDs that should be excluded or '*' for all. */ private Set<String> exclude = new LinkedHashSet<>(); public Set<String> getInclude() { return this.include; } public void setInclude(Set<String> include) { this.include = include; } public Set<String> getExclude() { return this.exclude; }
public void setExclude(Set<String> exclude) { this.exclude = exclude; } } public static class Discovery { /** * Whether the discovery page is enabled. */ private boolean enabled = true; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\endpoint\web\WebEndpointProperties.java
2
请在Spring Boot框架中完成以下Java代码
public UserStateEnum getUserStateEnum() { return userStateEnum; } public void setUserStateEnum(UserStateEnum userStateEnum) { this.userStateEnum = userStateEnum; } public RoleEntity getRoleEntity() { return roleEntity; } public void setRoleEntity(RoleEntity roleEntity) { this.roleEntity = roleEntity; }
@Override public String toString() { return "UserEntity{" + "id='" + id + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + ", phone='" + phone + '\'' + ", mail='" + mail + '\'' + ", licencePic='" + licencePic + '\'' + ", registerTime=" + registerTime + ", userTypeEnum=" + userTypeEnum + ", userStateEnum=" + userStateEnum + ", roleEntity=" + roleEntity + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\user\UserEntity.java
2
请完成以下Java代码
public class PickingJobOptionsCollection { public static final PickingJobOptionsCollection EMPTY = new PickingJobOptionsCollection(ImmutableMap.of()); @NonNull private final ImmutableMap<PickingJobOptionsId, PickingJobOptions> byId; private PickingJobOptionsCollection(@NonNull final ImmutableMap<PickingJobOptionsId, PickingJobOptions> byId) { this.byId = byId; } private static PickingJobOptionsCollection ofMap(final Map<PickingJobOptionsId, PickingJobOptions> map) { return !map.isEmpty() ? new PickingJobOptionsCollection(ImmutableMap.copyOf(map)) : EMPTY; } public static Collector<Map.Entry<PickingJobOptionsId, PickingJobOptions>, ?, PickingJobOptionsCollection> collect()
{ return GuavaCollectors.collectUsingMapAccumulator(PickingJobOptionsCollection::ofMap); } @NonNull public PickingJobOptions getById(@NotNull PickingJobOptionsId id) { final PickingJobOptions pickingJobOptions = byId.get(id); if (pickingJobOptions == null) { throw new AdempiereException("No picking job options found for " + id); } return pickingJobOptions; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\config\mobileui\PickingJobOptionsCollection.java
1
请完成以下Java代码
public class DefaultDunnableSourceFactory implements IDunnableSourceFactory { private final Map<Class<? extends IDunnableSource>, IDunnableSource> dunnableSources = new HashMap<Class<? extends IDunnableSource>, IDunnableSource>(); @Override public List<IDunnableSource> getSources(IDunningContext context) { final List<IDunnableSource> result = new ArrayList<IDunnableSource>(); result.addAll(dunnableSources.values()); return result; } private IDunnableSource createSource(Class<? extends IDunnableSource> sourceClass) { final IDunnableSource source; try { source = sourceClass.newInstance(); return source; } catch (Exception e) {
throw new DunningException("Cannot create dunning source for " + sourceClass, e); } } @Override public void registerSource(Class<? extends IDunnableSource> clazz) { if (dunnableSources.containsKey(clazz)) { return; } final IDunnableSource source = createSource(clazz); dunnableSources.put(clazz, source); } @Override public String toString() { return "DefaultDunnableSourceFactory [dunnableSources=" + dunnableSources + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DefaultDunnableSourceFactory.java
1
请在Spring Boot框架中完成以下Java代码
public PrescriptedArticleLine updated(OffsetDateTime updated) { this.updated = updated; return this; } /** * Der Zeitstempel der letzten Änderung * @return updated **/ @Schema(description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getUpdated() { return updated; } public void setUpdated(OffsetDateTime updated) { this.updated = updated; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PrescriptedArticleLine prescriptedArticleLine = (PrescriptedArticleLine) o; return Objects.equals(this._id, prescriptedArticleLine._id) && Objects.equals(this.orderedArticleLineId, prescriptedArticleLine.orderedArticleLineId) && Objects.equals(this.articleId, prescriptedArticleLine.articleId) && Objects.equals(this.pcn, prescriptedArticleLine.pcn) && Objects.equals(this.productGroupName, prescriptedArticleLine.productGroupName) && Objects.equals(this.quantity, prescriptedArticleLine.quantity) && Objects.equals(this.unit, prescriptedArticleLine.unit) && Objects.equals(this.annotation, prescriptedArticleLine.annotation) && Objects.equals(this.updated, prescriptedArticleLine.updated); }
@Override public int hashCode() { return Objects.hash(_id, orderedArticleLineId, articleId, pcn, productGroupName, quantity, unit, annotation, updated); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PrescriptedArticleLine {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" orderedArticleLineId: ").append(toIndentedString(orderedArticleLineId)).append("\n"); sb.append(" articleId: ").append(toIndentedString(articleId)).append("\n"); sb.append(" pcn: ").append(toIndentedString(pcn)).append("\n"); sb.append(" productGroupName: ").append(toIndentedString(productGroupName)).append("\n"); sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); sb.append(" unit: ").append(toIndentedString(unit)).append("\n"); sb.append(" annotation: ").append(toIndentedString(annotation)).append("\n"); sb.append(" updated: ").append(toIndentedString(updated)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\PrescriptedArticleLine.java
2
请完成以下Java代码
final class HtmlTemplates { private HtmlTemplates() { } static Builder fromTemplate(String template) { return new Builder(template); } static final class Builder { private final String template; private final Map<String, String> values = new HashMap<>(); private Builder(String template) { this.template = template; } /** * HTML-escape, and inject value {@code value} in every {@code {{key}}} * placeholder. * @param key the placeholder name * @param value the value to inject * @return this instance for further templating */ Builder withValue(String key, @Nullable String value) { if (value != null) { this.values.put(key, HtmlUtils.htmlEscape(value)); } return this; } /** * Inject value {@code value} in every {@code {{key}}} placeholder without * HTML-escaping. Useful for injecting "sub-templates". * @param key the placeholder name * @param value the value to inject * @return this instance for further templating */ Builder withRawHtml(String key, String value) { if (!value.isEmpty() && value.charAt(value.length() - 1) == '\n') { value = value.substring(0, value.length() - 1); } this.values.put(key, value);
return this; } /** * Render the template. All placeholders MUST have a corresponding value. If a * placeholder does not have a corresponding value, throws * {@link IllegalStateException}. * @return the rendered template */ String render() { String template = this.template; for (String key : this.values.keySet()) { String pattern = Pattern.quote("{{" + key + "}}"); template = template.replaceAll(pattern, this.values.get(key)); } String unusedPlaceholders = Pattern.compile("\\{\\{([a-zA-Z0-9]+)}}") .matcher(template) .results() .map((result) -> result.group(1)) .collect(Collectors.joining(", ")); if (StringUtils.hasLength(unusedPlaceholders)) { throw new IllegalStateException("Unused placeholders in template: [%s]".formatted(unusedPlaceholders)); } return template; } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\ui\HtmlTemplates.java
1
请完成以下Java代码
private Function<Health.Builder, Health.Builder> withDistributedSystemDetails() { return healthBuilder -> getGemFireCache() .map(GemFireCache::getDistributedSystem) .map(distributedSystem -> healthBuilder .withDetail("geode.distributed-system.member-count", toMemberCount(distributedSystem)) .withDetail("geode.distributed-system.connection", toConnectedNoConnectedString(distributedSystem.isConnected())) .withDetail("geode.distributed-system.reconnecting", toYesNoString(distributedSystem.isReconnecting())) .withDetail("geode.distributed-system.properties-location", toString(DistributedSystem.getPropertiesFileURL())) .withDetail("geode.distributed-system.security-properties-location", toString(DistributedSystem.getSecurityPropertiesFileURL())) ) .orElse(healthBuilder); } private Function<Health.Builder, Health.Builder> withResourceManagerDetails() { return healthBuilder -> getGemFireCache() .map(GemFireCache::getResourceManager) .map(resourceManager -> healthBuilder .withDetail("geode.resource-manager.critical-heap-percentage", resourceManager.getCriticalHeapPercentage()) .withDetail("geode.resource-manager.critical-off-heap-percentage", resourceManager.getCriticalOffHeapPercentage()) .withDetail("geode.resource-manager.eviction-heap-percentage", resourceManager.getEvictionHeapPercentage()) .withDetail("geode.resource-manager.eviction-off-heap-percentage", resourceManager.getEvictionOffHeapPercentage()) ) .orElse(healthBuilder); } private String emptyIfUnset(String value) { return StringUtils.hasText(value) ? value : ""; }
private String toConnectedNoConnectedString(Boolean connected) { return Boolean.TRUE.equals(connected) ? "Connected" : "Not Connected"; } private int toMemberCount(DistributedSystem distributedSystem) { return CollectionUtils.nullSafeSize(distributedSystem.getAllOtherMembers()) + 1; } private String toString(URL url) { String urlString = url != null ? url.toExternalForm() : null; return emptyIfUnset(urlString); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-actuator\src\main\java\org\springframework\geode\boot\actuate\GeodeCacheHealthIndicator.java
1
请完成以下Java代码
protected ObjectNode links(ObjectNode parent, List<Type> types, String appUrl) { ObjectNode links = super.links(parent, types, appUrl); links.set("dependencies", dependenciesLink(appUrl)); parent.set("_links", links); return links; } @Override protected ObjectNode mapDependency(Dependency dependency) { ObjectNode content = mapValue(dependency); if (dependency.getRange() != null) { content.put("versionRange", formatVersionRange(dependency.getRange())); } if (dependency.getLinks() != null && !dependency.getLinks().isEmpty()) { content.set("_links", LinkMapper.mapLinks(dependency.getLinks())); } return content; } protected String formatVersionRange(VersionRange versionRange) {
return versionRange.format(Format.V1).toRangeString(); } protected ObjectNode dependenciesLink(String appUrl) { String uri = (appUrl != null) ? appUrl + "/dependencies" : "/dependencies"; UriTemplate uriTemplate = UriTemplate.of(uri, getDependenciesVariables()); ObjectNode result = nodeFactory().objectNode(); result.put("href", uriTemplate.toString()); result.put("templated", true); return result; } protected TemplateVariables getDependenciesVariables() { return this.dependenciesVariables; } }
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\mapper\InitializrMetadataV21JsonMapper.java
1
请完成以下Java代码
public int getDoc_User_ID() { if (m_AD_User_ID != 0) return m_AD_User_ID; if (getC_BPartner_ID() != 0) { final List<I_AD_User> users = Services.get(IBPartnerDAO.class).retrieveContacts(getCtx(), getC_BPartner_ID(), ITrx.TRXNAME_None); if (!users.isEmpty()) { m_AD_User_ID = users.get(0).getAD_User_ID(); return m_AD_User_ID; } } return getCreatedBy(); } // getDoc_User_ID /** * Get Document Currency * @return C_Currency_ID
*/ @Override public int getC_Currency_ID() { final I_M_PriceList pl = Services.get(IPriceListDAO.class).getById(getM_PriceList_ID()); return pl.getC_Currency_ID(); } // getC_Currency_ID /** * Document Status is Complete or Closed * @return true if CO, CL or RE */ public boolean isComplete() { String ds = getDocStatus(); return DOCSTATUS_Completed.equals(ds) || DOCSTATUS_Closed.equals(ds) || DOCSTATUS_Reversed.equals(ds); } // isComplete } // MTimeExpense
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MTimeExpense.java
1
请完成以下Java代码
List<Post> getAuthorPosts(String author) throws ExecutionException, InterruptedException { var postsResult = faunaClient.query(Map( Paginate( Join( Match(Index("posts_by_author"), Select(Value("ref"), Get(Match(Index("users_by_username"), Value(author))))), Index("posts_sort_by_created_desc") ) ), Lambda( Arr(Value("extra"), Value("ref")), Obj( "post", Get(Var("ref")), "author", Get(Select(Arr(Value("data"), Value("authorRef")), Get(Var("ref")))) ) ) )).get(); var posts = postsResult.at("data").asCollectionOf(Value.class).get(); return posts.stream().map(this::parsePost).collect(Collectors.toList()); } public void createPost(String author, String title, String contents) throws ExecutionException, InterruptedException { faunaClient.query( Create(Collection("posts"), Obj( "data", Obj( "title", Value(title), "contents", Value(contents), "created", Now(), "authorRef", Select(Value("ref"), Get(Match(Index("users_by_username"), Value(author))))) ) ) ).get(); } public void updatePost(String id, String title, String contents) throws ExecutionException, InterruptedException { faunaClient.query( Update(Ref(Collection("posts"), id),
Obj( "data", Obj( "title", Value(title), "contents", Value(contents)) ) ) ).get(); } private Post parsePost(Value entry) { var author = entry.at("author"); var post = entry.at("post"); return new Post( post.at("ref").to(Value.RefV.class).get().getId(), post.at("data", "title").to(String.class).get(), post.at("data", "contents").to(String.class).get(), new Author( author.at("data", "username").to(String.class).get(), author.at("data", "name").to(String.class).get() ), post.at("data", "created").to(Instant.class).get(), post.at("ts").to(Long.class).get() ); } }
repos\tutorials-master\persistence-modules\fauna\src\main\java\com\baeldung\faunablog\posts\PostsService.java
1
请完成以下Java代码
public static class ExecutionPlan { public int number = Integer.MAX_VALUE; public int length = 0; public NumberOfDigits numberOfDigits= new NumberOfDigits(); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void stringBasedSolution(ExecutionPlan plan) { plan.length = plan.numberOfDigits.stringBasedSolution(plan.number); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void logarithmicApproach(ExecutionPlan plan) { plan.length = plan.numberOfDigits.logarithmicApproach(plan.number); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void repeatedMultiplication(ExecutionPlan plan) {
plan.length = plan.numberOfDigits.repeatedMultiplication(plan.number); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void shiftOperators(ExecutionPlan plan) { plan.length = plan.numberOfDigits.shiftOperators(plan.number); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void dividingWithPowersOf2(ExecutionPlan plan) { plan.length = plan.numberOfDigits.dividingWithPowersOf2(plan.number); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void divideAndConquer(ExecutionPlan plan) { plan.length = plan.numberOfDigits.divideAndConquer(plan.number); } }
repos\tutorials-master\core-java-modules\core-java-numbers\src\main\java\com\baeldung\numberofdigits\Benchmarking.java
1
请在Spring Boot框架中完成以下Java代码
public OffsetDateTime getCreatedAt() { return createdAt; } public void setCreatedAt(OffsetDateTime createdAt) { this.createdAt = createdAt; } public Document updatedAt(OffsetDateTime updatedAt) { this.updatedAt = updatedAt; return this; } /** * Der Zeitstempel der letzten Änderung * @return updatedAt **/ @Schema(description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getUpdatedAt() { return updatedAt; } public void setUpdatedAt(OffsetDateTime updatedAt) { this.updatedAt = updatedAt; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Document document = (Document) o; return Objects.equals(this._id, document._id) && Objects.equals(this.name, document.name) && Objects.equals(this.patientId, document.patientId) && Objects.equals(this.therapyId, document.therapyId) && Objects.equals(this.therapyTypeId, document.therapyTypeId) && Objects.equals(this.archived, document.archived) && Objects.equals(this.createdBy, document.createdBy) &&
Objects.equals(this.updatedBy, document.updatedBy) && Objects.equals(this.createdAt, document.createdAt) && Objects.equals(this.updatedAt, document.updatedAt); } @Override public int hashCode() { return Objects.hash(_id, name, patientId, therapyId, therapyTypeId, archived, createdBy, updatedBy, createdAt, updatedAt); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Document {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" patientId: ").append(toIndentedString(patientId)).append("\n"); sb.append(" therapyId: ").append(toIndentedString(therapyId)).append("\n"); sb.append(" therapyTypeId: ").append(toIndentedString(therapyTypeId)).append("\n"); sb.append(" archived: ").append(toIndentedString(archived)).append("\n"); sb.append(" createdBy: ").append(toIndentedString(createdBy)).append("\n"); sb.append(" updatedBy: ").append(toIndentedString(updatedBy)).append("\n"); sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n"); sb.append(" updatedAt: ").append(toIndentedString(updatedAt)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-document-api\src\main\java\io\swagger\client\model\Document.java
2
请完成以下Java代码
public String getOrderCode() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); int a = (int)(Math.random() * 9000.0D) + 1000; System.out.println(a); Date date = new Date(); String str = sdf.format(date); String[] split = str.split("-"); String s = split[0] + split[1] + split[2]; String[] split1 = s.split(" "); String s1 = split1[0] + split1[1]; String[] split2 = s1.split(":"); return split2[0] + split2[1] + split2[2] + a; } /** * 校验签名 * @param request HttpServletRequest * @param alipay 阿里云配置 * @return boolean */ public boolean rsaCheck(HttpServletRequest request, AlipayConfig alipay){ // 获取支付宝POST过来反馈信息 Map<String,String> params = new HashMap<>(1); Map<String, String[]> requestParams = request.getParameterMap(); for (Object o : requestParams.keySet()) { String name = (String) o; String[] values = requestParams.get(name); String valueStr = ""; for (int i = 0; i < values.length; i++) { valueStr = (i == values.length - 1) ? valueStr + values[i]
: valueStr + values[i] + ","; } params.put(name, valueStr); } try { return AlipaySignature.rsaCheckV1(params, alipay.getPublicKey(), alipay.getCharset(), alipay.getSignType()); } catch (AlipayApiException e) { return false; } } }
repos\eladmin-master\eladmin-tools\src\main\java\me\zhengjie\utils\AlipayUtils.java
1
请完成以下Java代码
final class MqttPendingUnsubscription { private final Promise<Void> future; private final String topic; @Getter(AccessLevel.NONE) private final RetransmissionHandler<MqttUnsubscribeMessage> retransmissionHandler; private MqttPendingUnsubscription( Promise<Void> future, String topic, MqttUnsubscribeMessage unsubscribeMessage, String ownerId, MqttClientConfig.RetransmissionConfig retransmissionConfig, PendingOperation operation ) { this.future = future; this.topic = topic; retransmissionHandler = new RetransmissionHandler<>(retransmissionConfig, operation, ownerId); retransmissionHandler.setOriginalMessage(unsubscribeMessage); } void startRetransmissionTimer(EventLoop eventLoop, Consumer<Object> sendPacket) { retransmissionHandler.setHandler((fixedHeader, originalMessage) -> sendPacket.accept(new MqttUnsubscribeMessage(fixedHeader, originalMessage.variableHeader(), originalMessage.payload()))); retransmissionHandler.start(eventLoop); } void onUnsubackReceived() { retransmissionHandler.stop(); } void onChannelClosed() { retransmissionHandler.stop(); } static Builder builder() { return new Builder(); } static class Builder { private Promise<Void> future; private String topic; private MqttUnsubscribeMessage unsubscribeMessage; private String ownerId; private PendingOperation pendingOperation; private MqttClientConfig.RetransmissionConfig retransmissionConfig;
Builder future(Promise<Void> future) { this.future = future; return this; } Builder topic(String topic) { this.topic = topic; return this; } Builder unsubscribeMessage(MqttUnsubscribeMessage unsubscribeMessage) { this.unsubscribeMessage = unsubscribeMessage; return this; } Builder ownerId(String ownerId) { this.ownerId = ownerId; return this; } Builder retransmissionConfig(MqttClientConfig.RetransmissionConfig retransmissionConfig) { this.retransmissionConfig = retransmissionConfig; return this; } Builder pendingOperation(PendingOperation pendingOperation) { this.pendingOperation = pendingOperation; return this; } MqttPendingUnsubscription build() { return new MqttPendingUnsubscription(future, topic, unsubscribeMessage, ownerId, retransmissionConfig, pendingOperation); } } }
repos\thingsboard-master\netty-mqtt\src\main\java\org\thingsboard\mqtt\MqttPendingUnsubscription.java
1
请完成以下Java代码
public class MAttributeInstance extends X_M_AttributeInstance { @SuppressWarnings("unused") public MAttributeInstance(Properties ctx, int id, String trxName) { super(ctx, id, trxName); } // MAttributeInstance @SuppressWarnings("unused") public MAttributeInstance(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MAttributeInstance @Override public void setValueNumber(BigDecimal ValueNumber) { super.setValueNumber(ValueNumber); if (ValueNumber == null) { setValue(null); return; } if (ValueNumber.signum() == 0)
{ setValue("0"); return; } setValue(ValueNumber.toString()); } // setValueNumber /** * String Representation * * @return info */ @Override public String toString() { final String value = getValue(); return value == null ? "" : value; } // toString } // MAttributeInstance
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAttributeInstance.java
1
请完成以下Java代码
public String getServiceId() { return delegate.getServiceId(); } @Override public String getHost() { return delegate.getHost(); } @Override public int getPort() { return delegate.getPort(); } @Override public boolean isSecure() { // TODO: move to map if ("https".equals(this.overrideScheme) || "wss".equals(this.overrideScheme)) { return true; } return delegate.isSecure(); } @Override public URI getUri() { return delegate.getUri();
} @Override public Map<String, String> getMetadata() { return delegate.getMetadata(); } @Override public String getScheme() { String scheme = delegate.getScheme(); if (scheme != null) { return scheme; } return this.overrideScheme; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\support\DelegatingServiceInstance.java
1
请完成以下Java代码
public UomId getBomProductUOMId() { return UomId.ofRepoId(bomProductUOM.getC_UOM_ID()); } /** * @deprecated consider using {@link #computeQtyRequired(Quantity)} */ @Deprecated public Quantity computeQtyRequired(@NonNull final BigDecimal qtyOfFinishedGood) { return computeQtyRequired(Quantity.of(qtyOfFinishedGood, bomProductUOM)); } public Quantity computeQtyRequired(@NonNull final Quantity qtyOfFinishedGood) { final Quantity qtyOfFinishedGoodInRightUOM = uomConversionService.convertQuantityTo(qtyOfFinishedGood, UOMConversionContext.of(bomProductId), UomId.ofRepoId(bomProductUOM.getC_UOM_ID())); final Quantity qtyRequiredForOneFinishedGood = getQtyRequiredForOneFinishedGood(); final Quantity qtyRequired; if (componentType.isTools()) { qtyRequired = qtyRequiredForOneFinishedGood; } else { qtyRequired = qtyRequiredForOneFinishedGood .multiply(qtyOfFinishedGoodInRightUOM.toBigDecimal()) .setScale(UOMPrecision.ofInt(8), RoundingMode.UP); } // // Adjust the qtyRequired by adding the scrap percentage to it. return ProductBOMQtys.computeQtyWithScrap(qtyRequired, scrap); } @VisibleForTesting public Quantity getQtyRequiredForOneFinishedGood() { if (qtyPercentage) { // // We also need to multiply by BOM UOM to BOM Line UOM multiplier // see http://dewiki908/mediawiki/index.php/06973_Fix_percentual_BOM_line_quantities_calculation_%28108941319640%29 final UOMConversionRate bomToLineRate = uomConversionService.getRate(bomProductId, UomId.ofRepoId(bomProductUOM.getC_UOM_ID()), UomId.ofRepoId(uom.getC_UOM_ID())); final BigDecimal bomToLineUOMMultiplier = bomToLineRate.getFromToMultiplier(); return Quantity.of( percentOfFinishedGood.computePercentageOf(bomToLineUOMMultiplier, 12), uom); } else { return qtyForOneFinishedGood;
} } @Deprecated public Quantity computeQtyOfFinishedGoodsForComponentQty(@NonNull final BigDecimal componentsQty) { return computeQtyOfFinishedGoodsForComponentQty(Quantity.of(componentsQty, uom)); } public Quantity computeQtyOfFinishedGoodsForComponentQty(@NonNull final Quantity componentsQty) { final Quantity qtyRequiredForOneFinishedGood = getQtyRequiredForOneFinishedGood(); final Quantity componentsQtyConverted = uomConversionService.convertQuantityTo(componentsQty, UOMConversionContext.of(productId), uom); final BigDecimal qtyOfFinishedGoodsBD = componentsQtyConverted .toBigDecimal() .divide( qtyRequiredForOneFinishedGood.toBigDecimal(), bomProductUOM.getStdPrecision(), RoundingMode.DOWN); // IMPORTANT to round DOWN because we need complete products. return Quantity.of(qtyOfFinishedGoodsBD, bomProductUOM); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\api\QtyCalculationsBOMLine.java
1
请完成以下Java代码
private WebuiHUTransformCommandResult action_SplitTU_To_ExistingLU(final HUEditorRow tuRow, final I_M_HU luHU, final QtyTU qtyTU) { newHUTransformation().tuToExistingLU(tuRow.getM_HU(), qtyTU, luHU); final HUEditorRowId tuRowId = tuRow.getHURowId(); return WebuiHUTransformCommandResult.builder() .huIdChanged(tuRowId.getTopLevelHUId()) .huIdChanged(HuId.ofRepoId(luHU.getM_HU_ID())) .fullViewInvalidation(true) // because it might be that the TU is inside an LU of which we don't know the ID .build(); } /** * Split TU to new LU (only one LU!). * * @param tuRow represents the TU (or TUs in the aggregate-HU-case) that is our split source * @param qtyTU the number of TUs we want to split from the given {@code tuRow} */ private WebuiHUTransformCommandResult action_SplitTU_To_NewLU( final HUEditorRow tuRow, final I_M_HU_PI_Item huPIItem, final QtyTU qtyTU, final boolean isOwnPackingMaterials) { final List<I_M_HU> createdHUs = newHUTransformation().tuToNewLUs(tuRow.getM_HU(), qtyTU, huPIItem, isOwnPackingMaterials).getLURecords(); final ImmutableSet<HuId> huIdsToAddToView = createdHUs.stream() .map(I_M_HU::getM_HU_ID) .map(HuId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); return WebuiHUTransformCommandResult.builder() .huIdsCreated(huIdsToAddToView) .huIdsToAddToView(huIdsToAddToView) .huIdChanged(tuRow.getHURowId().getTopLevelHUId()) .fullViewInvalidation(true) // because it might be that the TU is inside an LU of which we don't know the ID .build(); } /** * Split a given number of TUs from current selected TU line to new TUs. */ private WebuiHUTransformCommandResult action_SplitTU_To_NewTUs(final HUEditorRow tuRow, final QtyTU qtyTU)
{ final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class); // TODO: if qtyTU is the "maximum", then don't do anything, but show a user message final I_M_HU fromTU = tuRow.getM_HU(); final I_M_HU fromTopLevelHU = handlingUnitsBL.getTopLevelParent(fromTU); final List<I_M_HU> createdHUs = newHUTransformation().tuToNewTUs(fromTU, qtyTU).getAllTURecords(); final ImmutableSet<HuId> huIdsToAddToView = createdHUs.stream() .map(I_M_HU::getM_HU_ID) .map(HuId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); final WebuiHUTransformCommandResultBuilder resultBuilder = WebuiHUTransformCommandResult.builder() .huIdsToAddToView(huIdsToAddToView) .huIdsCreated(huIdsToAddToView); if (handlingUnitsBL.isDestroyedRefreshFirst(fromTopLevelHU)) { resultBuilder.huIdToRemoveFromView(HuId.ofRepoId(fromTopLevelHU.getM_HU_ID())); } else { resultBuilder.huIdChanged(HuId.ofRepoId(fromTopLevelHU.getM_HU_ID())); } return resultBuilder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WebuiHUTransformCommand.java
1
请在Spring Boot框架中完成以下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 String getGenre() { return genre; } public void setGenre(String genre) {
this.genre = genre; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Short getVersion() { return version; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchInsertsJpaRepository\src\main\java\com\bookstore\entity\Author.java
2
请完成以下Java代码
protected String doIt() { final InventoryId inventoryId = InventoryId.ofRepoId(getRecord_ID()); final ProductsToProcess productsToProcess = getProductsToProcess(inventoryId).orElse(null); if (productsToProcess == null) { return MSG_OK; } process(productsToProcess); return MSG_OK; } private Optional<ProductsToProcess> getProductsToProcess(@NonNull final InventoryId inventoryId) { final Action actionToRun = getActionToRun(inventoryId); if (actionToRun == null) { // throw new AdempiereException("@Invalid@ @DocStatus@"); return Optional.empty(); } final ProductsToProcess.ProductsToProcessBuilder resultBuilder = ProductsToProcess.builder() .action(actionToRun) .inventoryId(inventoryId); for (final SecurPharmProduct product : securPharmService.findProductsToDecommissionForInventoryId(inventoryId)) { if (actionToRun == Action.DECOMMISSION) { if (securPharmService.isEligibleForDecommission(product)) { resultBuilder.product(product); } } else if (actionToRun == Action.UNDO_DECOMMISSION) { if (securPharmService.isEligibleForUndoDecommission(product)) { resultBuilder.product(product); } } } final ProductsToProcess result = resultBuilder.build(); if (result.isEmpty()) { return Optional.empty(); } return Optional.of(result); } private void process(@NonNull final ProductsToProcess productsToProcess) { final Action action = productsToProcess.getAction(); final InventoryId inventoryId = productsToProcess.getInventoryId(); for (final SecurPharmProduct product : productsToProcess.getProducts()) { process(product, action, inventoryId); } } private void process( @NonNull final SecurPharmProduct product, @NonNull final Action action, @NonNull final InventoryId inventoryId) { if (action == Action.DECOMMISSION) { securPharmService.decommissionProductIfEligible(product, inventoryId); } else if (action == Action.UNDO_DECOMMISSION) { securPharmService.undoDecommissionProductIfEligible(product, inventoryId); } else {
throw new AdempiereException("Invalid action: " + action); } } private Action getActionToRun(@NonNull final InventoryId inventoryId) { final DocStatus inventoryDocStatus = Services.get(IInventoryBL.class).getDocStatus(inventoryId); if (DocStatus.Completed.equals(inventoryDocStatus)) { return Action.DECOMMISSION; } else if (DocStatus.Reversed.equals(inventoryDocStatus)) { return Action.UNDO_DECOMMISSION; } else { return null; } } private enum Action { DECOMMISSION, UNDO_DECOMMISSION } @Value @Builder private static class ProductsToProcess { @NonNull Action action; @NonNull InventoryId inventoryId; @NonNull @Singular ImmutableList<SecurPharmProduct> products; public boolean isEmpty() { return getProducts().isEmpty(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\process\M_Inventory_SecurpharmActionRetry.java
1
请在Spring Boot框架中完成以下Java代码
public void setInstanceId(String instanceId) { this.instanceId = instanceId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } public Boolean getFailed() { return failed; } public void setFailed(Boolean failed) { this.failed = failed; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; }
public String getDecisionKey() { return decisionKey; } public void setDecisionKey(String decisionKey) { this.decisionKey = decisionKey; } public String getDecisionName() { return decisionName; } public void setDecisionName(String decisionName) { this.decisionName = decisionName; } public String getDecisionVersion() { return decisionVersion; } public void setDecisionVersion(String decisionVersion) { this.decisionVersion = decisionVersion; } }
repos\flowable-engine-main\modules\flowable-dmn-rest\src\main\java\org\flowable\dmn\rest\service\api\history\HistoricDecisionExecutionResponse.java
2
请完成以下Java代码
public static Document createDocumentFromString(final String str) throws ParserConfigurationException, SAXException, IOException { // path to file is global // String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; // String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema"; // String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource"; final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); // validate against XML Schema in dbsql2xml.xsd // documentBuilderFactory.setNamespaceAware(true); // INFO change validation to true. Someday when xsd file is complete... documentBuilderFactory.setValidating(false); // documentBuilderFactory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); // documentBuilderFactory.setAttribute(JAXP_SCHEMA_SOURCE, new File(pathToXsdFile)); final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); final Document document = documentBuilder.parse(new InputSource(new StringReader(str))); return document; } // t.schoneberg@metas.de, 03132: code extraced from class 'TopicRplExportProcessor' public static String createStringFromDOMNode(final Node node) { final Writer writer = new StringWriter(); writeDocument(writer, node); return writer.toString(); } // t.schoneberg@metas.de, 03132: code extraced from class 'TopicRplExportProcessor'
public static void writeDocument(final Writer writer, final Node node) { // Construct Transformer Factory and Transformer final TransformerFactory tranFactory = TransformerFactory.newInstance(); Transformer aTransformer; try { aTransformer = tranFactory.newTransformer(); } catch (final TransformerConfigurationException e) { throw new AdempiereException(e); } aTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); final Source src = new DOMSource(node); // =================================== Write to String // Writer writer = new StringWriter(); final Result dest2 = new StreamResult(writer); try { aTransformer.transform(src, dest2); } catch (final TransformerException e) { throw new AdempiereException(e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\process\rpl\XMLHelper.java
1
请完成以下Java代码
public AttachmentEntry withRemovedLinkedRecords(@NonNull final List<TableRecordReference> linkedRecordsToRemove) { final HashSet<TableRecordReference> linkedRecords = new HashSet<>(getLinkedRecords()); if (linkedRecords.removeAll(linkedRecordsToRemove)) { return toBuilder().clearLinkedRecords().linkedRecords(linkedRecords).build(); } else { return this; } } public AttachmentEntry withAdditionalTag(@NonNull final AttachmentTags attachmentTags) { return toBuilder() .tags(getTags().withTags(attachmentTags)) .build(); } public AttachmentEntry withoutTags(@NonNull final AttachmentTags attachmentTags) { return toBuilder() .tags(getTags().withoutTags(attachmentTags)) .build(); } /** * @return the attachment's filename as seen from the given {@code tableRecordReference}. Note that different records might share the same attachment, but refer to it under different file names. */ @NonNull public String getFilename(@NonNull final TableRecordReference tableRecordReference)
{ if (linkedRecord2AttachmentName == null) { return filename; } return CoalesceUtil.coalesceNotNull( linkedRecord2AttachmentName.get(tableRecordReference), filename); } public boolean hasLinkToRecord(@NonNull final TableRecordReference tableRecordReference) { return linkedRecords.contains(tableRecordReference); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\attachments\AttachmentEntry.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isIncludeException() { return this.includeException; } public void setIncludeException(boolean includeException) { this.includeException = includeException; } public IncludeAttribute getIncludeStacktrace() { return this.includeStacktrace; } public void setIncludeStacktrace(IncludeAttribute includeStacktrace) { this.includeStacktrace = includeStacktrace; } public IncludeAttribute getIncludeMessage() { return this.includeMessage; } public void setIncludeMessage(IncludeAttribute includeMessage) { this.includeMessage = includeMessage; } public IncludeAttribute getIncludeBindingErrors() { return this.includeBindingErrors; } public void setIncludeBindingErrors(IncludeAttribute includeBindingErrors) { this.includeBindingErrors = includeBindingErrors; } public IncludeAttribute getIncludePath() { return this.includePath; } public void setIncludePath(IncludeAttribute includePath) { this.includePath = includePath; } public Whitelabel getWhitelabel() { return this.whitelabel; } /** * Include error attributes options. */ public enum IncludeAttribute { /** * Never add error attribute. */ NEVER, /** * Always add error attribute. */ ALWAYS,
/** * Add error attribute when the appropriate request parameter is not "false". */ ON_PARAM } public static class Whitelabel { /** * Whether to enable the default error page displayed in browsers in case of a * server error. */ private boolean enabled = true; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\web\ErrorProperties.java
2
请在Spring Boot框架中完成以下Java代码
public int hashCode() { return Objects.hash(convertedFromCurrency, convertedFromValue, currency, exchangeRate, value); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class DisputeAmount {\n"); sb.append(" convertedFromCurrency: ").append(toIndentedString(convertedFromCurrency)).append("\n"); sb.append(" convertedFromValue: ").append(toIndentedString(convertedFromValue)).append("\n"); sb.append(" currency: ").append(toIndentedString(currency)).append("\n"); sb.append(" exchangeRate: ").append(toIndentedString(exchangeRate)).append("\n"); sb.append(" value: ").append(toIndentedString(value)).append("\n"); sb.append("}");
return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\DisputeAmount.java
2
请完成以下Java代码
public String getAuthorizedClientRegistrationId() { return this.authorizedClientRegistrationId; } @Override public Builder<?> toBuilder() { return new Builder<>(this); } /** * A builder of {@link OAuth2AuthenticationToken} instances * * @since 7.0 */ public static class Builder<B extends Builder<B>> extends AbstractAuthenticationBuilder<B> { private OAuth2User principal; private String authorizedClientRegistrationId; protected Builder(OAuth2AuthenticationToken token) { super(token); this.principal = token.principal; this.authorizedClientRegistrationId = token.authorizedClientRegistrationId; } @Override public B principal(@Nullable Object principal) { Assert.isInstanceOf(OAuth2User.class, principal, "principal must be of type OAuth2User"); this.principal = (OAuth2User) principal; return (B) this; } /**
* Use this * {@link org.springframework.security.oauth2.client.registration.ClientRegistration} * {@code registrationId}. * @param authorizedClientRegistrationId the registration id to use * @return the {@link Builder} for further configurations * @see OAuth2AuthenticationToken#getAuthorizedClientRegistrationId */ public B authorizedClientRegistrationId(String authorizedClientRegistrationId) { this.authorizedClientRegistrationId = authorizedClientRegistrationId; return (B) this; } @Override public OAuth2AuthenticationToken build() { return new OAuth2AuthenticationToken(this); } } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\authentication\OAuth2AuthenticationToken.java
1
请在Spring Boot框架中完成以下Java代码
public static class Template { /** * Whether to ignore JDBC statement warnings (SQLWarning). When set to false, * throw an SQLWarningException instead. */ private boolean ignoreWarnings = true; /** * Number of rows that should be fetched from the database when more rows are * needed. Use -1 to use the JDBC driver's default configuration. */ private int fetchSize = -1; /** * Maximum number of rows. Use -1 to use the JDBC driver's default configuration. */ private int maxRows = -1; /** * Query timeout. Default is to use the JDBC driver's default configuration. If a * duration suffix is not specified, seconds will be used. */ @DurationUnit(ChronoUnit.SECONDS) private @Nullable Duration queryTimeout; /** * Whether results processing should be skipped. Can be used to optimize callable * statement processing when we know that no results are being passed back. */ private boolean skipResultsProcessing; /** * Whether undeclared results should be skipped. */ private boolean skipUndeclaredResults; /** * Whether execution of a CallableStatement will return the results in a Map that * uses case-insensitive names for the parameters. */ private boolean resultsMapCaseInsensitive; public boolean isIgnoreWarnings() { return this.ignoreWarnings; } public void setIgnoreWarnings(boolean ignoreWarnings) { this.ignoreWarnings = ignoreWarnings; } public int getFetchSize() {
return this.fetchSize; } public void setFetchSize(int fetchSize) { this.fetchSize = fetchSize; } public int getMaxRows() { return this.maxRows; } public void setMaxRows(int maxRows) { this.maxRows = maxRows; } public @Nullable Duration getQueryTimeout() { return this.queryTimeout; } public void setQueryTimeout(@Nullable Duration queryTimeout) { this.queryTimeout = queryTimeout; } public boolean isSkipResultsProcessing() { return this.skipResultsProcessing; } public void setSkipResultsProcessing(boolean skipResultsProcessing) { this.skipResultsProcessing = skipResultsProcessing; } public boolean isSkipUndeclaredResults() { return this.skipUndeclaredResults; } public void setSkipUndeclaredResults(boolean skipUndeclaredResults) { this.skipUndeclaredResults = skipUndeclaredResults; } public boolean isResultsMapCaseInsensitive() { return this.resultsMapCaseInsensitive; } public void setResultsMapCaseInsensitive(boolean resultsMapCaseInsensitive) { this.resultsMapCaseInsensitive = resultsMapCaseInsensitive; } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\JdbcProperties.java
2
请完成以下Java代码
public Double getWidth() { return width; } public void setWidth(Double width) { this.width = width; } public String getUom() { return uom; } public void setUom(String uom) { this.uom = uom; }
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Size size = (Size) o; return Objects.equals(height, size.height) && Objects.equals(width, size.width) && Objects.equals(uom, size.uom); } @Override public int hashCode() { return Objects.hash(height, width, uom); } }
repos\tutorials-master\persistence-modules\spring-data-mongodb-2\src\main\java\com\baeldung\projection\model\Size.java
1
请在Spring Boot框架中完成以下Java代码
public class SecuredDirectChannel { @Bean(name = "startDirectChannel") @SecuredChannel(interceptor = "channelSecurityInterceptor", sendAccess = { "ROLE_VIEWER", "jane" }) public DirectChannel startDirectChannel() { return new DirectChannel(); } @ServiceActivator(inputChannel = "startDirectChannel", outputChannel = "endDirectChannel") @PreAuthorize("hasRole('ROLE_LOGGER')") public Message<?> logMessage(Message<?> message) { Logger.getAnonymousLogger().info(message.toString()); return message; } @Bean(name = "endDirectChannel")
@SecuredChannel(interceptor = "channelSecurityInterceptor", sendAccess = { "ROLE_EDITOR" }) public DirectChannel endDirectChannel() { return new DirectChannel(); } @Autowired @Bean public ChannelSecurityInterceptor channelSecurityInterceptor(AuthenticationManager authenticationManager, AccessDecisionManager customAccessDecisionManager) { ChannelSecurityInterceptor channelSecurityInterceptor = new ChannelSecurityInterceptor(); channelSecurityInterceptor.setAuthenticationManager(authenticationManager); channelSecurityInterceptor.setAccessDecisionManager(customAccessDecisionManager); return channelSecurityInterceptor; } }
repos\tutorials-master\spring-integration\src\main\java\com\baeldung\si\security\SecuredDirectChannel.java
2
请完成以下Java代码
public void setMKTG_Platform_ID (int MKTG_Platform_ID) { if (MKTG_Platform_ID < 1) set_ValueNoCheck (COLUMNNAME_MKTG_Platform_ID, null); else set_ValueNoCheck (COLUMNNAME_MKTG_Platform_ID, Integer.valueOf(MKTG_Platform_ID)); } /** Get MKTG_Platform. @return MKTG_Platform */ @Override public int getMKTG_Platform_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_Platform_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Kennwort. @param Password Kennwort */ @Override 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 Registered EMail. @param UserName Email of the responsible for the System */ @Override public void setUserName (java.lang.String UserName) { set_Value (COLUMNNAME_UserName, UserName); } /** Get Registered EMail. @return Email of the responsible for the System */ @Override public java.lang.String getUserName () { return (java.lang.String)get_Value(COLUMNNAME_UserName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\cleverreach\src\main\java-gen\de\metas\marketing\cleverreach\model\X_MKTG_CleverReach_Config.java
1
请完成以下Java代码
public void setHUIterator(final IHUIterator iterator) { if (this.iterator != null && iterator != null && this.iterator != iterator) { throw new AdempiereException("Changing the iterator from " + this.iterator + " to " + iterator + " is not allowed for " + this + "." + " You need to explicitelly set it to null first and then set it again."); } this.iterator = iterator; } public final IHUIterator getHUIterator() { return iterator; } @Override public Result beforeHU(final IMutable<I_M_HU> hu) { return getDefaultResult(); } @Override public Result afterHU(final I_M_HU hu) { return getDefaultResult(); } @Override
public Result beforeHUItem(final IMutable<I_M_HU_Item> item) { return getDefaultResult(); } @Override public Result afterHUItem(final I_M_HU_Item item) { return getDefaultResult(); } @Override public Result beforeHUItemStorage(final IMutable<IHUItemStorage> itemStorage) { return getDefaultResult(); } @Override public Result afterHUItemStorage(final IHUItemStorage itemStorage) { return getDefaultResult(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\HUIteratorListenerAdapter.java
1
请完成以下Java代码
public Builder setRetrieveAppsActionMsg(final boolean retrieveAppsActionMessage) { this.retrieveAppsActionMessage = retrieveAppsActionMessage; return this; } private boolean isIsRetrieveAppsActionMessage() { return retrieveAppsActionMessage; } public Builder setAccelerator(final KeyStroke accelerator) { this.accelerator = accelerator; return this; } private KeyStroke getAccelerator() { return accelerator; } public Builder setText(final String text) { this.text = text; useTextFromAction = false; return this; } public Builder useTextFromActionName() { return useTextFromActionName(true); } public Builder useTextFromActionName(final boolean useTextFromAction) { this.useTextFromAction = useTextFromAction; return this; } private final boolean isUseTextFromActionName() { return useTextFromAction; } private String getText() { return text; } public Builder setToolTipText(final String toolTipText) { this.toolTipText = toolTipText; return this; } private String getToolTipText() { return toolTipText; } /** * Advice the builder that we will build a toggle button. */ public Builder setToggleButton() { return setToggleButton(true); } /** * @param toggleButton is toggle action (maintains state) */ public Builder setToggleButton(final boolean toggleButton) { this.toggleButton = toggleButton; return this; } private boolean isToggleButton() { return toggleButton; } /** * Advice the builder to create a small size button. */ public Builder setSmallSize() { return setSmallSize(true); } /** * Advice the builder if a small size button is needed or not. * * @param smallSize true if small size button shall be created */ public Builder setSmallSize(final boolean smallSize)
{ this.smallSize = smallSize; return this; } private boolean isSmallSize() { return smallSize; } /** * Advice the builder to set given {@link Insets} to action's button. * * @param buttonInsets * @see AbstractButton#setMargin(Insets) */ public Builder setButtonInsets(final Insets buttonInsets) { this.buttonInsets = buttonInsets; return this; } private final Insets getButtonInsets() { return buttonInsets; } /** * Sets the <code>defaultCapable</code> property, which determines whether the button can be made the default button for its root pane. * * @param defaultCapable * @return * @see JButton#setDefaultCapable(boolean) */ public Builder setButtonDefaultCapable(final boolean defaultCapable) { buttonDefaultCapable = defaultCapable; return this; } private Boolean getButtonDefaultCapable() { return buttonDefaultCapable; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\AppsAction.java
1
请完成以下Java代码
public void deleteParams(@NonNull final I_C_Queue_WorkPackage wp) { final QueueWorkPackageId workpackageId = QueueWorkPackageId.ofRepoId(wp.getC_Queue_WorkPackage_ID()); workpackageParamDAO.deleteWorkpackageParams(workpackageId); } @ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE) public void deleteLogs(@NonNull final I_C_Queue_WorkPackage wp) { final IWorkpackageLogsRepository logsRepository = SpringContextHolder.instance.getBean(IWorkpackageLogsRepository.class); final QueueWorkPackageId workpackageId = QueueWorkPackageId.ofRepoId(wp.getC_Queue_WorkPackage_ID()); logsRepository.deleteLogsInTrx(workpackageId); } @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = { I_C_Queue_WorkPackage.COLUMNNAME_Processed, I_C_Queue_WorkPackage.COLUMNNAME_IsError }) public void processBatchFromWP(@NonNull final I_C_Queue_WorkPackage wp)
{ if (wp.getC_Async_Batch_ID() <= 0) { return; } final String trxName = InterfaceWrapperHelper.getTrxName(wp); final AsyncBatchId asyncBatchId = AsyncBatchId.ofRepoId(wp.getC_Async_Batch_ID()); trxManager .getTrxListenerManager(trxName) .runAfterCommit(() -> processBatchInOwnTrx(asyncBatchId)); } private void processBatchInOwnTrx(@NonNull final AsyncBatchId asyncBatchId) { trxManager.runInNewTrx(() -> asyncBatchService.checkProcessed(asyncBatchId, ITrx.TRXNAME_ThreadInherited)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\model\validator\C_Queue_WorkPackage.java
1
请完成以下Java代码
public void output(PrintWriter out) { boolean prettyPrint = getPrettyPrint(); int tabLevel = getTabLevel(); if (registry.size() == 0) { if ((prettyPrint && this instanceof Printable) && (tabLevel > 0)) putTabs(tabLevel, out); super.output(out); } else { if ((prettyPrint && this instanceof Printable) && (tabLevel > 0)) putTabs(tabLevel, out); out.write(createStartTag()); // If this is a StringElement that has ChildElements still print the TagText if(getTagText() != null) out.write(getTagText()); Enumeration<String> en = registryList.elements(); while(en.hasMoreElements()) { Object obj = registry.get(en.nextElement()); if(obj instanceof GenericElement) { Element e = (Element)obj; if (prettyPrint && this instanceof Printable) { if (getNeedLineBreak()) { out.write('\n'); e.setTabLevel(tabLevel + 1); } } e.output(out); } else { if (prettyPrint && this instanceof Printable) { if (getNeedLineBreak()) { out.write('\n'); putTabs(tabLevel + 1, out); } } String string = obj.toString(); if(getFilterState()) out.write(getFilter().process(string)); else out.write(string); } } if (getNeedClosingTag()) { if (prettyPrint && this instanceof Printable) { if (getNeedLineBreak()) { out.write('\n'); if (tabLevel > 0) putTabs(tabLevel, out); } } out.write(createEndTag()); } } }
/** * Allows all Elements the ability to be cloned. */ public Object clone() { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(this); out.close(); ByteArrayInputStream bin = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream in = new ObjectInputStream(bin); Object clone = in.readObject(); in.close(); return(clone); } catch(ClassNotFoundException cnfe) { throw new InternalError(cnfe.toString()); } catch(StreamCorruptedException sce) { throw new InternalError(sce.toString()); } catch(IOException ioe) { throw new InternalError(ioe.toString()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\ConcreteElement.java
1
请完成以下Java代码
private ShipmentScheduleDeletedEvent createDeletedEvent(@NonNull final I_M_ShipmentSchedule shipmentSchedule) { final MaterialDescriptor materialDescriptor = createMaterialDescriptor(shipmentSchedule); final BigDecimal qtyOrdered = shipmentScheduleEffectiveBL.computeQtyOrdered(shipmentSchedule); return ShipmentScheduleDeletedEvent.builder() .eventDescriptor(EventDescriptor.ofClientAndOrg(shipmentSchedule.getAD_Client_ID(), shipmentSchedule.getAD_Org_ID())) .materialDescriptor(materialDescriptor) .shipmentScheduleDetail(ShipmentScheduleDetail.builder() .orderedQuantity(qtyOrdered) .orderedQuantityDelta(qtyOrdered) .reservedQuantity(shipmentSchedule.getQtyReserved()) .reservedQuantityDelta(shipmentSchedule.getQtyReserved()) .build()) .shipmentScheduleId(shipmentSchedule.getM_ShipmentSchedule_ID()) .build(); } @NonNull private MaterialDescriptor createMaterialDescriptor(@NonNull final I_M_ShipmentSchedule shipmentSchedule) { final BigDecimal orderedQuantity = shipmentScheduleEffectiveBL.computeQtyOrdered(shipmentSchedule); final ZonedDateTime preparationDate = shipmentScheduleEffectiveBL.getPreparationDate(shipmentSchedule); final ProductDescriptor productDescriptor = productDescriptorFactory.createProductDescriptor(shipmentSchedule); return MaterialDescriptor.builder() .date(preparationDate.toInstant()) .productDescriptor(productDescriptor) .warehouseId(shipmentScheduleEffectiveBL.getWarehouseId(shipmentSchedule)) .locatorId(shipmentScheduleEffectiveBL.getDefaultLocatorId(shipmentSchedule)) .customerId(shipmentScheduleEffectiveBL.getBPartnerId(shipmentSchedule))
.quantity(orderedQuantity.subtract(getDeliveredQtyFromHUs(shipmentSchedule))) .build(); } @NonNull private BigDecimal getDeliveredQtyFromHUs(@NonNull final I_M_ShipmentSchedule shipmentSchedule) { final List<I_M_ShipmentSchedule_QtyPicked> shipmentScheduleQtyPicked = shipmentScheduleAllocDAO .retrieveAllQtyPickedRecords(shipmentSchedule, I_M_ShipmentSchedule_QtyPicked.class); return shipmentScheduleQtyPicked .stream() .filter(I_M_ShipmentSchedule_QtyPicked::isActive) .filter(I_M_ShipmentSchedule_QtyPicked::isProcessed) .filter(qtyPicked -> qtyPicked.getM_InOutLine_ID() > 0) //dev-note: we only care about "real" qty movements // getValueOptional(qtyPicked, "VHU_ID") - it's an ugly workaround to avoid a circular dependency with de.metas.handlingunits.base .filter(qtyPicked -> InterfaceWrapperHelper.getValueOptional(qtyPicked, "VHU_ID").isPresent()) .map(I_M_ShipmentSchedule_QtyPicked::getQtyPicked) .reduce(BigDecimal::add) .orElse(BigDecimal.ZERO); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\material\interceptor\M_ShipmentSchedule_PostMaterialEvent.java
1
请在Spring Boot框架中完成以下Java代码
public Result<String> add(@RequestBody SysComment sysComment) { sysCommentService.save(sysComment); return Result.OK("添加成功!"); } /** * 编辑 * * @param sysComment * @return */ //@AutoLog(value = "系统评论回复表-编辑") @Operation(summary = "系统评论回复表-编辑") //@RequiresPermissions("org.jeecg.modules.demo:sys_comment:edit") @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST}) public Result<String> edit(@RequestBody SysComment sysComment) { sysCommentService.updateById(sysComment); return Result.OK("编辑成功!"); } /** * 通过id删除 * * @param id * @return */ //@AutoLog(value = "系统评论回复表-通过id删除") @Operation(summary = "系统评论回复表-通过id删除") //@RequiresPermissions("org.jeecg.modules.demo:sys_comment:delete") @DeleteMapping(value = "/delete") public Result<String> delete(@RequestParam(name = "id", required = true) String id) { sysCommentService.removeById(id); return Result.OK("删除成功!"); } /** * 批量删除 * * @param ids * @return */ //@AutoLog(value = "系统评论回复表-批量删除") @Operation(summary = "系统评论回复表-批量删除") //@RequiresPermissions("org.jeecg.modules.demo:sys_comment:deleteBatch") @DeleteMapping(value = "/deleteBatch") public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) { this.sysCommentService.removeByIds(Arrays.asList(ids.split(","))); return Result.OK("批量删除成功!"); } /** * 通过id查询 * * @param id * @return */ //@AutoLog(value = "系统评论回复表-通过id查询") @Operation(summary = "系统评论回复表-通过id查询") @GetMapping(value = "/queryById") public Result<SysComment> queryById(@RequestParam(name = "id", required = true) String id) { SysComment sysComment = sysCommentService.getById(id);
if (sysComment == null) { return Result.error("未找到对应数据"); } return Result.OK(sysComment); } /** * 导出excel * * @param request * @param sysComment */ //@RequiresPermissions("org.jeecg.modules.demo:sys_comment:exportXls") @RequestMapping(value = "/exportXls") public ModelAndView exportXls(HttpServletRequest request, SysComment sysComment) { return super.exportXls(request, sysComment, SysComment.class, "系统评论回复表"); } /** * 通过excel导入数据 * * @param request * @param response * @return */ //@RequiresPermissions("sys_comment:importExcel") @RequestMapping(value = "/importExcel", method = RequestMethod.POST) public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) { return super.importExcel(request, response, SysComment.class); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysCommentController.java
2
请完成以下Java代码
public void setPrecision (final int Precision) { set_Value (COLUMNNAME_Precision, Precision); } @Override public int getPrecision() { return get_ValueAsInt(COLUMNNAME_Precision); } @Override public void setQty (final @Nullable java.lang.String Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override
public java.lang.String getQty() { return get_ValueAsString(COLUMNNAME_Qty); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Ingredients.java
1
请完成以下Java代码
public List<OLCand> getByQuery(@NonNull final OLCandQuery olCandQuery) { final OLCandFactory olCandFactory = new OLCandFactory(); return toSqlQueryBuilder(olCandQuery) .create() .stream() .map(olCandFactory::toOLCand) .collect(ImmutableList.toImmutableList()); } private IQueryBuilder<I_C_OLCand> toSqlQueryBuilder(@NonNull final OLCandQuery olCandQuery) { final IQueryBuilder<I_C_OLCand> queryBuilder = Services.get(IQueryBL.class) .createQueryBuilder(I_C_OLCand.class) .addOnlyActiveRecordsFilter(); if (olCandQuery.getExternalHeaderId() != null) { queryBuilder.addEqualsFilter(I_C_OLCand.COLUMN_ExternalHeaderId, olCandQuery.getExternalHeaderId()); } if (olCandQuery.getExternalSystemType() != null) { final ExternalSystemId externalSystemId = externalSystemRepository.getIdByType(olCandQuery.getExternalSystemType()); queryBuilder.addEqualsFilter(I_C_OLCand.COLUMNNAME_ExternalSystem_ID, externalSystemId); } if (Check.isNotBlank(olCandQuery.getInputDataSourceName())) { final InputDataSourceId inputDataSourceId = inputDataSourceDAO.retrieveInputDataSourceIdByInternalName(olCandQuery.getInputDataSourceName());
queryBuilder.addEqualsFilter(I_C_OLCand.COLUMN_AD_InputDataSource_ID, inputDataSourceId); } if (olCandQuery.getExternalLineId() != null) { queryBuilder.addEqualsFilter(I_C_OLCand.COLUMNNAME_ExternalLineId, olCandQuery.getExternalLineId()); } if (olCandQuery.getOrgId() != null) { queryBuilder.addEqualsFilter(I_C_OLCand.COLUMNNAME_AD_Org_ID, olCandQuery.getOrgId()); } return queryBuilder; } @NonNull public Set<OrderId> getOrderIdsByOLCandIds(@NonNull final Set<OLCandId> olCandIds) { return olCandDAO.getOrderIdsByOLCandIds(olCandIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\OLCandRepository.java
1
请在Spring Boot框架中完成以下Java代码
public int updateMoneyInfo(OmsMoneyInfoParam moneyInfoParam) { OmsOrder order = new OmsOrder(); order.setId(moneyInfoParam.getOrderId()); order.setFreightAmount(moneyInfoParam.getFreightAmount()); order.setDiscountAmount(moneyInfoParam.getDiscountAmount()); order.setModifyTime(new Date()); int count = orderMapper.updateByPrimaryKeySelective(order); //插入操作记录 OmsOrderOperateHistory history = new OmsOrderOperateHistory(); history.setOrderId(moneyInfoParam.getOrderId()); history.setCreateTime(new Date()); history.setOperateMan("后台管理员"); history.setOrderStatus(moneyInfoParam.getStatus()); history.setNote("修改费用信息"); orderOperateHistoryMapper.insert(history); return count; } @Override public int updateNote(Long id, String note, Integer status) {
OmsOrder order = new OmsOrder(); order.setId(id); order.setNote(note); order.setModifyTime(new Date()); int count = orderMapper.updateByPrimaryKeySelective(order); OmsOrderOperateHistory history = new OmsOrderOperateHistory(); history.setOrderId(id); history.setCreateTime(new Date()); history.setOperateMan("后台管理员"); history.setOrderStatus(status); history.setNote("修改备注信息:"+note); orderOperateHistoryMapper.insert(history); return count; } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\OmsOrderServiceImpl.java
2
请完成以下Java代码
public Predicate<ServerWebExchange> apply(Config config) { return new GatewayPredicate() { @Override public boolean test(ServerWebExchange exchange) { String host; if (includePort) { host = exchange.getRequest().getHeaders().getFirst("Host"); } else { InetSocketAddress address = exchange.getRequest().getHeaders().getHost(); if (address != null) { host = address.getHostString(); } else { return false; } } if (host == null) { return false; } String match = null; for (int i = 0; i < config.getPatterns().size(); i++) { String pattern = config.getPatterns().get(i); if (pathMatcher.match(pattern, host)) { match = pattern; break; } } if (match != null) { Map<String, String> variables = pathMatcher.extractUriTemplateVariables(match, host); ServerWebExchangeUtils.putUriTemplateVariables(exchange, variables); return true; } return false; } @Override public Object getConfig() {
return config; } @Override public String toString() { return String.format("Hosts: %s", config.getPatterns()); } }; } public static class Config { private List<String> patterns = new ArrayList<>(); public List<String> getPatterns() { return patterns; } public Config setPatterns(List<String> patterns) { this.patterns = patterns; return this; } @Override public String toString() { return new ToStringCreator(this).append("patterns", patterns).toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\HostRoutePredicateFactory.java
1
请在Spring Boot框架中完成以下Java代码
public class SwaggerConfig extends WebMvcConfigurationSupport { // @Bean public Docket postsApi() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.urunov.mongodb.controller")) .paths(regex("/api/v1.*")) .build() .apiInfo(metaData()); } private ApiInfo metaData() { return new ApiInfoBuilder() .title("Spring Boot REST API with Swagger")
.description("\"Spring Boot REST API for Employee") .version("1.0.0") .license("Apache License Version 2.0") .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0\"") .contact(new Contact("Urunov Hamdamboy", "https://github.com/urunov/", "myindexu@gamil.com")) .build(); } @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
repos\Spring-Boot-Advanced-Projects-main\SpringBoot-MongoDB-NoSQL-CRUD\src\main\java\com\urunov\mongodb\configSwag\SwaggerConfig.java
2
请完成以下Java代码
public int getC_DunningDoc_Line_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DunningDoc_Line_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_DunningLevel getC_DunningLevel() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_DunningLevel_ID, org.compiere.model.I_C_DunningLevel.class); } @Override public void setC_DunningLevel(org.compiere.model.I_C_DunningLevel C_DunningLevel) { set_ValueFromPO(COLUMNNAME_C_DunningLevel_ID, org.compiere.model.I_C_DunningLevel.class, C_DunningLevel); } /** Set Mahnstufe. @param C_DunningLevel_ID Mahnstufe */ @Override public void setC_DunningLevel_ID (int C_DunningLevel_ID) { if (C_DunningLevel_ID < 1) set_ValueNoCheck (COLUMNNAME_C_DunningLevel_ID, null); else set_ValueNoCheck (COLUMNNAME_C_DunningLevel_ID, Integer.valueOf(C_DunningLevel_ID)); } /** Get Mahnstufe. @return Mahnstufe */ @Override public int getC_DunningLevel_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DunningLevel_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Notiz. @param Note Optional weitere Information */ @Override public void setNote (java.lang.String Note) { set_Value (COLUMNNAME_Note, Note); } /** Get Notiz. @return Optional weitere Information */ @Override public java.lang.String getNote () { return (java.lang.String)get_Value(COLUMNNAME_Note); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed)
{ set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } @Override public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class); } @Override public void setSalesRep(org.compiere.model.I_AD_User SalesRep) { set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep); } /** Set Aussendienst. @param SalesRep_ID Aussendienst */ @Override public void setSalesRep_ID (int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID)); } /** Get Aussendienst. @return Aussendienst */ @Override public int getSalesRep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java-gen\de\metas\dunning\model\X_C_DunningDoc_Line.java
1
请完成以下Java代码
public Book setAuthor(String author) { this.author = author; return this; } public Publisher getPublisher() { return publisher; } public Book setPublisher(Publisher publisher) { this.publisher = publisher; return this; } public double getCost() { return cost; } public Book setCost(double cost) { this.cost = cost; return this; } public LocalDateTime getPublishDate() { return publishDate; } public Book setPublishDate(LocalDateTime publishDate) { this.publishDate = publishDate; return this; } public Set<Book> getCompanionBooks() { return companionBooks; } public Book addCompanionBooks(Book book) { if (companionBooks != null) this.companionBooks.add(book); return this; } @Override public String toString() { return "Book [isbn=" + isbn + ", title=" + title + ", author=" + author + ", publisher=" + publisher + ", cost=" + cost + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((author == null) ? 0 : author.hashCode()); long temp; temp = Double.doubleToLongBits(cost); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((isbn == null) ? 0 : isbn.hashCode()); result = prime * result + ((publisher == null) ? 0 : publisher.hashCode()); result = prime * result + ((title == null) ? 0 : title.hashCode()); return result; } @Override
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Book other = (Book) obj; if (author == null) { if (other.author != null) return false; } else if (!author.equals(other.author)) return false; if (Double.doubleToLongBits(cost) != Double.doubleToLongBits(other.cost)) return false; if (isbn == null) { if (other.isbn != null) return false; } else if (!isbn.equals(other.isbn)) return false; if (publisher == null) { if (other.publisher != null) return false; } else if (!publisher.equals(other.publisher)) return false; if (title == null) { if (other.title != null) return false; } else if (!title.equals(other.title)) return false; return true; } }
repos\tutorials-master\persistence-modules\java-mongodb\src\main\java\com\baeldung\bsontojson\Book.java
1
请完成以下Java代码
public class StopExecutionFurtherCode { boolean shouldContinue = true; int performTask(int a, int b) { if (!shouldContinue) { System.exit(0); } return a + b; } void stop() { this.shouldContinue = false; } int calculateFactorial(int n) { if (n <= 1) { return 1; // base case } return n * calculateFactorial(n - 1); } int calculateSum(int[] x) { int sum = 0; for (int i = 0; i < 10; i++) { if (x[i] < 0) { break; } sum += x[i]; } return sum; } <T> T stopExecutionUsingException(T object) { if (object instanceof Number) { throw new IllegalArgumentException("Parameter can not be number."); } T upperCase = (T) String.valueOf(object) .toUpperCase(Locale.ENGLISH); return upperCase; } int processLines(String[] lines) { int statusCode = 0; parser: for (String line : lines) { System.out.println("Processing line: " + line); if (line.equals("stop")) { System.out.println("Stopping parsing...");
statusCode = -1; break parser; // Stop parsing and exit the loop } System.out.println("Line processed."); } return statusCode; } void download(String fileUrl, String destinationPath) throws MalformedURLException, URISyntaxException { if (fileUrl == null || fileUrl.isEmpty() || destinationPath == null || destinationPath.isEmpty()) { return; } // execute downloading URL url = new URI(fileUrl).toURL(); try (InputStream in = url.openStream(); FileOutputStream out = new FileOutputStream(destinationPath)) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } } catch (IOException e) { throw new RuntimeException(e); } } }
repos\tutorials-master\core-java-modules\core-java-lang-6\src\main\java\com\baeldung\stopexecution\StopExecutionFurtherCode.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setInternalName (final java.lang.String InternalName) { set_Value (COLUMNNAME_InternalName, InternalName); } @Override public java.lang.String getInternalName() { return get_ValueAsString(COLUMNNAME_InternalName); } @Override public void setMobile_Application_Action_ID (final int Mobile_Application_Action_ID)
{ if (Mobile_Application_Action_ID < 1) set_ValueNoCheck (COLUMNNAME_Mobile_Application_Action_ID, null); else set_ValueNoCheck (COLUMNNAME_Mobile_Application_Action_ID, Mobile_Application_Action_ID); } @Override public int getMobile_Application_Action_ID() { return get_ValueAsInt(COLUMNNAME_Mobile_Application_Action_ID); } @Override public void setMobile_Application_ID (final int Mobile_Application_ID) { if (Mobile_Application_ID < 1) set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, null); else set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, Mobile_Application_ID); } @Override public int getMobile_Application_ID() { return get_ValueAsInt(COLUMNNAME_Mobile_Application_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Mobile_Application_Action.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_PricingSystem[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Beschreibung. @param Description Optionale kurze Beschreibung fuer den Eintrag */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Optionale kurze Beschreibung fuer den Eintrag */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Preise. @param M_PricingSystem_ID Preise */ public void setM_PricingSystem_ID (int M_PricingSystem_ID) { if (M_PricingSystem_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PricingSystem_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PricingSystem_ID, Integer.valueOf(M_PricingSystem_ID)); } /** Get Preise. @return Preise */ public int getM_PricingSystem_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PricingSystem_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumerische Bezeichnung fuer diesen Eintrag
*/ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumerische Bezeichnung fuer diesen Eintrag */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Suchschluessel. @param Value Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschluessel. @return Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\compiere\model\X_M_PricingSystem.java
1
请完成以下Java代码
public HttpSessionWrapper getSession() { return getSession(true); } @Override public String getRequestedSessionId() { if (this.requestedSessionId == null) { getRequestedSession(); } return this.requestedSessionId; } @Override public RequestDispatcher getRequestDispatcher(String path) { RequestDispatcher requestDispatcher = super.getRequestDispatcher(path); return new SessionCommittingRequestDispatcher(requestDispatcher); } private S getRequestedSession() { if (!this.requestedSessionCached) { List<String> sessionIds = SessionRepositoryFilter.this.httpSessionIdResolver.resolveSessionIds(this); for (String sessionId : sessionIds) { if (this.requestedSessionId == null) { this.requestedSessionId = sessionId; } S session = SessionRepositoryFilter.this.sessionRepository.findById(sessionId); if (session != null) { this.requestedSession = session; break; } } this.requestedSessionCached = true; } return this.requestedSession; } private void clearRequestedSessionCache() { this.requestedSessionCached = false; this.requestedSession = null; this.requestedSessionId = null; } /** * Allows creating an HttpSession from a Session instance. * * @author Rob Winch * @since 1.0 */ private final class HttpSessionWrapper extends HttpSessionAdapter<S> { HttpSessionWrapper(S session, ServletContext servletContext) { super(session, servletContext); } @Override public void invalidate() { super.invalidate();
SessionRepositoryRequestWrapper.this.requestedSessionInvalidated = true; setCurrentSession(null); clearRequestedSessionCache(); SessionRepositoryFilter.this.sessionRepository.deleteById(getId()); } } /** * Ensures session is committed before issuing an include. * * @since 1.3.4 */ private final class SessionCommittingRequestDispatcher implements RequestDispatcher { private final RequestDispatcher delegate; SessionCommittingRequestDispatcher(RequestDispatcher delegate) { this.delegate = delegate; } @Override public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException { this.delegate.forward(request, response); } @Override public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException { if (!SessionRepositoryRequestWrapper.this.hasCommittedInInclude) { SessionRepositoryRequestWrapper.this.commitSession(); SessionRepositoryRequestWrapper.this.hasCommittedInInclude = true; } this.delegate.include(request, response); } } } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\SessionRepositoryFilter.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable CacheControl toHttpCacheControl() { PropertyMapper map = PropertyMapper.get(); CacheControl control = createCacheControl(); map.from(this::getMustRevalidate).whenTrue().toCall(control::mustRevalidate); map.from(this::getNoTransform).whenTrue().toCall(control::noTransform); map.from(this::getCachePublic).whenTrue().toCall(control::cachePublic); map.from(this::getCachePrivate).whenTrue().toCall(control::cachePrivate); map.from(this::getProxyRevalidate).whenTrue().toCall(control::proxyRevalidate); map.from(this::getStaleWhileRevalidate) .to((duration) -> control.staleWhileRevalidate(duration.getSeconds(), TimeUnit.SECONDS)); map.from(this::getStaleIfError) .to((duration) -> control.staleIfError(duration.getSeconds(), TimeUnit.SECONDS)); map.from(this::getSMaxAge) .to((duration) -> control.sMaxAge(duration.getSeconds(), TimeUnit.SECONDS)); // check if cacheControl remained untouched if (control.getHeaderValue() == null) { return null; } return control; } private CacheControl createCacheControl() { if (Boolean.TRUE.equals(this.noStore)) { return CacheControl.noStore(); } if (Boolean.TRUE.equals(this.noCache)) {
return CacheControl.noCache(); } if (this.maxAge != null) { return CacheControl.maxAge(this.maxAge.getSeconds(), TimeUnit.SECONDS); } return CacheControl.empty(); } private boolean hasBeenCustomized() { return this.customized; } } } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\web\WebProperties.java
2
请在Spring Boot框架中完成以下Java代码
public void setSubject(String value) { this.subject = value; } /** * Gets the value of the textFunctionCode property. * * @return * possible object is * {@link String } * */ public String getTextFunctionCode() { return textFunctionCode; } /** * Sets the value of the textFunctionCode property. * * @param value * allowed object is * {@link String } * */ public void setTextFunctionCode(String value) { this.textFunctionCode = value; } /** * Gets the value of the textCode property. * * @return * possible object is * {@link String } * */ public String getTextCode() { return textCode; } /** * Sets the value of the textCode property. * * @param value * allowed object is * {@link String } * */ public void setTextCode(String value) { this.textCode = value; } /** * Gets the value of the text property. * * @return * possible object is * {@link String } * */ public String getText() { return text; } /** * Sets the value of the text property. * * @param value * allowed object is * {@link String } * */ public void setText(String value) { this.text = value; } /** * Gets the value of the agencyCode property. * * @return * possible object is * {@link String } * */ public String getAgencyCode() { return agencyCode; }
/** * Sets the value of the agencyCode property. * * @param value * allowed object is * {@link String } * */ public void setAgencyCode(String value) { this.agencyCode = value; } /** * Gets the value of the language property. * * @return * possible object is * {@link String } * */ public String getLanguage() { return language; } /** * Sets the value of the language property. * * @param value * allowed object is * {@link String } * */ public void setLanguage(String value) { this.language = value; } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\FreeTextType.java
2
请完成以下Java代码
public List<Execution> findExecutionsByNativeQuery( Map<String, Object> parameterMap, int firstResult, int maxResults ) { return getDbSqlSession().selectListWithRawParameter( "selectExecutionByNativeQuery", parameterMap, firstResult, maxResults ); } @Override @SuppressWarnings("unchecked") public List<ProcessInstance> findProcessInstanceByNativeQuery( Map<String, Object> parameterMap, int firstResult, int maxResults ) { return getDbSqlSession().selectListWithRawParameter( "selectExecutionByNativeQuery", parameterMap, firstResult, maxResults ); } @Override public long findExecutionCountByNativeQuery(Map<String, Object> parameterMap) { return (Long) getDbSqlSession().selectOne("selectExecutionCountByNativeQuery", parameterMap); } @Override public void updateExecutionTenantIdForDeployment(String deploymentId, String newTenantId) { HashMap<String, Object> params = new HashMap<String, Object>(); params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId); getDbSqlSession().update("updateExecutionTenantIdForDeployment", params); } @Override public void updateProcessInstanceLockTime(String processInstanceId, Date lockDate, Date expirationTime) { HashMap<String, Object> params = new HashMap<String, Object>(); params.put("id", processInstanceId); params.put("lockTime", lockDate); params.put("expirationTime", expirationTime); int result = getDbSqlSession().update("updateProcessInstanceLockTime", params); if (result == 0) { throw new ActivitiOptimisticLockingException("Could not lock process instance"); } } @Override public void updateAllExecutionRelatedEntityCountFlags(boolean newValue) { getDbSqlSession().update("updateExecutionRelatedEntityCountEnabled", newValue); } @Override public void clearProcessInstanceLockTime(String processInstanceId) { HashMap<String, Object> params = new HashMap<String, Object>(); params.put("id", processInstanceId); getDbSqlSession().update("clearProcessInstanceLockTime", params); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisExecutionDataManager.java
1
请完成以下Java代码
public TenantId getTenantId() { return tenantId; } public void setTenantId(TenantId tenantId) { this.tenantId = tenantId; } @Schema(description = "JSON object with Customer Id. Use 'assignAssetToCustomer' to change the Customer Id.", accessMode = Schema.AccessMode.READ_ONLY) public CustomerId getCustomerId() { return customerId; } public void setCustomerId(CustomerId customerId) { this.customerId = customerId; } @JsonIgnore public EntityId getOwnerId() { return customerId != null && !customerId.isNullUid() ? customerId : tenantId; } @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Unique Asset Name in scope of Tenant", example = "Empire State Building") @Override public String getName() { return name; } public void setName(String name) { this.name = name; } @Schema(description = "Asset type", example = "Building") public String getType() { return type; } public void setType(String type) { this.type = type; } @Schema(description = "Label that may be used in widgets", example = "NY Building") public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } @Schema(description = "JSON object with Asset Profile Id.") public AssetProfileId getAssetProfileId() { return assetProfileId; } public void setAssetProfileId(AssetProfileId assetProfileId) { this.assetProfileId = assetProfileId; } @Schema(description = "Additional parameters of the asset",implementation = com.fasterxml.jackson.databind.JsonNode.class) @Override public JsonNode getAdditionalInfo() {
return super.getAdditionalInfo(); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Asset [tenantId="); builder.append(tenantId); builder.append(", customerId="); builder.append(customerId); builder.append(", name="); builder.append(name); builder.append(", type="); builder.append(type); builder.append(", label="); builder.append(label); builder.append(", assetProfileId="); builder.append(assetProfileId); builder.append(", additionalInfo="); builder.append(getAdditionalInfo()); builder.append(", createdTime="); builder.append(createdTime); builder.append(", id="); builder.append(id); builder.append("]"); return builder.toString(); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\asset\Asset.java
1
请完成以下Java代码
public float cosine(Vector other) { return dot(other) / this.norm() / other.norm(); } public Vector minus(Vector other) { float[] result = new float[size()]; for (int i = 0; i < result.length; i++) { result[i] = elementArray[i] - other.elementArray[i]; } return new Vector(result); } public Vector add(Vector other) { float[] result = new float[size()]; for (int i = 0; i < result.length; i++) { result[i] = elementArray[i] + other.elementArray[i]; } return new Vector(result); } public Vector addToSelf(Vector other) { for (int i = 0; i < elementArray.length; i++) { elementArray[i] = elementArray[i] + other.elementArray[i]; } return this; } public Vector divideToSelf(int n) { for (int i = 0; i < elementArray.length; i++) { elementArray[i] = elementArray[i] / n; } return this; } public Vector divideToSelf(float f) { for (int i = 0; i < elementArray.length; i++) { elementArray[i] = elementArray[i] / f; } return this;
} /** * 自身归一化 * * @return */ public Vector normalize() { divideToSelf(norm()); return this; } public float[] getElementArray() { return elementArray; } public void setElementArray(float[] elementArray) { this.elementArray = elementArray; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\Vector.java
1
请在Spring Boot框架中完成以下Java代码
public MSV3PeerAuthToken authTokenString(@Value("${msv3server.peer.authToken:}") final String authTokenStringValue) { if (authTokenStringValue == null || authTokenStringValue.trim().isEmpty()) { // a token is needed on the receiver side, even if it's not valid return MSV3PeerAuthToken.TOKEN_NOT_SET; } return MSV3PeerAuthToken.of(authTokenStringValue); } @Override public void afterPropertiesSet() { try {
if (requestAllDataOnStartup) { msv3ServerPeerService.requestAllUpdates(); } else if (requestConfigDataOnStartup) { msv3ServerPeerService.requestConfigUpdates(); } } catch (Exception ex) { logger.warn("Error while requesting ALL updates. Skipped.", ex); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\Application.java
2
请在Spring Boot框架中完成以下Java代码
public class QualityNoteId implements RepoIdAware { @JsonCreator public static QualityNoteId ofRepoId(final int repoId) { return new QualityNoteId(repoId); } public static QualityNoteId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new QualityNoteId(repoId) : null; } public static int toRepoId(@Nullable final QualityNoteId id) { return id != null ? id.getRepoId() : -1;
} int repoId; private QualityNoteId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_QualityNote_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inout\QualityNoteId.java
2
请完成以下Java代码
public DtlsConnectorConfig dtlsConnectorConfig(Configuration configuration) throws UnknownHostException { DtlsConnectorConfig.Builder configBuilder = new DtlsConnectorConfig.Builder(configuration); configBuilder.setAddress(getInetSocketAddress()); SslCredentials sslCredentials = this.coapDtlsCredentialsConfig.getCredentials(); SslContextUtil.Credentials serverCredentials = new SslContextUtil.Credentials(sslCredentials.getPrivateKey(), null, sslCredentials.getCertificateChain()); configBuilder.set(DTLS_CLIENT_AUTHENTICATION_MODE, WANTED); configBuilder.set(DTLS_RETRANSMISSION_TIMEOUT, dtlsRetransmissionTimeout, MILLISECONDS); configBuilder.set(DTLS_ROLE, SERVER_ONLY); if (cIdLength != null) { configBuilder.set(DTLS_CONNECTION_ID_LENGTH, cIdLength); if (cIdLength > 4) { configBuilder.set(DTLS_CONNECTION_ID_NODE_ID, 0); } else { configBuilder.set(DTLS_CONNECTION_ID_NODE_ID, null); } } if (maxTransmissionUnit > 0) { configBuilder.set(DTLS_MAX_TRANSMISSION_UNIT, maxTransmissionUnit); } if (maxFragmentLength > 0) { Length length = fromLength(maxFragmentLength); if (length != null) { configBuilder.set(DTLS_MAX_FRAGMENT_LENGTH, length); } } configBuilder.setAdvancedCertificateVerifier( new TbCoapDtlsCertificateVerifier( transportService, serviceInfoProvider, dtlsSessionInactivityTimeout, dtlsSessionReportTimeout, skipValidityCheckForClientCert
) ); configBuilder.setCertificateIdentityProvider(new SingleCertificateProvider(serverCredentials.getPrivateKey(), serverCredentials.getCertificateChain(), Collections.singletonList(CertificateType.X_509))); return configBuilder.build(); } private InetSocketAddress getInetSocketAddress() throws UnknownHostException { InetAddress addr = InetAddress.getByName(host); return new InetSocketAddress(addr, port); } private static Length fromLength(int length) { for (Length l : Length.values()) { if (l.length() == length) { return l; } } return null; } }
repos\thingsboard-master\common\coap-server\src\main\java\org\thingsboard\server\coapserver\TbCoapDtlsSettings.java
1
请完成以下Java代码
public String toString() { return "%"; } }; public static final Operator MUL = new SimpleOperator() { @Override public Object apply(TypeConverter converter, Object o1, Object o2) { return NumberOperations.mul(converter, o1, o2); } @Override public String toString() { return "*"; } }; public static final Operator NE = new SimpleOperator() { @Override public Object apply(TypeConverter converter, Object o1, Object o2) { return BooleanOperations.ne(converter, o1, o2); } @Override public String toString() { return "!="; } }; public static final Operator OR = new Operator() { public Object eval(Bindings bindings, ELContext context, AstNode left, AstNode right) { Boolean l = bindings.convert(left.eval(bindings, context), Boolean.class); return Boolean.TRUE.equals(l) ? Boolean.TRUE : bindings.convert(right.eval(bindings, context), Boolean.class); } @Override public String toString() { return "||"; } }; public static final Operator SUB = new SimpleOperator() { @Override public Object apply(TypeConverter converter, Object o1, Object o2) { return NumberOperations.sub(converter, o1, o2); } @Override public String toString() { return "-"; } }; private final Operator operator;
private final AstNode left, right; public AstBinary(AstNode left, AstNode right, Operator operator) { this.left = left; this.right = right; this.operator = operator; } public Operator getOperator() { return operator; } @Override public Object eval(Bindings bindings, ELContext context) { return operator.eval(bindings, context, left, right); } @Override public String toString() { return "'" + operator.toString() + "'"; } @Override public void appendStructure(StringBuilder b, Bindings bindings) { left.appendStructure(b, bindings); b.append(' '); b.append(operator); b.append(' '); right.appendStructure(b, bindings); } public int getCardinality() { return 2; } public AstNode getChild(int i) { return i == 0 ? left : i == 1 ? right : null; } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstBinary.java
1
请在Spring Boot框架中完成以下Java代码
public class HistoricEntityLinkEntityManagerImpl extends AbstractServiceEngineEntityManager<EntityLinkServiceConfiguration, HistoricEntityLinkEntity, HistoricEntityLinkDataManager> implements HistoricEntityLinkEntityManager { public HistoricEntityLinkEntityManagerImpl(EntityLinkServiceConfiguration entityLinkServiceConfiguration, HistoricEntityLinkDataManager historicEntityLinkDataManager) { super(entityLinkServiceConfiguration, entityLinkServiceConfiguration.getEngineName(), historicEntityLinkDataManager); } @Override public HistoricEntityLinkEntity create() { HistoricEntityLinkEntity entityLinkEntity = super.create(); entityLinkEntity.setCreateTime(getClock().getCurrentTime()); return entityLinkEntity; } @Override public List<HistoricEntityLink> findHistoricEntityLinksWithSameRootScopeForScopeIdAndScopeType(String scopeId, String scopeType, String linkType) { return dataManager.findHistoricEntityLinksWithSameRootScopeForScopeIdAndScopeType(scopeId, scopeType, linkType); } @Override public List<HistoricEntityLink> findHistoricEntityLinksWithSameRootScopeForScopeIdsAndScopeType(Collection<String> scopeIds, String scopeType, String linkType) { return dataManager.findHistoricEntityLinksWithSameRootScopeForScopeIdsAndScopeType(scopeIds, scopeType, linkType); } @Override public InternalEntityLinkQuery<HistoricEntityLinkEntity> createInternalHistoricEntityLinkQuery() { return new InternalEntityLinkQueryImpl<>(dataManager::findHistoricEntityLinksByQuery, dataManager::findHistoricEntityLinkByQuery); }
@Override public void deleteHistoricEntityLinksByScopeIdAndScopeType(String scopeId, String scopeType) { dataManager.deleteHistoricEntityLinksByScopeIdAndType(scopeId, scopeType); } @Override public void deleteHistoricEntityLinksByScopeDefinitionIdAndScopeType(String scopeDefinitionId, String scopeType) { dataManager.deleteHistoricEntityLinksByScopeDefinitionIdAndType(scopeDefinitionId, scopeType); } @Override public void bulkDeleteHistoricEntityLinksForScopeTypeAndScopeIds(String scopeType, Collection<String> scopeIds) { dataManager.bulkDeleteHistoricEntityLinksForScopeTypeAndScopeIds(scopeType, scopeIds); } @Override public void deleteHistoricEntityLinksForNonExistingProcessInstances() { dataManager.deleteHistoricEntityLinksForNonExistingProcessInstances(); } @Override public void deleteHistoricEntityLinksForNonExistingCaseInstances() { dataManager.deleteHistoricEntityLinksForNonExistingCaseInstances(); } }
repos\flowable-engine-main\modules\flowable-entitylink-service\src\main\java\org\flowable\entitylink\service\impl\persistence\entity\HistoricEntityLinkEntityManagerImpl.java
2