instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } @Override protected CaseDefinitionQuery createNewQuery(ProcessEngine engine) { return engine.getRepositoryService().createCaseDefinitionQuery(); } @Override protected void applyFilters(CaseDefinitionQuery query) { if (caseDefinitionId != null) { query.caseDefinitionId(caseDefinitionId); } if (caseDefinitionIdIn != null && !caseDefinitionIdIn.isEmpty()) { query.caseDefinitionIdIn(caseDefinitionIdIn.toArray(new String[caseDefinitionIdIn.size()])); } if (category != null) { query.caseDefinitionCategory(category); } if (categoryLike != null) { query.caseDefinitionCategoryLike(categoryLike); } if (name != null) { query.caseDefinitionName(name); } if (nameLike != null) { query.caseDefinitionNameLike(nameLike); } if (deploymentId != null) { query.deploymentId(deploymentId); } if (key != null) { query.caseDefinitionKey(key); } if (keyLike != null) { query.caseDefinitionKeyLike(keyLike); } if (resourceName != null) { query.caseDefinitionResourceName(resourceName); } if (resourceNameLike != null) { query.caseDefinitionResourceNameLike(resourceNameLike); } if (version != null) {
query.caseDefinitionVersion(version); } if (TRUE.equals(latestVersion)) { query.latestVersion(); } if (tenantIds != null && !tenantIds.isEmpty()) { query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); } if (TRUE.equals(withoutTenantId)) { query.withoutTenantId(); } if (TRUE.equals(includeDefinitionsWithoutTenantId)) { query.includeCaseDefinitionsWithoutTenantId(); } } @Override protected void applySortBy(CaseDefinitionQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_CATEGORY_VALUE)) { query.orderByCaseDefinitionCategory(); } else if (sortBy.equals(SORT_BY_KEY_VALUE)) { query.orderByCaseDefinitionKey(); } else if (sortBy.equals(SORT_BY_ID_VALUE)) { query.orderByCaseDefinitionId(); } else if (sortBy.equals(SORT_BY_VERSION_VALUE)) { query.orderByCaseDefinitionVersion(); } else if (sortBy.equals(SORT_BY_NAME_VALUE)) { query.orderByCaseDefinitionName(); } else if (sortBy.equals(SORT_BY_DEPLOYMENT_ID_VALUE)) { query.orderByDeploymentId(); } else if (sortBy.equals(SORT_BY_TENANT_ID)) { query.orderByTenantId(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\CaseDefinitionQueryDto.java
2
请在Spring Boot框架中完成以下Java代码
public Context currentContext() { return this.context; } @Override public void onSubscribe(Subscription s) { this.delegate.onSubscribe(s); } @Override public void onNext(T t) { this.delegate.onNext(t); } @Override public void onError(Throwable ex) { this.delegate.onError(ex); } @Override public void onComplete() { this.delegate.onComplete(); } } /** * A map that computes each value when {@link #get} is invoked */ static class LoadingMap<K, V> implements Map<K, V> { private final Map<K, V> loaded = new ConcurrentHashMap<>(); private final Map<K, Supplier<V>> loaders; LoadingMap(Map<K, Supplier<V>> loaders) { this.loaders = Collections.unmodifiableMap(new HashMap<>(loaders)); } @Override public int size() { return this.loaders.size(); } @Override public boolean isEmpty() { return this.loaders.isEmpty(); } @Override public boolean containsKey(Object key) { return this.loaders.containsKey(key); } @Override public Set<K> keySet() { return this.loaders.keySet(); } @Override public V get(Object key) { if (!this.loaders.containsKey(key)) { throw new IllegalArgumentException( "This map only supports the following keys: " + this.loaders.keySet()); } return this.loaded.computeIfAbsent((K) key, (k) -> this.loaders.get(k).get()); } @Override public V put(K key, V value) { if (!this.loaders.containsKey(key)) { throw new IllegalArgumentException( "This map only supports the following keys: " + this.loaders.keySet()); } return this.loaded.put(key, value);
} @Override public V remove(Object key) { if (!this.loaders.containsKey(key)) { throw new IllegalArgumentException( "This map only supports the following keys: " + this.loaders.keySet()); } return this.loaded.remove(key); } @Override public void putAll(Map<? extends K, ? extends V> m) { for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) { put(entry.getKey(), entry.getValue()); } } @Override public void clear() { this.loaded.clear(); } @Override public boolean containsValue(Object value) { return this.loaded.containsValue(value); } @Override public Collection<V> values() { return this.loaded.values(); } @Override public Set<Entry<K, V>> entrySet() { return this.loaded.entrySet(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LoadingMap<?, ?> that = (LoadingMap<?, ?>) o; return this.loaded.equals(that.loaded); } @Override public int hashCode() { return this.loaded.hashCode(); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configuration\SecurityReactorContextConfiguration.java
2
请完成以下Java代码
public void updateFromOrder(@NonNull final I_C_Payment record) { final OrderId orderId = OrderId.ofRepoIdOrNull(record.getC_Order_ID()); if (orderId == null) { return; } final OrderPayScheduleId orderPayScheduleId = OrderPayScheduleId.ofRepoIdOrNull(record.getC_OrderPaySchedule_ID()); if (orderPayScheduleId != null) { return; // do not update form order, since all amounts are calculated } final I_C_Order order = orderDAO.getById(orderId); final PaymentTermId paymentTermId = PaymentTermId.ofRepoId(order.getC_PaymentTerm_ID()); final Percent paymentTermDiscountPercent = paymentTermService.getPaymentTermDiscount(paymentTermId); final Currency currency = currencyRepository.getById(record.getC_Currency_ID()); final BigDecimal priceActual = paymentTermDiscountPercent.subtractFromBase(order.getGrandTotal(), currency.getPrecision().toInt()); final BigDecimal discountAmount = paymentTermDiscountPercent.computePercentageOf(order.getGrandTotal(), currency.getPrecision().toInt()); record.setC_BPartner_ID(firstGreaterThanZero(order.getBill_BPartner_ID(), order.getC_BPartner_ID())); record.setC_Currency_ID(order.getC_Currency_ID()); record.setC_Invoice(null); record.setC_Charge_ID(0); record.setIsPrepayment(true); record.setWriteOffAmt(BigDecimal.ZERO); record.setIsOverUnderPayment(false);
record.setOverUnderAmt(BigDecimal.ZERO); // record.setPayAmt(priceActual); record.setDiscountAmt(discountAmount); paymentBL.validateDocTypeIsInSync(record); } @DocValidate(timings = { ModelValidator.TIMING_AFTER_COMPLETE }) public void updateOrderPayScheduleStatus(final I_C_Payment payment) { final OrderId orderId = OrderId.ofRepoIdOrNull(payment.getC_Order_ID()); final OrderPayScheduleId orderPayScheduleId = OrderPayScheduleId.ofRepoIdOrNull(payment.getC_OrderPaySchedule_ID()); if (orderId == null || orderPayScheduleId == null) { return; } orderPayScheduleService.markAsPaid(orderId, orderPayScheduleId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\C_Payment.java
1
请完成以下Java代码
public void commit() { // Do nothing, transaction is managed by spring } public void rollback() { // Just in case the rollback isn't triggered by an // exception, we mark the current transaction rollBackOnly. transactionManager.getTransaction(null).setRollbackOnly(); } public void addTransactionListener( final TransactionState transactionState, final TransactionListener transactionListener ) { if (transactionState.equals(TransactionState.COMMITTING)) { TransactionSynchronizationManager.registerSynchronization( new TransactionSynchronizationAdapter() { @Override public void beforeCommit(boolean readOnly) { transactionListener.execute(commandContext); } } ); } else if (transactionState.equals(TransactionState.COMMITTED)) { TransactionSynchronizationManager.registerSynchronization( new TransactionSynchronizationAdapter() { @Override public void afterCommit() { transactionListener.execute(commandContext); } } ); } else if (transactionState.equals(TransactionState.ROLLINGBACK)) { TransactionSynchronizationManager.registerSynchronization( new TransactionSynchronizationAdapter() { @Override public void beforeCompletion() { transactionListener.execute(commandContext); } } ); } else if (transactionState.equals(TransactionState.ROLLED_BACK)) { TransactionSynchronizationManager.registerSynchronization( new TransactionSynchronizationAdapter() { @Override public void afterCompletion(int status) { if (TransactionSynchronization.STATUS_ROLLED_BACK == status) { transactionListener.execute(commandContext); }
} } ); } } protected abstract class TransactionSynchronizationAdapter implements TransactionSynchronization, Ordered { public void suspend() {} public void resume() {} public void flush() {} public void beforeCommit(boolean readOnly) {} public void beforeCompletion() {} public void afterCommit() {} public void afterCompletion(int status) {} @Override public int getOrder() { return transactionSynchronizationAdapterOrder; } } }
repos\Activiti-develop\activiti-core\activiti-spring\src\main\java\org\activiti\spring\SpringTransactionContext.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 retoureSupportID property. * */ public int getRetoureSupportID() { return retoureSupportID; } /** * Sets the value of the retoureSupportID property. * */ public void setRetoureSupportID(int value) { this.retoureSupportID = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;extension base="{urn:msv3:v2}RetourePositionType"&gt; * &lt;attribute name="RetourenAnteilTyp" use="required" type="{urn:msv3:v2}RetourenAnteilTypType" /&gt; * &lt;/extension&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> *
* */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class Position extends RetourePositionType { @XmlAttribute(name = "RetourenAnteilTyp", required = true) protected RetourenAnteilTypType retourenAnteilTyp; /** * Gets the value of the retourenAnteilTyp property. * * @return * possible object is * {@link RetourenAnteilTypType } * */ public RetourenAnteilTypType getRetourenAnteilTyp() { return retourenAnteilTyp; } /** * Sets the value of the retourenAnteilTyp property. * * @param value * allowed object is * {@link RetourenAnteilTypType } * */ public void setRetourenAnteilTyp(RetourenAnteilTypType value) { this.retourenAnteilTyp = value; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\RetourenavisAnfrageAntwort.java
1
请完成以下Java代码
public boolean isDefault() { return get_ValueAsBoolean(COLUMNNAME_IsDefault); } @Override public void setM_Shipper_ID (final int M_Shipper_ID) { if (M_Shipper_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, M_Shipper_ID); } @Override public int getM_Shipper_ID() { return get_ValueAsInt(COLUMNNAME_M_Shipper_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPickupTimeFrom (final java.sql.Timestamp PickupTimeFrom) { set_Value (COLUMNNAME_PickupTimeFrom, PickupTimeFrom); } @Override public java.sql.Timestamp getPickupTimeFrom() { return get_ValueAsTimestamp(COLUMNNAME_PickupTimeFrom); } @Override public void setPickupTimeTo (final java.sql.Timestamp PickupTimeTo) { set_Value (COLUMNNAME_PickupTimeTo, PickupTimeTo); } @Override public java.sql.Timestamp getPickupTimeTo() { return get_ValueAsTimestamp(COLUMNNAME_PickupTimeTo); } /** * ShipperGateway AD_Reference_ID=540808 * Reference name: ShipperGateway */ public static final int SHIPPERGATEWAY_AD_Reference_ID=540808; /** GO = go */ public static final String SHIPPERGATEWAY_GO = "go"; /** Der Kurier = derKurier */ public static final String SHIPPERGATEWAY_DerKurier = "derKurier"; /** DHL = dhl */ public static final String SHIPPERGATEWAY_DHL = "dhl"; /** DPD = dpd */ public static final String SHIPPERGATEWAY_DPD = "dpd"; /** nShift = nshift */
public static final String SHIPPERGATEWAY_NShift = "nshift"; @Override public void setShipperGateway (final @Nullable java.lang.String ShipperGateway) { set_Value (COLUMNNAME_ShipperGateway, ShipperGateway); } @Override public java.lang.String getShipperGateway() { return get_ValueAsString(COLUMNNAME_ShipperGateway); } @Override public void setTrackingURL (final @Nullable java.lang.String TrackingURL) { set_Value (COLUMNNAME_TrackingURL, TrackingURL); } @Override public java.lang.String getTrackingURL() { return get_ValueAsString(COLUMNNAME_TrackingURL); } @Override public void setValue (final @Nullable java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Shipper.java
1
请完成以下Java代码
public static Period detectAndParse(String value, @Nullable ChronoUnit unit) { return detect(value).parse(value, unit); } /** * Detect the style from the given source value. * @param value the source value * @return the period style * @throws IllegalArgumentException if the value is not a known style */ public static PeriodStyle detect(String value) { Assert.notNull(value, "'value' must not be null"); for (PeriodStyle candidate : values()) { if (candidate.matches(value)) { return candidate; } } throw new IllegalArgumentException("'" + value + "' is not a valid period"); } private enum Unit { /** * Days, represented by suffix {@code d}. */ DAYS(ChronoUnit.DAYS, "d", Period::getDays, Period::ofDays), /** * Weeks, represented by suffix {@code w}. */ WEEKS(ChronoUnit.WEEKS, "w", null, Period::ofWeeks), /** * Months, represented by suffix {@code m}. */ MONTHS(ChronoUnit.MONTHS, "m", Period::getMonths, Period::ofMonths), /** * Years, represented by suffix {@code y}. */ YEARS(ChronoUnit.YEARS, "y", Period::getYears, Period::ofYears); private final ChronoUnit chronoUnit; private final String suffix; private final @Nullable Function<Period, Integer> intValue; private final Function<Integer, Period> factory; Unit(ChronoUnit chronoUnit, String suffix, @Nullable Function<Period, Integer> intValue,
Function<Integer, Period> factory) { this.chronoUnit = chronoUnit; this.suffix = suffix; this.intValue = intValue; this.factory = factory; } private Period parse(String value) { return this.factory.apply(Integer.parseInt(value)); } private String print(Period value) { return intValue(value) + this.suffix; } private boolean isZero(Period value) { return intValue(value) == 0; } private int intValue(Period value) { Assert.state(this.intValue != null, () -> "intValue cannot be extracted from " + name()); return this.intValue.apply(value); } private static Unit fromChronoUnit(@Nullable ChronoUnit chronoUnit) { if (chronoUnit == null) { return Unit.DAYS; } for (Unit candidate : values()) { if (candidate.chronoUnit == chronoUnit) { return candidate; } } throw new IllegalArgumentException("Unsupported unit " + chronoUnit); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\convert\PeriodStyle.java
1
请在Spring Boot框架中完成以下Java代码
public class UserConfirmationSupportUtil { @Value @Builder public static class UIComponentProps { @Nullable String question; boolean confirmed; @Builder.Default @NonNull WFActivityAlwaysAvailableToUser alwaysAvailableToUser = WFActivityAlwaysAvailableToUser.DEFAULT; public static UIComponentPropsBuilder builderFrom(final @NonNull WFActivity wfActivity) { return builder() .confirmed(wfActivity.getStatus().isCompleted()) .alwaysAvailableToUser(wfActivity.getAlwaysAvailableToUser()); } } public static UIComponent createUIComponent(@NonNull final UIComponentProps props) {
return UIComponent.builder() .type(UIComponentType.CONFIRM_BUTTON) .alwaysAvailableToUser(props.getAlwaysAvailableToUser()) .properties(Params.builder() .value("question", props.getQuestion()) .value("confirmed", props.isConfirmed()) .build()) .build(); } public static UIComponent createUIComponent(@NonNull final WFActivity wfActivity) { return createUIComponent(UIComponentProps.builderFrom(wfActivity).build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\activity_features\user_confirmation\UserConfirmationSupportUtil.java
2
请完成以下Java代码
public List<Event> findEventsByProcessInstanceId(String processInstanceId) { checkHistoryEnabled(); return commentDataManager.findEventsByProcessInstanceId(processInstanceId); } @Override public void deleteCommentsByTaskId(String taskId) { checkHistoryEnabled(); commentDataManager.deleteCommentsByTaskId(taskId); } @Override public void deleteCommentsByProcessInstanceId(String processInstanceId) { checkHistoryEnabled(); commentDataManager.deleteCommentsByProcessInstanceId(processInstanceId); } @Override public List<Comment> findCommentsByProcessInstanceId(String processInstanceId) { checkHistoryEnabled(); return commentDataManager.findCommentsByProcessInstanceId(processInstanceId); } @Override public List<Comment> findCommentsByProcessInstanceId(String processInstanceId, String type) { checkHistoryEnabled(); return commentDataManager.findCommentsByProcessInstanceId(processInstanceId, type); } @Override public Comment findComment(String commentId) { return commentDataManager.findComment(commentId); } @Override public Event findEvent(String commentId) { return commentDataManager.findEvent(commentId); } @Override public void delete(CommentEntity commentEntity) { checkHistoryEnabled(); delete(commentEntity, false); Comment comment = (Comment) commentEntity; if (getEventDispatcher().isEnabled()) { // Forced to fetch the process-instance to associate the right // process definition String processDefinitionId = null; String processInstanceId = comment.getProcessInstanceId(); if (comment.getProcessInstanceId() != null) { ExecutionEntity process = getExecutionEntityManager().findById(comment.getProcessInstanceId()); if (process != null) {
processDefinitionId = process.getProcessDefinitionId(); } } getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent( ActivitiEventType.ENTITY_DELETED, commentEntity, processInstanceId, processInstanceId, processDefinitionId ) ); } } protected void checkHistoryEnabled() { if (!getHistoryManager().isHistoryEnabled()) { throw new ActivitiException("In order to use comments, history should be enabled"); } } public CommentDataManager getCommentDataManager() { return commentDataManager; } public void setCommentDataManager(CommentDataManager commentDataManager) { this.commentDataManager = commentDataManager; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\CommentEntityManagerImpl.java
1
请完成以下Java代码
public void setC_Aggregation_Attribute_ID (int C_Aggregation_Attribute_ID) { if (C_Aggregation_Attribute_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Aggregation_Attribute_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Aggregation_Attribute_ID, Integer.valueOf(C_Aggregation_Attribute_ID)); } /** Get Aggregation Attribute. @return Aggregation Attribute */ @Override public int getC_Aggregation_Attribute_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Aggregation_Attribute_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Validierungscode. @param Code Validierungscode */ @Override public void setCode (java.lang.String Code) { set_Value (COLUMNNAME_Code, Code); } /** Get Validierungscode. @return Validierungscode */ @Override public java.lang.String getCode () { return (java.lang.String)get_Value(COLUMNNAME_Code); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** * EntityType AD_Reference_ID=389 * Reference name: _EntityTypeNew */ public static final int ENTITYTYPE_AD_Reference_ID=389; /** Set Entitäts-Art. @param EntityType Dictionary Entity Type; Determines ownership and synchronization */ @Override public void setEntityType (java.lang.String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entitäts-Art. @return Dictionary Entity Type; Determines ownership and synchronization */ @Override public java.lang.String getEntityType () { return (java.lang.String)get_Value(COLUMNNAME_EntityType); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name);
} /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** * Type AD_Reference_ID=540533 * Reference name: C_Aggregation_Attribute_Type */ public static final int TYPE_AD_Reference_ID=540533; /** Attribute = A */ public static final String TYPE_Attribute = "A"; /** Set Art. @param Type Type of Validation (SQL, Java Script, Java Language) */ @Override public void setType (java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Art. @return Type of Validation (SQL, Java Script, Java Language) */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java-gen\de\metas\aggregation\model\X_C_Aggregation_Attribute.java
1
请完成以下Java代码
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
请在Spring Boot框架中完成以下Java代码
public boolean enabled() { return obtain(GangliaProperties::isEnabled, GangliaConfig.super::enabled); } @Override public Duration step() { return obtain(GangliaProperties::getStep, GangliaConfig.super::step); } @Override public TimeUnit durationUnits() { return obtain(GangliaProperties::getDurationUnits, GangliaConfig.super::durationUnits); } @Override public GMetric.UDPAddressingMode addressingMode() { return obtain(GangliaProperties::getAddressingMode, GangliaConfig.super::addressingMode); } @Override
public int ttl() { return obtain(GangliaProperties::getTimeToLive, GangliaConfig.super::ttl); } @Override public String host() { return obtain(GangliaProperties::getHost, GangliaConfig.super::host); } @Override public int port() { return obtain(GangliaProperties::getPort, GangliaConfig.super::port); } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\ganglia\GangliaPropertiesConfigAdapter.java
2
请在Spring Boot框架中完成以下Java代码
public abstract class DiagramElement implements Serializable { private static final long serialVersionUID = 1L; protected String id; public DiagramElement() {} public DiagramElement(String id) { this.id = id; } /** * Id of the diagram element. */ public String getId() {
return id; } public void setId(String id) { this.id = id; } @Override public String toString() { return "id=" + getId(); } public abstract boolean isNode(); public abstract boolean isEdge(); }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\repository\DiagramElement.java
2
请在Spring Boot框架中完成以下Java代码
public class GithubController { private OAuth20Service createService(String state) { return new ServiceBuilder("e1f8d4f1a5c71467a159") .apiSecret("4851597541a8f33a4f1bf1c70f3cedcfefbeb13b") .state(state) .callback("http://localhost:8080/spring-mvc-simple/github/callback") .build(GitHubApi.instance()); } @GetMapping(value = "/authorization") public RedirectView authorization(HttpServletRequest servletReq) throws InterruptedException, ExecutionException, IOException { String state = String.valueOf(new Random().nextInt(999_999)); OAuth20Service githubService = createService(state); servletReq.getSession().setAttribute("state", state); String authorizationUrl = githubService.getAuthorizationUrl(); RedirectView redirectView = new RedirectView(); redirectView.setUrl(authorizationUrl); return redirectView; } @GetMapping(value = "/callback", produces = "text/plain") @ResponseBody
public String callback(HttpServletRequest servletReq, @RequestParam("code") String code, @RequestParam("state") String state) throws InterruptedException, ExecutionException, IOException { String initialState = (String) servletReq.getSession().getAttribute("state"); if(initialState.equals(state)) { OAuth20Service githubService = createService(initialState); OAuth2AccessToken accessToken = githubService.getAccessToken(code); OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.github.com/user"); githubService.signRequest(accessToken, request); Response response = githubService.execute(request); return response.getBody(); } return "Error"; } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics-2\src\main\java\com\baeldung\spring\controller\scribe\GithubController.java
2
请完成以下Java代码
public String getParentTaskId() { return parentTaskId; } public void setParentTaskId(String parentTaskId) { this.parentTaskId = parentTaskId; } public void setDeleteReason(final String deleteReason) { this.deleteReason = deleteReason; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getTaskId() { return taskId; } public String getTaskDefinitionKey() { return taskDefinitionKey; } public void setTaskDefinitionKey(String taskDefinitionKey) { this.taskDefinitionKey = taskDefinitionKey; } public String getActivityInstanceId() { return activityInstanceId; } public void setActivityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTaskState() { return taskState; } public void setTaskState(String taskState) { this.taskState = taskState; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; }
@Override public String toString() { return this.getClass().getSimpleName() + "[taskId" + taskId + ", assignee=" + assignee + ", owner=" + owner + ", name=" + name + ", description=" + description + ", dueDate=" + dueDate + ", followUpDate=" + followUpDate + ", priority=" + priority + ", parentTaskId=" + parentTaskId + ", deleteReason=" + deleteReason + ", taskDefinitionKey=" + taskDefinitionKey + ", durationInMillis=" + durationInMillis + ", startTime=" + startTime + ", endTime=" + endTime + ", id=" + id + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", processInstanceId=" + processInstanceId + ", activityInstanceId=" + activityInstanceId + ", tenantId=" + tenantId + ", taskState=" + taskState + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricTaskInstanceEventEntity.java
1
请在Spring Boot框架中完成以下Java代码
static class Jackson2JsonMessageConvertersCustomizer implements ClientHttpMessageConvertersCustomizer, ServerHttpMessageConvertersCustomizer { private final ObjectMapper objectMapper; Jackson2JsonMessageConvertersCustomizer(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @Override public void customize(ClientBuilder builder) { builder.withJsonConverter( new org.springframework.http.converter.json.MappingJackson2HttpMessageConverter(this.objectMapper)); } @Override public void customize(ServerBuilder builder) { builder.withJsonConverter( new org.springframework.http.converter.json.MappingJackson2HttpMessageConverter(this.objectMapper)); } } static class Jackson2XmlMessageConvertersCustomizer implements ClientHttpMessageConvertersCustomizer, ServerHttpMessageConvertersCustomizer { private final ObjectMapper objectMapper; Jackson2XmlMessageConvertersCustomizer(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @Override public void customize(ClientBuilder builder) { builder.withXmlConverter(new org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter( this.objectMapper)); }
@Override public void customize(ServerBuilder builder) { builder.withXmlConverter(new org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter( this.objectMapper)); } } private static class PreferJackson2OrJacksonUnavailableCondition extends AnyNestedCondition { PreferJackson2OrJacksonUnavailableCondition() { super(ConfigurationPhase.REGISTER_BEAN); } @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue = "jackson2") static class Jackson2Preferred { } @ConditionalOnMissingBean(JacksonJsonHttpMessageConvertersCustomizer.class) static class JacksonUnavailable { } } }
repos\spring-boot-4.0.1\module\spring-boot-http-converter\src\main\java\org\springframework\boot\http\converter\autoconfigure\Jackson2HttpMessageConvertersConfiguration.java
2
请完成以下Java代码
public int getC_Greeting_ID() { return get_ValueAsInt(COLUMNNAME_C_Greeting_ID); } @Override public void setGreeting (final @Nullable java.lang.String Greeting) { set_Value (COLUMNNAME_Greeting, Greeting); } @Override public java.lang.String getGreeting() { return get_ValueAsString(COLUMNNAME_Greeting); } /** * GreetingStandardType AD_Reference_ID=541326 * Reference name: GreetingStandardType */ public static final int GREETINGSTANDARDTYPE_AD_Reference_ID=541326; /** MR = MR */ public static final String GREETINGSTANDARDTYPE_MR = "MR"; /** MRS = MRS */ public static final String GREETINGSTANDARDTYPE_MRS = "MRS"; /** MR+MRS = MR+MRS */ public static final String GREETINGSTANDARDTYPE_MRPlusMRS = "MR+MRS"; /** MRS+MR = MRS+MR */ public static final String GREETINGSTANDARDTYPE_MRSPlusMR = "MRS+MR"; @Override public void setGreetingStandardType (final @Nullable java.lang.String GreetingStandardType) { set_Value (COLUMNNAME_GreetingStandardType, GreetingStandardType); } @Override public java.lang.String getGreetingStandardType() { return get_ValueAsString(COLUMNNAME_GreetingStandardType); } @Override public void setIsDefault (final boolean IsDefault) {
set_Value (COLUMNNAME_IsDefault, IsDefault); } @Override public boolean isDefault() { return get_ValueAsBoolean(COLUMNNAME_IsDefault); } @Override public void setIsFirstNameOnly (final boolean IsFirstNameOnly) { set_Value (COLUMNNAME_IsFirstNameOnly, IsFirstNameOnly); } @Override public boolean isFirstNameOnly() { return get_ValueAsBoolean(COLUMNNAME_IsFirstNameOnly); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Greeting.java
1
请完成以下Java代码
public class IgnoreConfig { /** * 需要忽略的 URL 格式,不考虑请求方法 */ private List<String> pattern = Lists.newArrayList(); /** * 需要忽略的 GET 请求 */ private List<String> get = Lists.newArrayList(); /** * 需要忽略的 POST 请求 */ private List<String> post = Lists.newArrayList(); /** * 需要忽略的 DELETE 请求 */ private List<String> delete = Lists.newArrayList(); /** * 需要忽略的 PUT 请求 */ private List<String> put = Lists.newArrayList(); /** * 需要忽略的 HEAD 请求 */
private List<String> head = Lists.newArrayList(); /** * 需要忽略的 PATCH 请求 */ private List<String> patch = Lists.newArrayList(); /** * 需要忽略的 OPTIONS 请求 */ private List<String> options = Lists.newArrayList(); /** * 需要忽略的 TRACE 请求 */ private List<String> trace = Lists.newArrayList(); }
repos\spring-boot-demo-master\demo-rbac-security\src\main\java\com\xkcoding\rbac\security\config\IgnoreConfig.java
1
请在Spring Boot框架中完成以下Java代码
public class ShipmentScheduleStockChangedEventHandler implements MaterialEventHandler<StockChangedEvent> { private final ShipmentScheduleInvalidateBL scheduleInvalidateBL; private final IWarehouseDAO warehouseDAO = Services.get(IWarehouseDAO.class); public ShipmentScheduleStockChangedEventHandler(@NonNull final ShipmentScheduleInvalidateBL scheduleInvalidateBL) { this.scheduleInvalidateBL = scheduleInvalidateBL; } @Override public Collection<Class<? extends StockChangedEvent>> getHandledEventType() { return ImmutableList.of(StockChangedEvent.class); } @Override public void handleEvent(@NonNull final StockChangedEvent event)
{ final ProductDescriptor productDescriptor = event.getProductDescriptor(); final ShipmentScheduleAttributeSegment shipmentScheduleAttributeSegment = ShipmentScheduleAttributeSegment.ofAttributeSetInstanceId(AttributeSetInstanceId.ofRepoIdOrNone(productDescriptor.getAttributeSetInstanceId())); final Set<WarehouseId> warehouseIds = warehouseDAO.getWarehouseIdsOfSamePickingGroup(event.getWarehouseId()); final ImmutableSet<LocatorId> locatorIds = warehouseDAO.getLocatorIdsByWarehouseIds(warehouseIds); final IShipmentScheduleSegment storageSegment = ImmutableShipmentScheduleSegment.builder() .productIds(ImmutableSet.of(productDescriptor.getProductId())) .attributes(ImmutableSet.of(shipmentScheduleAttributeSegment)) .locatorIds(LocatorId.toRepoIds(locatorIds)) .bpartnerId(IShipmentScheduleSegment.ANY) .build(); scheduleInvalidateBL.flagForRecomputeStorageSegment(storageSegment); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\spi\ShipmentScheduleStockChangedEventHandler.java
2
请完成以下Java代码
private boolean checkEnabled() { final boolean enabled = model.isEnabled(); action.setEnabled(enabled); final JMenuItem menuItem = action.getMenuItem(); menuItem.setEnabled(enabled); menuItem.setVisible(enabled); return enabled; } private void assertEnabled() { if (!checkEnabled()) { throw new AdempiereException("Action is not enabled"); } } private void save() { assertEnabled(); final GridController gc = parent.getCurrentGridController(); save(gc); for (final GridController child : gc.getChildGridControllers()) { save(child); } } private void save(final GridController gc) { Check.assumeNotNull(gc, "gc not null");
final GridTab gridTab = gc.getMTab(); final VTable table = gc.getVTable(); // // Check CTable to GridTab synchronizer final CTableColumns2GridTabSynchronizer synchronizer = CTableColumns2GridTabSynchronizer.get(table); if (synchronizer == null) { // synchronizer does not exist, nothing to save return; } // // Make sure we have the latest values in GridTab synchronizer.saveToGridTab(); // // Ask model to settings to database model.save(gridTab); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\AWindowSaveState.java
1
请完成以下Java代码
public String getDocAction () { return (String)get_Value(COLUMNNAME_DocAction); } /** Set Grant. @param GrantPermission Grant Permission */ public void setGrantPermission (String GrantPermission) { set_Value (COLUMNNAME_GrantPermission, GrantPermission); } /** Get Grant. @return Grant Permission */ public String getGrantPermission () { return (String)get_Value(COLUMNNAME_GrantPermission); } /** Set Permission Granted. @param IsPermissionGranted Permission Granted */ public void setIsPermissionGranted (boolean IsPermissionGranted) { set_ValueNoCheck (COLUMNNAME_IsPermissionGranted, Boolean.valueOf(IsPermissionGranted)); } /** Get Permission Granted. @return Permission Granted */ public boolean isPermissionGranted () { Object oo = get_Value(COLUMNNAME_IsPermissionGranted); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Read Write. @param IsReadWrite Field is read / write */ public void setIsReadWrite (boolean IsReadWrite) {
set_Value (COLUMNNAME_IsReadWrite, Boolean.valueOf(IsReadWrite)); } /** Get Read Write. @return Field is read / write */ public boolean isReadWrite () { Object oo = get_Value(COLUMNNAME_IsReadWrite); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Revoke. @param RevokePermission Revoke Permission */ public void setRevokePermission (String RevokePermission) { set_Value (COLUMNNAME_RevokePermission, RevokePermission); } /** Get Revoke. @return Revoke Permission */ public String getRevokePermission () { return (String)get_Value(COLUMNNAME_RevokePermission); } @Override public void setDescription(String Description) { set_ValueNoCheck (COLUMNNAME_Description, Description); } @Override public String getDescription() { return (String)get_Value(COLUMNNAME_Description); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role_PermRequest.java
1
请在Spring Boot框架中完成以下Java代码
public InvoiceLinePriceAndDiscount withUpdatedPriceEntered() { if (priceActual.signum() == 0) { return toBuilder().priceEntered(ZERO).build(); } final BigDecimal priceEntered = discount.addToBase(priceActual, precision.toInt(), precision.getRoundingMode()); return toBuilder().priceEntered(priceEntered).build(); } public InvoiceLinePriceAndDiscount withUpdatedDiscount() { if (priceEntered.signum() == 0) { return toBuilder().discount(Percent.ZERO).build(); }
final BigDecimal delta = priceEntered.subtract(priceActual); final Percent discount = Percent.of(delta, priceEntered, precision.toInt()); return toBuilder().discount(discount).build(); } public void applyTo(@NonNull final I_C_InvoiceLine invoiceLine) { logger.debug("Applying {} to {}", this, invoiceLine); invoiceLine.setPriceEntered(priceEntered); invoiceLine.setDiscount(discount.toBigDecimal()); invoiceLine.setPriceActual(priceActual); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\service\impl\InvoiceLinePriceAndDiscount.java
2
请完成以下Java代码
public static OrgMappingId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new OrgMappingId(repoId) : null; } public static Optional<OrgMappingId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } public static int toRepoId(@Nullable final OrgMappingId orgMappingId) { return toRepoIdOr(orgMappingId, -1); } public static int toRepoIdOr(@Nullable final OrgMappingId orgMappingId, final int defaultValue) { return orgMappingId != null ? orgMappingId.getRepoId() : defaultValue;
} private OrgMappingId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "AD_Org_Mapping_ID"); } @JsonValue public int toJson() { return getRepoId(); } public static boolean equals(@Nullable final OrgMappingId o1, @Nullable final OrgMappingId o2) { return Objects.equals(o1, o2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\OrgMappingId.java
1
请完成以下Java代码
protected HttpRequestHandler createHttpRequestHandler(FlowableHttpRequestHandler handler, CmmnEngineConfiguration cmmnEngineConfiguration) { HttpRequestHandler requestHandler = null; if (handler != null) { if (IMPLEMENTATION_TYPE_CLASS.equalsIgnoreCase(handler.getImplementationType())) { requestHandler = new ClassDelegateHttpHandler(handler.getImplementation(), handler.getFieldExtensions()); } else if (IMPLEMENTATION_TYPE_DELEGATEEXPRESSION.equalsIgnoreCase(handler.getImplementationType())) { requestHandler = new DelegateExpressionHttpHandler( cmmnEngineConfiguration.getExpressionManager().createExpression(handler.getImplementation()), handler.getFieldExtensions()); } } return requestHandler; } protected HttpResponseHandler createHttpResponseHandler(FlowableHttpResponseHandler handler, CmmnEngineConfiguration cmmnEngineConfiguration) { HttpResponseHandler responseHandler = null; if (handler != null) { if (ImplementationType.IMPLEMENTATION_TYPE_CLASS.equalsIgnoreCase(handler.getImplementationType())) {
responseHandler = new ClassDelegateHttpHandler(handler.getImplementation(), handler.getFieldExtensions()); } else if (ImplementationType.IMPLEMENTATION_TYPE_DELEGATEEXPRESSION.equalsIgnoreCase(handler.getImplementationType())) { responseHandler = new DelegateExpressionHttpHandler( cmmnEngineConfiguration.getExpressionManager().createExpression(handler.getImplementation()), handler.getFieldExtensions()); } } return responseHandler; } @Override protected void propagateError(VariableContainer container, String code) { // NOP } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\behavior\impl\http\DefaultCmmnHttpActivityDelegate.java
1
请完成以下Java代码
public class Car { private String make; private String model; public Car() { } public Car(String make, String model) { this.make = make; this.model = model; } public String getMake() {
return make; } public void setMake(String make) { this.make = make; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } }
repos\tutorials-master\spring-web-modules\spring-freemarker\src\main\java\com\baeldung\freemarker\model\Car.java
1
请完成以下Java代码
private File img2txt(File file) throws IOException { BufferedImage image = ImageIO.read(file); BufferedImage scaled = getScaledImg(image); char[][] array = getImageMatrix(scaled); StringBuffer sb = new StringBuffer(); for (char[] cs : array) { for (char c : cs) { sb.append(c); // System.out.print(c); } sb.append("\r\n"); // System.out.println(); } String outName = file.getAbsolutePath() + ".txt"; File outFile = new File(outName); IOUtils.write(sb.toString(), new FileOutputStream(outFile)); return outFile; } private static char[][] getImageMatrix(BufferedImage img) { int w = img.getWidth(), h = img.getHeight(); char[][] rst = new char[w][h]; for (int i = 0; i < w; i++) for (int j = 0; j < h; j++) { int rgb = img.getRGB(i, j); // 注意溢出
int r = Integer.valueOf(Integer.toBinaryString(rgb).substring(0, 8), 2); int g = (rgb & 0xff00) >> 8; int b = rgb & 0xff; int gray = (int) (0.2126 * r + 0.7152 * g + 0.0722 * b); // 把int gray转换成char int len = toChar.length(); int base = 256 / len + 1; int charIdx = gray / base; rst[j][i] = toChar.charAt(charIdx); // 注意i和j的处理顺序,如果是rst[j][i],图像是逆时针90度打印的,仔细体会下getRGB(i,j)这 } return rst; } private static BufferedImage getScaledImg(BufferedImage image) { BufferedImage rst = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); rst.getGraphics().drawImage(image, 0, 0, width, height, null); return rst; } }
repos\spring-boot-quick-master\quick-img2txt\src\main\java\com\quick\img2txt\Img2TxtService.java
1
请完成以下Java代码
public static <T> HttpResult<T> success(T obj, int code) { SuccessResult<T> result = new SuccessResult<T>(); result.setStatus(true); result.setCode(200); result.setEntry(obj); return result; } public static <T> HttpResult<List<T>> success(List<T> list) { SuccessResult<List<T>> result = new SuccessResult<List<T>>(); result.setStatus(true); result.setCode(200); if (null == list) { result.setEntry(new ArrayList<T>(0)); } else { result.setEntry(list); } return result; } public static HttpResult<Boolean> success() { SuccessResult<Boolean> result = new SuccessResult<Boolean>(); result.setStatus(true); result.setEntry(true); result.setCode(200); return result; } public static <T> HttpResult<T> success(T entry, String message) { SuccessResult<T> result = new SuccessResult<T>(); result.setStatus(true); result.setEntry(entry); result.setMessage(message); result.setCode(200); return result; } /** * Result set data with paging information */ public static class PageSuccessResult<T> extends HttpResult<T> { @Override public String getMessage() { return null != message ? message : HttpResult.MESSAGE_SUCCESS; } @Override public int getCode() { return HttpResult.RESPONSE_SUCCESS; } } public static class SuccessResult<T> extends HttpResult<T> { @Override
public String getMessage() { return null != message ? message : HttpResult.MESSAGE_SUCCESS; } @Override public int getCode() { return code != 0 ? code : HttpResult.RESPONSE_SUCCESS; } } public static class FailureResult<T> extends HttpResult<T> { @Override public String getMessage() { return null != message ? message : HttpResult.MESSAGE_FAILURE; } @Override public int getCode() { return code != 0 ? code : HttpResult.RESPONSE_FAILURE; } } }
repos\springboot-demo-master\Aviator\src\main\java\com\et\exception\HttpResult.java
1
请完成以下Java代码
protected DataManager<AttachmentEntity> getDataManager() { return attachmentDataManager; } @Override public List<AttachmentEntity> findAttachmentsByProcessInstanceId(String processInstanceId) { checkHistoryEnabled(); return attachmentDataManager.findAttachmentsByProcessInstanceId(processInstanceId); } @Override public List<AttachmentEntity> findAttachmentsByTaskId(String taskId) { checkHistoryEnabled(); return attachmentDataManager.findAttachmentsByTaskId(taskId); } @Override public void deleteAttachmentsByTaskId(String taskId) { checkHistoryEnabled(); List<AttachmentEntity> attachments = findAttachmentsByTaskId(taskId); boolean dispatchEvents = getEventDispatcher().isEnabled(); String processInstanceId = null; String processDefinitionId = null; String executionId = null; if (dispatchEvents && attachments != null && !attachments.isEmpty()) { // Forced to fetch the task to get hold of the process definition // for event-dispatching, if available Task task = getTaskEntityManager().findById(taskId); if (task != null) { processDefinitionId = task.getProcessDefinitionId(); processInstanceId = task.getProcessInstanceId(); executionId = task.getExecutionId(); } } for (Attachment attachment : attachments) { String contentId = attachment.getContentId(); if (contentId != null) { getByteArrayEntityManager().deleteByteArrayById(contentId); } attachmentDataManager.delete((AttachmentEntity) attachment); if (dispatchEvents) { getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(
ActivitiEventType.ENTITY_DELETED, attachment, executionId, processInstanceId, processDefinitionId ) ); } } } protected void checkHistoryEnabled() { if (!getHistoryManager().isHistoryEnabled()) { throw new ActivitiException("In order to use attachments, history should be enabled"); } } public AttachmentDataManager getAttachmentDataManager() { return attachmentDataManager; } public void setAttachmentDataManager(AttachmentDataManager attachmentDataManager) { this.attachmentDataManager = attachmentDataManager; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AttachmentEntityManagerImpl.java
1
请完成以下Java代码
public static boolean isSameWeek(Date date1, Date date2) { if (date1 == null || date2 == null) { return false; } Calendar calendar1 = Calendar.getInstance(); calendar1.setTime(date1); Calendar calendar2 = Calendar.getInstance(); calendar2.setTime(date2); boolean isSameYear = calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR); return isSameYear && calendar1.get(Calendar.WEEK_OF_YEAR) == calendar2.get(Calendar.WEEK_OF_YEAR); } /** * 判断两个时间是否是同一月 * * @param date1 * @param date2 * @return */ public static boolean isSameMonth(Date date1, Date date2) { if (date1 == null || date2 == null) { return false; } Calendar calendar1 = Calendar.getInstance(); calendar1.setTime(date1); Calendar calendar2 = Calendar.getInstance(); calendar2.setTime(date2); boolean isSameYear = calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR); return isSameYear && calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH); } /** * 判断两个时间是否是同一年 * * @param date1 * @param date2 * @return */ public static boolean isSameYear(Date date1, Date date2) { if (date1 == null || date2 == null) { return false; } Calendar calendar1 = Calendar.getInstance(); calendar1.setTime(date1); Calendar calendar2 = Calendar.getInstance(); calendar2.setTime(date2); return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR); } /** * 获取两个日期之间的所有日期列表,包含开始和结束日期 * * @param begin * @param end
* @return */ public static List<Date> getDateRangeList(Date begin, Date end) { List<Date> dateList = new ArrayList<>(); if (begin == null || end == null) { return dateList; } // 清除时间部分,只比较日期 Calendar beginCal = Calendar.getInstance(); beginCal.setTime(begin); beginCal.set(Calendar.HOUR_OF_DAY, 0); beginCal.set(Calendar.MINUTE, 0); beginCal.set(Calendar.SECOND, 0); beginCal.set(Calendar.MILLISECOND, 0); Calendar endCal = Calendar.getInstance(); endCal.setTime(end); endCal.set(Calendar.HOUR_OF_DAY, 0); endCal.set(Calendar.MINUTE, 0); endCal.set(Calendar.SECOND, 0); endCal.set(Calendar.MILLISECOND, 0); if (endCal.before(beginCal)) { return dateList; } dateList.add(beginCal.getTime()); while (beginCal.before(endCal)) { beginCal.add(Calendar.DAY_OF_YEAR, 1); dateList.add(beginCal.getTime()); } return dateList; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\DateUtils.java
1
请完成以下Java代码
public static void main(String[] args) throws IOException, GitAPIException { // prepare a new test-repository try (Repository repository = Helper.createNewRepository()) { try (Git git = new Git(repository)) { // create the file File myfile = new File(repository.getDirectory().getParent(), "testfile"); if(!myfile.createNewFile()) { throw new IOException("Could not create file " + myfile); } // Stage all files in the repo including new files git.add().addFilepattern(".").call(); // and then commit the changes. git.commit() .setMessage("Commit all changes including additions") .call();
try(PrintWriter writer = new PrintWriter(myfile)) { writer.append("Hello, world!"); } // Stage all changed files, omitting new files, and commit with one command git.commit() .setAll(true) .setMessage("Commit changes to all files") .call(); logger.debug("Committed all changes to repository at " + repository.getDirectory()); } } } }
repos\tutorials-master\jgit\src\main\java\com\baeldung\jgit\porcelain\CommitAll.java
1
请完成以下Spring Boot application配置
spring: h2: console: enabled: true path: /h2-console settings.trace: false settings.web-allow-others: false datasource: url: jdbc:h2:mem:mydb username: sa password: password driverClassName: org.h2.Driver jpa: database
-platform: org.hibernate.dialect.H2Dialect properties: hibernate: globally_quoted_identifiers: true
repos\tutorials-master\persistence-modules\spring-boot-persistence-h2\src\main\resources\application.yaml
2
请完成以下Java代码
public boolean isReadonlyUI(final IAttributeValueContext ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute) { final String attributeKey = attribute.getValue(); if (RepackNumberUtils.ATTR_IsRepackNumberRequired.equals(attributeKey)) { return true; } else if (RepackNumberUtils.ATTR_RepackNumber.equals(attributeKey)) { return !RepackNumberUtils.isRepackNumberRequired(attributeSet); } else { return false; } } @Override public boolean isDisplayedUI(final IAttributeSet attributeSet, final I_M_Attribute attribute)
{ final String attributeKey = attribute.getValue(); if (RepackNumberUtils.ATTR_IsRepackNumberRequired.equals(attributeKey)) { return RepackNumberUtils.isRepackNumberRequired(attributeSet); } else if (RepackNumberUtils.ATTR_RepackNumber.equals(attributeKey)) { return RepackNumberUtils.isRepackNumberRequired(attributeSet); } else { return false; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\vertical\pharma\attributes\RepackNumberAttributeCallout.java
1
请完成以下Java代码
private boolean isActiveEventSubscription(EventSubscriptionEntity signalEventSubscriptionEntity) { ExecutionEntity execution = signalEventSubscriptionEntity.getExecution(); return !execution.isEnded() && !execution.isCanceled(); } private void startProcessInstances(List<EventSubscriptionEntity> startSignalEventSubscriptions, Map<String, ProcessDefinitionEntity> processDefinitions) { for (EventSubscriptionEntity signalStartEventSubscription : startSignalEventSubscriptions) { ProcessDefinitionEntity processDefinition = processDefinitions.get(signalStartEventSubscription.getId()); if (processDefinition != null) { ActivityImpl signalStartEvent = processDefinition.findActivity(signalStartEventSubscription.getActivityId()); PvmProcessInstance processInstance = processDefinition.createProcessInstanceForInitial(signalStartEvent); processInstance.start(builder.getVariables()); } } } protected List<EventSubscriptionEntity> filterIntermediateSubscriptions(List<EventSubscriptionEntity> subscriptions) { List<EventSubscriptionEntity> result = new ArrayList<EventSubscriptionEntity>(); for (EventSubscriptionEntity subscription : subscriptions) { if (subscription.getExecutionId() != null) { result.add(subscription); } }
return result; } protected List<EventSubscriptionEntity> filterStartSubscriptions(List<EventSubscriptionEntity> subscriptions) { List<EventSubscriptionEntity> result = new ArrayList<EventSubscriptionEntity>(); for (EventSubscriptionEntity subscription : subscriptions) { if (subscription.getExecutionId() == null) { result.add(subscription); } } return result; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SignalEventReceivedCmd.java
1
请完成以下Java代码
public boolean hasInvoices() { final String whereClause = "C_DunningRunEntry_ID=? AND C_Invoice_ID IS NOT NULL"; return new Query(getCtx(), I_C_DunningRunLine.Table_Name, whereClause, get_TrxName()) .setParameters(getC_DunningRunEntry_ID()) .anyMatch(); } // hasInvoices /** * Get Parent * * @return Dunning Run */ private MDunningRun getParent() { if (m_parent == null) m_parent = new MDunningRun(getCtx(), getC_DunningRun_ID(), get_TrxName()); return m_parent; } // getParent @Override protected boolean beforeSave(boolean newRecord) { final IBPartnerStatsDAO bpartnerStatsDAO = Services.get(IBPartnerStatsDAO.class); I_C_DunningLevel level = getC_DunningLevel(); // Set Amt if (isProcessed()) { MDunningRunLine[] theseLines = getLines(); for (int i = 0; i < theseLines.length; i++) { theseLines[i].setProcessed(true); theseLines[i].saveEx(get_TrxName()); }
if (level.isSetCreditStop() || level.isSetPaymentTerm()) { final IBPartnerDAO bpartnersRepo = Services.get(IBPartnerDAO.class); final I_C_BPartner thisBPartner = bpartnersRepo.getById(getC_BPartner_ID()); final BPartnerStats stats =bpartnerStatsDAO.getCreateBPartnerStats(thisBPartner); if (level.isSetCreditStop()) { // set this particular credit status in the bp stats bpartnerStatsDAO.setSOCreditStatus(stats, X_C_BPartner_Stats.SOCREDITSTATUS_CreditStop); } if (level.isSetPaymentTerm()) { thisBPartner.setC_PaymentTerm_ID(level.getC_PaymentTerm_ID()); } bpartnersRepo.save(thisBPartner); } } return true; } // beforeSave } // MDunningRunEntry
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MDunningRunEntry.java
1
请完成以下Java代码
public String registerNamespace(String namespaceUri) { synchronized(document) { String lookupPrefix = lookupPrefix(namespaceUri); if (lookupPrefix == null) { // check if a prefix is known String prefix = XmlQName.KNOWN_PREFIXES.get(namespaceUri); // check if prefix is not already used if (prefix != null && getRootElement() != null && getRootElement().hasAttribute(XMLNS_ATTRIBUTE_NS_URI, prefix)) { prefix = null; } if (prefix == null) { // generate prefix prefix = ((DomDocumentImpl) getDocument()).getUnusedGenericNsPrefix(); } registerNamespace(prefix, namespaceUri); return prefix; } else { return lookupPrefix; } } } public void registerNamespace(String prefix, String namespaceUri) { synchronized(document) {
element.setAttributeNS(XMLNS_ATTRIBUTE_NS_URI, XMLNS_ATTRIBUTE + ":" + prefix, namespaceUri); } } public String lookupPrefix(String namespaceUri) { synchronized(document) { return element.lookupPrefix(namespaceUri); } } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DomElementImpl that = (DomElementImpl) o; return element.equals(that.element); } public int hashCode() { return element.hashCode(); } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\instance\DomElementImpl.java
1
请完成以下Java代码
public String getLocationUri() { return locationUriAttribute.getValue(this); } public void setLocationUri(String locationUri) { locationUriAttribute.setValue(this, locationUri); } public Collection<AuthorityRequirement> getAuthorityRequirement() { return authorityRequirementCollection.get(this); } public Type getType() { return typeChild.getChild(this); } public void setType(Type type) { typeChild.setChild(this, type); } public OrganizationUnit getOwner() { return ownerRef.getReferenceTargetElement(this); } public void setOwner(OrganizationUnit owner) { ownerRef.setReferenceTargetElement(this, owner); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(KnowledgeSource.class, DMN_ELEMENT_KNOWLEDGE_SOURCE) .namespaceUri(LATEST_DMN_NS) .extendsType(DrgElement.class) .instanceProvider(new ModelTypeInstanceProvider<KnowledgeSource>() {
public KnowledgeSource newInstance(ModelTypeInstanceContext instanceContext) { return new KnowledgeSourceImpl(instanceContext); } }); locationUriAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_LOCATION_URI) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); authorityRequirementCollection = sequenceBuilder.elementCollection(AuthorityRequirement.class) .build(); typeChild = sequenceBuilder.element(Type.class) .build(); ownerRef = sequenceBuilder.element(OwnerReference.class) .uriElementReference(OrganizationUnit.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\KnowledgeSourceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public int getMaxScale() { return this.maxScale; } public void setMaxScale(int maxScale) { this.maxScale = maxScale; } public int getMaxBucketCount() { return this.maxBucketCount; } public void setMaxBucketCount(int maxBucketCount) { this.maxBucketCount = maxBucketCount; } public TimeUnit getBaseTimeUnit() { return this.baseTimeUnit; } public void setBaseTimeUnit(TimeUnit baseTimeUnit) { this.baseTimeUnit = baseTimeUnit; } public Map<String, Meter> getMeter() { return this.meter; } /** * Per-meter settings. */
public static class Meter { /** * Maximum number of buckets to be used for exponential histograms, if configured. * This has no effect on explicit bucket histograms. */ private @Nullable Integer maxBucketCount; /** * Histogram type when histogram publishing is enabled. */ private @Nullable HistogramFlavor histogramFlavor; public @Nullable Integer getMaxBucketCount() { return this.maxBucketCount; } public void setMaxBucketCount(@Nullable Integer maxBucketCount) { this.maxBucketCount = maxBucketCount; } public @Nullable HistogramFlavor getHistogramFlavor() { return this.histogramFlavor; } public void setHistogramFlavor(@Nullable HistogramFlavor histogramFlavor) { this.histogramFlavor = histogramFlavor; } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\otlp\OtlpMetricsProperties.java
2
请完成以下Java代码
public class X_WEBUI_Board extends org.compiere.model.PO implements I_WEBUI_Board, org.compiere.model.I_Persistent { private static final long serialVersionUID = -522212501L; /** Standard Constructor */ public X_WEBUI_Board (final Properties ctx, final int WEBUI_Board_ID, @Nullable final String trxName) { super (ctx, WEBUI_Board_ID, trxName); } /** Load Constructor */ public X_WEBUI_Board (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_Table_ID (final int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID); } @Override public int getAD_Table_ID() { return get_ValueAsInt(COLUMNNAME_AD_Table_ID); } @Override public org.compiere.model.I_AD_Val_Rule getAD_Val_Rule() { return get_ValueAsPO(COLUMNNAME_AD_Val_Rule_ID, org.compiere.model.I_AD_Val_Rule.class); } @Override public void setAD_Val_Rule(final org.compiere.model.I_AD_Val_Rule AD_Val_Rule) { set_ValueFromPO(COLUMNNAME_AD_Val_Rule_ID, org.compiere.model.I_AD_Val_Rule.class, AD_Val_Rule); } @Override public void setAD_Val_Rule_ID (final int AD_Val_Rule_ID) { if (AD_Val_Rule_ID < 1) set_Value (COLUMNNAME_AD_Val_Rule_ID, null);
else set_Value (COLUMNNAME_AD_Val_Rule_ID, AD_Val_Rule_ID); } @Override public int getAD_Val_Rule_ID() { return get_ValueAsInt(COLUMNNAME_AD_Val_Rule_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setWEBUI_Board_ID (final int WEBUI_Board_ID) { if (WEBUI_Board_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, WEBUI_Board_ID); } @Override public int getWEBUI_Board_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_Board_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_Board.java
1
请完成以下Java代码
private Individual tournamentSelection(Population pop) { Population tournament = new Population(tournamentSize, false); for (int i = 0; i < tournamentSize; i++) { int randomId = (int) (Math.random() * pop.getIndividuals().size()); tournament.getIndividuals().add(i, pop.getIndividual(randomId)); } Individual fittest = tournament.getFittest(); return fittest; } protected static int getFitness(Individual individual) { int fitness = 0; for (int i = 0; i < individual.getDefaultGeneLength() && i < solution.length; i++) { if (individual.getSingleGene(i) == solution[i]) { fitness++; } } return fitness; } protected int getMaxFitness() { int maxFitness = solution.length; return maxFitness;
} protected void setSolution(String newSolution) { solution = new byte[newSolution.length()]; for (int i = 0; i < newSolution.length(); i++) { String character = newSolution.substring(i, i + 1); if (character.contains("0") || character.contains("1")) { solution[i] = Byte.parseByte(character); } else { solution[i] = 0; } } } }
repos\tutorials-master\algorithms-modules\algorithms-genetic\src\main\java\com\baeldung\algorithms\ga\binary\SimpleGeneticAlgorithm.java
1
请完成以下Java代码
public final VNumber getVNumber(final String columnName, final boolean mandatory) { final Properties ctx = Env.getCtx(); final String title = Services.get(IMsgBL.class).translate(ctx, columnName); return new VNumber(columnName, mandatory, false, // isReadOnly true, // isUpdateable DisplayType.Number, // displayType title); } @Override public final void disposeDialogForColumnData(final int windowNo, final JDialog dialog, final List<String> columnNames) { if (columnNames == null || columnNames.isEmpty()) { return; } final StringBuilder missingColumnsBuilder = new StringBuilder(); final Iterator<String> columnNamesIt = columnNames.iterator(); while (columnNamesIt.hasNext())
{ final String columnName = columnNamesIt.next(); missingColumnsBuilder.append("@").append(columnName).append("@"); if (columnNamesIt.hasNext()) { missingColumnsBuilder.append(", "); } } final Exception ex = new AdempiereException("@NotFound@ " + missingColumnsBuilder.toString()); ADialog.error(windowNo, dialog.getContentPane(), ex.getLocalizedMessage()); dialog.dispose(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\api\impl\SwingEditorFactory.java
1
请完成以下Java代码
public abstract static class TransactionStateSynchronization { protected final TransactionListener transactionListener; protected final TransactionState transactionState; private final CommandContext commandContext; public TransactionStateSynchronization(TransactionState transactionState, TransactionListener transactionListener, CommandContext commandContext) { this.transactionState = transactionState; this.transactionListener = transactionListener; this.commandContext = commandContext; } public void beforeCompletion() { if(TransactionState.COMMITTING.equals(transactionState) || TransactionState.ROLLINGBACK.equals(transactionState)) { transactionListener.execute(commandContext); } } public void afterCompletion(int status) { if(isRolledBack(status) && TransactionState.ROLLED_BACK.equals(transactionState)) { transactionListener.execute(commandContext); } else if(isCommitted(status) && TransactionState.COMMITTED.equals(transactionState)) { transactionListener.execute(commandContext); } }
protected abstract boolean isCommitted(int status); protected abstract boolean isRolledBack(int status); } @Override public boolean isTransactionActive() { try { return isTransactionActiveInternal(); } catch (Exception e) { throw LOG.exceptionWhileInteractingWithTransaction("getting transaction state", e); } } protected abstract void doRollback() throws Exception; protected abstract boolean isTransactionActiveInternal() throws Exception; protected abstract void addTransactionListener(TransactionState transactionState, TransactionListener transactionListener, CommandContext commandContext) throws Exception; }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\jta\AbstractTransactionContext.java
1
请在Spring Boot框架中完成以下Java代码
public class CreatePackagesForInOutRequest { @NonNull I_M_InOut shipment; boolean processed; @Nullable List<PackageInfo> packageInfos; public static CreatePackagesForInOutRequest ofShipment(@NonNull final I_M_InOut shipment) { return CreatePackagesForInOutRequest.builder() .shipment(shipment) .processed(false)
.packageInfos(null) .build(); } public InOutId getShipmentId() { return InOutId.ofRepoId(shipment.getM_InOut_ID()); } @Nullable public ShipperTransportationId getShipperTransportationId() { return ShipperTransportationId.ofRepoIdOrNull(shipment.getM_ShipperTransportation_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipping\CreatePackagesForInOutRequest.java
2
请完成以下Java代码
public class MessageEntity extends JobEntity { public static final String TYPE = "message"; private static final long serialVersionUID = 1L; private final static EnginePersistenceLogger LOG = ProcessEngineLogger.PERSISTENCE_LOGGER; private String repeat = null; public String getRepeat() { return repeat; } public void setRepeat(String repeat) { this.repeat = repeat; } @Override public String getType() { return TYPE; } @Override protected void postExecute(CommandContext commandContext) { LOG.debugJobExecuted(this); if (repeat != null && !repeat.isEmpty()) { init(commandContext, false, true); } else { delete(true); } commandContext.getHistoricJobLogManager().fireJobSuccessfulEvent(this);
} @Override public void init(CommandContext commandContext, boolean shouldResetLock, boolean shouldCallDeleteHandler) { super.init(commandContext, shouldResetLock, shouldCallDeleteHandler); repeat = null; } @Override public String toString() { return this.getClass().getSimpleName() + "[repeat=" + repeat + ", id=" + id + ", revision=" + revision + ", duedate=" + duedate + ", lockOwner=" + lockOwner + ", lockExpirationTime=" + lockExpirationTime + ", executionId=" + executionId + ", processInstanceId=" + processInstanceId + ", isExclusive=" + isExclusive + ", retries=" + retries + ", jobHandlerType=" + jobHandlerType + ", jobHandlerConfiguration=" + jobHandlerConfiguration + ", exceptionByteArray=" + exceptionByteArray + ", exceptionByteArrayId=" + exceptionByteArrayId + ", exceptionMessage=" + exceptionMessage + ", deploymentId=" + deploymentId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\MessageEntity.java
1
请完成以下Java代码
protected String getEngineVersion() { return CmmnEngine.VERSION; } @Override protected String getSchemaVersionPropertyName() { return "cmmn.schema.version"; } @Override protected String getDbSchemaLockName() { return CMMN_DB_SCHEMA_LOCK_NAME; } @Override protected String getEngineTableName() { return "ACT_CMMN_RU_CASE_INST"; } @Override protected String getChangeLogTableName() { return "ACT_CMMN_DATABASECHANGELOG";
} @Override protected String getDbVersionForChangelogVersion(String changeLogVersion) { if (StringUtils.isNotEmpty(changeLogVersion) && changeLogVersionMap.containsKey(changeLogVersion)) { return changeLogVersionMap.get(changeLogVersion); } return "6.1.2.0"; } @Override protected String getResourcesRootDirectory() { return "org/flowable/cmmn/db/"; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\db\CmmnDbSchemaManager.java
1
请完成以下Java代码
protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (!getSelectedRowIds().isSingleDocumentId()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } final PickingSlotRow pickingSlotRow = getSingleSelectedRow(); if (!pickingSlotRow.isPickingSourceHURow()) { return ProcessPreconditionsResolution.rejectWithInternalReason(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_SELECT_SOURCE_HU)); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final PickingSlotRow rowToProcess = getSingleSelectedRow(); final HuId huId = rowToProcess.getHuId(); this.sourceWasDeleted = SourceHUsService.get().deleteSourceHuMarker(huId);
return MSG_OK; } @Override protected void postProcess(final boolean success) { if (!success) { return; } if (sourceWasDeleted) { // unselect the row we just deleted the record of, to avoid an 'EntityNotFoundException' invalidatePickingSlotsView(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\process\WEBUI_Picking_M_Source_HU_Delete.java
1
请完成以下Java代码
public void setEntityType (java.lang.String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entitäts-Art. @return Dictionary Entity Type; Determines ownership and synchronization */ @Override public java.lang.String getEntityType () { return (java.lang.String)get_Value(COLUMNNAME_EntityType); } /** Set Request handler type. @param IMP_RequestHandlerType_ID Request handler type */ @Override public void setIMP_RequestHandlerType_ID (int IMP_RequestHandlerType_ID) { if (IMP_RequestHandlerType_ID < 1) set_ValueNoCheck (COLUMNNAME_IMP_RequestHandlerType_ID, null); else set_ValueNoCheck (COLUMNNAME_IMP_RequestHandlerType_ID, Integer.valueOf(IMP_RequestHandlerType_ID)); } /** Get Request handler type. @return Request handler type */
@Override public int getIMP_RequestHandlerType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_IMP_RequestHandlerType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\process\rpl\requesthandler\model\X_IMP_RequestHandlerType.java
1
请完成以下Java代码
public InformationItem getVariable() { return variable; } public void setVariable(InformationItem variable) { this.variable = variable; } public List<InformationRequirement> getRequiredDecisions() { return requiredDecisions; } public void setRequiredDecisions(List<InformationRequirement> requiredDecisions) { this.requiredDecisions = requiredDecisions; } public void addRequiredDecision(InformationRequirement requiredDecision) { this.requiredDecisions.add(requiredDecision); } public List<InformationRequirement> getRequiredInputs() { return requiredInputs; } public void setRequiredInputs(List<InformationRequirement> requiredInputs) { this.requiredInputs = requiredInputs; } public void addRequiredInput(InformationRequirement requiredInput) { this.requiredInputs.add(requiredInput); } public List<AuthorityRequirement> getAuthorityRequirements() { return authorityRequirements; } public void setAuthorityRequirements(List<AuthorityRequirement> authorityRequirements) { this.authorityRequirements = authorityRequirements; } public void addAuthorityRequirement(AuthorityRequirement authorityRequirement) { this.authorityRequirements.add(authorityRequirement); }
public Expression getExpression() { return expression; } public void setExpression(Expression expression) { this.expression = expression; } public boolean isForceDMN11() { return forceDMN11; } public void setForceDMN11(boolean forceDMN11) { this.forceDMN11 = forceDMN11; } @JsonIgnore public DmnDefinition getDmnDefinition() { return dmnDefinition; } public void setDmnDefinition(DmnDefinition dmnDefinition) { this.dmnDefinition = dmnDefinition; } }
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\Decision.java
1
请在Spring Boot框架中完成以下Java代码
public class PPOrderNodeId implements RepoIdAware { @JsonCreator public static PPOrderNodeId ofRepoId(final int repoId) { return new PPOrderNodeId(repoId); } public static PPOrderNodeId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new PPOrderNodeId(repoId) : null; } public static Optional<PPOrderNodeId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } public static int toRepoId(final PPOrderNodeId id) { return toRepoIdOr(id, -1); }
public static int toRepoIdOr(final PPOrderNodeId id, final int defaultValue) { return id != null ? id.getRepoId() : defaultValue; } int repoId; private PPOrderNodeId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "PP_Order_Node_ID"); } @JsonValue public int toJson() { return getRepoId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\PPOrderNodeId.java
2
请完成以下Java代码
public class Lecture { @PlanningId private Long id; private Integer roomNumber; private Integer period; public Lecture(Long i) { this.id = i; } public Lecture() { } @PlanningVariable(valueRangeProviderRefs = {"availablePeriods"}) public Integer getPeriod() { return period; }
@PlanningVariable(valueRangeProviderRefs = {"availableRooms"}) public Integer getRoomNumber() { return roomNumber; } public void setPeriod(Integer period) { this.period = period; } public void setRoomNumber(Integer roomNumber) { this.roomNumber = roomNumber; } }
repos\tutorials-master\optaplanner\src\main\java\com\baeldung\optaplanner\Lecture.java
1
请在Spring Boot框架中完成以下Java代码
public static class Validation { /** * Whether to enable LDAP schema validation. */ private boolean enabled = true; /** * Path to the custom schema. */ private @Nullable Resource schema; public boolean isEnabled() { return this.enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; } public @Nullable Resource getSchema() { return this.schema; } public void setSchema(@Nullable Resource schema) { this.schema = schema; } } }
repos\spring-boot-4.0.1\module\spring-boot-ldap\src\main\java\org\springframework\boot\ldap\autoconfigure\embedded\EmbeddedLdapProperties.java
2
请完成以下Java代码
public boolean isIncludeProcessVariables() { return includeProcessVariables; } public boolean iswithException() { return withJobException; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public List<ProcessInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } /** * Methods needed for ibatis because of re-use of query-xml for executions. ExecutionQuery contains a parentId property. */ public String getParentId() { return null; } public boolean isOnlyChildExecutions() { return onlyChildExecutions; } public boolean isOnlyProcessInstanceExecutions() { return onlyProcessInstanceExecutions; } public boolean isOnlySubProcessExecutions() { return onlySubProcessExecutions; } public Date getStartedBefore() { return startedBefore; }
public void setStartedBefore(Date startedBefore) { this.startedBefore = startedBefore; } public Date getStartedAfter() { return startedAfter; } public void setStartedAfter(Date startedAfter) { this.startedAfter = startedAfter; } public String getStartedBy() { return startedBy; } public void setStartedBy(String startedBy) { this.startedBy = startedBy; } public List<String> getInvolvedGroups() { return involvedGroups; } public ProcessInstanceQuery involvedGroupsIn(List<String> involvedGroups) { if (involvedGroups == null || involvedGroups.isEmpty()) { throw new ActivitiIllegalArgumentException("Involved groups list is null or empty."); } if (inOrStatement) { this.currentOrQueryObject.involvedGroups = involvedGroups; } else { this.involvedGroups = involvedGroups; } return this; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ProcessInstanceQueryImpl.java
1
请完成以下Java代码
public static List<GrantedAuthority> commaSeparatedStringToAuthorityList(String authorityString) { return createAuthorityList(StringUtils.tokenizeToStringArray(authorityString, ",")); } /** * Converts an array of GrantedAuthority objects to a Set. * @return a Set of the Strings obtained from each call to * GrantedAuthority.getAuthority() */ public static Set<String> authorityListToSet(Collection<? extends GrantedAuthority> userAuthorities) { Assert.notNull(userAuthorities, "userAuthorities cannot be null"); Set<String> set = new HashSet<>(userAuthorities.size()); for (GrantedAuthority authority : userAuthorities) { set.add(authority.getAuthority()); } return set; } /** * Converts authorities into a List of GrantedAuthority objects. * @param authorities the authorities to convert * @return a List of GrantedAuthority objects */ public static List<GrantedAuthority> createAuthorityList(String... authorities) { Assert.notNull(authorities, "authorities cannot be null"); List<GrantedAuthority> grantedAuthorities = new ArrayList<>(authorities.length); for (String authority : authorities) {
grantedAuthorities.add(new SimpleGrantedAuthority(authority)); } return grantedAuthorities; } /** * Converts authorities into a List of GrantedAuthority objects. * @param authorities the authorities to convert * @return a List of GrantedAuthority objects * @since 6.1 */ public static List<GrantedAuthority> createAuthorityList(Collection<String> authorities) { List<GrantedAuthority> grantedAuthorities = new ArrayList<>(authorities.size()); for (String authority : authorities) { grantedAuthorities.add(new SimpleGrantedAuthority(authority)); } return grantedAuthorities; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\authority\AuthorityUtils.java
1
请在Spring Boot框架中完成以下Java代码
public void configureWebSocketTransport(WebSocketTransportRegistration registration) { registration.addDecoratorFactory(wsConnectHandlerDecoratorFactory()); } @Bean public static WebSocketRegistryListener webSocketRegistryListener() { return new WebSocketRegistryListener(); } @Bean public WebSocketConnectHandlerDecoratorFactory wsConnectHandlerDecoratorFactory() { return new WebSocketConnectHandlerDecoratorFactory(this.eventPublisher); } @Bean @SuppressWarnings("unchecked") public SessionRepositoryMessageInterceptor<S> sessionRepositoryInterceptor() { return new SessionRepositoryMessageInterceptor<>(this.sessionRepository); } /** * A {@link StompEndpointRegistry} that applies {@link HandshakeInterceptor}. */ static class SessionStompEndpointRegistry implements StompEndpointRegistry { private final WebMvcStompEndpointRegistry registry; private final HandshakeInterceptor interceptor; SessionStompEndpointRegistry(WebMvcStompEndpointRegistry registry, HandshakeInterceptor interceptor) { this.registry = registry; this.interceptor = interceptor; } @Override public StompWebSocketEndpointRegistration addEndpoint(String... paths) { StompWebSocketEndpointRegistration endpoints = this.registry.addEndpoint(paths); endpoints.addInterceptors(this.interceptor);
return endpoints; } @Override public void setOrder(int order) { this.registry.setOrder(order); } @Override public void setUrlPathHelper(UrlPathHelper urlPathHelper) { this.registry.setUrlPathHelper(urlPathHelper); } @Override public WebMvcStompEndpointRegistry setErrorHandler(StompSubProtocolErrorHandler errorHandler) { return this.registry.setErrorHandler(errorHandler); } @Override public WebMvcStompEndpointRegistry setPreserveReceiveOrder(boolean preserveReceiveOrder) { return this.registry.setPreserveReceiveOrder(preserveReceiveOrder); } } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\socket\config\annotation\AbstractSessionWebSocketMessageBrokerConfigurer.java
2
请在Spring Boot框架中完成以下Java代码
public Duration getQuery() { return this.query; } public void setQuery(Duration query) { this.query = query; } public Duration getView() { return this.view; } public void setView(Duration view) { this.view = view; } public Duration getSearch() { return this.search; } public void setSearch(Duration search) { this.search = search; } public Duration getAnalytics() { return this.analytics;
} public void setAnalytics(Duration analytics) { this.analytics = analytics; } public Duration getManagement() { return this.management; } public void setManagement(Duration management) { this.management = management; } } }
repos\spring-boot-4.0.1\module\spring-boot-couchbase\src\main\java\org\springframework\boot\couchbase\autoconfigure\CouchbaseProperties.java
2
请完成以下Java代码
public String getTypeLanguage() { return typeLanguageAttribute.getValue(this); } public void setTypeLanguage(String typeLanguage) { typeLanguageAttribute.setValue(this, typeLanguage); } public String getExporter() { return exporterAttribute.getValue(this); } public void setExporter(String exporter) { exporterAttribute.setValue(this, exporter); } public String getExporterVersion() { return exporterVersionAttribute.getValue(this); } public void setExporterVersion(String exporterVersion) { exporterVersionAttribute.setValue(this, exporterVersion); } public Collection<Import> getImports() { return importCollection.get(this); }
public Collection<Extension> getExtensions() { return extensionCollection.get(this); } public Collection<RootElement> getRootElements() { return rootElementCollection.get(this); } public Collection<BpmnDiagram> getBpmDiagrams() { return bpmnDiagramCollection.get(this); } public Collection<Relationship> getRelationships() { return relationshipCollection.get(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\DefinitionsImpl.java
1
请完成以下Java代码
public class JwtResponse { private String token; private String type = "Bearer"; private String username; public JwtResponse(String accessToken, String username) { this.token = accessToken; this.username = username; } public String getAccessToken() { return token; } public void setAccessToken(String accessToken) { this.token = accessToken; }
public String getTokenType() { return type; } public void setTokenType(String tokenType) { this.type = tokenType; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\jwtsignkey\response\JwtResponse.java
1
请完成以下Java代码
public int getM_Picking_Job_ID() { return get_ValueAsInt(COLUMNNAME_M_Picking_Job_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public de.metas.handlingunits.model.I_M_HU getPickFrom_HU() { return get_ValueAsPO(COLUMNNAME_PickFrom_HU_ID, de.metas.handlingunits.model.I_M_HU.class); } @Override public void setPickFrom_HU(final de.metas.handlingunits.model.I_M_HU PickFrom_HU) { set_ValueFromPO(COLUMNNAME_PickFrom_HU_ID, de.metas.handlingunits.model.I_M_HU.class, PickFrom_HU); } @Override public void setPickFrom_HU_ID (final int PickFrom_HU_ID) { if (PickFrom_HU_ID < 1) set_ValueNoCheck (COLUMNNAME_PickFrom_HU_ID, null); else set_ValueNoCheck (COLUMNNAME_PickFrom_HU_ID, PickFrom_HU_ID); } @Override public int getPickFrom_HU_ID() { return get_ValueAsInt(COLUMNNAME_PickFrom_HU_ID); } @Override public void setPickFrom_Locator_ID (final int PickFrom_Locator_ID) { if (PickFrom_Locator_ID < 1) set_Value (COLUMNNAME_PickFrom_Locator_ID, null); else set_Value (COLUMNNAME_PickFrom_Locator_ID, PickFrom_Locator_ID); }
@Override public int getPickFrom_Locator_ID() { return get_ValueAsInt(COLUMNNAME_PickFrom_Locator_ID); } @Override public void setPickFrom_Warehouse_ID (final int PickFrom_Warehouse_ID) { if (PickFrom_Warehouse_ID < 1) set_Value (COLUMNNAME_PickFrom_Warehouse_ID, null); else set_Value (COLUMNNAME_PickFrom_Warehouse_ID, PickFrom_Warehouse_ID); } @Override public int getPickFrom_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_PickFrom_Warehouse_ID); } @Override public void setQtyAvailable (final BigDecimal QtyAvailable) { set_Value (COLUMNNAME_QtyAvailable, QtyAvailable); } @Override public BigDecimal getQtyAvailable() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyAvailable); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job_HUAlternative.java
1
请在Spring Boot框架中完成以下Java代码
public void setPassword(String password) { this.password = password; } } @NotBlank private String hostName; @Min(1025) @Max(65536) private int port; @Pattern(regexp = "^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,6}$") private String from; private Credentials credentials; private List<String> defaultRecipients; private Map<String, String> additionalHeaders; public String getHostName() { return hostName; } public void setHostName(String hostName) { this.hostName = hostName; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getFrom() {
return from; } public void setFrom(String from) { this.from = from; } public Credentials getCredentials() { return credentials; } public void setCredentials(Credentials credentials) { this.credentials = credentials; } public List<String> getDefaultRecipients() { return defaultRecipients; } public void setDefaultRecipients(List<String> defaultRecipients) { this.defaultRecipients = defaultRecipients; } public Map<String, String> getAdditionalHeaders() { return additionalHeaders; } public void setAdditionalHeaders(Map<String, String> additionalHeaders) { this.additionalHeaders = additionalHeaders; } @Bean @ConfigurationProperties(prefix = "item") public Item item(){ return new Item(); } }
repos\tutorials-master\spring-boot-modules\spring-boot-core\src\main\java\com\baeldung\configurationproperties\ConfigProperties.java
2
请完成以下Java代码
public void setTour(String value) { this.tour = value; } /** * Gets the value of the retourenAnteilTyp property. * * @return * possible object is * {@link RetourenAnteilTypType } * */ public RetourenAnteilTypType getRetourenAnteilTyp() { return retourenAnteilTyp; } /** * Sets the value of the retourenAnteilTyp property. * * @param value * allowed object is * {@link RetourenAnteilTypType } * */ public void setRetourenAnteilTyp(RetourenAnteilTypType value) { this.retourenAnteilTyp = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt;
* &lt;extension base="{urn:msv3:v2}RetourePositionType"&gt; * &lt;/extension&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class Position extends RetourePositionType { } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\RetourenavisAnkuendigungAntwort.java
1
请完成以下Java代码
public class MEXPFormatLine extends X_EXP_FormatLine { /** * */ private static final long serialVersionUID = 1855089248134520749L; /** Static Logger */ private static Logger s_log = LogManager.getLogger(X_EXP_FormatLine.class); public MEXPFormatLine(Properties ctx, int C_EDIFormat_Line_ID, String trxName) { super(ctx, C_EDIFormat_Line_ID, trxName); } public MEXPFormatLine (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } @Override public String toString() { StringBuffer sb = new StringBuffer ("X_EXP_FormatLine[ID=").append(get_ID()).append("; Value="+getValue()+"; Type="+getType()+"]"); return sb.toString(); } public static MEXPFormatLine getFormatLineByValue(Properties ctx, String value, int EXP_Format_ID, String trxName) throws SQLException { MEXPFormatLine result = null; StringBuffer sql = new StringBuffer("SELECT * ") .append(" FROM ").append(X_EXP_FormatLine.Table_Name) .append(" WHERE ").append(X_EXP_Format.COLUMNNAME_Value).append("=?") //.append(" AND IsActive = ?") //.append(" AND AD_Client_ID = ?") .append(" AND ").append(X_EXP_Format.COLUMNNAME_EXP_Format_ID).append(" = ?") ; PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement (sql.toString(), trxName); pstmt.setString(1, value); pstmt.setInt(2, EXP_Format_ID); ResultSet rs = pstmt.executeQuery (); if ( rs.next() ) { result = new MEXPFormatLine (ctx, rs, trxName); } rs.close (); pstmt.close ();
pstmt = null; } catch (SQLException e) { s_log.error(sql.toString(), e); throw e; } finally { try { if (pstmt != null) pstmt.close (); pstmt = null; } catch (Exception e) { pstmt = null; } } return result; } @Override protected boolean afterSave (boolean newRecord, boolean success) { if(!success) { return false; } CacheMgt.get().reset(I_EXP_Format.Table_Name); return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MEXPFormatLine.java
1
请完成以下Java代码
public void updateProcessed(final I_C_Async_Batch asyncBatch) { // // Our batch was processed right now => notify user by sending email if (asyncBatch.isProcessed() && isNotificationType(asyncBatch, X_C_Async_Batch_Type.NOTIFICATIONTYPE_AsyncBatchProcessed)) { asyncBatchListeners.notify(asyncBatch); } } @ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE, ifColumnsChanged = { I_C_Async_Batch.COLUMNNAME_CountProcessed, I_C_Async_Batch.COLUMNNAME_LastProcessed_WorkPackage_ID }) public void updateCountProcessed(final I_C_Async_Batch asyncBatch) {
// // Our batch was not processed => notify user with note when workpackage processed if (!asyncBatch.isProcessed() && isNotificationType(asyncBatch, X_C_Async_Batch_Type.NOTIFICATIONTYPE_WorkpackageProcessed)) { asyncBatchListeners.notify(asyncBatch); } } private boolean isNotificationType(@NonNull final I_C_Async_Batch asyncBatch, @NonNull final String expectedNotificationType) { final String notificationType = asyncBatchBL.getAsyncBatchType(asyncBatch).map(AsyncBatchType::getNotificationType).orElse(null); return Objects.equals(notificationType, expectedNotificationType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\model\validator\C_Async_Batch.java
1
请完成以下Java代码
public ChannelDefinitionEntity findChannelDefinitionByKeyAndVersion(String channelDefinitionKey, Integer eventVersion) { Map<String, Object> params = new HashMap<>(); params.put("channelDefinitionKey", channelDefinitionKey); params.put("eventVersion", eventVersion); List<ChannelDefinitionEntity> results = getDbSqlSession().selectList("selectChannelDefinitionsByKeyAndVersion", params); if (results.size() == 1) { return results.get(0); } else if (results.size() > 1) { throw new FlowableException("There are " + results.size() + " event definitions with key = '" + channelDefinitionKey + "' and version = '" + eventVersion + "'."); } return null; } @Override @SuppressWarnings("unchecked") public ChannelDefinitionEntity findChannelDefinitionByKeyAndVersionAndTenantId(String channelDefinitionKey, Integer eventVersion, String tenantId) { Map<String, Object> params = new HashMap<>(); params.put("channelDefinitionKey", channelDefinitionKey); params.put("eventVersion", eventVersion); params.put("tenantId", tenantId); List<ChannelDefinitionEntity> results = getDbSqlSession().selectList("selectChannelDefinitionsByKeyAndVersionAndTenantId", params); if (results.size() == 1) { return results.get(0); } else if (results.size() > 1) { throw new FlowableException("There are " + results.size() + " event definitions with key = '" + channelDefinitionKey + "' and version = '" + eventVersion + "' in tenant = '" + tenantId + "'."); } return null; } @Override @SuppressWarnings("unchecked") public List<ChannelDefinition> findChannelDefinitionsByNativeQuery(Map<String, Object> parameterMap) { return getDbSqlSession().selectListWithRawParameter("selectChannelDefinitionByNativeQuery", parameterMap); }
@Override public long findChannelDefinitionCountByNativeQuery(Map<String, Object> parameterMap) { return (Long) getDbSqlSession().selectOne("selectChannelDefinitionCountByNativeQuery", parameterMap); } @Override public void updateChannelDefinitionTenantIdForDeployment(String deploymentId, String newTenantId) { HashMap<String, Object> params = new HashMap<>(); params.put("deploymentId", deploymentId); params.put("tenantId", newTenantId); getDbSqlSession().directUpdate("updateChannelDefinitionTenantIdForDeploymentId", params); } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\data\impl\MybatisChannelDefinitionDataManager.java
1
请完成以下Java代码
public void setId(Integer id) { this.id = id; } public Integer getProductId() { return productId; } public void setProductId(Integer productId) { this.productId = productId; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getCustomerId() { return customerId; }
public void setCustomerId(String customerId) { this.customerId = customerId; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getCreationDate() { return creationDate; } public void setCreationDate(String creationDate) { this.creationDate = creationDate; } }
repos\tutorials-master\spring-boot-modules\spring-boot-graphql-2\src\main\java\com\baeldung\graphqlvsrest\entity\Order.java
1
请完成以下Java代码
public CleanableHistoricProcessInstanceReport createCleanableHistoricProcessInstanceReport() { return new CleanableHistoricProcessInstanceReportImpl(commandExecutor); } public CleanableHistoricDecisionInstanceReport createCleanableHistoricDecisionInstanceReport() { return new CleanableHistoricDecisionInstanceReportImpl(commandExecutor); } public CleanableHistoricCaseInstanceReport createCleanableHistoricCaseInstanceReport() { return new CleanableHistoricCaseInstanceReportImpl(commandExecutor); } public CleanableHistoricBatchReport createCleanableHistoricBatchReport() { return new CleanableHistoricBatchReportImpl(commandExecutor); } public HistoricBatchQuery createHistoricBatchQuery() { return new HistoricBatchQueryImpl(commandExecutor); } public void deleteHistoricBatch(String batchId) { commandExecutor.execute(new DeleteHistoricBatchCmd(batchId)); } @Override public HistoricDecisionInstanceStatisticsQuery createHistoricDecisionInstanceStatisticsQuery(String decisionRequirementsDefinitionId) { return new HistoricDecisionInstanceStatisticsQueryImpl(decisionRequirementsDefinitionId, commandExecutor); } @Override public HistoricExternalTaskLogQuery createHistoricExternalTaskLogQuery() { return new HistoricExternalTaskLogQueryImpl(commandExecutor); } @Override public String getHistoricExternalTaskLogErrorDetails(String historicExternalTaskLogId) { return commandExecutor.execute(new GetHistoricExternalTaskLogErrorDetailsCmd(historicExternalTaskLogId)); } public SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder setRemovalTimeToHistoricProcessInstances() { return new SetRemovalTimeToHistoricProcessInstancesBuilderImpl(commandExecutor); }
public SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder setRemovalTimeToHistoricDecisionInstances() { return new SetRemovalTimeToHistoricDecisionInstancesBuilderImpl(commandExecutor); } public SetRemovalTimeSelectModeForHistoricBatchesBuilder setRemovalTimeToHistoricBatches() { return new SetRemovalTimeToHistoricBatchesBuilderImpl(commandExecutor); } public void setAnnotationForOperationLogById(String operationId, String annotation) { commandExecutor.execute(new SetAnnotationForOperationLog(operationId, annotation)); } public void clearAnnotationForOperationLogById(String operationId) { commandExecutor.execute(new SetAnnotationForOperationLog(operationId, null)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoryServiceImpl.java
1
请完成以下Java代码
private void deactivatePartner(@NonNull final I_C_BPartner partner) { partner.setIsActive(false); InterfaceWrapperHelper.save(partner); } private ImportRecordResult importOrUpdateBPartner(@NonNull final I_I_Pharma_BPartner importRecord, final boolean isInsertOnly) { final boolean bpartnerExists = importRecord.getC_BPartner_ID() > 0; if (isInsertOnly && bpartnerExists) { return ImportRecordResult.Nothing; } IFABPartnerImportHelper.importRecord(importRecord); return bpartnerExists ? ImportRecordResult.Updated : ImportRecordResult.Inserted; }
private ImportRecordResult doNothingAndUsePreviousPartner(@NonNull final I_I_Pharma_BPartner importRecord, @NonNull final I_I_Pharma_BPartner previousImportRecord) { importRecord.setC_BPartner(previousImportRecord.getC_BPartner()); return ImportRecordResult.Nothing; } @Override protected void markImported(@NonNull final I_I_Pharma_BPartner importRecord) { importRecord.setI_IsImported(X_I_Pharma_Product.I_ISIMPORTED_Imported); importRecord.setProcessed(true); InterfaceWrapperHelper.save(importRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\impexp\bpartner\IFABPartnerImportProcess.java
1
请在Spring Boot框架中完成以下Java代码
public class MyBatisUsersConfig { /** * 创建 users 数据源 */ @Bean(name = "usersDataSource") @ConfigurationProperties(prefix = "spring.datasource.users") public DataSource dataSource() { return DataSourceBuilder.create().build(); } /** * 创建 MyBatis SqlSessionFactory */ @Bean(name = "sqlSessionFactory") public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); // 设置 users 数据源 bean.setDataSource(this.dataSource()); // 设置 entity 所在包 bean.setTypeAliasesPackage("cn.iocoder.springboot.lab17.dynamicdatasource.dataobject"); // 设置 config 路径 bean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis-config.xml")); // 设置 mapper 路径 bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/users/*.xml"));
return bean.getObject(); } /** * 创建 MyBatis SqlSessionTemplate */ @Bean(name = "usersSqlSessionTemplate") public SqlSessionTemplate sqlSessionTemplate() throws Exception { return new SqlSessionTemplate(this.sqlSessionFactory()); } /** * 创建 users 数据源的 TransactionManager 事务管理器 */ @Bean(name = DBConstants.TX_MANAGER_USERS) public PlatformTransactionManager transactionManager() { return new DataSourceTransactionManager(this.dataSource()); } }
repos\SpringBoot-Labs-master\lab-17\lab-17-dynamic-datasource-mybatis\src\main\java\cn\iocoder\springboot\lab17\dynamicdatasource\config\MyBatisUsersConfig.java
2
请完成以下Java代码
public boolean isCompletable() { return completable; } @Override public String getEntryCriterionId() { return entryCriterionId; } @Override public String getExitCriterionId() { return exitCriterionId; } @Override public String getFormKey() { return formKey; } @Override public String getExtraValue() { return extraValue; } @Override public boolean hasVariable(String variableName) { return variables.containsKey(variableName); } @Override public Object getVariable(String variableName) { return variables.get(variableName); } @Override public String getTenantId() { return tenantId; }
@Override public Set<String> getVariableNames() { return variables.keySet(); } @Override public Map<String, Object> getPlanItemInstanceLocalVariables() { return localVariables; } @Override public PlanItem getPlanItem() { return planItem; } @Override public String toString() { return new StringJoiner(", ", getClass().getSimpleName() + "[", "]") .add("id='" + id + "'") .add("planItemDefinitionId='" + planItemDefinitionId + "'") .add("elementId='" + elementId + "'") .add("caseInstanceId='" + caseInstanceId + "'") .add("caseDefinitionId='" + caseDefinitionId + "'") .add("tenantId='" + tenantId + "'") .toString(); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\delegate\ReadOnlyDelegatePlanItemInstanceImpl.java
1
请完成以下Java代码
public List<FactTrxLines> createFactTrxLines(final List<FactLine> factLines) { if (factLines.isEmpty()) { return ImmutableList.of(); } final Map<Integer, FactTrxLines.FactTrxLinesBuilder> factTrxLinesByKey = new LinkedHashMap<>(); for (final FactLine factLine : factLines) { factTrxLinesByKey.computeIfAbsent(extractGroupNo(factLine), key -> FactTrxLines.builder()) .factLine(factLine); } return factTrxLinesByKey.values() .stream() .map(FactTrxLines.FactTrxLinesBuilder::build) .collect(ImmutableList.toImmutableList()); }
private static int extractGroupNo(final FactLine factLine) { final DocLine<?> docLine = factLine.getDocLine(); if (docLine instanceof DocLine_GLJournal) { return ((DocLine_GLJournal)docLine).getGroupNo(); } else { throw new AdempiereException("Expected a DocLine_GLJournal: " + docLine); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_GLJournal_FactTrxStrategy.java
1
请完成以下Java代码
public class Agent { /** * The {@link AgentId}. */ private final AgentId id; /** * The version of the agent, if any. */ private final String version; public Agent(AgentId id, String version) { this.id = id; this.version = version; } public AgentId getId() { return this.id; } public String getVersion() { return this.version; } /** * Create an {@link Agent} based on the specified {@code User-Agent} header. * @param userAgent the user agent * @return an {@link Agent} instance or {@code null} */ public static Agent fromUserAgent(String userAgent) { return UserAgentHandler.parse(userAgent); } /** * Defines the various known agents. */ public enum AgentId { /** * CURL. */ CURL("curl", "curl"), /** * HTTPie. */ HTTPIE("httpie", "HTTPie"), /** * JBoss Forge. */ JBOSS_FORGE("jbossforge", "SpringBootForgeCli"), /** * The Spring Boot CLI. */ SPRING_BOOT_CLI("spring", "SpringBootCli"), /** * Spring Tools Suite. */ STS("sts", "STS"), /** * IntelliJ IDEA. */ INTELLIJ_IDEA("intellijidea", "IntelliJ IDEA"), /** * Netbeans. */ NETBEANS("netbeans", "NetBeans"), /** * Visual Studio Code. */ VSCODE("vscode", "vscode"), /** * Jenkins X. */ JENKINSX("jenkinsx", "jx"),
/** * NX. */ NX("nx", "@nxrocks_nx-spring-boot"), /** * A generic browser. */ BROWSER("browser", "Browser"); final String id; final String name; public String getId() { return this.id; } public String getName() { return this.name; } AgentId(String id, String name) { this.id = id; this.name = name; } } private static final class UserAgentHandler { private static final Pattern TOOL_REGEX = Pattern.compile("([^\\/]*)\\/([^ ]*).*"); private static final Pattern STS_REGEX = Pattern.compile("STS (.*)"); private static final Pattern NETBEANS_REGEX = Pattern.compile("nb-springboot-plugin\\/(.*)"); static Agent parse(String userAgent) { Matcher matcher = TOOL_REGEX.matcher(userAgent); if (matcher.matches()) { String name = matcher.group(1); for (AgentId id : AgentId.values()) { if (name.equals(id.name)) { String version = matcher.group(2); return new Agent(id, version); } } } matcher = STS_REGEX.matcher(userAgent); if (matcher.matches()) { return new Agent(AgentId.STS, matcher.group(1)); } matcher = NETBEANS_REGEX.matcher(userAgent); if (matcher.matches()) { return new Agent(AgentId.NETBEANS, matcher.group(1)); } if (userAgent.equals(AgentId.INTELLIJ_IDEA.name)) { return new Agent(AgentId.INTELLIJ_IDEA, null); } if (userAgent.contains("Mozilla/5.0")) { // Super heuristics return new Agent(AgentId.BROWSER, null); } return null; } } }
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\support\Agent.java
1
请完成以下Java代码
private static PackageItem toPackageItem(@NonNull final I_M_InOutLine inOutLine) { final ProductId productId = ProductId.ofRepoIdOrNull(inOutLine.getM_Product_ID()); final OrderLineId orderLineId = OrderLineId.ofRepoIdOrNull(inOutLine.getC_OrderLine_ID()); if (productId == null || orderLineId == null) { return null; } return PackageItem.builder() .productId(productId) .quantity(Quantitys.of(inOutLine.getMovementQty(), UomId.ofRepoId(inOutLine.getC_UOM_ID()))) .orderAndLineId(OrderAndLineId.of(OrderId.ofRepoId(inOutLine.getC_Order_ID()), orderLineId)) .build(); } public Collection<I_M_ShippingPackage> getBy(final @NonNull ShippingPackageQuery query) { return toShippingPackageQueryBuilder(query) .create() .list(); } private IQuery<I_M_Package> toPackageSqlQuery(final @NonNull ShippingPackageQuery query) { final IQueryBuilder<I_M_ShippingPackage> builder = toShippingPackageQueryBuilder(query); return builder.andCollect(I_M_ShippingPackage.COLUMN_M_Package_ID) .create(); } private IQueryBuilder<I_M_ShippingPackage> toShippingPackageQueryBuilder(final @NonNull ShippingPackageQuery query) { if(query.getOrderIds().isEmpty() && query.getOrderLineIds().isEmpty()) {
return queryBL.createQueryBuilder(I_M_ShippingPackage.class) .filter(ConstantQueryFilter.of(false)); } final IQueryBuilder<I_M_ShippingPackage> builder = queryBL.createQueryBuilder(I_M_ShippingPackage.class) .addOnlyActiveRecordsFilter(); final Collection<OrderId> orderIds = query.getOrderIds(); if (!orderIds.isEmpty()) { builder.addInArrayFilter(I_M_ShippingPackage.COLUMNNAME_C_Order_ID, orderIds); } final Collection<OrderLineId> orderLineIds = query.getOrderLineIds(); if (!orderLineIds.isEmpty()) { builder.addInArrayFilter(I_M_ShippingPackage.COLUMNNAME_C_OrderLine_ID, orderLineIds); } return builder; } public void deleteBy(@NonNull final ShippingPackageQuery query) { deleteFromShipperTransportation(toPackageSqlQuery(query).listIds(PackageId::ofRepoId)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipping\PurchaseOrderToShipperTransportationRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class UploadConfig { @Value("${qiniu.accessKey}") private String accessKey; @Value("${qiniu.secretKey}") private String secretKey; private final MultipartProperties multipartProperties; @Autowired public UploadConfig(MultipartProperties multipartProperties) { this.multipartProperties = multipartProperties; } /** * 上传配置 */ @Bean @ConditionalOnMissingBean public MultipartConfigElement multipartConfigElement() { return this.multipartProperties.createMultipartConfig(); } /** * 注册解析器 */ @Bean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME) @ConditionalOnMissingBean(MultipartResolver.class) public StandardServletMultipartResolver multipartResolver() { StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver(); multipartResolver.setResolveLazily(this.multipartProperties.isResolveLazily()); return multipartResolver; }
/** * 华东机房 */ @Bean public com.qiniu.storage.Configuration qiniuConfig() { return new com.qiniu.storage.Configuration(Zone.zone0()); } /** * 构建一个七牛上传工具实例 */ @Bean public UploadManager uploadManager() { return new UploadManager(qiniuConfig()); } /** * 认证信息实例 */ @Bean public Auth auth() { return Auth.create(accessKey, secretKey); } /** * 构建七牛空间管理实例 */ @Bean public BucketManager bucketManager() { return new BucketManager(auth(), qiniuConfig()); } }
repos\spring-boot-demo-master\demo-upload\src\main\java\com\xkcoding\upload\config\UploadConfig.java
2
请完成以下Java代码
class CreateOrUpdateOrderLineFromOrderCostCommand { // // services @NonNull private final IOrderBL orderBL; @NonNull private final MoneyService moneyService; // // Params @NonNull private final OrderCost orderCost; @Nullable private final ProductId productId; // // State @Nullable private I_C_Order _order; @Builder private CreateOrUpdateOrderLineFromOrderCostCommand( final @NonNull IOrderBL orderBL, final @NonNull MoneyService moneyService, final @NonNull OrderCost orderCost, final @Nullable ProductId productId, final @Nullable I_C_Order loadedOrder) { this.orderBL = orderBL; this.moneyService = moneyService; this.orderCost = orderCost; this.productId = productId; if (loadedOrder != null && loadedOrder.getC_Order_ID() == orderCost.getOrderId().getRepoId()) { this._order = loadedOrder; } } public OrderAndLineId execute() { final OrderAndLineId orderAndLineId = OrderAndLineId.ofNullable(orderCost.getOrderId(), orderCost.getCreatedOrderLineId()); final I_C_OrderLine orderLine = orderAndLineId != null ? orderBL.getLineById(orderAndLineId) : orderBL.createOrderLine(getOrder()); if (productId != null) {
orderBL.setProductId(orderLine, productId, true); } orderLine.setQtyEntered(BigDecimal.ONE); orderLine.setQtyOrdered(BigDecimal.ONE); orderLine.setIsManualPrice(true); orderLine.setIsPriceEditable(false); final Money costAmountConv = convertToOrderCurrency(orderCost.getCostAmount()); orderLine.setPriceEntered(costAmountConv.toBigDecimal()); orderLine.setPriceActual(costAmountConv.toBigDecimal()); orderLine.setIsManualDiscount(true); orderLine.setDiscount(BigDecimal.ZERO); orderBL.save(orderLine); return OrderAndLineId.ofRepoIds(orderLine.getC_Order_ID(), orderLine.getC_OrderLine_ID()); } private I_C_Order getOrder() { if (_order == null) { _order = orderBL.getById(orderCost.getOrderId()); } return _order; } private Money convertToOrderCurrency(final Money amt) { final I_C_Order order = getOrder(); final CurrencyId orderCurrencyId = CurrencyId.ofRepoId(order.getC_Currency_ID()); final CurrencyConversionContext conversionCtx = orderBL.getCurrencyConversionContext(order); return moneyService.convertMoneyToCurrency(amt, orderCurrencyId, conversionCtx); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\CreateOrUpdateOrderLineFromOrderCostCommand.java
1
请完成以下Java代码
public static DDOrderCandidateAllocList of(@NonNull final Collection<DDOrderCandidateAlloc> list) { return list.isEmpty() ? EMPTY : new DDOrderCandidateAllocList(list); } public static Collector<DDOrderCandidateAlloc, ?, DDOrderCandidateAllocList> collect() { return GuavaCollectors.collectUsingListAccumulator(DDOrderCandidateAllocList::of); } public boolean isEmpty() {return list.isEmpty();} public Set<DDOrderCandidateId> getDDOrderCandidateIds() { return list.stream() .map(DDOrderCandidateAlloc::getDdOrderCandidateId) .collect(ImmutableSet.toImmutableSet()); } public Set<DDOrderId> getDDOrderIds() { return list.stream().map(DDOrderCandidateAlloc::getDdOrderId).collect(ImmutableSet.toImmutableSet()); } public Set<DDOrderLineId> getDDOrderLineIds() { return list.stream().map(DDOrderCandidateAlloc::getDdOrderLineId).collect(ImmutableSet.toImmutableSet()); } @Override @NonNull public Iterator<DDOrderCandidateAlloc> iterator() {
return list.iterator(); } public Map<DDOrderCandidateId, DDOrderCandidateAllocList> groupByCandidateId() { if (list.isEmpty()) { return ImmutableMap.of(); } return list.stream().collect(Collectors.groupingBy(DDOrderCandidateAlloc::getDdOrderCandidateId, collect())); } public Optional<Quantity> getQtySum() { return list.stream() .map(DDOrderCandidateAlloc::getQty) .reduce(Quantity::add); } public Set<Integer> getIds() { if (list.isEmpty()) { return ImmutableSet.of(); } return list.stream() .map(DDOrderCandidateAlloc::getId) .filter(id -> id > 0) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddordercandidate\DDOrderCandidateAllocList.java
1
请在Spring Boot框架中完成以下Java代码
public ResponseEntity<String> usingResponseEntityConstructor() { HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("Baeldung-Example-Header", "Value-ResponseEntityContructor"); String responseBody = "Response with header using ResponseEntity (constructor)"; HttpStatus responseStatus = HttpStatus.OK; return new ResponseEntity<String>(responseBody, responseHeaders, responseStatus); } @GetMapping("/response-entity-contructor-multiple-headers") public ResponseEntity<String> usingResponseEntityConstructorAndMultipleHeaders() { List<MediaType> acceptableMediaTypes = new ArrayList<>(Arrays.asList(MediaType.APPLICATION_JSON)); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("Baeldung-Example-Header", "Value-ResponseEntityConstructorAndHeaders"); responseHeaders.setAccept(acceptableMediaTypes); String responseBody = "Response with header using ResponseEntity (constructor)"; HttpStatus responseStatus = HttpStatus.OK; return new ResponseEntity<String>(responseBody, responseHeaders, responseStatus); } @GetMapping("/response-entity-builder") public ResponseEntity<String> usingResponseEntityBuilder() { String responseHeaderKey = "Baeldung-Example-Header"; String responseHeaderValue = "Value-ResponseEntityBuilder"; String responseBody = "Response with header using ResponseEntity (builder)";
return ResponseEntity.ok() .header(responseHeaderKey, responseHeaderValue) .body(responseBody); } @GetMapping("/response-entity-builder-with-http-headers") public ResponseEntity<String> usingResponseEntityBuilderAndHttpHeaders() { HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("Baeldung-Example-Header", "Value-ResponseEntityBuilderWithHttpHeaders"); String responseBody = "Response with header using ResponseEntity (builder)"; return ResponseEntity.ok() .headers(responseHeaders) .body(responseBody); } }
repos\tutorials-master\spring-web-modules\spring-rest-http\src\main\java\com\baeldung\responseheaders\controllers\ResponseHeaderController.java
2
请完成以下Java代码
private int hashNode(int id) { int hashValue = 0; for (; id != 0; id = _nodes.get(id).sibling) { int unit = _nodes.get(id).unit(); byte label = _nodes.get(id).label; hashValue ^= hash(((label & 0xFF) << 24) ^ unit); } return hashValue; } private int appendUnit() { _isIntersections.append(); _units.add(0); _labels.add((byte) 0); return _isIntersections.size() - 1; } private int appendNode() { int id; if (_recycleBin.empty()) { id = _nodes.size(); _nodes.add(new DawgNode()); } else { id = _recycleBin.get(_recycleBin.size() - 1); _nodes.get(id).reset(); _recycleBin.deleteLast();
} return id; } private void freeNode(int id) { _recycleBin.add(id); } private static int hash(int key) { key = ~key + (key << 15); // key = (key << 15) - key - 1; key = key ^ (key >>> 12); key = key + (key << 2); key = key ^ (key >>> 4); key = key * 2057; // key = (key + (key << 3)) + (key << 11); key = key ^ (key >>> 16); return key; } private static final int INITIAL_TABLE_SIZE = 1 << 10; private ArrayList<DawgNode> _nodes = new ArrayList<DawgNode>(); private AutoIntPool _units = new AutoIntPool(); private AutoBytePool _labels = new AutoBytePool(); private BitVector _isIntersections = new BitVector(); private AutoIntPool _table = new AutoIntPool(); private AutoIntPool _nodeStack = new AutoIntPool(); private AutoIntPool _recycleBin = new AutoIntPool(); private int _numStates; }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\DawgBuilder.java
1
请完成以下Java代码
public boolean equals(Object obj) { if ((obj == null) || (obj.getClass() != this.getClass())) return false; if (obj == this) return true; Campus other = (Campus) obj; return this.hashCode() == other.hashCode(); } @SuppressWarnings("unused") private Campus() { } public Campus(Builder b) { this.id = b.id; this.name = b.name; this.location = b.location; } public static class Builder { private String id; private String name; private Point location; public static Builder newInstance() { return new Builder(); } public Campus build() { return new Campus(this); } public Builder id(String id) {
this.id = id; return this; } public Builder name(String name) { this.name = name; return this; } public Builder location(Point location) { this.location = location; return this; } } }
repos\tutorials-master\persistence-modules\spring-data-couchbase-2\src\main\java\com\baeldung\spring\data\couchbase\model\Campus.java
1
请完成以下Java代码
public void setLastProcessed (final @Nullable java.sql.Timestamp LastProcessed) { set_Value (COLUMNNAME_LastProcessed, LastProcessed); } @Override public java.sql.Timestamp getLastProcessed() { return get_ValueAsTimestamp(COLUMNNAME_LastProcessed); } @Override public de.metas.async.model.I_C_Queue_WorkPackage getLastProcessed_WorkPackage() { return get_ValueAsPO(COLUMNNAME_LastProcessed_WorkPackage_ID, de.metas.async.model.I_C_Queue_WorkPackage.class); } @Override public void setLastProcessed_WorkPackage(final de.metas.async.model.I_C_Queue_WorkPackage LastProcessed_WorkPackage) { set_ValueFromPO(COLUMNNAME_LastProcessed_WorkPackage_ID, de.metas.async.model.I_C_Queue_WorkPackage.class, LastProcessed_WorkPackage); } @Override public void setLastProcessed_WorkPackage_ID (final int LastProcessed_WorkPackage_ID) { if (LastProcessed_WorkPackage_ID < 1) set_Value (COLUMNNAME_LastProcessed_WorkPackage_ID, null); else set_Value (COLUMNNAME_LastProcessed_WorkPackage_ID, LastProcessed_WorkPackage_ID); } @Override public int getLastProcessed_WorkPackage_ID() { return get_ValueAsInt(COLUMNNAME_LastProcessed_WorkPackage_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public de.metas.async.model.I_C_Async_Batch getParent_Async_Batch() { return get_ValueAsPO(COLUMNNAME_Parent_Async_Batch_ID, de.metas.async.model.I_C_Async_Batch.class); } @Override public void setParent_Async_Batch(final de.metas.async.model.I_C_Async_Batch Parent_Async_Batch)
{ set_ValueFromPO(COLUMNNAME_Parent_Async_Batch_ID, de.metas.async.model.I_C_Async_Batch.class, Parent_Async_Batch); } @Override public void setParent_Async_Batch_ID (final int Parent_Async_Batch_ID) { if (Parent_Async_Batch_ID < 1) set_Value (COLUMNNAME_Parent_Async_Batch_ID, null); else set_Value (COLUMNNAME_Parent_Async_Batch_ID, Parent_Async_Batch_ID); } @Override public int getParent_Async_Batch_ID() { return get_ValueAsInt(COLUMNNAME_Parent_Async_Batch_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Async_Batch.java
1
请完成以下Java代码
public List<Object> getContent() { if (content == null) { content = new ArrayList<Object>(); } return this.content; } /** * Gets the value of the algorithm property. * * @return * possible object is * {@link String } * */ public String getAlgorithm() {
return algorithm; } /** * Sets the value of the algorithm property. * * @param value * allowed object is * {@link String } * */ public void setAlgorithm(String value) { this.algorithm = 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\AgreementMethodType.java
1
请完成以下Java代码
protected String doIt() throws Exception { ppOrderCandidateService.setDateStartSchedule(getSelectedPPOrderCandidateIds(), convertParamsToTimestamp()); return MSG_OK; } @ProcessParamLookupValuesProvider(parameterName = PARAM_Hour, numericKey = false, lookupSource = DocumentLayoutElementFieldDescriptor.LookupSource.list) private LookupValuesList hourLookupProvider() { return LookupValuesList.fromCollection( IntStream.range(0, 24) .mapToObj(this::toStringLookupValue) .collect(ImmutableList.toImmutableList()) ); } @ProcessParamLookupValuesProvider(parameterName = PARAM_Minute, numericKey = false, lookupSource = DocumentLayoutElementFieldDescriptor.LookupSource.list) private LookupValuesList minuteLookupProvider() { final ResourcePlanningPrecision precision = ppOrderCandidateService.getResourcePlanningPrecision(); final ImmutableSet<LookupValue.StringLookupValue> minutes = precision.getMinutes() .stream() .map(this::toStringLookupValue) .collect(ImmutableSet.toImmutableSet()); return LookupValuesList.fromCollection(minutes); } private ImmutableSet<PPOrderCandidateId> getSelectedPPOrderCandidateIds() { final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); if (selectedRowIds.isAll()) { return getView().streamByIds(selectedRowIds) .limit(rowsLimit) .map(PP_Order_Candidate_SetStartDate::extractPPOrderCandidateId) .collect(ImmutableSet.toImmutableSet()); } else { return selectedRowIds.stream() .map(PP_Order_Candidate_SetStartDate::toPPOrderCandidateId)
.collect(ImmutableSet.toImmutableSet()); } } @NonNull private Timestamp convertParamsToTimestamp() { return Timestamp.valueOf(TimeUtil.asLocalDate(p_Date) .atTime(Integer.parseInt(p_Hour), Integer.parseInt(p_Minute))); } @NonNull private LookupValue.StringLookupValue toStringLookupValue(final int value) { final String formattedValue = String.format("%02d", value); return LookupValue.StringLookupValue.of(formattedValue, formattedValue); } @NonNull private static PPOrderCandidateId extractPPOrderCandidateId(final IViewRow row) {return toPPOrderCandidateId(row.getId());} @NonNull private static PPOrderCandidateId toPPOrderCandidateId(final DocumentId rowId) {return PPOrderCandidateId.ofRepoId(rowId.toInt());} }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.webui\src\main\java\de\metas\manufacturing\webui\process\PP_Order_Candidate_SetStartDate.java
1
请完成以下Java代码
public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Target URL. @param TargetURL URL for the Target */ public void setTargetURL (String TargetURL) { set_Value (COLUMNNAME_TargetURL, TargetURL); } /** Get Target URL. @return URL for the Target */ public String getTargetURL () { return (String)get_Value(COLUMNNAME_TargetURL); } /** Set Click Count.
@param W_ClickCount_ID Web Click Management */ public void setW_ClickCount_ID (int W_ClickCount_ID) { if (W_ClickCount_ID < 1) set_ValueNoCheck (COLUMNNAME_W_ClickCount_ID, null); else set_ValueNoCheck (COLUMNNAME_W_ClickCount_ID, Integer.valueOf(W_ClickCount_ID)); } /** Get Click Count. @return Web Click Management */ public int getW_ClickCount_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_ClickCount_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_ClickCount.java
1
请完成以下Java代码
public class RoleGroup { @Getter private final String name; private static final ConcurrentHashMap<String, RoleGroup> cache = new ConcurrentHashMap<>(); private RoleGroup(@NonNull final String name) { this.name = name; } @Nullable public static RoleGroup ofNullableString(@Nullable final String name) { final String nameNorm = StringUtils.trimBlankToNull(name);
if (nameNorm == null) { return null; } return cache.computeIfAbsent(name, RoleGroup::new); } @Override @Deprecated public String toString() { return getName(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\RoleGroup.java
1
请在Spring Boot框架中完成以下Java代码
public ResolveHUResponse resolveHU(@NonNull final ResolveHURequest request) { return newHUScannedCodeResolveCommand() .scannedCode(request.getScannedCode()) .inventory(getById(request.getWfProcessId(), request.getCallerId())) .lineId(request.getLineId()) .locatorId(request.getLocatorId()) .build() .execute(); } private ResolveHUCommandBuilder newHUScannedCodeResolveCommand() { return ResolveHUCommand.builder() .productService(productService) .huService(huService); } public Inventory reportCounting(@NonNull final JsonCountRequest request, final UserId callerId) { final InventoryId inventoryId = toInventoryId(request.getWfProcessId());
return inventoryService.updateById(inventoryId, inventory -> { inventory.assertHasAccess(callerId); return inventory.updatingLineById(request.getLineId(), line -> { // TODO handle the case when huId is null final Quantity qtyBook = huService.getQty(request.getHuId(), line.getProductId()); final Quantity qtyCount = Quantity.of(request.getQtyCount(), qtyBook.getUOM()); return line.withCounting(InventoryLineCountRequest.builder() .huId(request.getHuId()) .scannedCode(request.getScannedCode()) .qtyBook(qtyBook) .qtyCount(qtyCount) .asiId(productService.createASI(line.getProductId(), request.getAttributesAsMap())) .build()); }); }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\job\service\InventoryJobService.java
2
请完成以下Java代码
public EmployerAddressType getEmployer() { return employer; } /** * Sets the value of the employer property. * * @param value * allowed object is * {@link EmployerAddressType } * */ public void setEmployer(EmployerAddressType value) { this.employer = value; } /** * Gets the value of the balance property. * * @return * possible object is * {@link BalanceTGType } * */ public BalanceTGType getBalance() { return balance; } /** * Sets the value of the balance property. * * @param value * allowed object is
* {@link BalanceTGType } * */ public void setBalance(BalanceTGType value) { this.balance = value; } /** * Gets the value of the paymentPeriod property. * * @return * possible object is * {@link Duration } * */ public Duration getPaymentPeriod() { return paymentPeriod; } /** * Sets the value of the paymentPeriod property. * * @param value * allowed object is * {@link Duration } * */ public void setPaymentPeriod(Duration value) { this.paymentPeriod = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\request\GarantType.java
1
请完成以下Java代码
public void onCR_TaxAmt(final I_GL_JournalLine glJournalLine) { final ITaxAccountable taxAccountable = asTaxAccountable(glJournalLine, ACCTSIGN_Credit); taxAccountableCallout.onTaxAmt(taxAccountable); } @CalloutMethod(columnNames = I_GL_JournalLine.COLUMNNAME_DR_TaxTotalAmt) public void onDR_TaxTotalAmt(final I_GL_JournalLine glJournalLine) { final ITaxAccountable taxAccountable = asTaxAccountable(glJournalLine, ACCTSIGN_Debit); taxAccountableCallout.onTaxTotalAmt(taxAccountable); } @CalloutMethod(columnNames = I_GL_JournalLine.COLUMNNAME_CR_TaxTotalAmt) public void onCR_TaxTotalAmt(final I_GL_JournalLine glJournalLine) { final ITaxAccountable taxAccountable = asTaxAccountable(glJournalLine, ACCTSIGN_Credit); taxAccountableCallout.onTaxTotalAmt(taxAccountable); } private void setAutoTaxType(final I_GL_JournalLine glJournalLine) { final boolean drAutoTax = isAutoTaxAccount(glJournalLine.getAccount_DR()); final boolean crAutoTax = isAutoTaxAccount(glJournalLine.getAccount_CR()); // // We can activate tax accounting only for one side if (drAutoTax && crAutoTax) { throw new AdempiereException("@" + MSG_AutoTaxAccountDrCrNotAllowed + "@"); } final boolean taxRecord = drAutoTax || crAutoTax; // // Tax accounting can be allowed only if in a new transaction final boolean isPartialTrx = !glJournalLine.isAllowAccountDR() || !glJournalLine.isAllowAccountCR(); if (taxRecord && isPartialTrx) { throw new AdempiereException("@" + MSG_AutoTaxNotAllowedOnPartialTrx + "@"); } // // Set AutoTaxaAcount flags
glJournalLine.setDR_AutoTaxAccount(drAutoTax); glJournalLine.setCR_AutoTaxAccount(crAutoTax); // // Update journal line type final String type = taxRecord ? X_GL_JournalLine.TYPE_Tax : X_GL_JournalLine.TYPE_Normal; glJournalLine.setType(type); } private ITaxAccountable asTaxAccountable(final I_GL_JournalLine glJournalLine, final boolean accountSignDR) { final IGLJournalLineBL glJournalLineBL = Services.get(IGLJournalLineBL.class); return glJournalLineBL.asTaxAccountable(glJournalLine, accountSignDR); } private boolean isAutoTaxAccount(final I_C_ValidCombination accountVC) { if (accountVC == null) { return false; } final I_C_ElementValue account = accountVC.getAccount(); if (account == null) { return false; } return account.isAutoTaxAccount(); } private boolean isAutoTax(final I_GL_JournalLine glJournalLine) { return glJournalLine.isDR_AutoTaxAccount() || glJournalLine.isCR_AutoTaxAccount(); } @Nullable private AccountConceptualName suggestAccountConceptualName(@NonNull final AccountId accountId) { final ElementValueId elementValueId = accountDAO.getElementValueIdByAccountId(accountId); final ElementValue elementValue = elementValueRepository.getById(elementValueId); return elementValue.getAccountConceptualName(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\callout\GL_JournalLine.java
1
请完成以下Java代码
public Object getValue(ELContext context, Object base, Object property) { context.setPropertyResolved(false); ELResolver delegate = getElResolverDelegate(); if(delegate == null) { return null; } else { return delegate.getValue(context, base, property); } } public boolean isReadOnly(ELContext context, Object base, Object property) { context.setPropertyResolved(false); ELResolver delegate = getElResolverDelegate(); if(delegate == null) { return true; } else { return delegate.isReadOnly(context, base, property); } } public void setValue(ELContext context, Object base, Object property, Object value) { context.setPropertyResolved(false);
ELResolver delegate = getElResolverDelegate(); if(delegate != null) { delegate.setValue(context, base, property, value); } } public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) { context.setPropertyResolved(false); ELResolver delegate = getElResolverDelegate(); if(delegate == null) { return null; } else { return delegate.invoke(context, base, method, paramTypes, params); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\el\AbstractElResolverDelegate.java
1
请完成以下Java代码
public void deleteDeployment(String deploymentId) { repositoryService.deleteDeployment(deploymentId); } @ManagedOperation(description = "Suspend given process ID") public void suspendProcessDefinitionById(String processId) { repositoryService.suspendProcessDefinitionById(processId); } @ManagedOperation(description = "Activate given process ID") public void activatedProcessDefinitionById(String processId) { repositoryService.activateProcessDefinitionById(processId); } @ManagedOperation(description = "Suspend given process ID")
public void suspendProcessDefinitionByKey(String processDefinitionKey) { repositoryService.suspendProcessDefinitionByKey(processDefinitionKey); } @ManagedOperation(description = "Activate given process ID") public void activatedProcessDefinitionByKey(String processDefinitionKey) { repositoryService.activateProcessDefinitionByKey(processDefinitionKey); } @ManagedOperation(description = "Deploy Process Definition") public void deployProcessDefinition(String resourceName, String processDefinitionFile) throws FileNotFoundException { DeploymentBuilder deploymentBuilder = repositoryService.createDeployment(); Deployment deployment = deploymentBuilder.addInputStream(resourceName, new FileInputStream(processDefinitionFile)).deploy(); } }
repos\flowable-engine-main\modules\flowable-jmx\src\main\java\org\flowable\management\jmx\mbeans\ProcessDefinitionsMBean.java
1
请完成以下Java代码
public void setHistoryConfiguration(String historyConfiguration) { this.historyConfiguration = historyConfiguration; } public String getIncidentMessage() { return incidentMessage; } public void setIncidentMessage(String incidentMessage) { this.incidentMessage = incidentMessage; } public void setIncidentState(int incidentState) { this.incidentState = incidentState; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getJobDefinitionId() { return jobDefinitionId; } public void setJobDefinitionId(String jobDefinitionId) { this.jobDefinitionId = jobDefinitionId; } public boolean isOpen() { return IncidentState.DEFAULT.getStateCode() == incidentState; } public boolean isDeleted() { return IncidentState.DELETED.getStateCode() == incidentState; }
public boolean isResolved() { return IncidentState.RESOLVED.getStateCode() == incidentState; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public String getFailedActivityId() { return failedActivityId; } public void setFailedActivityId(String failedActivityId) { this.failedActivityId = failedActivityId; } public String getAnnotation() { return annotation; } public void setAnnotation(String annotation) { this.annotation = annotation; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricIncidentEventEntity.java
1
请在Spring Boot框架中完成以下Java代码
public class PrimaryConfig { @Autowired private JpaProperties jpaProperties; @Autowired @Qualifier("primaryDataSource") private DataSource primaryDataSource; @Bean(name = "entityManagerPrimary") @Primary public EntityManager entityManager(EntityManagerFactoryBuilder builder) { return entityManagerFactoryPrimary(builder).getObject().createEntityManager(); } @Bean(name = "entityManagerFactoryPrimary") @Primary public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) { return builder .dataSource(primaryDataSource)
.properties(getVendorProperties(primaryDataSource)) .packages("com.neo.domain") //设置实体类所在位置 .persistenceUnit("primaryPersistenceUnit") .build(); } private Map<String, String> getVendorProperties(DataSource dataSource) { return jpaProperties.getHibernateProperties(dataSource); } @Bean(name = "transactionManagerPrimary") @Primary PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) { return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject()); } }
repos\spring-boot-leaning-master\1.x\第04课:Spring Data Jpa 的使用\spring-boot-multi-Jpa\src\main\java\com\neo\config\PrimaryConfig.java
2
请完成以下Java代码
private CampaignPriceProvider createCampaignPriceProvider(@NonNull final Order order) { if (!order.getSoTrx().isSales()) { return CampaignPriceProviders.none(); } if (order.getCountryId() == null) { return CampaignPriceProviders.none(); } if (!bpartnersRepo.isCampaignPriceAllowed(order.getBpartnerId())) { return CampaignPriceProviders.none(); } final BPGroupId bpGroupId = bpartnersRepo.getBPGroupIdByBPartnerId(order.getBpartnerId()); return CampaignPriceProviders.standard() .campaignPriceService(campaignPriceService) .bpartnerId(order.getBpartnerId()) .bpGroupId(bpGroupId) .pricingSystemId(order.getPricingSystemId()) .countryId(order.getCountryId()) .currencyId(order.getCurrency().getId()) .date(TimeUtil.asLocalDate(order.getDatePromised())) .build(); } @Override protected List<RelatedProcessDescriptor> getRelatedProcessDescriptors()
{ return ImmutableList.of( createProcessDescriptor(WEBUI_ProductsProposal_SaveProductPriceToCurrentPriceListVersion.class), createProcessDescriptor(WEBUI_ProductsProposal_ShowProductsToAddFromBasePriceList.class), createProcessDescriptor(WEBUI_ProductsProposal_ShowProductsSoldToOtherCustomers.class), createProcessDescriptor(WEBUI_ProductsProposal_Delete.class)); } @Override protected void beforeViewClose(@NonNull final ViewId viewId, @NonNull final ViewCloseAction closeAction) { if (ViewCloseAction.DONE.equals(closeAction)) { final ProductsProposalView view = getById(viewId); if (view.getOrderId() != null) { createOrderLines(view); } } } private void createOrderLines(final ProductsProposalView view) { OrderLinesFromProductProposalsProducer.builder() .orderId(view.getOrderId().get()) .rows(view.getAllRows()) .build() .produce(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\view\OrderProductsProposalViewFactory.java
1
请完成以下Java代码
private void enqueueChunk(final Collection<DocumentToRepost> documentsToRepost) { FactAcctRepostCommand.builder() .documentsToRepost(documentsToRepost) .forcePosting(forcePosting) .onErrorNotifyUserId(getUserId()) .build() .execute(); } private Stream<DocumentToRepost> streamDocumentsToRepost() { return getView().streamByIds(getSelectedRowIds(), QueryLimit.NO_LIMIT) .map(this::extractDocumentToRepost); } private DocumentToRepost extractDocumentToRepost(@NonNull final IViewRow row) { final String tableName = getTableName(); if (I_Fact_Acct.Table_Name.equals(tableName) || FactAcctFilterDescriptorsProviderFactory.FACT_ACCT_TRANSACTIONS_VIEW.equals(tableName) || TABLENAME_RV_UnPosted.equals(tableName)) { return extractDocumentToRepostFromTableAndRecordIdRow(row); } else { return extractDocumentToRepostFromRegularRow(row); } } private DocumentToRepost extractDocumentToRepostFromTableAndRecordIdRow(final IViewRow row) { final int adTableId = row.getFieldValueAsInt(I_Fact_Acct.COLUMNNAME_AD_Table_ID, -1); final int recordId = row.getFieldValueAsInt(I_Fact_Acct.COLUMNNAME_Record_ID, -1); final ClientId adClientId = ClientId.ofRepoId(row.getFieldValueAsInt(I_Fact_Acct.COLUMNNAME_AD_Client_ID, -1)); return DocumentToRepost.builder() .adTableId(adTableId)
.recordId(recordId) .clientId(adClientId) .build(); } private DocumentToRepost extractDocumentToRepostFromRegularRow(final IViewRow row) { final int adTableId = adTablesRepo.retrieveTableId(getTableName()); final int recordId = row.getId().toInt(); final ClientId adClientId = ClientId.ofRepoId(row.getFieldValueAsInt(I_Fact_Acct.COLUMNNAME_AD_Client_ID, -1)); return DocumentToRepost.builder() .adTableId(adTableId) .recordId(recordId) .clientId(adClientId) .build(); } @Override protected void postProcess(final boolean success) { getView().invalidateSelection(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\accounting\process\WEBUI_Fact_Acct_Repost_ViewRows.java
1
请完成以下Java代码
public Object getValue(ELContext context, Object base, Object property) { if (base == null) { if (wrappedMap.containsKey(property)) { context.setPropertyResolved(true); return wrappedMap.get(property); } } return null; } @Override public boolean isReadOnly(ELContext context, Object base, Object property) { return true; } @Override public void setValue(ELContext context, Object base, Object property, Object value) { if (base == null) {
if (wrappedMap.containsKey(property)) { throw new FlowableException("Cannot set value of '" + property + "', it's readonly!"); } } } @Override public Class<?> getCommonPropertyType(ELContext context, Object arg) { return Object.class; } @Override public Class<?> getType(ELContext context, Object arg1, Object arg2) { return Object.class; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\el\ReadOnlyMapELResolver.java
1
请完成以下Spring Boot application配置
spring: application: name: Main-APP mvc: static-path-pattern: /static/** jooq: sql-dialect: MySQL liquibase: enabled: true change-log: classpath:/liquibase/master.xml jpa: open-in-view: false hibernate: ddl-auto: none # we use liquibase generate_statistics: true naming: physical-strategy: gt.app.hibernate.PrefixedNamingStrategy implicit-strategy: org.springframework.boot.hibernate.SpringImplicitNamingStrategy datasource: url: jdbc:mysql://${MYSQL_HOST:localhost}:${MYSQL_PORT:3306}/${MYSQL_DB:seedapp}?useUnicode=true&allowPublicKeyRetrieval=true username: ${MYSQL_USERNAME:root} password: ${MYSQL_PASSWORD:password} artemis: user: ${ACTIVEMQ_ARTEMIS_USER:admin} password: ${ACTIVEMQ_ARTEMIS_PASSWORD:admin} broker-url: tcp://${ACTIVEMQ_ARTEMIS_HOST:localhost}:${ACTIVEMQ_ARTEMIS_PORT:61616} cloud: openfeign: micrometer: enabled: true security: oauth2: client: # we are using authorization code flow (login within keycloak app web ui) provider: oidc: # use http://localhost:8080/realms/articleapp/.well-known/openid-configuration to get config from keycloak issuer-uri: http://${KEYCLOAK_HOST:localhost}:${KEYCLOAK_PORT:8080}/realms/seedapp registration: oidc: # authorization-grant-type: refresh_token client-id: seed-app-gateway-client client-secret: secret123 scope: openid, profile, email, offline_access # last one for refresh tokens # we can have multiple auth providers server: port: 8081 logging: level: security: INFO web: INFO cloud: INFO sql: INFO ROOT: INFO gt: TRACE # 'org.springframework.web.socket': TRACE feign-clients: email-service: url: http://${EMAIL_SERVICE_HOST:localhost}:${EMAIL_SERVICE_PORT:8085}/ #TODO: use service discovery report-service: url: http://${REPORT_SERVICE_HOST:localhost}:${REPORT_SERVICE_PORT:8086}/ #TODO: use service discovery app-properties: jms: content-checkerrequest-queue: jms-content-checker-requestqueue content-checkercallback-response-queue: jms-content-checkercallback-responsequeue file-storage: upload-folder: ${java.io.tmpdir}/uploads web: base-url: http://localhost:${server.port} wro4j: jmx-enabled: false debug: true manager-fact
ory: post-processors: cssVariables,cssMinJawr,jsMin pre-processors: cssUrlRewriting,cssImport,semicolonAppender,removeSourceMaps,singlelineStripper filter-url: /wro4j # this is the default, needs to be used in secConfig and the htmls # https://github.com/gavlyukovskiy/spring-boot-data-source-decorator # note that both `jdbc.datasource-proxy` and `decorator.datasource` cannot be enabled at same time due to bean name conflict decorator: datasource: enabled: true # disabled for now flexy-pool: threshold: connection: lease: 0 acquisition: -1 datasource-proxy: slow-query: threshold: 1 # 1 second is slow query: log-level: INFO # https://github.com/jdbc-observations/datasource-micrometer jdbc: datasource-proxy: enabled: false management: tracing: sampling: probability: 1.0 zipkin: export: tracing: endpoint: http://${ZIPKIN_HOST:localhost}:${ZIPKIN_PORT:9411}/api/v2/spans health: jms: enabled: true
repos\spring-boot-web-application-sample-master\main-app\main-webapp\src\main\resources\application.yml
2
请完成以下Java代码
public class UserNotificationSettings { @NotNull @Valid private final Map<NotificationType, NotificationPref> prefs; public static final UserNotificationSettings DEFAULT = new UserNotificationSettings(Collections.emptyMap()); public static final Set<NotificationDeliveryMethod> deliveryMethods = NotificationTargetType.PLATFORM_USERS.getSupportedDeliveryMethods(); @JsonCreator public UserNotificationSettings(@JsonProperty("prefs") Map<NotificationType, NotificationPref> prefs) { this.prefs = prefs; } public boolean isEnabled(NotificationType notificationType, NotificationDeliveryMethod deliveryMethod) { NotificationPref pref = prefs.get(notificationType); if (pref == null) { return true; } if (!pref.isEnabled()) { return false; } return pref.getEnabledDeliveryMethods().getOrDefault(deliveryMethod, true);
} @Data public static class NotificationPref { private boolean enabled; @NotNull private Map<NotificationDeliveryMethod, Boolean> enabledDeliveryMethods; public static NotificationPref createDefault() { NotificationPref pref = new NotificationPref(); pref.setEnabled(true); pref.setEnabledDeliveryMethods(deliveryMethods.stream().collect(Collectors.toMap(v -> v, v -> true))); return pref; } @JsonIgnore @AssertTrue(message = "Only email, Web and SMS delivery methods are allowed") public boolean isValid() { return enabledDeliveryMethods.entrySet().stream() .allMatch(entry -> deliveryMethods.contains(entry.getKey()) && entry.getValue() != null); } } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\notification\settings\UserNotificationSettings.java
1
请在Spring Boot框架中完成以下Java代码
public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(unique = true) private String username; @Column private String password; @Column(unique = true) private String email; @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_name")) private Set<Role> roles = new HashSet<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; }
public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Set<Role> getRoles() { return roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } public void addRole(Role role) { roles.add(role); } public void removeRole(Role role) { roles.remove(role); } }
repos\tutorials-master\quarkus-modules\quarkus-rbac\src\main\java\com\baeldung\quarkus\rbac\users\User.java
2
请完成以下Java代码
public void appendStructure(StringBuilder builder, Bindings bindings) { parameters.appendStructure(builder, bindings); builder.append(" -> "); body.appendStructure(builder, bindings); } @Override public Object eval(Bindings bindings, ELContext context) { // Create a ValueExpression from the body ValueExpression bodyExpression = new LambdaBodyValueExpression(bindings, body); // Create and return a LambdaExpression LambdaExpression lambda = new LambdaExpression(parameters.getParameterNames(), bodyExpression); lambda.setELContext(context); return lambda; } @Override public int getCardinality() { return 2; } @Override public AstNode getChild(int i) { return i == 0 ? parameters : i == 1 ? body : null; } @Override public String toString() { return parameters.toString() + " -> " + body.toString(); } /** * Simple ValueExpression implementation that wraps an AstNode for lambda body evaluation. */ private static class LambdaBodyValueExpression extends ValueExpression { private final Bindings bindings; private final AstNode body; public LambdaBodyValueExpression(Bindings bindings, AstNode body) { this.bindings = bindings; this.body = body; } @Override public Object getValue(ELContext context) throws ELException { return body.eval(bindings, context); } @Override public void setValue(ELContext context, Object value) throws ELException { throw new ELException("Lambda body is not an lvalue"); } @Override public boolean isReadOnly(ELContext context) throws ELException { return true; } @Override public Class<?> getType(ELContext context) throws ELException { return Object.class; } @Override public Class<?> getExpectedType() { return Object.class; }
@Override public String getExpressionString() { return body.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof LambdaBodyValueExpression)) return false; LambdaBodyValueExpression other = (LambdaBodyValueExpression) obj; return body.equals(other.body) && bindings.equals(other.bindings); } @Override public int hashCode() { return body.hashCode() * 31 + bindings.hashCode(); } @Override public boolean isLiteralText() { return false; } @Override public ValueReference getValueReference(ELContext context) { return null; } } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\de\odysseus\el\tree\impl\ast\AstLambdaExpression.java
1
请在Spring Boot框架中完成以下Java代码
public class BaseCaseDefinitionResource { @Autowired protected CmmnRestResponseFactory restResponseFactory; @Autowired protected CmmnRepositoryService repositoryService; @Autowired(required=false) protected CmmnRestApiInterceptor restApiInterceptor; /** * Returns the {@link CaseDefinition} that is requested and calls the access interceptor. * Throws the right exceptions when bad request was made or definition was not found. */ protected CaseDefinition getCaseDefinitionFromRequest(String caseDefinitionId) { CaseDefinition caseDefinition = getCaseDefinitionFromRequestWithoutAccessCheck(caseDefinitionId); if (restApiInterceptor != null) { restApiInterceptor.accessCaseDefinitionById(caseDefinition); } return caseDefinition;
} /** * Returns the {@link CaseDefinition} that is requested without calling the access interceptor * Throws the right exceptions when bad request was made or definition was not found. */ protected CaseDefinition getCaseDefinitionFromRequestWithoutAccessCheck(String caseDefinitionId) { CaseDefinition caseDefinition = repositoryService.getCaseDefinition(caseDefinitionId); if (caseDefinition == null) { throw new FlowableObjectNotFoundException("Could not find a case definition with id '" + caseDefinitionId + "'.", CaseDefinition.class); } return caseDefinition; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\BaseCaseDefinitionResource.java
2
请完成以下Java代码
public void createTenant(TenantDto dto) { if (getIdentityService().isReadOnly()) { throw new InvalidRequestException(Status.FORBIDDEN, "Identity service implementation is read-only."); } Tenant newTenant = getIdentityService().newTenant(dto.getId()); dto.update(newTenant); getIdentityService().saveTenant(newTenant); } @Override public ResourceOptionsDto availableOperations(UriInfo context) { UriBuilder baseUriBuilder = context.getBaseUriBuilder() .path(relativeRootResourcePath) .path(TenantRestService.PATH); ResourceOptionsDto resourceOptionsDto = new ResourceOptionsDto(); // GET / URI baseUri = baseUriBuilder.build(); resourceOptionsDto.addReflexiveLink(baseUri, HttpMethod.GET, "list");
// GET /count URI countUri = baseUriBuilder.clone().path("/count").build(); resourceOptionsDto.addReflexiveLink(countUri, HttpMethod.GET, "count"); // POST /create if (!getIdentityService().isReadOnly() && isAuthorized(CREATE)) { URI createUri = baseUriBuilder.clone().path("/create").build(); resourceOptionsDto.addReflexiveLink(createUri, HttpMethod.POST, "create"); } return resourceOptionsDto; } protected IdentityService getIdentityService() { return getProcessEngine().getIdentityService(); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\TenantRestServiceImpl.java
1
请完成以下Java代码
public void setDefaultAsyncJobAcquireWaitTimeInMillis(int defaultAsyncJobAcquireWaitTimeInMillis) { this.defaultAsyncJobAcquireWaitTimeInMillis = defaultAsyncJobAcquireWaitTimeInMillis; } public void setTimerJobRunnable(AcquireTimerJobsRunnable timerJobRunnable) { this.timerJobRunnable = timerJobRunnable; } public int getDefaultQueueSizeFullWaitTimeInMillis() { return defaultQueueSizeFullWaitTime; } public void setDefaultQueueSizeFullWaitTimeInMillis(int defaultQueueSizeFullWaitTime) { this.defaultQueueSizeFullWaitTime = defaultQueueSizeFullWaitTime; } public void setAsyncJobsDueRunnable(AcquireAsyncJobsDueRunnable asyncJobsDueRunnable) { this.asyncJobsDueRunnable = asyncJobsDueRunnable; } public void setResetExpiredJobsRunnable(ResetExpiredJobsRunnable resetExpiredJobsRunnable) { this.resetExpiredJobsRunnable = resetExpiredJobsRunnable; } public int getRetryWaitTimeInMillis() { return retryWaitTimeInMillis; } public void setRetryWaitTimeInMillis(int retryWaitTimeInMillis) { this.retryWaitTimeInMillis = retryWaitTimeInMillis; }
public int getResetExpiredJobsInterval() { return resetExpiredJobsInterval; } public void setResetExpiredJobsInterval(int resetExpiredJobsInterval) { this.resetExpiredJobsInterval = resetExpiredJobsInterval; } public int getResetExpiredJobsPageSize() { return resetExpiredJobsPageSize; } public void setResetExpiredJobsPageSize(int resetExpiredJobsPageSize) { this.resetExpiredJobsPageSize = resetExpiredJobsPageSize; } public ExecuteAsyncRunnableFactory getExecuteAsyncRunnableFactory() { return executeAsyncRunnableFactory; } public void setExecuteAsyncRunnableFactory(ExecuteAsyncRunnableFactory executeAsyncRunnableFactory) { this.executeAsyncRunnableFactory = executeAsyncRunnableFactory; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\asyncexecutor\DefaultAsyncJobExecutor.java
1
请在Spring Boot框架中完成以下Java代码
public InMemoryUserDetailsManager createUserDetailsManager() { UserDetails userDetails1 = createNewUser("in28minutes", "dummy"); UserDetails userDetails2 = createNewUser("ranga", "dummydummy"); return new InMemoryUserDetailsManager(userDetails1, userDetails2); } private UserDetails createNewUser(String username, String password) { Function<String, String> passwordEncoder = input -> passwordEncoder().encode(input); UserDetails userDetails = User.builder() .passwordEncoder(passwordEncoder) .username(username) .password(password) .roles("USER","ADMIN") .build(); return userDetails; } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } //All URLs are protected //A login form is shown for unauthorized requests //CSRF disable //Frames @Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests( auth -> auth.anyRequest().authenticated()); http.formLogin(withDefaults()); http.csrf(AbstractHttpConfigurer::disable); // OR // http.csrf(AbstractHttpConfigurer::disable); http.headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable)); // Starting from SB 3.1.x return http.build(); } }
repos\master-spring-and-spring-boot-main\11-web-application\src\main\java\com\in28minutes\springboot\myfirstwebapp\security\SpringSecurityConfiguration.java
2
请完成以下Java代码
class Person { /** * The {@literal id} and {@link RedisHash#toString()} build up the {@literal key} for the Redis {@literal HASH}. * <br /> * * <pre> * <code> * {@link RedisHash#value()} + ":" + {@link Person#id} * //eg. persons:9b0ed8ee-14be-46ec-b5fa-79570aadb91d * </code> * </pre> * * <strong>Note:</strong> empty {@literal id} fields are automatically assigned during save operation. */ private @Id String id; /** * Using {@link Indexed} marks the property as for indexing which uses Redis {@literal SET} to keep track of * {@literal ids} for objects with matching values. <br /> * * <pre> * <code> * {@link RedisHash#value()} + ":" + {@link Field#getName()} +":" + {@link Field#get(Object)} * //eg. persons:firstname:eddard * </code> * </pre> */ private @Indexed String firstname; private @Indexed String lastname; private Gender gender; /** * Since {@link Indexed} is used on {@link Address#getCity()}, index structures for {@code persons:address:city} are * maintained. */ private Address address; /** * Using {@link Reference} allows to link to existing objects via their {@literal key}. The values stored in the * objects {@literal HASH} looks like:
* * <pre> * <code> * children.[0] := persons:41436096-aabe-42fa-bd5a-9a517fbf0260 * children.[1] := persons:1973d8e7-fbd4-4f93-abab-a2e3a00b3f53 * children.[2] := persons:440b24c6-ede2-495a-b765-2d8b8d6e3995 * </code> * </pre> */ private @Reference List<Person> children; public Person(String firstname, String lastname, Gender gender) { this.firstname = firstname; this.lastname = lastname; this.gender = gender; } }
repos\spring-data-examples-main\redis\repositories\src\main\java\example\springdata\redis\repositories\Person.java
1