instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public java.lang.String getHelp () { return (java.lang.String)get_Value(COLUMNNAME_Help); } /** 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); } /** * RuleType AD_Reference_ID=53235 * Reference name: AD_Rule_RuleType */ public static final int RULETYPE_AD_Reference_ID=53235; /** AspectOrientProgram = A */ public static final String RULETYPE_AspectOrientProgram = "A"; /** JSR223ScriptingAPIs = S */ public static final String RULETYPE_JSR223ScriptingAPIs = "S"; /** JSR94RuleEngineAPI = R */ public static final String RULETYPE_JSR94RuleEngineAPI = "R"; /** SQL = Q */ public static final String RULETYPE_SQL = "Q"; /** Set Rule Type. @param RuleType Rule Type */ @Override public void setRuleType (java.lang.String RuleType) { set_Value (COLUMNNAME_RuleType, RuleType); } /** Get Rule Type. @return Rule Type */ @Override public java.lang.String getRuleType ()
{ return (java.lang.String)get_Value(COLUMNNAME_RuleType); } /** Set Skript. @param Script Dynamic Java Language Script to calculate result */ @Override public void setScript (java.lang.String Script) { set_Value (COLUMNNAME_Script, Script); } /** Get Skript. @return Dynamic Java Language Script to calculate result */ @Override public java.lang.String getScript () { return (java.lang.String)get_Value(COLUMNNAME_Script); } /** Set Suchschlüssel. @param Value Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Rule.java
1
请完成以下Java代码
public static boolean sortDictionary(String path) { try { BufferedReader br = new BufferedReader(new InputStreamReader(IOUtil.newInputStream(path), "UTF-8")); TreeMap<String, String> map = new TreeMap<String, String>(); String line; while ((line = br.readLine()) != null) { String[] param = line.split("\\s"); map.put(param[0], line); } br.close(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(IOUtil.newOutputStream(path), "UTF-8"));
for (Map.Entry<String, String> entry : map.entrySet()) { bw.write(entry.getValue()); bw.newLine(); } bw.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\util\DictionaryUtil.java
1
请完成以下Spring Boot application配置
spring: # datasource 数据源配置内容,对应 DataSourceProperties 配置属性类 datasource: url: jdbc:mysql://127.0.0.1:43063/demo-68-authorization-server?useSSL=false&useUnicode=true&characterEncoding=UTF-8 driver-
class-name: com.mysql.jdbc.Driver username: root # 数据库账号 password: 123456 # 数据库密码
repos\SpringBoot-Labs-master\lab-68-spring-security-oauth\lab-68-demo11-authorization-server-by-jdbc-store\src\main\resources\application.yaml
2
请完成以下Java代码
protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } /** Set Parzelle. @param C_Allotment_ID Parzelle */ @Override public void setC_Allotment_ID (int C_Allotment_ID) { if (C_Allotment_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Allotment_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Allotment_ID, Integer.valueOf(C_Allotment_ID)); } /** Get Parzelle. @return Parzelle */ @Override public int getC_Allotment_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Allotment_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_Location getC_Location() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_Location_ID, org.compiere.model.I_C_Location.class); } @Override public void setC_Location(org.compiere.model.I_C_Location C_Location) { set_ValueFromPO(COLUMNNAME_C_Location_ID, org.compiere.model.I_C_Location.class, C_Location); } /** Set Anschrift. @param C_Location_ID Adresse oder Anschrift */ @Override public void setC_Location_ID (int C_Location_ID) { if (C_Location_ID < 1) set_Value (COLUMNNAME_C_Location_ID, null); else set_Value (COLUMNNAME_C_Location_ID, Integer.valueOf(C_Location_ID)); } /** Get Anschrift.
@return Adresse oder Anschrift */ @Override public int getC_Location_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Location_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); } /** Set Suchschlüssel. @param Value Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_C_Allotment.java
1
请完成以下Java代码
public void setC_RevenueRecognition_Run_ID (int C_RevenueRecognition_Run_ID) { if (C_RevenueRecognition_Run_ID < 1) set_ValueNoCheck (COLUMNNAME_C_RevenueRecognition_Run_ID, null); else set_ValueNoCheck (COLUMNNAME_C_RevenueRecognition_Run_ID, Integer.valueOf(C_RevenueRecognition_Run_ID)); } /** Get Revenue Recognition Run. @return Revenue Recognition Run or Process */ public int getC_RevenueRecognition_Run_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_RevenueRecognition_Run_ID); if (ii == null) return 0; return ii.intValue(); } public I_GL_Journal getGL_Journal() throws RuntimeException { return (I_GL_Journal)MTable.get(getCtx(), I_GL_Journal.Table_Name) .getPO(getGL_Journal_ID(), get_TrxName()); } /** Set Journal. @param GL_Journal_ID General Ledger Journal */ public void setGL_Journal_ID (int GL_Journal_ID) { if (GL_Journal_ID < 1) set_ValueNoCheck (COLUMNNAME_GL_Journal_ID, null); else set_ValueNoCheck (COLUMNNAME_GL_Journal_ID, Integer.valueOf(GL_Journal_ID)); }
/** Get Journal. @return General Ledger Journal */ public int getGL_Journal_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_Journal_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Recognized Amount. @param RecognizedAmt Recognized Amount */ public void setRecognizedAmt (BigDecimal RecognizedAmt) { set_ValueNoCheck (COLUMNNAME_RecognizedAmt, RecognizedAmt); } /** Get Recognized Amount. @return Recognized Amount */ public BigDecimal getRecognizedAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RecognizedAmt); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RevenueRecognition_Run.java
1
请完成以下Java代码
public final class SessionsDescriptor implements OperationResponseBody { private final List<SessionDescriptor> sessions; public SessionsDescriptor(Map<String, ? extends Session> sessions) { this.sessions = sessions.values().stream().map(SessionDescriptor::new).toList(); } public List<SessionDescriptor> getSessions() { return this.sessions; } /** * A description of user's {@link Session session} exposed by {@code sessions} * endpoint. Primarily intended for serialization to JSON. */ public static final class SessionDescriptor { private final String id; private final Set<String> attributeNames; private final Instant creationTime; private final Instant lastAccessedTime; private final long maxInactiveInterval; private final boolean expired; SessionDescriptor(Session session) { this.id = session.getId(); this.attributeNames = session.getAttributeNames(); this.creationTime = session.getCreationTime(); this.lastAccessedTime = session.getLastAccessedTime(); this.maxInactiveInterval = session.getMaxInactiveInterval().getSeconds(); this.expired = session.isExpired(); }
public String getId() { return this.id; } public Set<String> getAttributeNames() { return this.attributeNames; } public Instant getCreationTime() { return this.creationTime; } public Instant getLastAccessedTime() { return this.lastAccessedTime; } public long getMaxInactiveInterval() { return this.maxInactiveInterval; } public boolean isExpired() { return this.expired; } } }
repos\spring-boot-4.0.1\module\spring-boot-session\src\main\java\org\springframework\boot\session\actuate\endpoint\SessionsDescriptor.java
1
请完成以下Java代码
public final class MutableInt implements Comparable<MutableInt>, Serializable { public static MutableInt zero() { return new MutableInt(0); } private int value; public MutableInt(final int value) { this.value = value; } @Override public String toString() { return String.valueOf(value); } @Override public int hashCode() { return value; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof MutableInt) { final MutableInt other = (MutableInt)obj; return value == other.value; } else { return false; } } @Override public int compareTo(final MutableInt obj) { return value - obj.value; }
public void add(final int valueToAdd) { value += valueToAdd; } public void increment() { value++; } public int incrementAndGet() { value++; return value; } public int decrementAndGet() { value--; return value; } public int incrementIf(final boolean condition) { if (condition) { value++; } return value; } public boolean isZero() { return value == 0; } public boolean isGreaterThanZero() { return value > 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\lang\MutableInt.java
1
请完成以下Java代码
public class NoUOMConversionException extends AdempiereException { private static final AdMessageKey MSG = AdMessageKey.of("NoUOMConversion"); public NoUOMConversionException( @Nullable final ProductId productId, @Nullable final UomId fromUomId, @Nullable final UomId toUomId) { super(buildMessage(productId, fromUomId, toUomId), Services.get(IMsgBL.class).getErrorCode(MSG)); } private static ITranslatableString buildMessage( @Nullable final ProductId productId, @Nullable final UomId fromUomId, @Nullable final UomId toUomId) { return TranslatableStrings.builder() .appendADMessage(MSG) .append(" ").appendADElement("M_Product_ID").append(": ").append(extractProductName(productId)) .append(" ").appendADElement("C_UOM_ID").append(": ").append(extractUOMSymbol(fromUomId)) .append(" ").appendADElement("C_UOM_To_ID").append(": ").append(extractUOMSymbol(toUomId)) .build(); } private static String extractProductName(@Nullable final ProductId productId) { if (productId == null) { return "<none>"; }
return Services.get(IProductBL.class).getProductValueAndName(productId); } private static String extractUOMSymbol(@Nullable final UomId uomId) { if (uomId == null) { return "<none>"; } try { final I_C_UOM uom = Services.get(IUOMDAO.class).getById(uomId); if (uom == null) { return "<" + uomId.getRepoId() + ">"; } return uom.getUOMSymbol(); } catch (final Exception ex) { return "<" + uomId.getRepoId() + ">"; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\adempiere\exceptions\NoUOMConversionException.java
1
请完成以下Java代码
public boolean isSameCurrency () { Object oo = get_Value(COLUMNNAME_IsSameCurrency); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Same Tax. @param IsSameTax Use the same tax as the main transaction */ public void setIsSameTax (boolean IsSameTax) { set_Value (COLUMNNAME_IsSameTax, Boolean.valueOf(IsSameTax)); } /** Get Same Tax. @return Use the same tax as the main transaction */ public boolean isSameTax () { Object oo = get_Value(COLUMNNAME_IsSameTax); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Price includes Tax. @param IsTaxIncluded Tax is included in the price */ public void setIsTaxIncluded (boolean IsTaxIncluded) { set_Value (COLUMNNAME_IsTaxIncluded, Boolean.valueOf(IsTaxIncluded)); } /** Get Price includes Tax. @return Tax is included in the price */ public boolean isTaxIncluded () { Object oo = get_Value(COLUMNNAME_IsTaxIncluded);
if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Charge.java
1
请完成以下Java代码
void reserve(int size) { if (size > _capacity) { resizeBuf(size); } } private void resizeBuf(int size) { int capacity; if (size >= _capacity * 2) { capacity = size; } else { capacity = 1; while (capacity < size)
{ capacity <<= 1; } } int[] buf = new int[capacity]; if (_size > 0) { System.arraycopy(_buf, 0, buf, 0, _size); } _buf = buf; _capacity = capacity; } private int[] _buf; private int _size; private int _capacity; }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\AutoIntPool.java
1
请完成以下Java代码
final class SpringProfileArbiter implements Arbiter { private final @Nullable Environment environment; private final Profiles profiles; private SpringProfileArbiter(@Nullable Environment environment, String[] profiles) { this.environment = environment; this.profiles = Profiles.of(profiles); } @Override public boolean isCondition() { return (this.environment != null) && this.environment.acceptsProfiles(this.profiles); } @PluginBuilderFactory static Builder newBuilder() { return new Builder(); } /** * Standard Builder to create the Arbiter. */ static final class Builder implements org.apache.logging.log4j.core.util.Builder<SpringProfileArbiter> { private static final Logger statusLogger = StatusLogger.getLogger(); @PluginBuilderAttribute @SuppressWarnings("NullAway.Init") private String name; @PluginConfiguration @SuppressWarnings("NullAway.Init") private Configuration configuration; @PluginLoggerContext @SuppressWarnings("NullAway.Init") private LoggerContext loggerContext; private Builder() { } /** * Sets the profile name or expression.
* @param name the profile name or expression * @return this * @see Profiles#of(String...) */ public Builder setName(String name) { this.name = name; return this; } @Override public SpringProfileArbiter build() { Environment environment = Log4J2LoggingSystem.getEnvironment(this.loggerContext); if (environment == null) { statusLogger.debug("Creating Arbiter without a Spring Environment"); } String name = this.configuration.getStrSubstitutor().replace(this.name); String[] profiles = trimArrayElements(StringUtils.commaDelimitedListToStringArray(name)); return new SpringProfileArbiter(environment, profiles); } // The array has no nulls in it, but StringUtils.trimArrayElements return // @Nullable String[] @SuppressWarnings("NullAway") private String[] trimArrayElements(String[] array) { return StringUtils.trimArrayElements(array); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\log4j2\SpringProfileArbiter.java
1
请完成以下Java代码
public void patchRow(final IEditableView.RowEditingContext ctx, final List<JSONDocumentChangedEvent> fieldChangeRequests) { final UnaryOperator<DataEntryDetailsRow> rowMapper = row -> { final DataEntryDetailsRow.DataEntryDetailsRowBuilder builder = row.toBuilder(); for (final JSONDocumentChangedEvent fieldChangeRequest : fieldChangeRequests) { if (fieldChangeRequest.getPath().equals(DataEntryDetailsRow.FIELD_Qty)) { builder.qty(fieldChangeRequest.getValueAsBigDecimal()); } // note that qty is currently the only editable field } return builder.build(); }; final DocumentId rowIdToChange = ctx.getRowId(); final UnaryOperator<ImmutableRowsIndex<DataEntryDetailsRow>> remappingFunction = rows -> rows.changingRow(rowIdToChange, rowMapper); rowsHolder.compute(remappingFunction); saveAll(); } @Override public Map<DocumentId, DataEntryDetailsRow> getDocumentId2TopLevelRows() { return rowsHolder.getDocumentId2TopLevelRows(); } @Override public DocumentIdsSelection getDocumentIdsToInvalidate(@NonNull final TableRecordReferenceSet recordRefs) { return recordRefs.streamIds( I_C_Flatrate_DataEntry_Detail.Table_Name, repoId -> FlatrateDataEntryDetailId.ofRepoId(flatrateDataEntryId, repoId)) .map(DataEntryDetailsRowUtil::createDocumentId) .filter(rowsHolder.isRelevantForRefreshingByDocumentId()) .collect(DocumentIdsSelection.toDocumentIdsSelection()); } @Override public void invalidateAll() { invalidate(DocumentIdsSelection.ALL); } @Override public void invalidate(@NonNull final DocumentIdsSelection rowIds) { final Function<DocumentId, FlatrateDataEntryDetailId> idMapper = documentId -> FlatrateDataEntryDetailId.ofRepoId(flatrateDataEntryId, documentId.toInt()); final ImmutableSet<FlatrateDataEntryDetailId> dataEntryIds = rowsHolder.getRecordIdsToRefresh(rowIds, idMapper); final Predicate<FlatrateDataEntryDetail> loadFilter = dataEntry -> dataEntryIds.contains(dataEntry.getId());
final List<DataEntryDetailsRow> newRows = loader.loadMatchingRows(loadFilter) .stream() // .map(newRow -> newRow) // we are just replacing the stale rows .collect(ImmutableList.toImmutableList()); rowsHolder.compute(rows -> rows.replacingRows(rowIds, newRows)); } private void saveAll() { final Map<DocumentId, DataEntryDetailsRow> documentId2TopLevelRows = getDocumentId2TopLevelRows(); final FlatrateDataEntry entry = flatrateDataEntryRepo.getById(flatrateDataEntryId); for (final FlatrateDataEntryDetail detail : entry.getDetails()) { final DocumentId documentId = DataEntryDetailsRowUtil.createDocumentId(detail); final DataEntryDetailsRow row = documentId2TopLevelRows.get(documentId); if(row.getQty() != null) { final Quantity quantity = Quantitys.of(row.getQty(), entry.getUomId()); detail.setQuantity(quantity); } else { detail.setQuantity(null); } } flatrateDataEntryRepo.save(entry); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\contract\flatrate\model\DataEntryDetailsRowsData.java
1
请完成以下Java代码
public Long getCustomerId() { return customerId; } public void setCustomerId(Long customerId) { this.customerId = customerId; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCardNumber() { return cardNumber; } public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; } public String getExpiryDate() {
return expiryDate; } public void setExpiryDate(String expiryDate) { this.expiryDate = expiryDate; } public CreditCard() { } @Override public String toString() { return "CreditCard{" + "id=" + id + ", cardNumber='" + cardNumber + '\'' + ", expiryDate='" + expiryDate + '\'' + ", customerId=" + customerId + '}'; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-query-2\src\main\java\com\baeldung\upsert\CreditCard.java
1
请完成以下Java代码
public IAllocationRequestBuilder setForceQtyAllocation(final Boolean forceQtyAllocation) { this.forceQtyAllocation = forceQtyAllocation; return this; } private boolean isForceQtyAllocationToUse() { if (forceQtyAllocation != null) { return forceQtyAllocation; } else if (baseAllocationRequest != null) { return baseAllocationRequest.isForceQtyAllocation(); } throw new AdempiereException("ForceQtyAllocation not set in " + this); } @Override public IAllocationRequestBuilder addEmptyHUListener(@NonNull final EmptyHUListener emptyHUListener) { if (emptyHUListeners == null) { emptyHUListeners = new ArrayList<>(); } emptyHUListeners.add(emptyHUListener); return this; } @Override public IAllocationRequestBuilder setClearanceStatusInfo(@Nullable final ClearanceStatusInfo clearanceStatusInfo) { this.clearanceStatusInfo = clearanceStatusInfo; return this; } @Override @Nullable public ClearanceStatusInfo getClearanceStatusInfo() { if (clearanceStatusInfo != null) { return clearanceStatusInfo; } else if (baseAllocationRequest != null) { return baseAllocationRequest.getClearanceStatusInfo(); } return null; } @Override public IAllocationRequestBuilder setDeleteEmptyAndJustCreatedAggregatedTUs(@Nullable final Boolean deleteEmptyAndJustCreatedAggregatedTUs) { this.deleteEmptyAndJustCreatedAggregatedTUs = deleteEmptyAndJustCreatedAggregatedTUs;
return this; } private boolean isDeleteEmptyAndJustCreatedAggregatedTUs() { if (deleteEmptyAndJustCreatedAggregatedTUs != null) { return deleteEmptyAndJustCreatedAggregatedTUs; } else if (baseAllocationRequest != null) { return baseAllocationRequest.isDeleteEmptyAndJustCreatedAggregatedTUs(); } return false; } @Override public IAllocationRequest create() { final IHUContext huContext = getHUContextToUse(); final ProductId productId = getProductIdToUse(); final Quantity quantity = getQuantityToUse(); final ZonedDateTime date = getDateToUse(); final TableRecordReference fromTableRecord = getFromReferencedTableRecordToUse(); final boolean forceQtyAllocation = isForceQtyAllocationToUse(); final ClearanceStatusInfo clearanceStatusInfo = getClearanceStatusInfo(); return new AllocationRequest( huContext, productId, quantity, date, fromTableRecord, forceQtyAllocation, clearanceStatusInfo, isDeleteEmptyAndJustCreatedAggregatedTUs()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AllocationRequestBuilder.java
1
请完成以下Java代码
public ShortcutType shortcutType() { return GATHER_LIST; } @Override public List<String> shortcutFieldOrder() { return Collections.singletonList("sources"); } @NotNull private List<IpSubnetFilterRule> convert(List<String> values) { List<IpSubnetFilterRule> sources = new ArrayList<>(); for (String arg : values) { addSource(sources, arg); } return sources; } @Override public Predicate<ServerWebExchange> apply(Config config) { List<IpSubnetFilterRule> sources = convert(config.sources); return new GatewayPredicate() { @Override public boolean test(ServerWebExchange exchange) { InetSocketAddress remoteAddress = config.remoteAddressResolver.resolve(exchange); if (remoteAddress != null && remoteAddress.getAddress() != null) { String hostAddress = remoteAddress.getAddress().getHostAddress(); String host = exchange.getRequest().getURI().getHost(); if (log.isDebugEnabled() && !hostAddress.equals(host)) { log.debug("Remote addresses didn't match " + hostAddress + " != " + host); } for (IpSubnetFilterRule source : sources) { if (source.matches(remoteAddress)) { return true; } } } return false; } @Override public Object getConfig() { return config; } @Override public String toString() { return String.format("RemoteAddrs: %s", config.getSources()); } }; }
private void addSource(List<IpSubnetFilterRule> sources, String source) { if (!source.contains("/")) { // no netmask, add default source = source + "/32"; } String[] ipAddressCidrPrefix = source.split("/", 2); String ipAddress = ipAddressCidrPrefix[0]; int cidrPrefix = Integer.parseInt(ipAddressCidrPrefix[1]); sources.add(new IpSubnetFilterRule(ipAddress, cidrPrefix, IpFilterRuleType.ACCEPT)); } public static class Config { @NotEmpty private List<String> sources = new ArrayList<>(); @NotNull private RemoteAddressResolver remoteAddressResolver = new RemoteAddressResolver() { }; public List<String> getSources() { return sources; } public Config setSources(List<String> sources) { this.sources = sources; return this; } public Config setSources(String... sources) { this.sources = Arrays.asList(sources); return this; } public Config setRemoteAddressResolver(RemoteAddressResolver remoteAddressResolver) { this.remoteAddressResolver = remoteAddressResolver; return this; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\RemoteAddrRoutePredicateFactory.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable Integer getMaxQueueSize() { return this.maxQueueSize; } public void setMaxQueueSize(@Nullable Integer maxQueueSize) { this.maxQueueSize = maxQueueSize; } public @Nullable Integer getMaxConcurrentRequests() { return this.maxConcurrentRequests; } public void setMaxConcurrentRequests(@Nullable Integer maxConcurrentRequests) { this.maxConcurrentRequests = maxConcurrentRequests; } public @Nullable Integer getMaxRequestsPerSecond() { return this.maxRequestsPerSecond; } public void setMaxRequestsPerSecond(@Nullable Integer maxRequestsPerSecond) { this.maxRequestsPerSecond = maxRequestsPerSecond; } public @Nullable Duration getDrainInterval() { return this.drainInterval; } public void setDrainInterval(@Nullable Duration drainInterval) { this.drainInterval = drainInterval; } } /** * Name of the algorithm used to compress protocol frames. */ public enum Compression { /** * Requires 'net.jpountz.lz4:lz4'. */ LZ4, /**
* Requires org.xerial.snappy:snappy-java. */ SNAPPY, /** * No compression. */ NONE } public enum ThrottlerType { /** * Limit the number of requests that can be executed in parallel. */ CONCURRENCY_LIMITING("ConcurrencyLimitingRequestThrottler"), /** * Limits the request rate per second. */ RATE_LIMITING("RateLimitingRequestThrottler"), /** * No request throttling. */ NONE("PassThroughRequestThrottler"); private final String type; ThrottlerType(String type) { this.type = type; } public String type() { return this.type; } } }
repos\spring-boot-4.0.1\module\spring-boot-cassandra\src\main\java\org\springframework\boot\cassandra\autoconfigure\CassandraProperties.java
2
请完成以下Java代码
public Timestamp getParameterAsTimestamp(final String parameterName) { return null; } @Override public LocalDate getParameterAsLocalDate(final String parameterName) { return null; } @Override public ZonedDateTime getParameterAsZonedDateTime(final String parameterName) { return null; } @Nullable @Override public Instant getParameterAsInstant(final String parameterName) { return null; } @Override public BigDecimal getParameterAsBigDecimal(final String paraCheckNetamttoinvoice)
{ return null; } /** * Returns an empty list. */ @Override public Collection<String> getParameterNames() { return ImmutableList.of(); } @Override public <T extends Enum<T>> Optional<T> getParameterAsEnum(final String parameterName, final Class<T> enumType) { return Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\api\NullParams.java
1
请完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AcquirableJobEntity other = (AcquirableJobEntity) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id))
return false; return true; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", revision=" + revision + ", lockOwner=" + lockOwner + ", lockExpirationTime=" + lockExpirationTime + ", duedate=" + duedate + ", rootProcessInstanceId=" + rootProcessInstanceId + ", processInstanceId=" + processInstanceId + ", isExclusive=" + isExclusive + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AcquirableJobEntity.java
1
请完成以下Java代码
public BigDecimal getTaxTotalAmt() { return isAccountSignDR() ? glJournalLine.getDR_TaxTotalAmt() : glJournalLine.getCR_TaxTotalAmt(); } @Override public void setTaxTotalAmt(final BigDecimal totalAmt) { if (isAccountSignDR()) { glJournalLine.setDR_TaxTotalAmt(totalAmt); } else { glJournalLine.setCR_TaxTotalAmt(totalAmt); } // // Update AmtSourceDr/Cr // NOTE: we are updating both sides because they shall be the SAME glJournalLine.setAmtSourceDr(totalAmt); glJournalLine.setAmtSourceCr(totalAmt); } @Override public I_C_ValidCombination getTaxBase_Acct() { return isAccountSignDR() ? glJournalLine.getAccount_DR() : glJournalLine.getAccount_CR(); } @Override
public I_C_ValidCombination getTaxTotal_Acct() { return isAccountSignDR() ? glJournalLine.getAccount_CR() : glJournalLine.getAccount_DR(); } @Override public CurrencyPrecision getPrecision() { final CurrencyId currencyId = CurrencyId.ofRepoIdOrNull(glJournalLine.getC_Currency_ID()); return currencyId != null ? Services.get(ICurrencyDAO.class).getStdPrecision(currencyId) : CurrencyPrecision.TWO; } @Override public AcctSchemaId getAcctSchemaId() { return AcctSchemaId.ofRepoId(glJournalLine.getGL_Journal().getC_AcctSchema_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal\impl\GLJournalLineTaxAccountable.java
1
请完成以下Java代码
public class MapUtil { public static String getString(Map map,String key){ if(map!=null && map.containsKey(key)){ try{ return map.get(key).toString(); }catch (Exception e){ e.printStackTrace(); return ""; } }else{ return ""; } } public static Integer getInteger(Map map,String key){ if(map!=null && map.containsKey(key)){ try{ return Integer.valueOf(map.get(key).toString()); }catch (Exception e){ e.printStackTrace(); return 0; } }else{ return 0;
} } public static Boolean getBoolean(Map map,String key){ if(map!=null && map.containsKey(key)){ try{ return Boolean.parseBoolean(map.get(key).toString()) || "true".equals(map.get(key).toString()); }catch (Exception e){ e.printStackTrace(); return false; } }else{ return false; } } }
repos\SpringBootCodeGenerator-master\src\main\java\com\softdev\system\generator\util\MapUtil.java
1
请完成以下Java代码
public class Dom4jTransformer { private final Document input; public Dom4jTransformer(String resourcePath) throws DocumentException, SAXException { // 1- Build the doc from the XML file SAXReader xmlReader = new SAXReader(); xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false); xmlReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); this.input = xmlReader.read(resourcePath); } public String modifyAttribute(String attribute, String oldValue, String newValue) throws TransformerException, TransformerException { // 2- Locate the node(s) with xpath, we can use index and iterator too. String expr = String.format("//*[contains(@%s, '%s')]", attribute, oldValue); XPath xpath = DocumentHelper.createXPath(expr);
List<Node> nodes = xpath.selectNodes(input); // 3- Make the change on the selected nodes for (int i = 0; i < nodes.size(); i++) { Element element = (Element) nodes.get(i); element.addAttribute(attribute, newValue); } // 4- Save the result to a new XML doc TransformerFactory factory = TransformerFactory.newInstance(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); Transformer xformer = factory.newTransformer(); xformer.setOutputProperty(OutputKeys.INDENT, "yes"); Writer output = new StringWriter(); xformer.transform(new DocumentSource(input), new StreamResult(output)); return output.toString(); } }
repos\tutorials-master\xml-modules\xml-2\src\main\java\com\baeldung\xml\attribute\Dom4jTransformer.java
1
请完成以下Java代码
public void setLoopDataOutputRef(String loopDataOutputRef) { this.loopDataOutputRef = loopDataOutputRef; } public String getOutputDataItem() { return outputDataItem; } public boolean hasOutputDataItem() { return outputDataItem != null && !outputDataItem.trim().isEmpty(); } public void setOutputDataItem(String outputDataItem) { this.outputDataItem = outputDataItem; } protected void updateResultCollection(DelegateExecution childExecution, DelegateExecution miRootExecution) { if (miRootExecution != null && hasLoopDataOutputRef()) { Object loopDataOutputReference = miRootExecution.getVariableLocal(getLoopDataOutputRef()); List<Object> resultCollection; if (loopDataOutputReference instanceof List) { resultCollection = (List<Object>) loopDataOutputReference; } else { resultCollection = new ArrayList<>(); } resultCollection.add(getResultElementItem(childExecution)); setLoopVariable(miRootExecution, getLoopDataOutputRef(), resultCollection); } } protected Object getResultElementItem(DelegateExecution childExecution) { return getResultElementItem(childExecution.getVariablesLocal()); } protected CommandContext getCommandContext() { return Context.getCommandContext(); }
protected Object getResultElementItem(Map<String, Object> availableVariables) { if (hasOutputDataItem()) { return availableVariables.get(getOutputDataItem()); } else { //exclude from the result all the built-in multi-instances variables //and loopDataOutputRef itself that may exist in the context depending // on the variable propagation List<String> resultItemExclusions = Arrays.asList( getLoopDataOutputRef(), getCollectionElementIndexVariable(), NUMBER_OF_INSTANCES, NUMBER_OF_COMPLETED_INSTANCES, NUMBER_OF_ACTIVE_INSTANCES ); HashMap<String, Object> resultItem = new HashMap<>(availableVariables); resultItemExclusions.forEach(resultItem.keySet()::remove); return resultItem; } } protected void propagateLoopDataOutputRefToProcessInstance(ExecutionEntity miRootExecution) { if (hasLoopDataOutputRef()) { miRootExecution .getProcessInstance() .setVariable(getLoopDataOutputRef(), miRootExecution.getVariable(getLoopDataOutputRef())); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\MultiInstanceActivityBehavior.java
1
请在Spring Boot框架中完成以下Java代码
public int create(List<SmsHomeBrand> homeBrandList) { for (SmsHomeBrand smsHomeBrand : homeBrandList) { smsHomeBrand.setRecommendStatus(1); smsHomeBrand.setSort(0); homeBrandMapper.insert(smsHomeBrand); } return homeBrandList.size(); } @Override public int updateSort(Long id, Integer sort) { SmsHomeBrand homeBrand = new SmsHomeBrand(); homeBrand.setId(id); homeBrand.setSort(sort); return homeBrandMapper.updateByPrimaryKeySelective(homeBrand); } @Override public int delete(List<Long> ids) { SmsHomeBrandExample example = new SmsHomeBrandExample(); example.createCriteria().andIdIn(ids); return homeBrandMapper.deleteByExample(example); } @Override public int updateRecommendStatus(List<Long> ids, Integer recommendStatus) {
SmsHomeBrandExample example = new SmsHomeBrandExample(); example.createCriteria().andIdIn(ids); SmsHomeBrand record = new SmsHomeBrand(); record.setRecommendStatus(recommendStatus); return homeBrandMapper.updateByExampleSelective(record,example); } @Override public List<SmsHomeBrand> list(String brandName, Integer recommendStatus, Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum,pageSize); SmsHomeBrandExample example = new SmsHomeBrandExample(); SmsHomeBrandExample.Criteria criteria = example.createCriteria(); if(!StrUtil.isEmpty(brandName)){ criteria.andBrandNameLike("%"+brandName+"%"); } if(recommendStatus!=null){ criteria.andRecommendStatusEqualTo(recommendStatus); } example.setOrderByClause("sort desc"); return homeBrandMapper.selectByExample(example); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\SmsHomeBrandServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public JpaProperties jpaProperties() { return new JpaProperties(); } /** * 获取主库实体管理工厂对象 * * @param primaryDataSource 注入名为primaryDataSource的数据源 * @param jpaProperties 注入名为primaryJpaProperties的jpa配置信息 * @param builder 注入EntityManagerFactoryBuilder * @return 实体管理工厂对象 */ @Primary @Bean(name = "primaryEntityManagerFactory") public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Qualifier("primaryDataSource") DataSource primaryDataSource, @Qualifier("primaryJpaProperties") JpaProperties jpaProperties, EntityManagerFactoryBuilder builder) { return builder // 设置数据源 .dataSource(primaryDataSource) // 设置jpa配置 .properties(jpaProperties.getProperties()) // 设置实体包名 .packages(ENTITY_PACKAGE) // 设置持久化单元名,用于@PersistenceContext注解获取EntityManager时指定数据源 .persistenceUnit("primaryPersistenceUnit").build(); } /** * 获取实体管理对象 * * @param factory 注入名为primaryEntityManagerFactory的bean
* @return 实体管理对象 */ @Primary @Bean(name = "primaryEntityManager") public EntityManager entityManager(@Qualifier("primaryEntityManagerFactory") EntityManagerFactory factory) { return factory.createEntityManager(); } /** * 获取主库事务管理对象 * * @param factory 注入名为primaryEntityManagerFactory的bean * @return 事务管理对象 */ @Primary @Bean(name = "primaryTransactionManager") public PlatformTransactionManager transactionManager(@Qualifier("primaryEntityManagerFactory") EntityManagerFactory factory) { return new JpaTransactionManager(factory); } }
repos\spring-boot-demo-master\demo-multi-datasource-jpa\src\main\java\com\xkcoding\multi\datasource\jpa\config\PrimaryJpaConfig.java
2
请完成以下Java代码
public float cosineForUnitVector(Vector other) { return dot(other); } /** * 夹角的余弦<br> * * @param other * @return */ public float cosine(Vector other) { return dot(other) / this.norm() / other.norm(); } public Vector minus(Vector other) { float[] result = new float[size()]; for (int i = 0; i < result.length; i++) { result[i] = elementArray[i] - other.elementArray[i]; } return new Vector(result); } public Vector add(Vector other) { float[] result = new float[size()]; for (int i = 0; i < result.length; i++) { result[i] = elementArray[i] + other.elementArray[i]; } return new Vector(result); } public Vector addToSelf(Vector other) { for (int i = 0; i < elementArray.length; i++) { elementArray[i] = elementArray[i] + other.elementArray[i]; } return this; } public Vector divideToSelf(int n) { for (int i = 0; i < elementArray.length; i++) { elementArray[i] = elementArray[i] / n; } return this; } public Vector divideToSelf(float f) { for (int i = 0; i < elementArray.length; i++) {
elementArray[i] = elementArray[i] / f; } return this; } /** * 自身归一化 * * @return */ public Vector normalize() { divideToSelf(norm()); return this; } public float[] getElementArray() { return elementArray; } public void setElementArray(float[] elementArray) { this.elementArray = elementArray; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\Vector.java
1
请完成以下Java代码
public int getLineWidth () { Integer ii = (Integer)get_Value(COLUMNNAME_LineWidth); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Red. @param Red RGB value */ public void setRed (int Red) { set_Value (COLUMNNAME_Red, Integer.valueOf(Red)); } /** Get Red. @return RGB value */ public int getRed () { Integer ii = (Integer)get_Value(COLUMNNAME_Red); if (ii == null) return 0; return ii.intValue(); } /** Set 2nd Red. @param Red_1 RGB value for second color */ public void setRed_1 (int Red_1) { set_Value (COLUMNNAME_Red_1, Integer.valueOf(Red_1)); } /** Get 2nd Red. @return RGB value for second color */ public int getRed_1 () { Integer ii = (Integer)get_Value(COLUMNNAME_Red_1); if (ii == null) return 0;
return ii.intValue(); } /** Set Repeat Distance. @param RepeatDistance Distance in points to repeat gradient color - or zero */ public void setRepeatDistance (int RepeatDistance) { set_Value (COLUMNNAME_RepeatDistance, Integer.valueOf(RepeatDistance)); } /** Get Repeat Distance. @return Distance in points to repeat gradient color - or zero */ public int getRepeatDistance () { Integer ii = (Integer)get_Value(COLUMNNAME_RepeatDistance); if (ii == null) return 0; return ii.intValue(); } /** StartPoint AD_Reference_ID=248 */ public static final int STARTPOINT_AD_Reference_ID=248; /** North = 1 */ public static final String STARTPOINT_North = "1"; /** North East = 2 */ public static final String STARTPOINT_NorthEast = "2"; /** East = 3 */ public static final String STARTPOINT_East = "3"; /** South East = 4 */ public static final String STARTPOINT_SouthEast = "4"; /** South = 5 */ public static final String STARTPOINT_South = "5"; /** South West = 6 */ public static final String STARTPOINT_SouthWest = "6"; /** West = 7 */ public static final String STARTPOINT_West = "7"; /** North West = 8 */ public static final String STARTPOINT_NorthWest = "8"; /** Set Start Point. @param StartPoint Start point of the gradient colors */ public void setStartPoint (String StartPoint) { set_Value (COLUMNNAME_StartPoint, StartPoint); } /** Get Start Point. @return Start point of the gradient colors */ public String getStartPoint () { return (String)get_Value(COLUMNNAME_StartPoint); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Color.java
1
请完成以下Java代码
public IWorkPackageParamsBuilder setParameter(final String parameterName, final Object parameterValue) { assertNotBuilt(); Check.assumeNotEmpty(parameterName, "parameterName not empty"); parameterName2valueMap.put(parameterName, parameterValue); return this; } @Override public IWorkPackageParamsBuilder setParameters(final Map<String, ?> parameters) { assertNotBuilt(); if (parameters == null || parameters.isEmpty()) { return this; } for (final Map.Entry<String, ?> param : parameters.entrySet()) { final String parameterName = param.getKey(); Check.assumeNotEmpty(parameterName, "parameterName not empty"); final Object parameterValue = param.getValue(); parameterName2valueMap.put(parameterName, parameterValue); } return this; } @Override public IWorkPackageParamsBuilder setParameters(@Nullable final IParams parameters) {
assertNotBuilt(); if (parameters == null) { return this; } final Collection<String> parameterNames = parameters.getParameterNames(); if(parameterNames.isEmpty()) { return this; } for (final String parameterName : parameterNames) { Check.assumeNotEmpty(parameterName, "parameterName not empty"); final Object parameterValue = parameters.getParameterAsObject(parameterName); parameterName2valueMap.put(parameterName, parameterValue); } return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\WorkPackageParamsBuilder.java
1
请完成以下Java代码
public void setKeyClassIdFieldName(String keyClassIdFieldName) { this.keyClassIdFieldName = keyClassIdFieldName; } public void setIdClassMapping(Map<String, Class<?>> idClassMapping) { this.idClassMapping.putAll(idClassMapping); createReverseMap(); } @Override public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } protected @Nullable ClassLoader getClassLoader() { return this.classLoader; } protected void addHeader(Headers headers, String headerName, Class<?> clazz) { if (this.classIdMapping.containsKey(clazz)) { headers.add(new RecordHeader(headerName, this.classIdMapping.get(clazz))); } else { headers.add(new RecordHeader(headerName, clazz.getName().getBytes(StandardCharsets.UTF_8))); } } protected String retrieveHeader(Headers headers, String headerName) { String classId = retrieveHeaderAsString(headers, headerName); if (classId == null) { throw new MessageConversionException( "failed to convert Message content. Could not resolve " + headerName + " in header"); } return classId; } protected @Nullable String retrieveHeaderAsString(Headers headers, String headerName) { Header header = headers.lastHeader(headerName);
if (header != null) { String classId = null; if (header.value() != null) { classId = new String(header.value(), StandardCharsets.UTF_8); } return classId; } return null; } private void createReverseMap() { this.classIdMapping.clear(); for (Map.Entry<String, Class<?>> entry : this.idClassMapping.entrySet()) { String id = entry.getKey(); Class<?> clazz = entry.getValue(); this.classIdMapping.put(clazz, id.getBytes(StandardCharsets.UTF_8)); } } public Map<String, Class<?>> getIdClassMapping() { return Collections.unmodifiableMap(this.idClassMapping); } /** * Configure the TypeMapper to use default key type class. * @param isKey Use key type headers if true * @since 2.1.3 */ public void setUseForKey(boolean isKey) { if (isKey) { setClassIdFieldName(AbstractJavaTypeMapper.KEY_DEFAULT_CLASSID_FIELD_NAME); setContentClassIdFieldName(AbstractJavaTypeMapper.KEY_DEFAULT_CONTENT_CLASSID_FIELD_NAME); setKeyClassIdFieldName(AbstractJavaTypeMapper.KEY_DEFAULT_KEY_CLASSID_FIELD_NAME); } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\mapping\AbstractJavaTypeMapper.java
1
请在Spring Boot框架中完成以下Java代码
public String getDecisionDefinitionId() { return decisionDefinitionId; } public void setDecisionDefinitionId(String decisionDefinitionId) { this.decisionDefinitionId = decisionDefinitionId; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public String getActivityId() { return activityId; } public void setActivityId(String activityId) { this.activityId = activityId; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public String getInstanceId() { return instanceId; } public void setInstanceId(String instanceId) { this.instanceId = instanceId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } public Boolean getFailed() { return failed; } public void setFailed(Boolean failed) { this.failed = failed; } public Date getStartTime() {
return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getDecisionKey() { return decisionKey; } public void setDecisionKey(String decisionKey) { this.decisionKey = decisionKey; } public String getDecisionName() { return decisionName; } public void setDecisionName(String decisionName) { this.decisionName = decisionName; } public String getDecisionVersion() { return decisionVersion; } public void setDecisionVersion(String decisionVersion) { this.decisionVersion = decisionVersion; } }
repos\flowable-engine-main\modules\flowable-dmn-rest\src\main\java\org\flowable\dmn\rest\service\api\history\HistoricDecisionExecutionResponse.java
2
请完成以下Java代码
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Task.class, CMMN_ELEMENT_TASK) .namespaceUri(CMMN11_NS) .extendsType(PlanItemDefinition.class) .instanceProvider(new ModelTypeInstanceProvider<Task>() { public Task newInstance(ModelTypeInstanceContext instanceContext) { return new TaskImpl(instanceContext); } }); isBlockingAttribute = typeBuilder.booleanAttribute(CMMN_ATTRIBUTE_IS_BLOCKING) .defaultValue(true) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); inputsCollection = sequenceBuilder.elementCollection(InputsCaseParameter.class)
.build(); outputsCollection = sequenceBuilder.elementCollection(OutputsCaseParameter.class) .build(); inputParameterCollection = sequenceBuilder.elementCollection(InputCaseParameter.class) .build(); outputParameterCollection = sequenceBuilder.elementCollection(OutputCaseParameter.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\TaskImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class PriceListVersionConfiguration { private static final Logger logger = LogManager.getLogger(PriceListVersionConfiguration.class); private static Supplier<IPricingRule> huPricingRuleFactory = null; public static void setupHUPricing( @NonNull final Supplier<IPricingRule> huPricingRuleFactory, @NonNull final ProductPriceQuery.IProductPriceQueryMatcher mainProductPriceMatcher) { PriceListVersionConfiguration.huPricingRuleFactory = huPricingRuleFactory; logger.info("Registered HUPricing factory: {}", huPricingRuleFactory); ProductPrices.registerMainProductPriceMatcher(mainProductPriceMatcher); } public static Supplier<IPricingRule> getHUPricingRuleFactory() { return huPricingRuleFactory;
} public static void reset() { if (!Adempiere.isUnitTestMode()) { throw new AdempiereException("Resetting PriceListVersion configuration is allowed only when running in JUnit mode"); } ProductPrices.clearMainProductPriceMatchers(); PriceListVersionConfiguration.huPricingRuleFactory = null; logger.info("Configuration reset"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\rules\price_list_version\PriceListVersionConfiguration.java
2
请完成以下Java代码
public class EventRegistryProcessingInfo { protected List<EventConsumerInfo> eventConsumerInfos; public boolean eventHandled() { return eventConsumerInfos != null && !eventConsumerInfos.isEmpty(); } public void addEventConsumerInfo(EventConsumerInfo eventInfo) { if (eventConsumerInfos == null) { eventConsumerInfos = new ArrayList<>(); } eventConsumerInfos.add(eventInfo); }
public List<EventConsumerInfo> getEventConsumerInfos() { return eventConsumerInfos; } public void setEventConsumerInfos(List<EventConsumerInfo> eventConsumerInfos) { this.eventConsumerInfos = eventConsumerInfos; } @Override public String toString() { return new StringJoiner(", ", getClass().getSimpleName() + "[", "]") .add("eventConsumerInfos=" + eventConsumerInfos) .toString(); } }
repos\flowable-engine-main\modules\flowable-event-registry-api\src\main\java\org\flowable\eventregistry\api\EventRegistryProcessingInfo.java
1
请完成以下Java代码
public String getDeploymentId() { return deploymentId; } public CaseExecutionState getState() { return state; } public boolean isCaseInstancesOnly() { return true; } public String getSuperProcessInstanceId() { return superProcessInstanceId; } public String getSubProcessInstanceId() { return subProcessInstanceId; } public String getSuperCaseInstanceId() {
return superCaseInstanceId; } public String getSubCaseInstanceId() { return subCaseInstanceId; } public Boolean isRequired() { return required; } public Boolean isRepeatable() { return repeatable; } public Boolean isRepetition() { return repetition; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\runtime\CaseInstanceQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public CacheProperties getCache() { return this.cache; } public ClusterProperties getCluster() { return this.cluster; } public DiskStoreProperties getDisk() { return this.disk; } public EntityProperties getEntities() { return this.entities; } public LocatorProperties getLocator() { return this.locator; } public String[] getLocators() { return this.locators; } public void setLocators(String[] locators) { this.locators = locators; } public LoggingProperties getLogging() { return this.logging; } public ManagementProperties getManagement() { return this.management; } public ManagerProperties getManager() { return this.manager; } public String getName() { return name; } public void setName(String name) { this.name = name; } public PdxProperties getPdx() { return this.pdx;
} public PoolProperties getPool() { return this.pool; } public SecurityProperties getSecurity() { return this.security; } public ServiceProperties getService() { return this.service; } public boolean isUseBeanFactoryLocator() { return this.useBeanFactoryLocator; } public void setUseBeanFactoryLocator(boolean useBeanFactoryLocator) { this.useBeanFactoryLocator = useBeanFactoryLocator; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\GemFireProperties.java
2
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_A_Depreciation_Convention[") .append(get_ID()).append("]"); return sb.toString(); } /** Set A_Depreciation_Convention_ID. @param A_Depreciation_Convention_ID A_Depreciation_Convention_ID */ public void setA_Depreciation_Convention_ID (int A_Depreciation_Convention_ID) { if (A_Depreciation_Convention_ID < 1) set_ValueNoCheck (COLUMNNAME_A_Depreciation_Convention_ID, null); else set_ValueNoCheck (COLUMNNAME_A_Depreciation_Convention_ID, Integer.valueOf(A_Depreciation_Convention_ID)); } /** Get A_Depreciation_Convention_ID. @return A_Depreciation_Convention_ID */ public int getA_Depreciation_Convention_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_A_Depreciation_Convention_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getA_Depreciation_Convention_ID())); } /** Set ConventionType. @param ConventionType ConventionType */ public void setConventionType (String ConventionType) { set_Value (COLUMNNAME_ConventionType, ConventionType); } /** Get ConventionType. @return ConventionType */ public String getConventionType () { return (String)get_Value(COLUMNNAME_ConventionType); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () {
return (String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Text Message. @param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Convention.java
1
请在Spring Boot框架中完成以下Java代码
ApplicationRunner runner(ReplyingKafkaTemplate<String, String, String> template) { return args -> { // tag::sendReceive[] RequestReplyTypedMessageFuture<String, String, Thing> future1 = template.sendAndReceive(MessageBuilder.withPayload("getAThing").build(), new ParameterizedTypeReference<Thing>() { }); log.info(future1.getSendFuture().get(10, TimeUnit.SECONDS).getRecordMetadata().toString()); Thing thing = future1.get(10, TimeUnit.SECONDS).getPayload(); log.info(thing.toString()); RequestReplyTypedMessageFuture<String, String, List<Thing>> future2 = template.sendAndReceive(MessageBuilder.withPayload("getThings").build(), new ParameterizedTypeReference<List<Thing>>() { }); log.info(future2.getSendFuture().get(10, TimeUnit.SECONDS).getRecordMetadata().toString()); List<Thing> things = future2.get(10, TimeUnit.SECONDS).getPayload(); things.forEach(thing1 -> log.info(thing1.toString())); // end::sendReceive[] }; } @KafkaListener(id = "myId", topics = "requests", properties = "auto.offset.reset:earliest") @SendTo public byte[] listen(String in) { log.info(in); if (in.equals("\"getAThing\"")) { return ("{\"thingProp\":\"someValue\"}").getBytes(); } if (in.equals("\"getThings\"")) { return ("[{\"thingProp\":\"someValue1\"},{\"thingProp\":\"someValue2\"}]").getBytes(); } return in.toUpperCase().getBytes(); } public static class Thing { private String thingProp;
public String getThingProp() { return this.thingProp; } public void setThingProp(String thingProp) { this.thingProp = thingProp; } @Override public String toString() { return "Thing [thingProp=" + this.thingProp + "]"; } } }
repos\spring-kafka-main\spring-kafka-docs\src\main\java\org\springframework\kafka\jdocs\requestreply\Application.java
2
请完成以下Java代码
public void setM_AttributeValue_ID (final int M_AttributeValue_ID) { if (M_AttributeValue_ID < 1) set_Value (COLUMNNAME_M_AttributeValue_ID, null); else set_Value (COLUMNNAME_M_AttributeValue_ID, M_AttributeValue_ID); } @Override public int getM_AttributeValue_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeValue_ID); } @Override public void setRecord_Attribute_ID (final int Record_Attribute_ID) { if (Record_Attribute_ID < 1) set_ValueNoCheck (COLUMNNAME_Record_Attribute_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_Attribute_ID, Record_Attribute_ID); } @Override public int getRecord_Attribute_ID() { return get_ValueAsInt(COLUMNNAME_Record_Attribute_ID); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); }
@Override public void setValueDate (final @Nullable java.sql.Timestamp ValueDate) { set_Value (COLUMNNAME_ValueDate, ValueDate); } @Override public java.sql.Timestamp getValueDate() { return get_ValueAsTimestamp(COLUMNNAME_ValueDate); } @Override public void setValueNumber (final @Nullable BigDecimal ValueNumber) { set_Value (COLUMNNAME_ValueNumber, ValueNumber); } @Override public BigDecimal getValueNumber() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumber); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setValueString (final @Nullable java.lang.String ValueString) { set_Value (COLUMNNAME_ValueString, ValueString); } @Override public java.lang.String getValueString() { return get_ValueAsString(COLUMNNAME_ValueString); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Record_Attribute.java
1
请完成以下Java代码
public void setReadCount(Integer readCount) { this.readCount = readCount; } public String getPics() { return pics; } public void setPics(String pics) { this.pics = pics; } public String getMemberIcon() { return memberIcon; } public void setMemberIcon(String memberIcon) { this.memberIcon = memberIcon; } public Integer getReplayCount() { return replayCount; } public void setReplayCount(Integer replayCount) { this.replayCount = replayCount; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" [");
sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productId=").append(productId); sb.append(", memberNickName=").append(memberNickName); sb.append(", productName=").append(productName); sb.append(", star=").append(star); sb.append(", memberIp=").append(memberIp); sb.append(", createTime=").append(createTime); sb.append(", showStatus=").append(showStatus); sb.append(", productAttribute=").append(productAttribute); sb.append(", collectCouont=").append(collectCouont); sb.append(", readCount=").append(readCount); sb.append(", pics=").append(pics); sb.append(", memberIcon=").append(memberIcon); sb.append(", replayCount=").append(replayCount); sb.append(", content=").append(content); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsComment.java
1
请完成以下Java代码
public class StreamFromEmptyList { public static void main(String[] args) { createStreamFromEmptyList(); List<String> nameList = getList(); printNameLengths(nameList); // passing null printNameLengths((nameList == null) ? List.of() : nameList); // passing empty list collectStreamOfEmptyListToAnotherList(); } private static void collectStreamOfEmptyListToAnotherList() { List<String> emptyList = new ArrayList<>(); List<String> collectedList = emptyList.stream().collect(Collectors.toList()); System.out.println(collectedList.size() == 0); collectedList = emptyList.stream().filter(s -> s.startsWith("a")).collect(Collectors.toList()); System.out.println(collectedList.size() == 0); } private static void createStreamFromEmptyList() { List<String> emptyList = new ArrayList<>(); Stream<String> emptyStream = emptyList.stream(); System.out.println(emptyStream.findAny().isEmpty()); } private static void printNameLengths(List<String> nameList) { // Without Stream - Traditional approach with null check if (nameList != null) {
for (String name : nameList) { System.out.println("Length of " + name + ": " + name.length()); } } else { System.out.println("List is null. Unable to process."); } // With Stream - More concise approach Optional.ofNullable(nameList).ifPresent(list -> list.stream() .map(name -> "Length of " + name + ": " + name.length()).forEach(System.out::println)); } private static List<String> getList() { // This method may return null for demonstration purposes return null; } }
repos\tutorials-master\core-java-modules\core-java-streams-6\src\main\java\com\baeldung\streams\emptylists\StreamFromEmptyList.java
1
请完成以下Java代码
public static RemoteToLocalSyncResult notYetAddedToRemotePlatform(@NonNull final DataRecord datarecord) { return RemoteToLocalSyncResult.builder() .synchedDataRecord(datarecord) .remoteToLocalStatus(RemoteToLocalStatus.NOT_YET_ADDED_TO_REMOTE_PLATFORM) .build(); } /** contact or campaign that doesn't yet exist locally */ public static RemoteToLocalSyncResult obtainedNewDataRecord(@NonNull final DataRecord datarecord) { return RemoteToLocalSyncResult.builder() .synchedDataRecord(datarecord) .remoteToLocalStatus(RemoteToLocalStatus.OBTAINED_NEW_CONTACT_PERSON) .build(); } public static RemoteToLocalSyncResult noChanges(@NonNull final DataRecord dataRecord) { return RemoteToLocalSyncResult.builder() .synchedDataRecord(dataRecord) .remoteToLocalStatus(RemoteToLocalStatus.NO_CHANGES) .build(); } public static RemoteToLocalSyncResult error(@NonNull final DataRecord datarecord, String errorMessage) { return RemoteToLocalSyncResult.builder() .synchedDataRecord(datarecord) .remoteToLocalStatus(RemoteToLocalStatus.ERROR) .errorMessage(errorMessage) .build(); } public enum RemoteToLocalStatus { /** See {@link RemoteToLocalSyncResult#deletedOnRemotePlatform(DataRecord)}. */ DELETED_ON_REMOTE_PLATFORM, /** See {@link RemoteToLocalSyncResult#notYetAddedToRemotePlatform(DataRecord)}. */ NOT_YET_ADDED_TO_REMOTE_PLATFORM, /** See {@link RemoteToLocalSyncResult#obtainedRemoteId(DataRecord)}. */ OBTAINED_REMOTE_ID, /** See {@link RemoteToLocalSyncResult#obtainedRemoteEmail(DataRecord)}. */ OBTAINED_REMOTE_EMAIL,
/** See {@link RemoteToLocalSyncResult#obtainedEmailBounceInfo(DataRecord)}. */ OBTAINED_EMAIL_BOUNCE_INFO, OBTAINED_NEW_CONTACT_PERSON, NO_CHANGES, OBTAINED_OTHER_REMOTE_DATA, ERROR; } RemoteToLocalStatus remoteToLocalStatus; String errorMessage; DataRecord synchedDataRecord; @Builder private RemoteToLocalSyncResult( @NonNull final DataRecord synchedDataRecord, @Nullable final RemoteToLocalStatus remoteToLocalStatus, @Nullable final String errorMessage) { this.synchedDataRecord = synchedDataRecord; this.remoteToLocalStatus = remoteToLocalStatus; this.errorMessage = errorMessage; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\model\RemoteToLocalSyncResult.java
1
请完成以下Java代码
public Batch updateSuspensionStateAsync(ProcessEngine engine) { int params = parameterCount(processInstanceIds, processInstanceQuery, historicProcessInstanceQuery); if (params == 0) { String message = "Either processInstanceIds, processInstanceQuery or historicProcessInstanceQuery should be set to update the suspension state."; throw new InvalidRequestException(Status.BAD_REQUEST, message); } UpdateProcessInstancesSuspensionStateBuilder updateSuspensionStateBuilder = createUpdateSuspensionStateGroupBuilder(engine); if (getSuspended()) { return updateSuspensionStateBuilder.suspendAsync(); } else { return updateSuspensionStateBuilder.activateAsync(); } } protected UpdateProcessInstancesSuspensionStateBuilder createUpdateSuspensionStateGroupBuilder(ProcessEngine engine) { UpdateProcessInstanceSuspensionStateSelectBuilder selectBuilder = engine.getRuntimeService().updateProcessInstanceSuspensionState(); UpdateProcessInstancesSuspensionStateBuilder groupBuilder = null; if (processInstanceIds != null) { groupBuilder = selectBuilder.byProcessInstanceIds(processInstanceIds); } if (processInstanceQuery != null) { if (groupBuilder == null) {
groupBuilder = selectBuilder.byProcessInstanceQuery(processInstanceQuery.toQuery(engine)); } else { groupBuilder.byProcessInstanceQuery(processInstanceQuery.toQuery(engine)); } } if (historicProcessInstanceQuery != null) { if (groupBuilder == null) { groupBuilder = selectBuilder.byHistoricProcessInstanceQuery(historicProcessInstanceQuery.toQuery(engine)); } else { groupBuilder.byHistoricProcessInstanceQuery(historicProcessInstanceQuery.toQuery(engine)); } } return groupBuilder; } protected int parameterCount(Object... o) { int count = 0; for (Object o1 : o) { count += (o1 != null ? 1 : 0); } return count; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\ProcessInstanceSuspensionStateAsyncDto.java
1
请完成以下Java代码
private void ignoringNoSuchMethodError(Runnable method) { try { method.run(); } catch (NoSuchMethodError ex) { } } private void skipAllTldScanning(TomcatEmbeddedContext context) { StandardJarScanFilter filter = new StandardJarScanFilter(); filter.setTldSkip("*.jar"); context.getJarScanner().setJarScanFilter(filter); } /** * Configure the Tomcat {@link Context}. * @param context the Tomcat context */ protected void configureContext(Context context) {
this.getContextLifecycleListeners().forEach(context::addLifecycleListener); new DisableReferenceClearingContextCustomizer().customize(context); this.getContextCustomizers().forEach((customizer) -> customizer.customize(context)); } /** * Factory method called to create the {@link TomcatWebServer}. Subclasses can * override this method to return a different {@link TomcatWebServer} or apply * additional processing to the Tomcat server. * @param tomcat the Tomcat server. * @return a new {@link TomcatWebServer} instance */ protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) { return new TomcatWebServer(tomcat, getPort() >= 0, getShutdown()); } }
repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\reactive\TomcatReactiveWebServerFactory.java
1
请完成以下Java代码
public void setPointsBase_Invoiced (final BigDecimal PointsBase_Invoiced) { set_Value (COLUMNNAME_PointsBase_Invoiced, PointsBase_Invoiced); } @Override public BigDecimal getPointsBase_Invoiced() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsBase_Invoiced); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPOReference (final @Nullable java.lang.String POReference) { set_Value (COLUMNNAME_POReference, POReference); }
@Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_Commission_Instance.java
1
请完成以下Java代码
public LookupDataSourceContext.Builder newContextForFetchingById(final Object id) { return LookupDataSourceContext.builderWithoutTableName(); } @Override @Nullable public abstract LookupValue retrieveLookupValueById(@NonNull LookupDataSourceContext evalCtx); @Override public LookupDataSourceContext.Builder newContextForFetchingList() { return LookupDataSourceContext.builderWithoutTableName(); } @Override public abstract LookupValuesPage retrieveEntities(LookupDataSourceContext evalCtx); @Override @Nullable public final String getCachePrefix() { // NOTE: method will never be called because isCached() == true return null; } @Override public final boolean isCached() {
return true; } @Override public void cacheInvalidate() { } @Override public Optional<WindowId> getZoomIntoWindowId() { return Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\SimpleLookupDescriptorTemplate.java
1
请在Spring Boot框架中完成以下Java代码
public void setRepairOrderSummary (final @Nullable java.lang.String RepairOrderSummary) { set_Value (COLUMNNAME_RepairOrderSummary, RepairOrderSummary); } @Override public java.lang.String getRepairOrderSummary() { return get_ValueAsString(COLUMNNAME_RepairOrderSummary); } @Override public void setRepairServicePerformed_Product_ID (final int RepairServicePerformed_Product_ID) { if (RepairServicePerformed_Product_ID < 1) set_Value (COLUMNNAME_RepairServicePerformed_Product_ID, null); else set_Value (COLUMNNAME_RepairServicePerformed_Product_ID, RepairServicePerformed_Product_ID); } @Override public int getRepairServicePerformed_Product_ID() { return get_ValueAsInt(COLUMNNAME_RepairServicePerformed_Product_ID); } @Override public void setRepair_VHU_ID (final int Repair_VHU_ID) { if (Repair_VHU_ID < 1) set_Value (COLUMNNAME_Repair_VHU_ID, null); else set_Value (COLUMNNAME_Repair_VHU_ID, Repair_VHU_ID); } @Override public int getRepair_VHU_ID() { return get_ValueAsInt(COLUMNNAME_Repair_VHU_ID); } /** * Status AD_Reference_ID=541245 * Reference name: C_Project_Repair_Task_Status */ public static final int STATUS_AD_Reference_ID=541245;
/** Not Started = NS */ public static final String STATUS_NotStarted = "NS"; /** In Progress = IP */ public static final String STATUS_InProgress = "IP"; /** Completed = CO */ public static final String STATUS_Completed = "CO"; @Override public void setStatus (final java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return get_ValueAsString(COLUMNNAME_Status); } /** * Type AD_Reference_ID=541243 * Reference name: C_Project_Repair_Task_Type */ public static final int TYPE_AD_Reference_ID=541243; /** ServiceRepairOrder = W */ public static final String TYPE_ServiceRepairOrder = "W"; /** SpareParts = P */ public static final String TYPE_SpareParts = "P"; @Override public void setType (final java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java-gen\de\metas\servicerepair\repository\model\X_C_Project_Repair_Task.java
2
请在Spring Boot框架中完成以下Java代码
public boolean isAutoCreateIndex() { return this.autoCreateIndex; } public void setAutoCreateIndex(boolean autoCreateIndex) { this.autoCreateIndex = autoCreateIndex; } public @Nullable String getUserName() { return this.userName; } public void setUserName(@Nullable String userName) { this.userName = userName; } public @Nullable String getPassword() { return this.password; } public void setPassword(@Nullable String password) { this.password = password; } public @Nullable String getPipeline() { return this.pipeline; } public void setPipeline(@Nullable String pipeline) { this.pipeline = pipeline; } public @Nullable String getApiKeyCredentials() {
return this.apiKeyCredentials; } public void setApiKeyCredentials(@Nullable String apiKeyCredentials) { this.apiKeyCredentials = apiKeyCredentials; } public boolean isEnableSource() { return this.enableSource; } public void setEnableSource(boolean enableSource) { this.enableSource = enableSource; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\elastic\ElasticProperties.java
2
请完成以下Java代码
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Customer patient = (Customer) o; return Objects.equals(id, patient.id); } @Override public int hashCode() { return Objects.hash(id); } public Long getId() { return id; } public String getEmail() { return email; } public void setEmail(String email) {
this.email = email; } public LocalDate getDob() { return dob; } public void setDob(LocalDate dob) { this.dob = dob; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\spring\data\jpa\joinquery\entities\Customer.java
1
请在Spring Boot框架中完成以下Java代码
public void saveUserPosition(String userIds, String positionId) { String[] userIdArray = userIds.split(SymbolConstant.COMMA); //存在的用户 StringBuilder userBuilder = new StringBuilder(); for (String userId : userIdArray) { //获取成员是否存在于职位中 Long count = sysUserPositionMapper.getUserPositionCount(userId, positionId); if (count == 0) { //插入到用户职位关系表里面 SysUserPosition userPosition = new SysUserPosition(); userPosition.setPositionId(positionId); userPosition.setUserId(userId); sysUserPositionMapper.insert(userPosition); } else { userBuilder.append(userId).append(SymbolConstant.COMMA); } } //如果用户id存在,说明已存在用户职位关系表中,提示用户已存在 String uIds = userBuilder.toString(); if (oConvertUtils.isNotEmpty(uIds)) { //查询用户列表 List<SysUser> sysUsers = userMapper.selectBatchIds(Arrays.asList(uIds.split(SymbolConstant.COMMA)));
String realnames = sysUsers.stream().map(SysUser::getRealname).collect(Collectors.joining(SymbolConstant.COMMA)); throw new JeecgBootException(realnames + "已存在该职位中"); } } @Override public void removeByPositionId(String positionId) { sysUserPositionMapper.removeByPositionId(positionId); } @Override public void removePositionUser(String userIds, String positionId) { String[] userIdArray = userIds.split(SymbolConstant.COMMA); sysUserPositionMapper.removePositionUser(Arrays.asList(userIdArray),positionId); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysUserPositionServiceImpl.java
2
请完成以下Java代码
public void setIsCanExport (boolean IsCanExport) { set_Value (COLUMNNAME_IsCanExport, Boolean.valueOf(IsCanExport)); } /** Get Kann exportieren. @return Users with this role can export data */ @Override public boolean isCanExport () { Object oo = get_Value(COLUMNNAME_IsCanExport); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Kann Berichte erstellen. @param IsCanReport Users with this role can create reports */ @Override public void setIsCanReport (boolean IsCanReport) { set_Value (COLUMNNAME_IsCanReport, Boolean.valueOf(IsCanReport)); } /** Get Kann Berichte erstellen. @return Users with this role can create reports */ @Override public boolean isCanReport () { Object oo = get_Value(COLUMNNAME_IsCanReport); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Ausschluß. @param IsExclude Exclude access to the data - if not selected Include access to the data */ @Override public void setIsExclude (boolean IsExclude) { set_Value (COLUMNNAME_IsExclude, Boolean.valueOf(IsExclude)); } /** Get Ausschluß. @return Exclude access to the data - if not selected Include access to the data */ @Override public boolean isExclude () { Object oo = get_Value(COLUMNNAME_IsExclude); if (oo != null) { if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Schreibgeschützt. @param IsReadOnly Field is read only */ @Override public void setIsReadOnly (boolean IsReadOnly) { set_Value (COLUMNNAME_IsReadOnly, Boolean.valueOf(IsReadOnly)); } /** Get Schreibgeschützt. @return Field is read only */ @Override public boolean isReadOnly () { Object oo = get_Value(COLUMNNAME_IsReadOnly); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Table_Access.java
1
请完成以下Java代码
private I_PP_Order_BOMLine getTargetOrderBOMLine(@NonNull final ProductId productId) { final List<I_PP_Order_BOMLine> targetBOMLines = targetOrderBOMLines; // // Find the BOM line which is strictly matching our product final I_PP_Order_BOMLine targetBOMLine = targetBOMLines .stream() .filter(bomLine -> bomLine.getM_Product_ID() == productId.getRepoId()) .findFirst() .orElse(null); if (targetBOMLine != null) { return targetBOMLine; } // // Find a BOM line which accepts any product return targetBOMLines .stream() .filter(I_PP_Order_BOMLine::isAllowIssuingAnyProduct) .findFirst() .orElseThrow(() -> new HUException("No BOM line found for productId=" + productId + " in " + targetBOMLines)); } /** * @return how much quantity to take "from" and issue it to given BOM line */ private Quantity calculateQtyToIssue(final I_PP_Order_BOMLine targetBOMLine, final IHUProductStorage from) { // // Case: enforced qty to issue if (remainingQtyToIssue != null) { final Quantity huStorageQty = from.getQty(remainingQtyToIssue.getUOM()); final Quantity qtyToIssue = huStorageQty.min(remainingQtyToIssue); remainingQtyToIssue = remainingQtyToIssue.subtract(qtyToIssue); return qtyToIssue; } if (considerIssueMethodForQtyToIssueCalculation) {
// // Case: if this is an Issue BOM Line, IssueMethod is Backflush and we did not over-issue on it yet // => enforce the capacity to Projected Qty Required (i.e. standard Qty that needs to be issued on this line). // initial concept: http://dewiki908/mediawiki/index.php/07433_Folie_Zuteilung_Produktion_Fertigstellung_POS_%28102170996938%29 // additional (use of projected qty required): http://dewiki908/mediawiki/index.php/07601_Calculation_of_Folie_in_Action_Receipt_%28102017845369%29 final BOMComponentIssueMethod issueMethod = BOMComponentIssueMethod.ofNullableCode(targetBOMLine.getIssueMethod()); if (BOMComponentIssueMethod.IssueOnlyForReceived.equals(issueMethod)) { final PPOrderId ppOrderId = PPOrderId.ofRepoId(targetBOMLine.getPP_Order_ID()); final DraftPPOrderQuantities draftQtys = huPPOrderQtyBL.getDraftPPOrderQuantities(ppOrderId); return ppOrderBOMBL.computeQtyToIssueBasedOnFinishedGoodReceipt(targetBOMLine, from.getC_UOM(), draftQtys); } } return from.getQty(); } private void validateSourceHUs(@NonNull final Collection<I_M_HU> sourceHUs) { for (final I_M_HU hu : sourceHUs) { if (!handlingUnitsBL.isHUHierarchyCleared(HuId.ofRepoId(hu.getM_HU_ID()))) { throw new HUException(MSG_IssuingNotClearedHUsNotAllowed) .markAsUserValidationError() .setParameter("M_HU_ID", hu.getM_HU_ID()); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\hu_pporder_issue_producer\CreateDraftIssuesCommand.java
1
请在Spring Boot框架中完成以下Java代码
private String convertResourceNameToURLString(final String resourceName) { if (Check.isEmpty(reportsPathPrefix)) { return resourceName; } final StringBuilder urlStr = new StringBuilder(); if (resourceName.startsWith(PLACEHOLDER)) { if (resourceName.startsWith(PLACEHOLDER + "/")) { urlStr.append(resourceName.replace(PLACEHOLDER, reportsPathPrefix)); } else { if (reportsPathPrefix.endsWith("/")) { urlStr.append(resourceName.replace(PLACEHOLDER, reportsPathPrefix)); } else { urlStr.append(resourceName.replace(PLACEHOLDER, reportsPathPrefix + "/")); } } alwaysPrependPrefix = true; return urlStr.toString(); } else { final Pattern pattern = Pattern.compile("@([\\S]+)@([\\S]+)"); final Matcher matcher = pattern.matcher(resourceName); if (matcher.find()) { reportsPathPrefix = matcher.group(1); urlStr.append(reportsPathPrefix); final String report = matcher.group(2); if (!reportsPathPrefix.endsWith("/") && !report.startsWith("/")) {
urlStr.append("/"); } urlStr.append(report); alwaysPrependPrefix = true; return urlStr.toString(); } } if (alwaysPrependPrefix) { urlStr.append(reportsPathPrefix); if (!reportsPathPrefix.endsWith("/") && !resourceName.startsWith("/")) { urlStr.append("/"); } } urlStr.append(resourceName); return urlStr.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\class_loader\JasperClassLoader.java
2
请在Spring Boot框架中完成以下Java代码
private void mergeFile(String fName, long page) { File file = new File(DOWN_PATH, fName); try { BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file)); for (long i = 0; i <= page; i++) { File tempFile = new File(DOWN_PATH, i + "-" + fName); while (!file.exists() || (i != page && tempFile.length() < PER_PAGE)) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } byte[] bytes = FileUtils.readFileToByteArray(tempFile); os.write(bytes); os.flush(); tempFile.delete(); } File testFile = new File(DOWN_PATH, -1 + "-null"); testFile.delete(); os.flush(); os.close(); } catch (IOException e) { e.printStackTrace(); } } /** * get file size */ private long getRemoteFileSize(String remoteFileUrl) throws IOException { long fileSize = 0; HttpURLConnection httpConnection = (HttpURLConnection) new URL(remoteFileUrl).openConnection(); //使用HEAD方法 httpConnection.setRequestMethod("HEAD"); int responseCode = httpConnection.getResponseCode(); if (responseCode >= 400) { LOGGER.debug("Web responsible fail!"); return 0; } String sHeader; for (int i = 1;; i++) { sHeader = httpConnection.getHeaderFieldKey(i);
if (sHeader != null && sHeader.equals("Content-Length")) { LOGGER.debug("file size ContentLength:" + httpConnection.getContentLength()); fileSize = Long.parseLong(httpConnection.getHeaderField(sHeader)); break; } } return fileSize; } class DownloadThread implements Callable<DownLoadFileInfo> { long start; long end; long page; String fName; public DownloadThread(long start, long end, long page, String fName) { this.start = start; this.end = end; this.page = page; this.fName = fName; } @Override public DownLoadFileInfo call() { return download(start, end, page, fName); } } }
repos\springboot-demo-master\file\src\main\java\com\et\controller\DownloadController.java
2
请完成以下Java代码
public final class ExpressionContext { public static final Builder builder() { return new Builder(); } public static final ExpressionContext EMPTY = new ExpressionContext(); private final ImmutableMap<String, Object> context; private ExpressionContext(final ImmutableMap<String, Object> context) { super(); this.context = context; } private ExpressionContext() { super(); context = ImmutableMap.of(); } public Object get(final String name) { return context.get(name); } public static final class Builder { private final ImmutableMap.Builder<String, Object> context = ImmutableMap.builder(); private Builder() {
super(); } public ExpressionContext build() { final ImmutableMap<String, Object> context = this.context.build(); if (context.isEmpty()) { return EMPTY; } return new ExpressionContext(context); } public Builder putContext(final String name, final Object value) { if (value == null) { return this; } context.put(name, value); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\ExpressionContext.java
1
请在Spring Boot框架中完成以下Java代码
public java.sql.Date read(JsonReader in) throws IOException { switch (in.peek()) { case NULL: in.nextNull(); return null; default: String date = in.nextString(); try { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } } } } /** * Gson TypeAdapter for java.util.Date type * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter<Date> { private DateFormat dateFormat; public DateTypeAdapter() { } public DateTypeAdapter(DateFormat dateFormat) { this.dateFormat = dateFormat; } public void setFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; } @Override public void write(JsonWriter out, Date date) throws IOException { if (date == null) { out.nullValue(); } else { String value;
if (dateFormat != null) { value = dateFormat.format(date); } else { value = ISO8601Utils.format(date, true); } out.value(value); } } @Override public Date read(JsonReader in) throws IOException { try { switch (in.peek()) { case NULL: in.nextNull(); return null; default: String date = in.nextString(); try { if (dateFormat != null) { return dateFormat.parse(date); } return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); } } } catch (IllegalArgumentException e) { throw new JsonParseException(e); } } } public JSON setDateFormat(DateFormat dateFormat) { dateTypeAdapter.setFormat(dateFormat); return this; } public JSON setSqlDateFormat(DateFormat dateFormat) { sqlDateTypeAdapter.setFormat(dateFormat); return this; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\JSON.java
2
请完成以下Java代码
public Integer getParseStrategy() { return parseStrategy; } public void setParseStrategy(Integer parseStrategy) { this.parseStrategy = parseStrategy; } public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; }
public String getPattern() { return pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public Integer getMatchStrategy() { return matchStrategy; } public void setMatchStrategy(Integer matchStrategy) { this.matchStrategy = matchStrategy; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\vo\gateway\rule\GatewayParamFlowItemVo.java
1
请完成以下Java代码
public class ClassDelegateCaseExecutionListener extends ClassDelegate implements CaseExecutionListener { protected static final CmmnBehaviorLogger LOG = ProcessEngineLogger.CMNN_BEHAVIOR_LOGGER; public ClassDelegateCaseExecutionListener(String className, List<FieldDeclaration> fieldDeclarations) { super(className, fieldDeclarations); } public ClassDelegateCaseExecutionListener(Class<?> clazz, List<FieldDeclaration> fieldDeclarations) { super(clazz, fieldDeclarations); } public void notify(DelegateCaseExecution caseExecution) throws Exception { CaseExecutionListener listenerInstance = getListenerInstance(); Context .getProcessEngineConfiguration() .getDelegateInterceptor()
.handleInvocation(new CaseExecutionListenerInvocation(listenerInstance, caseExecution)); } protected CaseExecutionListener getListenerInstance() { Object delegateInstance = instantiateDelegate(className, fieldDeclarations); if (delegateInstance instanceof CaseExecutionListener) { return (CaseExecutionListener) delegateInstance; } else { throw LOG.missingDelegateParentClassException(delegateInstance.getClass().getName(), CaseExecutionListener.class.getName()); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\listener\ClassDelegateCaseExecutionListener.java
1
请完成以下Java代码
public List<String> getFollowingIds() { return Collections.unmodifiableList(followingIds); } public List<String> getFavoriteArticleIds() { return Collections.unmodifiableList(favoriteArticleIds); } public void follow(String userId) { followingIds.add(userId); } public void unfollow(String userId) { followingIds.remove(userId); } public void follow(User user) { follow(user.getId()); } public void unfollow(User user) { unfollow(user.getId()); } public void favorite(Article article) {
article.incrementFavoritesCount(); favoriteArticleIds.add(article.getId()); } public void unfavorite(Article article) { article.decrementFavoritesCount(); favoriteArticleIds.remove(article.getId()); } public boolean isFavoriteArticle(Article article) { return favoriteArticleIds.contains(article.getId()); } public boolean isFollowing(User user) { return followingIds.contains(user.getId()); } public boolean isFollower(User user) { return user.isFollowing(this); } }
repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\user\User.java
1
请在Spring Boot框架中完成以下Java代码
public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setPrice (final BigDecimal Price) { set_Value (COLUMNNAME_Price, Price); } @Override public BigDecimal getPrice() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Price); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setProductName (final java.lang.String ProductName) { set_Value (COLUMNNAME_ProductName, ProductName); } @Override public java.lang.String getProductName() { return get_ValueAsString(COLUMNNAME_ProductName); } @Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setScannedBarcode (final @Nullable java.lang.String ScannedBarcode) {
set_Value (COLUMNNAME_ScannedBarcode, ScannedBarcode); } @Override public java.lang.String getScannedBarcode() { return get_ValueAsString(COLUMNNAME_ScannedBarcode); } @Override public void setTaxAmt (final BigDecimal TaxAmt) { set_Value (COLUMNNAME_TaxAmt, TaxAmt); } @Override public BigDecimal getTaxAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_OrderLine.java
2
请完成以下Java代码
protected void loadChildExecutionsFromCache(ExecutionEntity execution, List<ExecutionEntity> childExecutions) { List<ExecutionEntity> childrenOfThisExecution = execution.getExecutions(); if(childrenOfThisExecution != null) { childExecutions.addAll(childrenOfThisExecution); for (ExecutionEntity child : childrenOfThisExecution) { loadChildExecutionsFromCache(child, childExecutions); } } } protected Map<String, List<Incident>> groupIncidentIdsByExecutionId(CommandContext commandContext) { List<IncidentEntity> incidents = commandContext.getIncidentManager().findIncidentsByProcessInstance(processInstanceId); Map<String, List<Incident>> result = new HashMap<>(); for (IncidentEntity incidentEntity : incidents) { CollectionUtil.addToMapOfLists(result, incidentEntity.getExecutionId(), incidentEntity); } return result; } protected List<String> getIncidentIds(Map<String, List<Incident>> incidents, PvmExecutionImpl execution) { List<String> incidentIds = new ArrayList<>(); List<Incident> incidentList = incidents.get(execution.getId()); if (incidentList != null) { for (Incident incident : incidentList) { incidentIds.add(incident.getId()); } return incidentIds; } else { return Collections.emptyList(); } }
protected List<Incident> getIncidents(Map<String, List<Incident>> incidents, PvmExecutionImpl execution) { List<Incident> incidentList = incidents.get(execution.getId()); if (incidentList != null) { return incidentList; } else { return Collections.emptyList(); } } public static class ExecutionIdComparator implements Comparator<ExecutionEntity> { public static final ExecutionIdComparator INSTANCE = new ExecutionIdComparator(); @Override public int compare(ExecutionEntity o1, ExecutionEntity o2) { return o1.getId().compareTo(o2.getId()); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\GetActivityInstanceCmd.java
1
请完成以下Java代码
public class Email { @Column(name = "email", nullable = false) private String address; public Email(String address) { this.address = address; } protected Email() { } @Override public String toString() { return address;
} @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Email email = (Email) o; return address.equals(email.address); } @Override public int hashCode() { return Objects.hash(address); } }
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\user\Email.java
1
请完成以下Java代码
public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getProcessDefId() { return processDefId; } public void setProcessDefId(String processDefId) { this.processDefId = processDefId; } public TaskEntity getTask() { if ((task == null) && (taskId != null)) { this.task = Context.getCommandContext().getTaskEntityManager().findById(taskId); } return task; } public void setTask(TaskEntity task) { this.task = task; this.taskId = task.getId(); } public ExecutionEntity getProcessInstance() { if ((processInstance == null) && (processInstanceId != null)) { this.processInstance = Context.getCommandContext().getExecutionEntityManager().findById(processInstanceId); } return processInstance; } public void setProcessInstance(ExecutionEntity processInstance) { this.processInstance = processInstance; this.processInstanceId = processInstance.getId(); } public ProcessDefinitionEntity getProcessDef() { if ((processDef == null) && (processDefId != null)) { this.processDef = Context.getCommandContext().getProcessDefinitionEntityManager().findById(processDefId); } return processDef; } public void setProcessDef(ProcessDefinitionEntity processDef) { this.processDef = processDef; this.processDefId = processDef.getId(); } @Override public String getProcessDefinitionId() { return this.processDefId; }
public void setDetails(byte[] details) { this.details = details; } public byte[] getDetails() { return this.details; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("IdentityLinkEntity[id=").append(id); sb.append(", type=").append(type); if (userId != null) { sb.append(", userId=").append(userId); } if (groupId != null) { sb.append(", groupId=").append(groupId); } if (taskId != null) { sb.append(", taskId=").append(taskId); } if (processInstanceId != null) { sb.append(", processInstanceId=").append(processInstanceId); } if (processDefId != null) { sb.append(", processDefId=").append(processDefId); } if (details != null) { sb.append(", details=").append(new String(details)); } sb.append("]"); return sb.toString(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\IdentityLinkEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
private boolean isExternalSystemCompatible( @NonNull final Workplace workplace, @NonNull final ShipmentSchedule schedule) { final ImmutableSet<ExternalSystemId> workplaceExternalSystems = workplace.getExternalSystemIds(); if (workplaceExternalSystems.isEmpty()) { return true; } final ExternalSystemId externalSystemId = schedule.getExternalSystemId(); if (externalSystemId == null) { return false; } return workplaceExternalSystems.contains(externalSystemId); } private boolean isPriorityCompatible( @NonNull final Workplace workplace, @NonNull final ShipmentSchedule schedule) { final PriorityRule priorityRule = workplace.getPriorityRule(); if (priorityRule == null)
{ return true; } return PriorityRule.equals(priorityRule, schedule.getPriorityRule()); } private static class WorkplacesCapacity { private final Map<WorkplaceId, Integer> assignedCountPerWorkplace = new HashMap<>(); void increase(@NonNull final WorkplaceId workplaceId) { assignedCountPerWorkplace.merge(workplaceId, 1, Integer::sum); } boolean hasCapacity(@NonNull final Workplace workplace) { final int currentAssigned = assignedCountPerWorkplace.getOrDefault(workplace.getId(), 0); return currentAssigned < workplace.getMaxPickingJobs(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job_schedule\service\commands\PickingJobScheduleAutoAssignCommand.java
2
请在Spring Boot框架中完成以下Java代码
public Saml2MetadataConfigurer<H> metadataUrl(String metadataUrl) { Assert.hasText(metadataUrl, "metadataUrl cannot be empty"); this.metadataResponseResolver = (registrations) -> { if (USE_OPENSAML_5) { RequestMatcherMetadataResponseResolver metadata = new RequestMatcherMetadataResponseResolver( registrations, new OpenSaml5MetadataResolver()); metadata.setRequestMatcher(getRequestMatcherBuilder().matcher(metadataUrl)); return metadata; } throw new IllegalArgumentException( "Spring Security does not support OpenSAML " + Version.getVersion() + ". Please use OpenSAML 5"); }; return this; } /** * Use this {@link Saml2MetadataResponseResolver} to parse the request and respond * with SAML 2.0 metadata. * @param metadataResponseResolver to use * @return the {@link Saml2MetadataConfigurer} for more customizations */ public Saml2MetadataConfigurer<H> metadataResponseResolver(Saml2MetadataResponseResolver metadataResponseResolver) { Assert.notNull(metadataResponseResolver, "metadataResponseResolver cannot be null"); this.metadataResponseResolver = (registrations) -> metadataResponseResolver; return this; } public H and() { return getBuilder(); } @Override public void configure(H http) { Saml2MetadataResponseResolver metadataResponseResolver = createMetadataResponseResolver(http); http.addFilterBefore(new Saml2MetadataFilter(metadataResponseResolver), BasicAuthenticationFilter.class); } private Saml2MetadataResponseResolver createMetadataResponseResolver(H http) { if (this.metadataResponseResolver != null) { RelyingPartyRegistrationRepository registrations = getRelyingPartyRegistrationRepository(http); return this.metadataResponseResolver.apply(registrations); } Saml2MetadataResponseResolver metadataResponseResolver = getBeanOrNull(Saml2MetadataResponseResolver.class); if (metadataResponseResolver != null) { return metadataResponseResolver; }
RelyingPartyRegistrationRepository registrations = getRelyingPartyRegistrationRepository(http); if (USE_OPENSAML_5) { return new RequestMatcherMetadataResponseResolver(registrations, new OpenSaml5MetadataResolver()); } throw new IllegalArgumentException( "Spring Security does not support OpenSAML " + Version.getVersion() + ". Please use OpenSAML 5"); } private RelyingPartyRegistrationRepository getRelyingPartyRegistrationRepository(H http) { Saml2LoginConfigurer<H> login = http.getConfigurer(Saml2LoginConfigurer.class); if (login != null) { return login.relyingPartyRegistrationRepository(http); } else { return getBeanOrNull(RelyingPartyRegistrationRepository.class); } } private <C> C getBeanOrNull(Class<C> clazz) { if (this.context == null) { return null; } return this.context.getBeanProvider(clazz).getIfAvailable(); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\saml2\Saml2MetadataConfigurer.java
2
请完成以下Java代码
protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_AD_PrintColor[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Print Color. @param AD_PrintColor_ID Color used for printing and display */ public void setAD_PrintColor_ID (int AD_PrintColor_ID) { if (AD_PrintColor_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_PrintColor_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_PrintColor_ID, Integer.valueOf(AD_PrintColor_ID)); } /** Get Print Color. @return Color used for printing and display */ public int getAD_PrintColor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_PrintColor_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Validation code. @param Code Validation Code */ public void setCode (String Code) { set_Value (COLUMNNAME_Code, Code); } /** Get Validation code. @return Validation Code */ public String getCode () { return (String)get_Value(COLUMNNAME_Code); } /** Set Default. @param IsDefault Default value
*/ public void setIsDefault (boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); } /** Get Default. @return Default value */ public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintColor.java
1
请完成以下Java代码
public HashcodeBuilder append(final BigDecimal value) { if (value == null) { return appendHashcode(0); } final Double d = value.doubleValue(); return appendHashcode(d.hashCode()); } public HashcodeBuilder appendHashcode(final int hashcodeToAppend) { hashcode = prime * hashcode + hashcodeToAppend; return this; } public HashcodeBuilder append(Map<?, ?> map, boolean handleEmptyMapAsNull) { if (handleEmptyMapAsNull && (map == null || map.isEmpty())) { return append((Object)null); } return append(map); }
public int toHashcode() { return hashcode; } /** * Sames as {@link #toHashcode()} because: * <ul> * <li>we want to avoid bugs like calling this method instead of {@link #toHashcode()} * <li>the real hash code of this object does not matter * </ul> * * @deprecated Please use {@link #toHashcode()}. This method is present here, just to avoid some mistakes. */ @Deprecated @Override public int hashCode() { return toHashcode(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\lang\HashcodeBuilder.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { final long selectedRecordsCount = getSelectedRecordCount(context); if (selectedRecordsCount > 1) { return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_ERR_MULTIPLE_EXTERNAL_SELECTION, getExternalSystemType().getValue())); } else if (selectedRecordsCount == 0) { final Optional<ExternalSystemParentConfig> config = getSelectedExternalSystemConfig(ExternalSystemParentConfigId.ofRepoId(context.getSingleSelectedRecordId())); if (!config.isPresent()) { return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_ERR_NO_EXTERNAL_SELECTION, getExternalSystemType().getValue())); } if (config.get().isActive()) { return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_ERR_EXTERNAL_SYSTEM_CONFIG_ACTIVE)); } } return ProcessPreconditionsResolution.accept();
} @NonNull protected Optional<ExternalSystemParentConfig> getSelectedExternalSystemConfig(@NonNull final ExternalSystemParentConfigId externalSystemParentConfigId) { final ExternalSystemConfigQuery query = ExternalSystemConfigQuery.builder() .parentConfigId(externalSystemParentConfigId) .build(); return externalSystemConfigRepo.getByQuery(getExternalSystemType(), query); } protected abstract void activateRecord(); protected abstract ExternalSystemType getExternalSystemType(); protected abstract long getSelectedRecordCount(final IProcessPreconditionsContext context); }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\InvokeActivateExternalConfig.java
1
请完成以下Java代码
public void setDelegationState(DelegationState delegationState) { activiti5Task.setDelegationState(delegationState); } @Override public void setDueDate(Date dueDate) { activiti5Task.setDueDate(dueDate); } @Override public void setCategory(String category) { activiti5Task.setCategory(category); } @Override public void setParentTaskId(String parentTaskId) { activiti5Task.setParentTaskId(parentTaskId); }
@Override public void setTenantId(String tenantId) { activiti5Task.setTenantId(tenantId); } @Override public void setFormKey(String formKey) { activiti5Task.setFormKey(formKey); } @Override public boolean isSuspended() { return activiti5Task.isSuspended(); } }
repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5TaskWrapper.java
1
请完成以下Java代码
public static void main(String args[]) { SchedulerFactory schedFact = new StdSchedulerFactory(); try { Scheduler sched = schedFact.getScheduler(); JobDetail job = JobBuilder.newJob(SimpleJob.class).withIdentity("myJob", "group1").usingJobData("jobSays", "Hello World!").usingJobData("myFloatValue", 3.141f).build(); Trigger trigger = TriggerBuilder.newTrigger().withIdentity("myTrigger", "group1").startNow().withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(40).repeatForever()).build(); JobDetail jobA = JobBuilder.newJob(JobA.class).withIdentity("jobA", "group2").build(); JobDetail jobB = JobBuilder.newJob(JobB.class).withIdentity("jobB", "group2").build();
Trigger triggerA = TriggerBuilder.newTrigger().withIdentity("triggerA", "group2").startNow().withPriority(15).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(40).repeatForever()).build(); Trigger triggerB = TriggerBuilder.newTrigger().withIdentity("triggerB", "group2").startNow().withPriority(10).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(20).repeatForever()).build(); sched.scheduleJob(job, trigger); sched.scheduleJob(jobA, triggerA); sched.scheduleJob(jobB, triggerB); sched.start(); } catch (SchedulerException e) { e.printStackTrace(); } } }
repos\tutorials-master\libraries\src\main\java\com\baeldung\quartz\QuartzExample.java
1
请在Spring Boot框架中完成以下Java代码
public void configure(AbstractEngineConfiguration engineConfiguration) { if (dmnEngineConfiguration == null) { dmnEngineConfiguration = new StandaloneInMemDmnEngineConfiguration(); } initialiseCommonProperties(engineConfiguration, dmnEngineConfiguration); initEngine(); initServiceConfigurations(engineConfiguration, dmnEngineConfiguration); } @Override protected List<Class<? extends Entity>> getEntityInsertionOrder() { return EntityDependencyOrder.INSERT_ORDER; } @Override protected List<Class<? extends Entity>> getEntityDeletionOrder() { return EntityDependencyOrder.DELETE_ORDER;
} @Override protected DmnEngine buildEngine() { if (dmnEngineConfiguration == null) { throw new FlowableException("DmnEngineConfiguration is required"); } return dmnEngineConfiguration.buildDmnEngine(); } public DmnEngineConfiguration getDmnEngineConfiguration() { return dmnEngineConfiguration; } public DmnEngineConfigurator setDmnEngineConfiguration(DmnEngineConfiguration dmnEngineConfiguration) { this.dmnEngineConfiguration = dmnEngineConfiguration; return this; } }
repos\flowable-engine-main\modules\flowable-dmn-engine-configurator\src\main\java\org\flowable\dmn\engine\configurator\DmnEngineConfigurator.java
2
请完成以下Java代码
protected TreeBuilder createDefaultTreeBuilder(Feature... features) { return new Builder(features); } private Class<?> load(Class<?> clazz, Properties properties) { if (properties != null) { String className = properties.getProperty(clazz.getName()); if (className != null) { ClassLoader loader; try { loader = Thread.currentThread().getContextClassLoader(); } catch (Exception e) { throw new ELException("Could not get context class loader", e); } try { return loader == null ? Class.forName(className) : loader.loadClass(className); } catch (ClassNotFoundException e) { throw new ELException("Class " + className + " not found", e); } catch (Exception e) { throw new ELException("Class " + className + " could not be instantiated", e); } } } return null; } @Override public final <T> T coerceToType(Object obj, Class<T> targetType) { return converter.convert(obj, targetType); } @Override public final ObjectValueExpression createValueExpression(Object instance, Class<?> expectedType) {
return new ObjectValueExpression(converter, instance, expectedType); } @Override public final TreeValueExpression createValueExpression(ELContext context, String expression, Class<?> expectedType) { return new TreeValueExpression(store, context.getFunctionMapper(), context.getVariableMapper(), converter, expression, expectedType); } @Override public final TreeMethodExpression createMethodExpression(ELContext context, String expression, Class<?> expectedReturnType, Class<?>[] expectedParamTypes) { return new TreeMethodExpression(store, context.getFunctionMapper(), context.getVariableMapper(), converter, expression, expectedReturnType, expectedParamTypes); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\de\odysseus\el\ExpressionFactoryImpl.java
1
请完成以下Java代码
public org.compiere.model.I_Data_Export_Audit getData_Export_Audit() { return get_ValueAsPO(COLUMNNAME_Data_Export_Audit_ID, org.compiere.model.I_Data_Export_Audit.class); } @Override public void setData_Export_Audit(final org.compiere.model.I_Data_Export_Audit Data_Export_Audit) { set_ValueFromPO(COLUMNNAME_Data_Export_Audit_ID, org.compiere.model.I_Data_Export_Audit.class, Data_Export_Audit); } @Override public void setData_Export_Audit_ID (final int Data_Export_Audit_ID) { if (Data_Export_Audit_ID < 1) set_Value (COLUMNNAME_Data_Export_Audit_ID, null); else set_Value (COLUMNNAME_Data_Export_Audit_ID, Data_Export_Audit_ID); } @Override public int getData_Export_Audit_ID() { return get_ValueAsInt(COLUMNNAME_Data_Export_Audit_ID); } @Override public void setData_Export_Audit_Log_ID (final int Data_Export_Audit_Log_ID) {
if (Data_Export_Audit_Log_ID < 1) set_ValueNoCheck (COLUMNNAME_Data_Export_Audit_Log_ID, null); else set_ValueNoCheck (COLUMNNAME_Data_Export_Audit_Log_ID, Data_Export_Audit_Log_ID); } @Override public int getData_Export_Audit_Log_ID() { return get_ValueAsInt(COLUMNNAME_Data_Export_Audit_Log_ID); } @Override public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID) { if (ExternalSystem_Config_ID < 1) set_Value (COLUMNNAME_ExternalSystem_Config_ID, null); else set_Value (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID); } @Override public int getExternalSystem_Config_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Data_Export_Audit_Log.java
1
请完成以下Java代码
public void setElement(DmnElement element) { this.element = element; } public int getXmlRowNumber() { return xmlRowNumber; } public void setXmlRowNumber(int xmlRowNumber) { this.xmlRowNumber = xmlRowNumber; } public int getXmlColumnNumber() { return xmlColumnNumber; } public void setXmlColumnNumber(int xmlColumnNumber) { this.xmlColumnNumber = xmlColumnNumber; } public boolean equals(GraphicInfo ginfo) { if (this.getX() != ginfo.getX()) { return false; } if (this.getY() != ginfo.getY()) { return false; } if (this.getHeight() != ginfo.getHeight()) {
return false; } if (this.getWidth() != ginfo.getWidth()) { return false; } // check for zero value in case we are comparing model value to BPMN DI value // model values do not have xml location information if (0 != this.getXmlColumnNumber() && 0 != ginfo.getXmlColumnNumber() && this.getXmlColumnNumber() != ginfo.getXmlColumnNumber()) { return false; } if (0 != this.getXmlRowNumber() && 0 != ginfo.getXmlRowNumber() && this.getXmlRowNumber() != ginfo.getXmlRowNumber()) { return false; } // only check for elements that support this value if (null != this.getExpanded() && null != ginfo.getExpanded() && !this.getExpanded().equals(ginfo.getExpanded())) { return false; } return true; } }
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\GraphicInfo.java
1
请完成以下Java代码
public class QuartzExample { public static void main(String args[]) { SchedulerFactory schedFact = new StdSchedulerFactory(); try { Scheduler sched = schedFact.getScheduler(); JobDetail job = JobBuilder.newJob(SimpleJob.class).withIdentity("myJob", "group1").usingJobData("jobSays", "Hello World!").usingJobData("myFloatValue", 3.141f).build(); Trigger trigger = TriggerBuilder.newTrigger().withIdentity("myTrigger", "group1").startNow().withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(40).repeatForever()).build(); JobDetail jobA = JobBuilder.newJob(JobA.class).withIdentity("jobA", "group2").build(); JobDetail jobB = JobBuilder.newJob(JobB.class).withIdentity("jobB", "group2").build();
Trigger triggerA = TriggerBuilder.newTrigger().withIdentity("triggerA", "group2").startNow().withPriority(15).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(40).repeatForever()).build(); Trigger triggerB = TriggerBuilder.newTrigger().withIdentity("triggerB", "group2").startNow().withPriority(10).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(20).repeatForever()).build(); sched.scheduleJob(job, trigger); sched.scheduleJob(jobA, triggerA); sched.scheduleJob(jobB, triggerB); sched.start(); } catch (SchedulerException e) { e.printStackTrace(); } } }
repos\tutorials-master\libraries\src\main\java\com\baeldung\quartz\QuartzExample.java
1
请完成以下Java代码
public Evaluatee toEvaluatee() { Evaluatee evaluatee = _evaluatee; if (evaluatee == null) { evaluatee = _evaluatee = createEvaluatee(); } return evaluatee; } private Evaluatee createEvaluatee() { return Evaluatees.mapBuilder() .put(Env.CTXNAME_AD_User_ID, loggedUserId.map(UserId::getRepoId).orElse(-1)) .put(Env.CTXNAME_AD_Org_ID, OrgId.toRepoIdOrAny(orgId)) .put(Env.CTXNAME_AD_Language, adLanguage) .put(AccessSqlStringExpression.PARAM_UserRolePermissionsKey.getName(), permissionsKey.toPermissionsKeyString()) .build(); } public JSONOptions toJSONOptions() { JSONOptions jsonOptions = this._jsonOptions; if (jsonOptions == null)
{ jsonOptions = _jsonOptions = createJSONOptions(); } return jsonOptions; } private JSONOptions createJSONOptions() { return JSONOptions.builder() .adLanguage(adLanguage) .zoneId(timeZone) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewEvaluationCtx.java
1
请完成以下Java代码
public void setVisible(final boolean visible) { super.setVisible(visible); if (visible) { toFront(); } } // setVisible /** * Calculate size and display */ private void display() { pack(); final Dimension ss = Toolkit.getDefaultToolkit().getScreenSize();
final Rectangle bounds = getBounds(); setBounds((ss.width - bounds.width) / 2, (ss.height - bounds.height) / 2, bounds.width, bounds.height); setVisible(true); } // display /** * Dispose Splash */ @Override public void dispose() { super.dispose(); s_splash = null; } // dispose } // Splash
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Splash.java
1
请完成以下Java代码
public class Order { private UUID id; private OrderStatus status; private List<OrderItem> orderItems; private BigDecimal price; public Order(final UUID id, final Product product) { this.id = id; this.orderItems = new ArrayList<>(Collections.singletonList(new OrderItem(product))); this.status = OrderStatus.CREATED; this.price = product.getPrice(); } public void complete() { validateState(); this.status = OrderStatus.COMPLETED; } public void addOrder(final Product product) { validateState(); validateProduct(product); orderItems.add(new OrderItem(product)); price = price.add(product.getPrice()); } public void removeOrder(final UUID id) { validateState(); final OrderItem orderItem = getOrderItem(id); orderItems.remove(orderItem); price = price.subtract(orderItem.getPrice()); } private OrderItem getOrderItem(final UUID id) { return orderItems.stream() .filter(orderItem -> orderItem.getProductId() .equals(id)) .findFirst() .orElseThrow(() -> new DomainException("Product with " + id + " doesn't exist.")); } private void validateState() { if (OrderStatus.COMPLETED.equals(status)) { throw new DomainException("The order is in completed state.");
} } private void validateProduct(final Product product) { if (product == null) { throw new DomainException("The product cannot be null."); } } public UUID getId() { return id; } public OrderStatus getStatus() { return status; } public BigDecimal getPrice() { return price; } public List<OrderItem> getOrderItems() { return Collections.unmodifiableList(orderItems); } @Override public int hashCode() { return Objects.hash(id, orderItems, price, status); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Order)) return false; Order other = (Order) obj; return Objects.equals(id, other.id) && Objects.equals(orderItems, other.orderItems) && Objects.equals(price, other.price) && status == other.status; } private Order() { } }
repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\dddhexagonalspring\domain\Order.java
1
请完成以下Java代码
public void setPickingJobAggregationType (final java.lang.String PickingJobAggregationType) { set_Value (COLUMNNAME_PickingJobAggregationType, PickingJobAggregationType); } @Override public java.lang.String getPickingJobAggregationType() { return get_ValueAsString(COLUMNNAME_PickingJobAggregationType); } @Override public void setPicking_User_ID (final int Picking_User_ID) { if (Picking_User_ID < 1) set_Value (COLUMNNAME_Picking_User_ID, null); else set_Value (COLUMNNAME_Picking_User_ID, Picking_User_ID); } @Override public int getPicking_User_ID() { return get_ValueAsInt(COLUMNNAME_Picking_User_ID); } @Override public void setPreparationDate (final @Nullable java.sql.Timestamp PreparationDate) { set_Value (COLUMNNAME_PreparationDate, PreparationDate); }
@Override public java.sql.Timestamp getPreparationDate() { return get_ValueAsTimestamp(COLUMNNAME_PreparationDate); } @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.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job.java
1
请完成以下Java代码
public List<CleanableHistoricProcessInstanceReportResult> executeList(CommandContext commandContext, final Page page) { provideHistoryCleanupStrategy(commandContext); checkQueryOk(); return commandContext .getHistoricProcessInstanceManager() .findCleanableHistoricProcessInstancesReportByCriteria(this, page); } public Date getCurrentTimestamp() { return currentTimestamp; } public void setCurrentTimestamp(Date currentTimestamp) { this.currentTimestamp = currentTimestamp; } public String[] getProcessDefinitionIdIn() { return processDefinitionIdIn; } public String[] getProcessDefinitionKeyIn() { return processDefinitionKeyIn; } public String[] getTenantIdIn() { return tenantIdIn; }
public void setTenantIdIn(String[] tenantIdIn) { this.tenantIdIn = tenantIdIn; } public boolean isTenantIdSet() { return isTenantIdSet; } public boolean isCompact() { return isCompact; } protected void provideHistoryCleanupStrategy(CommandContext commandContext) { String historyCleanupStrategy = commandContext.getProcessEngineConfiguration() .getHistoryCleanupStrategy(); isHistoryCleanupStrategyRemovalTimeBased = HISTORY_CLEANUP_STRATEGY_REMOVAL_TIME_BASED.equals(historyCleanupStrategy); } public boolean isHistoryCleanupStrategyRemovalTimeBased() { return isHistoryCleanupStrategyRemovalTimeBased; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\CleanableHistoricProcessInstanceReportImpl.java
1
请在Spring Boot框架中完成以下Java代码
public SessionUserInfo getUserInfo() { String token = MDC.get("token"); return getUserInfoFromCache(token); } /** * 根据token查询用户信息 * 如果token无效,会抛未登录的异常 */ private SessionUserInfo getUserInfoFromCache(String token) { if (StringTools.isNullOrEmpty(token)) { throw new CommonJsonException(ErrorEnum.E_20011); } log.debug("根据token从缓存中查询用户信息,{}", token); SessionUserInfo info = cacheMap.getIfPresent(token); if (info == null) { log.info("没拿到缓存 token={}", token); throw new CommonJsonException(ErrorEnum.E_20011); } return info; } private void setCache(String token, String username) { SessionUserInfo info = getUserInfoByUsername(username); log.info("设置用户信息缓存:token={} , username={}, info={}", token, username, info); cacheMap.put(token, info); } /**
* 退出登录时,将token置为无效 */ public void invalidateToken() { String token = MDC.get("token"); if (!StringTools.isNullOrEmpty(token)) { cacheMap.invalidate(token); } log.debug("退出登录,清除缓存:token={}", token); } private SessionUserInfo getUserInfoByUsername(String username) { SessionUserInfo userInfo = loginDao.getUserInfo(username); if (userInfo.getRoleIds().contains(1)) { //管理员,查出全部按钮和权限码 userInfo.setMenuList(loginDao.getAllMenu()); userInfo.setPermissionList(loginDao.getAllPermissionCode()); } return userInfo; } }
repos\SpringBoot-Shiro-Vue-master\back\src\main\java\com\heeexy\example\service\TokenService.java
2
请在Spring Boot框架中完成以下Java代码
public Boolean isArchived() { return archived; } public void setArchived(Boolean archived) { this.archived = archived; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PackagingUnit packagingUnit = (PackagingUnit) o; return Objects.equals(this.unit, packagingUnit.unit) && Objects.equals(this.quantity, packagingUnit.quantity) && Objects.equals(this.pcn, packagingUnit.pcn) && Objects.equals(this.defaultPackagingUnit, packagingUnit.defaultPackagingUnit) && Objects.equals(this.archived, packagingUnit.archived); } @Override public int hashCode() { return Objects.hash(unit, quantity, pcn, defaultPackagingUnit, archived); } @Override
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PackagingUnit {\n"); sb.append(" unit: ").append(toIndentedString(unit)).append("\n"); sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); sb.append(" pcn: ").append(toIndentedString(pcn)).append("\n"); sb.append(" defaultPackagingUnit: ").append(toIndentedString(defaultPackagingUnit)).append("\n"); sb.append(" archived: ").append(toIndentedString(archived)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\PackagingUnit.java
2
请完成以下Java代码
public void setNotice(final String notice) { label.setText(notice); } public String getNotice() { return label.getText(); } /** * Load status from context */ public void load() { final Properties ctx = Env.getCtx(); // FRESH-352: check if we shall override the default background color which we set in the constructor final String windowHeaderNoticeBGColorStr = Env.getContext(ctx, Env.CTXNAME_UI_WindowHeader_Notice_BG_COLOR); if (!Check.isEmpty(windowHeaderNoticeBGColorStr, true)) { final Color backgroundColor = Colors.toColor(windowHeaderNoticeBGColorStr); if (backgroundColor != null) { this.setBackground(backgroundColor); } } final String windowHeaderNoticeFGColorStr = Env.getContext(ctx, Env.CTXNAME_UI_WindowHeader_Notice_FG_COLOR); if (!Check.isEmpty(windowHeaderNoticeBGColorStr, true)) { final Color foregroundColor = Colors.toColor(windowHeaderNoticeFGColorStr); if (foregroundColor != null) { label.setForeground(foregroundColor); } }
final String windowHeaderNotice = Env.getContext(ctx, Env.CTXNAME_UI_WindowHeader_Notice_Text); if (!Check.isEmpty(windowHeaderNotice, true) && !"-".equals(windowHeaderNotice)) { setNotice(windowHeaderNotice); setVisible(true); } else { setNotice(""); setVisible(false); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\swing\WindowHeaderNotice.java
1
请完成以下Java代码
public int getMSV3_BestellungAntwortPosition_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_BestellungAntwortPosition_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_Substitution getMSV3_BestellungSubstitution() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_MSV3_BestellungSubstitution_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_Substitution.class); } @Override public void setMSV3_BestellungSubstitution(de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_Substitution MSV3_BestellungSubstitution) { set_ValueFromPO(COLUMNNAME_MSV3_BestellungSubstitution_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_Substitution.class, MSV3_BestellungSubstitution); } /** Set BestellungSubstitution. @param MSV3_BestellungSubstitution_ID BestellungSubstitution */ @Override public void setMSV3_BestellungSubstitution_ID (int MSV3_BestellungSubstitution_ID)
{ if (MSV3_BestellungSubstitution_ID < 1) set_Value (COLUMNNAME_MSV3_BestellungSubstitution_ID, null); else set_Value (COLUMNNAME_MSV3_BestellungSubstitution_ID, Integer.valueOf(MSV3_BestellungSubstitution_ID)); } /** Get BestellungSubstitution. @return BestellungSubstitution */ @Override public int getMSV3_BestellungSubstitution_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_BestellungSubstitution_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_BestellungAntwortPosition.java
1
请完成以下Java代码
public class AttachmentEntityManager extends AbstractManager { @SuppressWarnings("unchecked") public List<Attachment> findAttachmentsByProcessInstanceId(String processInstanceId) { checkHistoryEnabled(); return getDbSqlSession().selectList("selectAttachmentsByProcessInstanceId", processInstanceId); } @SuppressWarnings("unchecked") public List<Attachment> findAttachmentsByTaskId(String taskId) { checkHistoryEnabled(); return getDbSqlSession().selectList("selectAttachmentsByTaskId", taskId); } @SuppressWarnings("unchecked") public void deleteAttachmentsByTaskId(String taskId) { checkHistoryEnabled(); List<AttachmentEntity> attachments = getDbSqlSession().selectList("selectAttachmentsByTaskId", taskId); boolean dispatchEvents = getProcessEngineConfiguration().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 = getTaskManager().findTaskById(taskId); if (task != null) { processDefinitionId = task.getProcessDefinitionId(); processInstanceId = task.getProcessInstanceId(); executionId = task.getExecutionId(); } } for (AttachmentEntity attachment : attachments) { String contentId = attachment.getContentId();
if (contentId != null) { getByteArrayManager().deleteByteArrayById(contentId); } getDbSqlSession().delete(attachment); if (dispatchEvents) { getProcessEngineConfiguration().getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, attachment, executionId, processInstanceId, processDefinitionId), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); } } } protected void checkHistoryEnabled() { if (!getHistoryManager().isHistoryEnabled()) { throw new ActivitiException("In order to use attachments, history should be enabled"); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AttachmentEntityManager.java
1
请完成以下Java代码
protected HistoricCaseInstanceEventEntity newCaseInstanceEventEntity(CaseExecutionEntity caseExecutionEntity) { return new HistoricCaseInstanceEventEntity(); } protected HistoricCaseInstanceEventEntity loadCaseInstanceEventEntity(CaseExecutionEntity caseExecutionEntity) { return newCaseInstanceEventEntity(caseExecutionEntity); } protected void initCaseInstanceEvent(HistoricCaseInstanceEventEntity evt, CaseExecutionEntity caseExecutionEntity, HistoryEventTypes eventType) { evt.setId(caseExecutionEntity.getCaseInstanceId()); evt.setEventType(eventType.getEventName()); evt.setCaseDefinitionId(caseExecutionEntity.getCaseDefinitionId()); evt.setCaseInstanceId(caseExecutionEntity.getCaseInstanceId()); evt.setCaseExecutionId(caseExecutionEntity.getId()); evt.setBusinessKey(caseExecutionEntity.getBusinessKey()); evt.setState(caseExecutionEntity.getState()); evt.setTenantId(caseExecutionEntity.getTenantId()); } protected HistoricCaseActivityInstanceEventEntity newCaseActivityInstanceEventEntity(CaseExecutionEntity caseExecutionEntity) { return new HistoricCaseActivityInstanceEventEntity(); } protected HistoricCaseActivityInstanceEventEntity loadCaseActivityInstanceEventEntity(CaseExecutionEntity caseExecutionEntity) { return newCaseActivityInstanceEventEntity(caseExecutionEntity); } protected void initCaseActivityInstanceEvent(HistoricCaseActivityInstanceEventEntity evt, CaseExecutionEntity caseExecutionEntity, HistoryEventTypes eventType) { evt.setId(caseExecutionEntity.getId()); evt.setParentCaseActivityInstanceId(caseExecutionEntity.getParentId());
evt.setEventType(eventType.getEventName()); evt.setCaseDefinitionId(caseExecutionEntity.getCaseDefinitionId()); evt.setCaseInstanceId(caseExecutionEntity.getCaseInstanceId()); evt.setCaseExecutionId(caseExecutionEntity.getId()); evt.setCaseActivityInstanceState(caseExecutionEntity.getState()); evt.setRequired(caseExecutionEntity.isRequired()); evt.setCaseActivityId(caseExecutionEntity.getActivityId()); evt.setCaseActivityName(caseExecutionEntity.getActivityName()); evt.setCaseActivityType(caseExecutionEntity.getActivityType()); evt.setTenantId(caseExecutionEntity.getTenantId()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\producer\DefaultCmmnHistoryEventProducer.java
1
请完成以下Java代码
public class NeurophXOR { public static NeuralNetwork assembleNeuralNetwork() { Layer inputLayer = new Layer(); inputLayer.addNeuron(new Neuron()); inputLayer.addNeuron(new Neuron()); Layer hiddenLayerOne = new Layer(); hiddenLayerOne.addNeuron(new Neuron()); hiddenLayerOne.addNeuron(new Neuron()); hiddenLayerOne.addNeuron(new Neuron()); hiddenLayerOne.addNeuron(new Neuron()); Layer hiddenLayerTwo = new Layer(); hiddenLayerTwo.addNeuron(new Neuron()); hiddenLayerTwo.addNeuron(new Neuron()); hiddenLayerTwo.addNeuron(new Neuron()); hiddenLayerTwo.addNeuron(new Neuron()); Layer outputLayer = new Layer(); outputLayer.addNeuron(new Neuron()); NeuralNetwork ann = new NeuralNetwork(); ann.addLayer(0, inputLayer); ann.addLayer(1, hiddenLayerOne); ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(1)); ann.addLayer(2, hiddenLayerTwo); ConnectionFactory.fullConnect(ann.getLayerAt(1), ann.getLayerAt(2)); ann.addLayer(3, outputLayer); ConnectionFactory.fullConnect(ann.getLayerAt(2), ann.getLayerAt(3)); ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(ann.getLayersCount() - 1), false); ann.setInputNeurons(inputLayer.getNeurons()); ann.setOutputNeurons(outputLayer.getNeurons()); ann.setNetworkType(NeuralNetworkType.MULTI_LAYER_PERCEPTRON); return ann; } public static NeuralNetwork trainNeuralNetwork(NeuralNetwork ann) {
int inputSize = 2; int outputSize = 1; DataSet ds = new DataSet(inputSize, outputSize); DataSetRow rOne = new DataSetRow(new double[] { 0, 1 }, new double[] { 1 }); ds.addRow(rOne); DataSetRow rTwo = new DataSetRow(new double[] { 1, 1 }, new double[] { 0 }); ds.addRow(rTwo); DataSetRow rThree = new DataSetRow(new double[] { 0, 0 }, new double[] { 0 }); ds.addRow(rThree); DataSetRow rFour = new DataSetRow(new double[] { 1, 0 }, new double[] { 1 }); ds.addRow(rFour); BackPropagation backPropagation = new BackPropagation(); backPropagation.setMaxIterations(1000); ann.learn(ds, backPropagation); return ann; } }
repos\tutorials-master\libraries-ai\src\main\java\neuroph\NeurophXOR.java
1
请完成以下Java代码
public int getRevisionNext() { return revision+1; } // getters and setters ////////////////////////////////////////////////////// public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public void setBytes(byte[] bytes) { this.bytes = bytes; } public int getRevision() { return revision; } public void setRevision(int revision) { this.revision = revision; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime;
} public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", revision=" + revision + ", name=" + name + ", deploymentId=" + deploymentId + ", tenantId=" + tenantId + ", type=" + type + ", createTime=" + createTime + ", rootProcessInstanceId=" + rootProcessInstanceId + ", removalTime=" + removalTime + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ByteArrayEntity.java
1
请在Spring Boot框架中完成以下Java代码
public class RedisRouteDefinitionRepository implements RouteDefinitionRepository { private static final Logger log = LoggerFactory.getLogger(RedisRouteDefinitionRepository.class); /** * Key prefix for RouteDefinition queries to redis. */ private static final String ROUTEDEFINITION_REDIS_KEY_PREFIX_QUERY = "routedefinition_"; private ReactiveRedisTemplate<String, RouteDefinition> reactiveRedisTemplate; private ReactiveValueOperations<String, RouteDefinition> routeDefinitionReactiveValueOperations; public RedisRouteDefinitionRepository(ReactiveRedisTemplate<String, RouteDefinition> reactiveRedisTemplate) { this.reactiveRedisTemplate = reactiveRedisTemplate; this.routeDefinitionReactiveValueOperations = reactiveRedisTemplate.opsForValue(); } @Override public Flux<RouteDefinition> getRouteDefinitions() { return reactiveRedisTemplate.scan(ScanOptions.scanOptions().match(createKey("*")).build()) .flatMap(key -> reactiveRedisTemplate.opsForValue().get(key)) .onErrorContinue((throwable, routeDefinition) -> { if (log.isErrorEnabled()) { log.error("get routes from redis error cause : {}", throwable.toString(), throwable); } }); } @Override public Mono<Void> save(Mono<RouteDefinition> route) { return route.flatMap(routeDefinition -> { Objects.requireNonNull(routeDefinition.getId(), "id may not be null"); return routeDefinitionReactiveValueOperations.set(createKey(routeDefinition.getId()), routeDefinition) .flatMap(success -> { if (success) { return Mono.empty(); } return Mono.defer(() -> Mono.error(new RuntimeException( String.format("Could not add route to redis repository: %s", routeDefinition))));
}); }); } @Override public Mono<Void> delete(Mono<String> routeId) { return routeId.flatMap(id -> routeDefinitionReactiveValueOperations.delete(createKey(id)).flatMap(success -> { if (success) { return Mono.empty(); } return Mono.defer(() -> Mono.error(new NotFoundException( String.format("Could not remove route from redis repository with id: %s", routeId)))); })); } private String createKey(String routeId) { return ROUTEDEFINITION_REDIS_KEY_PREFIX_QUERY + routeId; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\route\RedisRouteDefinitionRepository.java
2
请完成以下Java代码
public void addNewExecutionId(String executionId) { this.newExecutionIds.add(executionId); } public ExecutionEntity getCreatedEventSubProcess(String processDefinitionId) { return createdEventSubProcesses.get(processDefinitionId); } public void addCreatedEventSubProcess(String processDefinitionId, ExecutionEntity executionEntity) { createdEventSubProcesses.put(processDefinitionId, executionEntity); } public Map<String, Map<String, Object>> getFlowElementLocalVariableMap() { return flowElementLocalVariableMap; } public void setFlowElementLocalVariableMap(Map<String, Map<String, Object>> flowElementLocalVariableMap) { this.flowElementLocalVariableMap = flowElementLocalVariableMap; } public void addLocalVariableMap(String activityId, Map<String, Object> localVariables) {
this.flowElementLocalVariableMap.put(activityId, localVariables); } public static class FlowElementMoveEntry { protected FlowElement originalFlowElement; protected FlowElement newFlowElement; public FlowElementMoveEntry(FlowElement originalFlowElement, FlowElement newFlowElement) { this.originalFlowElement = originalFlowElement; this.newFlowElement = newFlowElement; } public FlowElement getOriginalFlowElement() { return originalFlowElement; } public FlowElement getNewFlowElement() { return newFlowElement; } } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\dynamic\MoveExecutionEntityContainer.java
1
请完成以下Java代码
protected String getDeploymentMode() { return DEPLOYMENT_MODE; } @Override protected void deployResourcesInternal(String deploymentNameHint, Resource[] resources, EventRegistryEngine engine) { EventRepositoryService repositoryService = engine.getEventRepositoryService(); // Create a single deployment for all resources using the name hint as the literal name final EventDeploymentBuilder deploymentBuilder = repositoryService.createDeployment().enableDuplicateFiltering().name(deploymentNameHint); for (final Resource resource : resources) { addResource(resource, deploymentBuilder); } try {
deploymentBuilder.deploy(); } catch (RuntimeException e) { if (isThrowExceptionOnDeploymentFailure()) { throw e; } else { LOGGER.warn("Exception while autodeploying event definitions. " + "This exception can be ignored if the root cause indicates a unique constraint violation, " + "which is typically caused by two (or more) servers booting up at the exact same time and deploying the same definitions. ", e); } } } }
repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\autodeployment\DefaultAutoDeploymentStrategy.java
1
请完成以下Java代码
public PickingJob closeTUPickingTarget( @NonNull final PickingJob pickingJob, @Nullable final PickingJobLineId lineId) { return pickingJobService.closeTUPickingTarget(pickingJob, lineId); } @NonNull public PickingJobOptions getPickingJobOptions(@Nullable final BPartnerId customerId) {return configService.getPickingJobOptions(customerId);} @NonNull public List<HuId> getClosedLUs( @NonNull final PickingJob pickingJob, @Nullable final PickingJobLineId lineId) { final Set<HuId> pickedHuIds = pickingJob.getPickedHuIds(lineId); if (pickedHuIds.isEmpty()) { return ImmutableList.of(); } final HuId currentlyOpenedLUId = pickingJob.getLuPickingTarget(lineId) .map(LUPickingTarget::getLuId) .orElse(null); return handlingUnitsBL.getTopLevelHUs(IHandlingUnitsBL.TopLevelHusQuery.builder() .hus(handlingUnitsBL.getByIds(pickedHuIds)) .build()) .stream() .filter(handlingUnitsBL::isLoadingUnit) .map(I_M_HU::getM_HU_ID) .map(HuId::ofRepoId) .filter(huId -> !HuId.equals(huId, currentlyOpenedLUId)) .collect(ImmutableList.toImmutableList()); } public PickingSlotSuggestions getPickingSlotsSuggestions(@NonNull final PickingJob pickingJob) {
return pickingJobService.getPickingSlotsSuggestions(pickingJob); } public PickingJob pickAll(@NonNull final PickingJobId pickingJobId, final @NonNull UserId callerId) { return pickingJobService.pickAll(pickingJobId, callerId); } public PickingJobQtyAvailable getQtyAvailable(@NonNull final PickingJobId pickingJobId, final @NonNull UserId callerId) { return pickingJobService.getQtyAvailable(pickingJobId, callerId); } public GetNextEligibleLineToPackResponse getNextEligibleLineToPack(final @NonNull GetNextEligibleLineToPackRequest request) { return pickingJobService.getNextEligibleLineToPack(request); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\PickingJobRestService.java
1
请完成以下Java代码
public void setProcessEngine(ProcessEngine processEngine) { this.processEngine = processEngine; } public void afterPropertiesSet() throws Exception { this.advisor = new ProcessStartingPointcutAdvisor(this.processEngine); } public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof AopInfrastructureBean) { // Ignore AOP infrastructure such as scoped proxies. return bean; } Class<?> targetClass = AopUtils.getTargetClass(bean); if (AopUtils.canApply(this.advisor, targetClass)) { if (bean instanceof Advised) { ((Advised) bean).addAdvisor(0, this.advisor); return bean; } else { ProxyFactory proxyFactory = new ProxyFactory(bean);
// Copy our properties (proxyTargetClass etc) inherited from ProxyConfig. proxyFactory.copyFrom(this); proxyFactory.addAdvisor(this.advisor); return proxyFactory.getProxy(this.beanClassLoader); } } else { // No async proxy needed. return bean; } } public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } }
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\components\aop\ProcessStartAnnotationBeanPostProcessor.java
1
请完成以下Java代码
public class PMMWeekReportEventsProcessor { public static final PMMWeekReportEventsProcessor newInstance() { return new PMMWeekReportEventsProcessor(); } private final transient ITrxItemProcessorExecutorService trxItemProcessorExecutorService = Services.get(ITrxItemProcessorExecutorService.class); private PMMWeekReportEventsProcessor() { super(); } public void processAll()
{ final Properties ctx = Env.getCtx(); final EventSource<I_PMM_WeekReport_Event> events = new EventSource<>(ctx, I_PMM_WeekReport_Event.class); final PMMWeekReportEventTrxItemProcessor itemProcessor = new PMMWeekReportEventTrxItemProcessor(); trxItemProcessorExecutorService.<I_PMM_WeekReport_Event, Void> createExecutor() .setContext(ctx, ITrx.TRXNAME_ThreadInherited) .setExceptionHandler(FailTrxItemExceptionHandler.instance) .setProcessor(itemProcessor) .process(events); Loggables.addLog(itemProcessor.getProcessSummary()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\event\impl\PMMWeekReportEventsProcessor.java
1
请在Spring Boot框架中完成以下Java代码
public static IPackingItem newPackingItem(@NonNull final PackingItemParts parts) { return new TransactionalPackingItem(parts); } public static IPackingItem newPackingItem(@NonNull final PackingItemPart part) { return new TransactionalPackingItem(PackingItemParts.of(part)); } public static ImmutableList<IPackingItem> createPackingItems(final Set<ShipmentScheduleId> shipmentScheduleIds) { if (shipmentScheduleIds.isEmpty()) { return ImmutableList.of(); } final IShipmentSchedulePA shipmentSchedulesRepo = Services.get(IShipmentSchedulePA.class); final IShipmentScheduleBL shipmentScheduleBL = Services.get(IShipmentScheduleBL.class); final Map<ShipmentScheduleId, I_M_ShipmentSchedule> shipmentSchedules = shipmentSchedulesRepo.getByIdsOutOfTrx(shipmentScheduleIds, I_M_ShipmentSchedule.class); final Map<PackingItemGroupingKey, IPackingItem> packingItems = new LinkedHashMap<>(); for (final I_M_ShipmentSchedule sched : shipmentSchedules.values()) { final Quantity qtyToDeliverTarget = shipmentScheduleBL.getQtyToDeliver(sched); if (qtyToDeliverTarget.signum() <= 0) { continue; } // task 08153: these code-lines are obsolete now, because the sched's qtyToDeliver(_Override) has the qtyPicked already factored in // final BigDecimal qtyPicked = shipmentScheduleAllocBL.getQtyPicked(sched); // final BigDecimal qtyToDeliver = qtyToDeliverTarget.subtract(qtyPicked == null ? BigDecimal.ZERO : qtyPicked); final PackingItemPart part = newPackingItemPart(sched) .qty(qtyToDeliverTarget) .build(); final IPackingItem newItem = newPackingItem(part); final IPackingItem existingItem = packingItems.get(newItem.getGroupingKey()); if (existingItem != null)
{ existingItem.addParts(newItem); } else { packingItems.put(newItem.getGroupingKey(), newItem); } } return ImmutableList.copyOf(packingItems.values()); } public static PackingItemPartBuilder newPackingItemPart(final de.metas.inoutcandidate.model.I_M_ShipmentSchedule sched) { final IShipmentScheduleEffectiveBL shipmentScheduleEffectiveBL = Services.get(IShipmentScheduleEffectiveBL.class); final IHUShipmentScheduleBL huShipmentScheduleBL = Services.get(IHUShipmentScheduleBL.class); final ShipmentScheduleId shipmentScheduleId = ShipmentScheduleId.ofRepoId(sched.getM_ShipmentSchedule_ID()); return PackingItemPart.builder() .id(PackingItemPartId.of(shipmentScheduleId)) .productId(ProductId.ofRepoId(sched.getM_Product_ID())) .bpartnerId(shipmentScheduleEffectiveBL.getBPartnerId(sched)) .bpartnerLocationId(shipmentScheduleEffectiveBL.getBPartnerLocationId(sched)) .packingMaterialId(huShipmentScheduleBL.getEffectivePackingMaterialId(sched)) .warehouseId(shipmentScheduleEffectiveBL.getWarehouseId(sched)) .deliveryRule(shipmentScheduleEffectiveBL.getDeliveryRule(sched)) .sourceDocumentLineRef(TableRecordReference.of(sched.getAD_Table_ID(), sched.getRecord_ID())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\PackingItems.java
2
请完成以下Java代码
public void setId(String id) { this.id = id; } public Expression getLabel() { return label; } public void setLabel(Expression name) { this.label = name; } public void setType(AbstractFormFieldType formType) { this.type = formType; } public void setProperties(Map<String, String> properties) { this.properties = properties; } public Map<String, String> getProperties() { return properties; } public FormType getType() { return type;
} public Expression getDefaultValueExpression() { return defaultValueExpression; } public void setDefaultValueExpression(Expression defaultValue) { this.defaultValueExpression = defaultValue; } public List<FormFieldValidationConstraintHandler> getValidationHandlers() { return validationHandlers; } public void setValidationHandlers(List<FormFieldValidationConstraintHandler> validationHandlers) { this.validationHandlers = validationHandlers; } public void setBusinessKey(boolean businessKey) { this.businessKey = businessKey; } public boolean isBusinessKey() { return businessKey; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\handler\FormFieldHandler.java
1
请在Spring Boot框架中完成以下Java代码
public class SyncRfQ implements IConfirmableDTO { String uuid; boolean deleted; long syncConfirmationId; LocalDate dateStart; LocalDate dateEnd; LocalDate dateClose; String bpartner_uuid; SyncProduct product; BigDecimal qtyRequested; String qtyCUInfo; String currencyCode; @JsonCreator @Builder(toBuilder = true) public SyncRfQ( @JsonProperty("uuid") final String uuid, @JsonProperty("deleted") final boolean deleted, @JsonProperty("syncConfirmationId") final long syncConfirmationId, @JsonProperty("dateStart") final LocalDate dateStart, @JsonProperty("dateEnd") final LocalDate dateEnd, @JsonProperty("dateClose") final LocalDate dateClose, @JsonProperty("bpartner_uuid") final String bpartner_uuid, @JsonProperty("product") final SyncProduct product, @JsonProperty("qtyRequested") final BigDecimal qtyRequested, @JsonProperty("qtyCUInfo") final String qtyCUInfo, @JsonProperty("currencyCode") final String currencyCode) { this.uuid = uuid; this.deleted = deleted; this.syncConfirmationId = syncConfirmationId; this.dateStart = dateStart; this.dateEnd = dateEnd; this.dateClose = dateClose; this.bpartner_uuid = bpartner_uuid; this.product = product; this.qtyRequested = qtyRequested; this.qtyCUInfo = qtyCUInfo;
this.currencyCode = currencyCode; } @Override public String toString() { return "SyncRfQ [" + "dateStart=" + dateStart + ", dateEnd=" + dateEnd + ", dateClose=" + dateClose // + ", bpartner_uuid=" + bpartner_uuid // + ", product=" + product + ", qtyRequested=" + qtyRequested + " " + qtyCUInfo // + ", currencyCode=" + currencyCode + "]"; } @Override public IConfirmableDTO withNotDeleted() { return toBuilder().deleted(false).build(); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-procurement\src\main\java\de\metas\common\procurement\sync\protocol\dto\SyncRfQ.java
2
请完成以下Java代码
public void on(OrderConfirmedEvent event) { orders.computeIfPresent(event.getOrderId(), (orderId, order) -> { order.setOrderConfirmed(); emitUpdate(order); return order; }); } @EventHandler public void on(OrderShippedEvent event) { orders.computeIfPresent(event.getOrderId(), (orderId, order) -> { order.setOrderShipped(); emitUpdate(order); return order; }); } @QueryHandler public List<Order> handle(FindAllOrderedProductsQuery query) { return new ArrayList<>(orders.values()); } @QueryHandler public Publisher<Order> handleStreaming(FindAllOrderedProductsQuery query) { return Mono.fromCallable(orders::values) .flatMapMany(Flux::fromIterable); } @QueryHandler public Integer handle(TotalProductsShippedQuery query) { return orders.values() .stream() .filter(o -> o.getOrderStatus() == OrderStatus.SHIPPED) .map(o -> Optional.ofNullable(o.getProducts() .get(query.getProductId())) .orElse(0))
.reduce(0, Integer::sum); } @QueryHandler public Order handle(OrderUpdatesQuery query) { return orders.get(query.getOrderId()); } private void emitUpdate(Order order) { emitter.emit(OrderUpdatesQuery.class, q -> order.getOrderId() .equals(q.getOrderId()), order); } @Override public void reset(List<Order> orderList) { orders.clear(); orderList.forEach(o -> orders.put(o.getOrderId(), o)); } }
repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\querymodel\InMemoryOrdersEventHandler.java
1
请在Spring Boot框架中完成以下Java代码
public class PickingJobProductService { @NonNull private final ProductRepository productRepository; @NonNull private final IProductBL productBL = Services.get(IProductBL.class); @NonNull private final IUOMDAO uomDAO = Services.get(IUOMDAO.class); public static PickingJobProductService newInstanceForUnitTesting() { Adempiere.assertUnitTestMode(); //noinspection DataFlowIssue return SpringContextHolder.getBeanOrSupply( PickingJobProductService.class, () -> new PickingJobProductService(ProductRepository.newInstanceForUnitTesting()) ); } @NonNull public ProductInfo getById(@NonNull final ProductId productId) { final I_M_Product product = productBL.getById(productId); final GS1ProductCodesCollection gs1ProductCodes = productBL.getGS1ProductCodesCollection(product); return ProductInfo.builder() .productId(productId) .productNo(product.getValue()) .gs1ProductCodes(gs1ProductCodes) .productCategoryId(ProductCategoryId.ofRepoId(product.getM_Product_Category_ID())) .name(InterfaceWrapperHelper.getModelTranslationMap(product).getColumnTrl(I_M_Product.COLUMNNAME_Name, product.getName())) .build(); } public ProductId getProductIdByGTINStrictlyNotNull(@NonNull final GTIN gtin, @NonNull final ClientId clientId) { return productBL.getProductIdByGTINStrictlyNotNull(gtin, clientId); }
public String getProductValue(@NonNull final ProductId productId) { return productBL.getProductValue(productId); } public boolean isValidEAN13Product(@NonNull final EAN13 ean13, @NonNull final ProductId expectedProductId, @Nullable final BPartnerId bpartnerId) { return productBL.isValidEAN13Product(ean13, expectedProductId, bpartnerId); } public ITranslatableString getUOMSymbolById(@NonNull final UomId uomId) {return uomDAO.getUOMSymbolById(uomId);} @NonNull public ImmutableMap<ProductId, Product> getByIdsAsMap(@NonNull final Set<ProductId> ids) { return productRepository.getByIdsAsMap(ids); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\external\product\PickingJobProductService.java
2
请完成以下Java代码
void onUnsubackReceived() { retransmissionHandler.stop(); } void onChannelClosed() { retransmissionHandler.stop(); } static Builder builder() { return new Builder(); } static class Builder { private Promise<Void> future; private String topic; private MqttUnsubscribeMessage unsubscribeMessage; private String ownerId; private PendingOperation pendingOperation; private MqttClientConfig.RetransmissionConfig retransmissionConfig; Builder future(Promise<Void> future) { this.future = future; return this; } Builder topic(String topic) { this.topic = topic; return this; } Builder unsubscribeMessage(MqttUnsubscribeMessage unsubscribeMessage) { this.unsubscribeMessage = unsubscribeMessage; return this; } Builder ownerId(String ownerId) {
this.ownerId = ownerId; return this; } Builder retransmissionConfig(MqttClientConfig.RetransmissionConfig retransmissionConfig) { this.retransmissionConfig = retransmissionConfig; return this; } Builder pendingOperation(PendingOperation pendingOperation) { this.pendingOperation = pendingOperation; return this; } MqttPendingUnsubscription build() { return new MqttPendingUnsubscription(future, topic, unsubscribeMessage, ownerId, retransmissionConfig, pendingOperation); } } }
repos\thingsboard-master\netty-mqtt\src\main\java\org\thingsboard\mqtt\MqttPendingUnsubscription.java
1
请完成以下Java代码
public String getAttributeValueType() { return X_M_Attribute.ATTRIBUTEVALUETYPE_List; } /** * @return <code>false</code>, because In/Ausland is a List attribute. */ @Override public boolean canGenerateValue(Properties ctx, IAttributeSet attributeSet, I_M_Attribute attribute) { return false; } @Override public AttributeListValue generateAttributeValue(Properties ctx, int tableId, int recordId, boolean isSOTrx, String trxName) { final ITableRecordReference record = TableRecordReference.of(tableId, recordId); Check.errorUnless(I_C_Country.Table_Name.equals(record.getTableName()), "Only C_Country table is supported. Given param 'tableId' is the ID of AD_Table {}", record.getTableName()); final int countryId = record.getRecord_ID();
final I_M_Attribute inAusLandAttribute = Services.get(IInAusLandAttributeDAO.class).retrieveInAusLandAttribute(ctx); if (inAusLandAttribute == null) { // In/Aus Land attribute was not configured => do nothing return null; } final String inAusLand = Services.get(IInAusLandAttributeBL.class).getAttributeStringValueByCountryId(countryId); return Services.get(IAttributeDAO.class).createAttributeValue(AttributeListValueCreateRequest.builder() .attributeId(AttributeId.ofRepoId(inAusLandAttribute.getM_Attribute_ID())) .value(inAusLand) .name(inAusLand) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\spi\impl\InAus_LandAttributeGenerator.java
1
请完成以下Java代码
protected class CmmnParseContextImpl implements CmmnParseContext { protected final EngineResource resource; protected final boolean newDeployment; public CmmnParseContextImpl(EngineResource resource, boolean newDeployment) { this.resource = resource; this.newDeployment = newDeployment; } @Override public EngineResource resource() { return resource; } @Override public boolean enableSafeXml() { return cmmnEngineConfiguration.isEnableSafeCmmnXml(); } @Override public String xmlEncoding() { return cmmnEngineConfiguration.getXmlEncoding(); } @Override public boolean validateXml() { // On redeploy, we assume it is validated at the first deploy return newDeployment && !cmmnEngineConfiguration.isDisableCmmnXmlValidation(); }
@Override public boolean validateCmmnModel() { // On redeploy, we assume it is validated at the first deploy return newDeployment && validateXml(); } @Override public CaseValidator caseValidator() { return cmmnEngineConfiguration.getCaseValidator(); } } @Override public void undeploy(EngineDeployment parentDeployment, boolean cascade) { // Nothing to do } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\deployer\CmmnDeployer.java
1