instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public String getLocation() { return location; } public String getParamName() { return paramName; } public String getApiKey() { return apiKey; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } public String getApiKeyPrefix() { return apiKeyPrefix; } public void setApiKeyPrefix(String apiKeyPrefix) { this.apiKeyPrefix = apiKeyPrefix; } @Override public void applyToParams(MultiValueMap<String, String> queryParams, HttpHeaders headerParams, MultiValueMap<String, String> cookieParams) { if (apiKey == null) { return; }
String value; if (apiKeyPrefix != null) { value = apiKeyPrefix + " " + apiKey; } else { value = apiKey; } if (location.equals("query")) { queryParams.add(paramName, value); } else if (location.equals("header")) { headerParams.add(paramName, value); } else if (location.equals("cookie")) { cookieParams.add(paramName, value); } } }
repos\tutorials-master\spring-swagger-codegen-modules\spring-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\invoker\auth\ApiKeyAuth.java
1
请完成以下Java代码
public void delete(int key) { root = delete(root, key); } public Node getRoot() { return root; } public int height() { return root == null ? -1 : root.height; } private Node insert(Node root, int key) { if (root == null) { return new Node(key); } else if (root.key > key) { root.left = insert(root.left, key); } else if (root.key < key) { root.right = insert(root.right, key); } else { throw new RuntimeException("duplicate Key!"); } return rebalance(root); } private Node delete(Node node, int key) { if (node == null) { return node; } else if (node.key > key) { node.left = delete(node.left, key); } else if (node.key < key) { node.right = delete(node.right, key); } else { if (node.left == null || node.right == null) { node = (node.left == null) ? node.right : node.left; } else { Node mostLeftChild = mostLeftChild(node.right); node.key = mostLeftChild.key; node.right = delete(node.right, node.key); } } if (node != null) { node = rebalance(node); } return node; } private Node mostLeftChild(Node node) { Node current = node; /* loop down to find the leftmost leaf */ while (current.left != null) { current = current.left; } return current; } private Node rebalance(Node z) { updateHeight(z); int balance = getBalance(z); if (balance > 1) { if (height(z.right.right) > height(z.right.left)) { z = rotateLeft(z); } else { z.right = rotateRight(z.right); z = rotateLeft(z); } } else if (balance < -1) { if (height(z.left.left) > height(z.left.right)) { z = rotateRight(z); } else { z.left = rotateLeft(z.left); z = rotateRight(z); }
} return z; } private Node rotateRight(Node y) { Node x = y.left; Node z = x.right; x.right = y; y.left = z; updateHeight(y); updateHeight(x); return x; } private Node rotateLeft(Node y) { Node x = y.right; Node z = x.left; x.left = y; y.right = z; updateHeight(y); updateHeight(x); return x; } private void updateHeight(Node n) { n.height = 1 + Math.max(height(n.left), height(n.right)); } private int height(Node n) { return n == null ? -1 : n.height; } public int getBalance(Node n) { return (n == null) ? 0 : height(n.right) - height(n.left); } }
repos\tutorials-master\data-structures-2\src\main\java\com\baeldung\avltree\AVLTree.java
1
请完成以下Java代码
public I_AD_Replication getAD_Replication() throws RuntimeException { return (I_AD_Replication)MTable.get(getCtx(), I_AD_Replication.Table_Name) .getPO(getAD_Replication_ID(), get_TrxName()); } /** Set Replication. @param AD_Replication_ID Data Replication Target */ public void setAD_Replication_ID (int AD_Replication_ID) { if (AD_Replication_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Replication_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Replication_ID, Integer.valueOf(AD_Replication_ID)); } /** Get Replication. @return Data Replication Target */ public int getAD_Replication_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Replication_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Replication Run. @param AD_Replication_Run_ID Data Replication Run */ public void setAD_Replication_Run_ID (int AD_Replication_Run_ID) { if (AD_Replication_Run_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Replication_Run_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Replication_Run_ID, Integer.valueOf(AD_Replication_Run_ID)); } /** Get Replication Run. @return Data Replication Run */ public int getAD_Replication_Run_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Replication_Run_ID); if (ii == null) return 0; return ii.intValue(); } /** 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 Replicated. @param IsReplicated
The data is successfully replicated */ public void setIsReplicated (boolean IsReplicated) { set_ValueNoCheck (COLUMNNAME_IsReplicated, Boolean.valueOf(IsReplicated)); } /** Get Replicated. @return The data is successfully replicated */ public boolean isReplicated () { Object oo = get_Value(COLUMNNAME_IsReplicated); 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_Replication_Run.java
1
请完成以下Java代码
public SetRemovalTimeToHistoricBatchesBuilder byIds(String... ids) { this.ids = ids != null ? Arrays.asList(ids) : null; return this; } public SetRemovalTimeToHistoricBatchesBuilder absoluteRemovalTime(Date removalTime) { ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode); this.mode = Mode.ABSOLUTE_REMOVAL_TIME; this.removalTime = removalTime; return this; } public SetRemovalTimeToHistoricBatchesBuilder calculatedRemovalTime() { ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode); this.mode = Mode.CALCULATED_REMOVAL_TIME; return this; } public SetRemovalTimeToHistoricBatchesBuilder clearedRemovalTime() { ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode); mode = Mode.CLEARED_REMOVAL_TIME; return this; } public Batch executeAsync() { return commandExecutor.execute(new SetRemovalTimeToHistoricBatchesCmd(this));
} public HistoricBatchQuery getQuery() { return query; } public List<String> getIds() { return ids; } public Date getRemovalTime() { return removalTime; } public Mode getMode() { return mode; } public enum Mode { CALCULATED_REMOVAL_TIME, ABSOLUTE_REMOVAL_TIME, CLEARED_REMOVAL_TIME; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\SetRemovalTimeToHistoricBatchesBuilderImpl.java
1
请完成以下Java代码
public int getEXP_ReplicationTrx_ID() { return get_ValueAsInt(COLUMNNAME_EXP_ReplicationTrx_ID); } @Override public void setIsError (final boolean IsError) { set_Value (COLUMNNAME_IsError, IsError); } @Override public boolean isError() { return get_ValueAsBoolean(COLUMNNAME_IsError); } @Override public void setIsReplicationTrxFinished (final boolean IsReplicationTrxFinished) { set_Value (COLUMNNAME_IsReplicationTrxFinished, IsReplicationTrxFinished); } @Override public boolean isReplicationTrxFinished() { return get_ValueAsBoolean(COLUMNNAME_IsReplicationTrxFinished); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); }
@Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setNote (final @Nullable java.lang.String Note) { set_Value (COLUMNNAME_Note, Note); } @Override public java.lang.String getNote() { return get_ValueAsString(COLUMNNAME_Note); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\process\rpl\model\X_EXP_ReplicationTrx.java
1
请完成以下Java代码
public abstract class AbstractCaseInstanceOperation extends CmmnOperation { protected String caseInstanceEntityId; protected CaseInstanceEntity caseInstanceEntity; public AbstractCaseInstanceOperation(CommandContext commandContext, String caseInstanceId, CaseInstanceEntity caseInstanceEntity) { super(commandContext); this.caseInstanceEntityId = caseInstanceId; this.caseInstanceEntity = caseInstanceEntity; } @Override public void run() { getCaseInstanceEntity(); getCaseInstanceId(); } @Override public String getCaseInstanceId() { if (caseInstanceEntityId == null) { caseInstanceEntityId = caseInstanceEntity.getId(); } return caseInstanceEntityId;
} public void setCaseInstanceEntityId(String caseInstanceEntityId) { this.caseInstanceEntityId = caseInstanceEntityId; } public CaseInstanceEntity getCaseInstanceEntity() { if (caseInstanceEntity == null) { caseInstanceEntity = CommandContextUtil.getCaseInstanceEntityManager(commandContext).findById(caseInstanceEntityId); } return caseInstanceEntity; } public void setCaseInstanceEntity(CaseInstanceEntity caseInstanceEntity) { this.caseInstanceEntity = caseInstanceEntity; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\AbstractCaseInstanceOperation.java
1
请完成以下Spring Boot application配置
spring: application: name: dmeo-application-mongodb data: # MongoDB 配置项,对应 MongoProperties 类 mongodb: host: 127.0.0.1 port: 27017 database: yourdat
abase username: test01 password: password01 # 上述属性,也可以只配置 uri
repos\SpringBoot-Labs-master\lab-40\lab-40-mongodb\src\main\resources\application.yml
2
请在Spring Boot框架中完成以下Java代码
public class AvailabilityInfoResultForWebui { List<Group> groups; @Builder private AvailabilityInfoResultForWebui(@Singular final List<Group> groups) { Check.assumeNotEmpty(groups, "groups is not empty"); this.groups = groups; } private Group getSingleGroup() { if (groups.size() > 1) { throw new AdempiereException("Not a single group: " + this); } return groups.get(0); } public Quantity getSingleQuantity() { return getSingleGroup().getQty(); } @Value public static class Group { public enum Type {
ATTRIBUTE_SET, OTHER_STORAGE_KEYS, ALL_STORAGE_KEYS } ProductId productId; Quantity qty; Type type; ImmutableAttributeSet attributes; @Builder public Group( @NonNull final Group.Type type, @NonNull final ProductId productId, @NonNull final Quantity qty, @Nullable final ImmutableAttributeSet attributes) { this.type = type; this.productId = productId; this.qty = qty; this.attributes = CoalesceUtil.coalesce(attributes, ImmutableAttributeSet.EMPTY); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\adapter\AvailabilityInfoResultForWebui.java
2
请在Spring Boot框架中完成以下Java代码
class TaskPoolConfig { @Bean public Executor taskExecutor1() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(2); executor.setMaxPoolSize(2); executor.setQueueCapacity(2); executor.setKeepAliveSeconds(60); executor.setThreadNamePrefix("executor-1-"); /**配置拒绝策略**/ // AbortPolicy策略:默认策略,如果线程池队列满了丢掉这个任务并且抛出RejectedExecutionException异常。 // executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy()); // DiscardPolicy策略:如果线程池队列满了,会直接丢掉这个任务并且不会有任何异常。 // executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy()); // DiscardOldestPolicy策略:如果队列满了,会将最早进入队列的任务删掉腾出空间,再尝试加入队列。 // executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy()); // CallerRunsPolicy策略:如果添加到线程池失败,那么主线程会自己去执行该任务,不会等待线程池中的线程去执行。 // executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 自定义策略 // executor.setRejectedExecutionHandler(new RejectedExecutionHandler() { // @Override // public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { // // } // }); return executor; } } }
repos\SpringBoot-Learning-master\2.x\chapter7-8\src\main\java\com\didispace\chapter78\Chapter78Application.java
2
请完成以下Java代码
public Collection<State> getStates() { return this.success.values(); } public Collection<Character> getTransitions() { return this.success.keySet(); } @Override public String toString() { final StringBuilder sb = new StringBuilder("State{"); sb.append("depth=").append(depth); sb.append(", ID=").append(index); sb.append(", emits=").append(emits); sb.append(", success=").append(success.keySet()); sb.append(", failureID=").append(failure == null ? "-1" : failure.index); sb.append(", failure=").append(failure); sb.append('}'); return sb.toString(); } /** * 获取goto表 * @return */
public Map<Character, State> getSuccess() { return success; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\AhoCorasick\State.java
1
请完成以下Java代码
public ServiceInfo generateNewServiceInfoWithCurrentSystemInfo() { ServiceInfo.Builder builder = ServiceInfo.newBuilder() .setServiceId(serviceId) .addAllServiceTypes(serviceTypes.stream().map(ServiceType::name).collect(Collectors.toList())) .setSystemInfo(getCurrentSystemInfoProto()); if (CollectionsUtil.isNotEmpty(assignedTenantProfiles)) { builder.addAllAssignedTenantProfiles(assignedTenantProfiles.stream().map(UUID::toString).collect(Collectors.toList())); } if (edqsConfig != null) { builder.setLabel(edqsConfig.getLabel()); } builder.setReady(ready); builder.addAllTaskTypes(taskTypes.stream().map(JobType::name).toList()); return serviceInfo = builder.build(); } @Override public boolean setReady(boolean ready) { boolean changed = this.ready != ready; this.ready = ready; return changed; }
private TransportProtos.SystemInfoProto getCurrentSystemInfoProto() { TransportProtos.SystemInfoProto.Builder builder = TransportProtos.SystemInfoProto.newBuilder(); getCpuUsage().ifPresent(builder::setCpuUsage); getMemoryUsage().ifPresent(builder::setMemoryUsage); getDiscSpaceUsage().ifPresent(builder::setDiskUsage); getCpuCount().ifPresent(builder::setCpuCount); getTotalMemory().ifPresent(builder::setTotalMemory); getTotalDiscSpace().ifPresent(builder::setTotalDiscSpace); return builder.build(); } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\discovery\DefaultTbServiceInfoProvider.java
1
请完成以下Java代码
public Collection<GrantedAuthority> convert(Jwt jwt) { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String authority : getAuthorities(jwt)) { grantedAuthorities.add(new SimpleGrantedAuthority(this.authorityPrefix + authority)); } return grantedAuthorities; } private Collection<String> getAuthorities(Jwt jwt) { Object authorities; try { if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Looking for authorities with expression. expression=%s", this.authoritiesClaimExpression.getExpressionString())); } authorities = this.authoritiesClaimExpression.getValue(jwt.getClaims(), Collection.class); if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Found authorities with expression. authorities=%s", authorities)); }
} catch (ExpressionException ee) { if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Failed to evaluate expression. error=%s", ee.getMessage())); } authorities = Collections.emptyList(); } if (authorities != null) { return castAuthoritiesToCollection(authorities); } return Collections.emptyList(); } @SuppressWarnings("unchecked") private Collection<String> castAuthoritiesToCollection(Object authorities) { return (Collection<String>) authorities; } }
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\authentication\ExpressionJwtGrantedAuthoritiesConverter.java
1
请在Spring Boot框架中完成以下Java代码
private void handle(ExecuteContext context, SQLExceptionTranslator translator, SQLException exception) { DataAccessException translated = translator.translate("jOOQ", context.sql(), exception); if (exception.getNextException() != null) { this.logger.error("Execution of SQL statement failed.", (translated != null) ? translated : exception); return; } if (translated != null) { context.exception(translated); } } /** * Default {@link SQLExceptionTranslator} factory that creates the translator based on * the Spring DB name. */ private static final class DefaultTranslatorFactory implements Function<ExecuteContext, SQLExceptionTranslator> { @Override public SQLExceptionTranslator apply(ExecuteContext context) {
return apply(context.configuration().dialect()); } private SQLExceptionTranslator apply(SQLDialect dialect) { String dbName = getSpringDbName(dialect); return (dbName != null) ? new SQLErrorCodeSQLExceptionTranslator(dbName) : new SQLExceptionSubclassTranslator(); } private @Nullable String getSpringDbName(@Nullable SQLDialect dialect) { return (dialect != null && dialect.thirdParty() != null) ? dialect.thirdParty().springDbName() : null; } } }
repos\spring-boot-4.0.1\module\spring-boot-jooq\src\main\java\org\springframework\boot\jooq\autoconfigure\DefaultExceptionTranslatorExecuteListener.java
2
请完成以下Java代码
public String[] getDebugClosedTransactionInfos() { final List<ITrx> trxs = getTrxManager().getDebugClosedTransactions(); return toStringArray(trxs); } private final String[] toStringArray(final List<ITrx> trxs) { if (trxs == null || trxs.isEmpty()) { return new String[] {}; } final String[] arr = new String[trxs.size()]; for (int i = 0; i < trxs.size(); i++) { final ITrx trx = trxs.get(0); if (trx == null) { arr[i] = "null"; } else { arr[i] = trx.toString(); } } return arr; } @Override public void rollbackAndCloseActiveTrx(final String trxName) { final ITrxManager trxManager = getTrxManager(); if (trxManager.isNull(trxName)) { throw new IllegalArgumentException("Only not null transactions are allowed: " + trxName); }
final ITrx trx = trxManager.getTrx(trxName); if (trxManager.isNull(trx)) { // shall not happen because getTrx is already throwning an exception throw new IllegalArgumentException("No transaction was found for: " + trxName); } boolean rollbackOk = false; try { rollbackOk = trx.rollback(true); } catch (SQLException e) { throw new RuntimeException("Could not rollback '" + trx + "' because: " + e.getLocalizedMessage(), e); } if (!rollbackOk) { throw new RuntimeException("Could not rollback '" + trx + "' for unknown reason"); } } @Override public void setDebugConnectionBackendId(boolean debugConnectionBackendId) { getTrxManager().setDebugConnectionBackendId(debugConnectionBackendId); } @Override public boolean isDebugConnectionBackendId() { return getTrxManager().isDebugConnectionBackendId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\jmx\JMXTrxManager.java
1
请完成以下Java代码
public void notifySegmentsChanged(@NonNull final Collection<IShipmentScheduleSegment> segments) { if (segments.isEmpty()) { return; } final ImmutableList<IShipmentScheduleSegment> segmentsEffective = segments.stream() .filter(segment -> !segment.isInvalid()) .flatMap(this::explodeByPickingBOMs) .collect(ImmutableList.toImmutableList()); if (segmentsEffective.isEmpty()) { return; } final ShipmentScheduleSegmentChangedProcessor collector = ShipmentScheduleSegmentChangedProcessor.getOrCreateIfThreadInheritedElseNull(this); if (collector != null) { collector.addSegments(segmentsEffective); // they will be flagged for recompute after commit } else { final ITaskExecutorService taskExecutorService = Services.get(ITaskExecutorService.class); taskExecutorService.submit( () -> flagSegmentForRecompute(segmentsEffective), this.getClass().getSimpleName()); } } private Stream<IShipmentScheduleSegment> explodeByPickingBOMs(final IShipmentScheduleSegment segment)
{ if (segment.isAnyProduct()) { return Stream.of(segment); } final PickingBOMsReversedIndex pickingBOMsReversedIndex = pickingBOMService.getPickingBOMsReversedIndex(); final Set<ProductId> componentIds = ProductId.ofRepoIds(segment.getProductIds()); final ImmutableSet<ProductId> pickingBOMProductIds = pickingBOMsReversedIndex.getBOMProductIdsByComponentIds(componentIds); if (pickingBOMProductIds.isEmpty()) { return Stream.of(segment); } final ImmutableShipmentScheduleSegment pickingBOMsSegment = ImmutableShipmentScheduleSegment.builder() .productIds(ProductId.toRepoIds(pickingBOMProductIds)) .anyBPartner() .locatorIds(segment.getLocatorIds()) .build(); return Stream.of(segment, pickingBOMsSegment); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\invalidation\impl\ShipmentScheduleInvalidateBL.java
1
请完成以下Java代码
public String getBeanName() { return this.beanName; } /** * Return the destination - {@code exchange/routingKey}. * @return the destination. */ public String getDestination() { return this.destination; } /** * Return the exchange. * @return the exchange. * @since 3.2
*/ public String getExchange() { return this.exchange; } /** * Return the routingKey. * @return the routingKey. * @since 3.2 */ public String getRoutingKey() { return this.routingKey; } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\support\micrometer\RabbitMessageSenderContext.java
1
请完成以下Java代码
public boolean isQtyOverrideEditableByUser() { return isFieldEditable(FIELD_QtyOverride); } @SuppressWarnings("SameParameterValue") private boolean isFieldEditable(final String fieldName) { final ViewEditorRenderMode renderMode = getViewEditorRenderModeByFieldName().get(fieldName); return renderMode != null && renderMode.isEditable(); } public boolean isApproved() { return approvalStatus != null && approvalStatus.isApproved(); } private boolean isEligibleForChangingPickStatus() { return !isProcessed() && getType().isPickable(); } public boolean isEligibleForPicking() { return isEligibleForChangingPickStatus() && !isApproved() && pickStatus != null && pickStatus.isEligibleForPicking(); } public boolean isEligibleForRejectPicking() { return isEligibleForChangingPickStatus() && !isApproved() && pickStatus != null && pickStatus.isEligibleForRejectPicking(); } public boolean isEligibleForPacking() { return isEligibleForChangingPickStatus() && isApproved() && pickStatus != null && pickStatus.isEligibleForPacking(); }
public boolean isEligibleForReview() { return isEligibleForChangingPickStatus() && pickStatus != null && pickStatus.isEligibleForReview(); } public boolean isEligibleForProcessing() { return isEligibleForChangingPickStatus() && pickStatus != null && pickStatus.isEligibleForProcessing(); } public String getLocatorName() { return locator != null ? locator.getDisplayName() : ""; } @Override public List<ProductsToPickRow> getIncludedRows() { return includedRows; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\rows\ProductsToPickRow.java
1
请完成以下Java代码
public final class JAXBDateUtils { private static final ThreadLocal<DatatypeFactory> datatypeFactoryHolder = new ThreadLocal<DatatypeFactory>() { @Override protected DatatypeFactory initialValue() { try { return DatatypeFactory.newInstance(); } catch (final DatatypeConfigurationException e) { throw new IllegalStateException("failed to create " + DatatypeFactory.class.getSimpleName(), e); } } }; public static XMLGregorianCalendar toXMLGregorianCalendar(final LocalDateTime date) { if (date == null) { return null; } final GregorianCalendar c = new GregorianCalendar(); c.setTimeInMillis(date.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); return datatypeFactoryHolder.get().newXMLGregorianCalendar(c); } public static XMLGregorianCalendar toXMLGregorianCalendar(final ZonedDateTime date) { if (date == null) { return null; } final GregorianCalendar c = new GregorianCalendar(); c.setTimeInMillis(date.toInstant().toEpochMilli()); return datatypeFactoryHolder.get().newXMLGregorianCalendar(c); } public static LocalDateTime toLocalDateTime(final XMLGregorianCalendar xml) { if (xml == null)
{ return null; } return xml.toGregorianCalendar().toZonedDateTime().toLocalDateTime(); } public static ZonedDateTime toZonedDateTime(final XMLGregorianCalendar xml) { if (xml == null) { return null; } return xml.toGregorianCalendar().toZonedDateTime(); } public static java.util.Date toDate(final XMLGregorianCalendar xml) { return xml == null ? null : xml.toGregorianCalendar().getTime(); } public static Timestamp toTimestamp(final XMLGregorianCalendar xmlGregorianCalendar) { final Date date = toDate(xmlGregorianCalendar); if (date == null) { return null; } return new Timestamp(date.getTime()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\util\JAXBDateUtils.java
1
请完成以下Java代码
public abstract class BaseConnector implements IImportConnector { Map<String, Parameter> currentParams; final IInboundProcessorBL inboundProcessorBL = new InboundProcessorBL(); @Override public final void open(final Collection<Parameter> params) { currentParams = mkMap(params); openSpecific(); } public final void open(final Map<String, Parameter> params) { currentParams = params; openSpecific(); } @Override public final void close() { currentParams = null; closeSpecific(); } protected abstract void openSpecific(); protected abstract void closeSpecific();
public final Map<String, Parameter> getCurrentParams() { return currentParams; } @Override public Parameter getParameter(final String name) { return getCurrentParams().get(name); } @Override public boolean hasParameter(final String name) { return getCurrentParams().containsKey(name); } private static Map<String, Parameter> mkMap(Collection<Parameter> params) { final Map<String, Parameter> name2param = new HashMap<String, Parameter>( params.size()); for (final Parameter param : params) { name2param.put(param.name, param); } return Collections.unmodifiableMap(name2param); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\impex\spi\impl\BaseConnector.java
1
请在Spring Boot框架中完成以下Java代码
public int getS_Parent_Issue_ID() { return get_ValueAsInt(COLUMNNAME_S_Parent_Issue_ID); } /** * Status AD_Reference_ID=541142 * Reference name: S_Issue_Status */ public static final int STATUS_AD_Reference_ID=541142; /** In progress = InProgress */ public static final String STATUS_InProgress = "InProgress"; /** Closed = Closed */ public static final String STATUS_Closed = "Closed"; /** Pending = Pending */ public static final String STATUS_Pending = "Pending"; /** Delivered = Delivered */ public static final String STATUS_Delivered = "Delivered"; /** New = New */ public static final String STATUS_New = "New"; /** Invoiced = Invoiced */ public static final String STATUS_Invoiced = "Invoiced"; @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); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_Issue.java
2
请完成以下Java代码
public void updateAncestorsGreyness(TreePath path) { TreePath[] parents = new TreePath[path.getPathCount()]; parents[0] = path; boolean greyAll = isPathGreyed(path); for (int i = 1; i < parents.length; i++) { parents[i] = parents[i - 1].getParentPath(); if (greyAll) { addToGreyedPathsSet(parents[i]); } else { updatePathGreyness(parents[i]); greyAll = isPathGreyed(parents[i]); } } } /** * Return the paths that are children of path, using methods of * TreeModel. Nodes don't have to be of type TreeNode. * * @param path the parent path * @return the array of children path */ protected TreePath[] getChildrenPath(TreePath path) { Object node = path.getLastPathComponent(); int childrenNumber = this.model.getChildCount(node); TreePath[] childrenPath = new TreePath[childrenNumber]; for (int childIndex = 0; childIndex < childrenNumber; childIndex++) { childrenPath[childIndex] = path.pathByAddingChild(this.model.getChild(node, childIndex)); } return childrenPath; } @Override public TreeModel getTreeModel() { return this.model; } /** * Sets the specified tree model. The current cheking is cleared. */ @Override public void setTreeModel(TreeModel newModel) { TreeModel oldModel = this.model; if (oldModel != null) { oldModel.removeTreeModelListener(this.propagateCheckingListener); } this.model = newModel; if (newModel != null) { newModel.addTreeModelListener(this.propagateCheckingListener); } clearChecking(); }
/** * Return a string that describes the tree model including the values of * checking, enabling, greying. */ @Override public String toString() { return toString(new TreePath(this.model.getRoot())); } /** * Convenience method for getting a string that describes the tree * starting at path. * * @param path the treepath root of the tree */ private String toString(TreePath path) { String checkString = "n"; String greyString = "n"; String enableString = "n"; if (isPathChecked(path)) { checkString = "y"; } if (isPathEnabled(path)) { enableString = "y"; } if (isPathGreyed(path)) { greyString = "y"; } String description = "Path checked: " + checkString + " greyed: " + greyString + " enabled: " + enableString + " Name: " + path.toString() + "\n"; for (TreePath childPath : getChildrenPath(path)) { description += toString(childPath); } return description; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\it\cnr\imaa\essi\lablib\gui\checkboxtree\DefaultTreeCheckingModel.java
1
请完成以下Java代码
public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_Value (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID); } @Override public int getM_ShipmentSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } @Override public void setPP_Order_ID (final int PP_Order_ID) { if (PP_Order_ID < 1) set_Value (COLUMNNAME_PP_Order_ID, null); else set_Value (COLUMNNAME_PP_Order_ID, PP_Order_ID); } @Override public int getPP_Order_ID()
{ return get_ValueAsInt(COLUMNNAME_PP_Order_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setQtyToPick (final BigDecimal QtyToPick) { set_Value (COLUMNNAME_QtyToPick, QtyToPick); } @Override public BigDecimal getQtyToPick() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job_Line.java
1
请完成以下Java代码
public class RootCertificateUtil { private RootCertificateUtil() { } public static X509Certificate getRootCertificate(X509Certificate endEntityCertificate, KeyStore trustStore) throws Exception { X509Certificate issuerCertificate = findIssuerCertificate(endEntityCertificate, trustStore); if (issuerCertificate != null) { if (isRoot(issuerCertificate)) { return issuerCertificate; } else { return getRootCertificate(issuerCertificate, trustStore); } } return null; } private static X509Certificate findIssuerCertificate(X509Certificate certificate, KeyStore trustStore) throws KeyStoreException { Enumeration<String> aliases = trustStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); Certificate cert = trustStore.getCertificate(alias); if (cert instanceof X509Certificate) { X509Certificate x509Cert = (X509Certificate) cert; if (x509Cert.getSubjectX500Principal().equals(certificate.getIssuerX500Principal())) {
return x509Cert; } } } return null; } private static boolean isRoot(X509Certificate certificate) { try { certificate.verify(certificate.getPublicKey()); return certificate.getKeyUsage() != null && certificate.getKeyUsage()[5]; } catch (Exception e) { return false; } } }
repos\tutorials-master\core-java-modules\core-java-security-4\src\main\java\com\baeldung\certificate\RootCertificateUtil.java
1
请完成以下Java代码
public void onApplicationEvent(ContextRefreshedEvent event) { if (Objects.equals(event.getApplicationContext(), this.applicationContext)) { this.contextRefreshed = true; } } /** * Return true if the application context is refreshed. * @return true if refreshed. * @since 2.7.8 */ public boolean isContextRefreshed() { return this.contextRefreshed; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public static class DestinationTopicHolder { private final DestinationTopic sourceDestination;
private final DestinationTopic nextDestination; DestinationTopicHolder(DestinationTopic sourceDestination, DestinationTopic nextDestination) { this.sourceDestination = sourceDestination; this.nextDestination = nextDestination; } protected DestinationTopic getNextDestination() { return this.nextDestination; } protected DestinationTopic getSourceDestination() { return this.sourceDestination; } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\DefaultDestinationTopicResolver.java
1
请在Spring Boot框架中完成以下Java代码
public Collection<Class<? extends ShipmentScheduleDeletedEvent>> getHandledEventType() { return ImmutableList.of(ShipmentScheduleDeletedEvent.class); } @Override public void handleEvent(@NonNull final ShipmentScheduleDeletedEvent event) { final DemandDetailsQuery demandDetailsQuery = DemandDetailsQuery.ofShipmentScheduleId(event.getShipmentScheduleId()); final CandidatesQuery candidatesQuery = CandidatesQuery .builder() .type(CandidateType.DEMAND) .businessCase(CandidateBusinessCase.SHIPMENT) .demandDetailsQuery(demandDetailsQuery) .build(); final Candidate candidate = candidateRepository.retrieveLatestMatchOrNull(candidatesQuery); if (candidate == null)
{ Loggables.withLogger(logger, Level.DEBUG).addLog("Found no records to change for shipmentScheduleId={}", event.getShipmentScheduleId()); return; } final DemandDetail updatedDemandDetail = candidate.getDemandDetail().toBuilder() .shipmentScheduleId(IdConstants.NULL_REPO_ID) .qty(ZERO) .build(); final Candidate updatedCandidate = candidate.toBuilder() .quantity(ZERO) .businessCaseDetail(updatedDemandDetail) .build(); candidateChangeHandler.onCandidateNewOrChange(updatedCandidate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\shipmentschedule\ShipmentScheduleDeletedHandler.java
2
请在Spring Boot框架中完成以下Java代码
public String getTechnologyType() { return this.technologyType; } public void setTechnologyType(String technologyType) { this.technologyType = technologyType; } } public static class V2 { /** * Default dimensions that are added to all metrics in the form of key-value * pairs. These are overwritten by Micrometer tags if they use the same key. */ private @Nullable Map<String, String> defaultDimensions; /** * Whether to enable Dynatrace metadata export. */ private boolean enrichWithDynatraceMetadata = true; /** * Prefix string that is added to all exported metrics. */ private @Nullable String metricKeyPrefix; /** * Whether to fall back to the built-in micrometer instruments for Timer and * DistributionSummary. */ private boolean useDynatraceSummaryInstruments = true; /** * Whether to export meter metadata (unit and description) to the Dynatrace * backend. */ private boolean exportMeterMetadata = true; public @Nullable Map<String, String> getDefaultDimensions() { return this.defaultDimensions; } public void setDefaultDimensions(@Nullable Map<String, String> defaultDimensions) { this.defaultDimensions = defaultDimensions; } public boolean isEnrichWithDynatraceMetadata() { return this.enrichWithDynatraceMetadata; }
public void setEnrichWithDynatraceMetadata(Boolean enrichWithDynatraceMetadata) { this.enrichWithDynatraceMetadata = enrichWithDynatraceMetadata; } public @Nullable String getMetricKeyPrefix() { return this.metricKeyPrefix; } public void setMetricKeyPrefix(@Nullable String metricKeyPrefix) { this.metricKeyPrefix = metricKeyPrefix; } public boolean isUseDynatraceSummaryInstruments() { return this.useDynatraceSummaryInstruments; } public void setUseDynatraceSummaryInstruments(boolean useDynatraceSummaryInstruments) { this.useDynatraceSummaryInstruments = useDynatraceSummaryInstruments; } public boolean isExportMeterMetadata() { return this.exportMeterMetadata; } public void setExportMeterMetadata(boolean exportMeterMetadata) { this.exportMeterMetadata = exportMeterMetadata; } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\dynatrace\DynatraceProperties.java
2
请在Spring Boot框架中完成以下Java代码
private I_C_BP_PrintFormat createOrUpdateRecord(@NonNull final BPPrintFormat bpPrintFormat) { final I_C_BP_PrintFormat bpPrintFormatRecord; if (bpPrintFormat.getBpPrintFormatId() > 0) { bpPrintFormatRecord = load(bpPrintFormat.getBpPrintFormatId(), I_C_BP_PrintFormat.class); } else { bpPrintFormatRecord = newInstance(I_C_BP_PrintFormat.class); } bpPrintFormatRecord.setC_BPartner_ID(bpPrintFormat.getBpartnerId().getRepoId()); bpPrintFormatRecord.setC_DocType_ID(bpPrintFormat.getDocTypeId() == null ? 0 : bpPrintFormat.getDocTypeId().getRepoId()); bpPrintFormatRecord.setAD_Table_ID(bpPrintFormat.getAdTableId() == null ? 0 : bpPrintFormat.getAdTableId().getRepoId()); bpPrintFormatRecord.setAD_PrintFormat_ID(bpPrintFormat.getPrintFormatId() == null ? 0 : bpPrintFormat.getPrintFormatId().getRepoId()); bpPrintFormatRecord.setC_BPartner_Location_ID(bpPrintFormat.getBPartnerLocationId() == null ? 0 : bpPrintFormat.getBPartnerLocationId().getRepoId()); bpPrintFormatRecord.setDocumentCopies_Override(bpPrintFormat.getPrintCopies().toInt());
return bpPrintFormatRecord; } public SeqNo getNextSeqNo(@NonNull final BPartnerId bPartnerId) { final int lastLineInt = queryBL.createQueryBuilder(I_C_BP_PrintFormat.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_BP_PrintFormat.COLUMNNAME_C_BPartner_ID, bPartnerId) .create() .maxInt(I_C_BP_PrintFormat.COLUMNNAME_SeqNo); final SeqNo lastLineNo = SeqNo.ofInt(Math.max(lastLineInt, 0)); return lastLineNo.next(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\BPartnerPrintFormatRepository.java
2
请完成以下Java代码
public String toString() {return toJsonString();} @JsonValue @NonNull public String toJsonString() {return groupId.getAsString() + SEPARATOR + value;} @NonNull public <T extends RepoIdAware> T getAsId(@NonNull final Class<T> type) {return RepoIdAwares.ofObject(value, type);} @NonNull public LocalDate getAsLocalDate() {return LocalDate.parse(value);} // NOTE: Quantity class is not accessible from this project :( @NonNull public ImmutablePair<BigDecimal, Integer> getAsQuantity() { try { final List<String> parts = Splitter.on(QTY_SEPARATOR).splitToList(value); if (parts.size() != 2) { throw new AdempiereException("Cannot get Quantity from " + this); } return ImmutablePair.of(new BigDecimal(parts.get(0)), Integer.parseInt(parts.get(1))); } catch (AdempiereException ex)
{ throw ex; } catch (final Exception ex) { throw new AdempiereException("Cannot get Quantity from " + this, ex); } } @NonNull public String getAsString() {return value;} @NonNull public <T> T deserializeTo(@NonNull final Class<T> targetClass) { return JSONObjectMapper.forClass(targetClass).readValue(value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\rest_workflows\facets\WorkflowLaunchersFacetId.java
1
请完成以下Java代码
public List<Object> getContent() { if (content == null) { content = new ArrayList<Object>(); } return this.content; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() {
return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\KeyInfoType.java
1
请完成以下Java代码
public class InformationItemImpl extends NamedElementImpl implements InformationItem { protected static Attribute<String> typeRefAttribute; public InformationItemImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public String getTypeRef() { return typeRefAttribute.getValue(this); } public void setTypeRef(String typeRef) { typeRefAttribute.setValue(this, typeRef); } public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(InformationItem.class, DMN_ELEMENT_INFORMATION_ITEM) .namespaceUri(LATEST_DMN_NS) .extendsType(NamedElement.class) .instanceProvider(new ModelTypeInstanceProvider<InformationItem>() { public InformationItem newInstance(ModelTypeInstanceContext instanceContext) { return new InformationItemImpl(instanceContext); } }); typeRefAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_TYPE_REF) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\InformationItemImpl.java
1
请完成以下Java代码
public class OrderLine { private String item; private int quantity; private BigDecimal unitPrice; public OrderLine() { } public OrderLine(String item, int quantity, BigDecimal unitPrice) { super(); this.item = item; this.quantity = quantity; this.unitPrice = unitPrice; } public String getItem() { return item; } public void setItem(String item) { this.item = item; } public int getQuantity() { return quantity;
} public void setQuantity(int quantity) { this.quantity = quantity; } public BigDecimal getUnitPrice() { return unitPrice; } public void setUnitPrice(BigDecimal unitPrice) { this.unitPrice = unitPrice; } @Override public String toString() { return "OrderLine [item=" + item + ", quantity=" + quantity + ", unitPrice=" + unitPrice + "]"; } }
repos\tutorials-master\jackson-modules\jackson-conversions-2\src\main\java\com\baeldung\jackson\csv\OrderLine.java
1
请完成以下Java代码
private static class UserEntityParametersMapper implements Function<PublicKeyCredentialUserEntity, List<SqlParameterValue>> { @Override public List<SqlParameterValue> apply(PublicKeyCredentialUserEntity userEntity) { List<SqlParameterValue> parameters = new ArrayList<>(); parameters.add(new SqlParameterValue(Types.VARCHAR, userEntity.getId().toBase64UrlString())); parameters.add(new SqlParameterValue(Types.VARCHAR, userEntity.getName())); parameters.add(new SqlParameterValue(Types.VARCHAR, userEntity.getDisplayName())); return parameters; } }
private static class UserEntityRecordRowMapper implements RowMapper<PublicKeyCredentialUserEntity> { @Override public PublicKeyCredentialUserEntity mapRow(ResultSet rs, int rowNum) throws SQLException { Bytes id = Bytes.fromBase64(new String(rs.getString("id").getBytes())); String name = rs.getString("name"); String displayName = rs.getString("display_name"); return ImmutablePublicKeyCredentialUserEntity.builder().id(id).name(name).displayName(displayName).build(); } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\management\JdbcPublicKeyCredentialUserEntityRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class DefaultAsyncHistoryJobExecutor extends DefaultAsyncJobExecutor { public DefaultAsyncHistoryJobExecutor() { setTimerRunnableNeeded(false); setAcquireRunnableThreadName("flowable-acquire-history-jobs"); setResetExpiredRunnableName("flowable-reset-expired-history-jobs"); setAsyncRunnableExecutionExceptionHandler(new UnacquireAsyncHistoryJobExceptionHandler()); } public DefaultAsyncHistoryJobExecutor(AsyncJobExecutorConfiguration configuration) { super(configuration); setTimerRunnableNeeded(false); if (configuration.getAcquireRunnableThreadName() == null) { setAcquireRunnableThreadName("flowable-acquire-history-jobs"); } if (configuration.getResetExpiredRunnableName() == null) { setResetExpiredRunnableName("flowable-reset-expired-history-jobs");
} setAsyncRunnableExecutionExceptionHandler(new UnacquireAsyncHistoryJobExceptionHandler()); } @Override protected void initializeJobEntityManager() { if (jobEntityManager == null) { jobEntityManager = jobServiceConfiguration.getHistoryJobEntityManager(); } } @Override protected ResetExpiredJobsRunnable createResetExpiredJobsRunnable(String resetRunnableName) { return new ResetExpiredJobsRunnable(resetRunnableName, this, jobServiceConfiguration.getHistoryJobEntityManager()); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\DefaultAsyncHistoryJobExecutor.java
2
请完成以下Java代码
public boolean isReadOnly(ELContext context, Object base, Object property) { Objects.requireNonNull(context, "context is null"); if (isResolvable(base)) { context.setPropertyResolved(base, property); if (LENGTH_PROPERTY_NAME.equals(property)) { // Always read-only return true; } try { int idx = coerce(property); checkBounds(base, idx); } catch (IllegalArgumentException e) { // ignore } } return readOnly; } /** * If the base object is a Java language array, returns the most general type that this resolver accepts for the * <code>property</code> argument. Otherwise, returns <code>null</code>. * * <p> * Assuming the base is an array, this method will always return <code>Integer.class</code>. This is because arrays * accept integers for their index. * </p> * * @param context The context of this evaluation. * @param base The array to analyze. Only bases that are a Java language array are handled by this resolver. * @return <code>null</code> if base is not a Java language array; otherwise <code>Integer.class</code>. */ @Override public Class<?> getCommonPropertyType(ELContext context, Object base) { return isResolvable(base) ? Integer.class : null; } /** * Test whether the given base should be resolved by this ELResolver. * * @param base * The bean to analyze. * @return base != null && base.getClass().isArray() */ private final boolean isResolvable(Object base) { return base != null && base.getClass().isArray(); }
private static void checkBounds(Object base, int idx) { if (idx < 0 || idx >= Array.getLength(base)) { throw new PropertyNotFoundException(new ArrayIndexOutOfBoundsException(idx).getMessage()); } } private static int coerce(Object property) { if (property instanceof Number) { return ((Number) property).intValue(); } if (property instanceof Character) { return (Character) property; } if (property instanceof Boolean) { return (Boolean) property ? 1 : 0; } if (property instanceof String) { try { return Integer.parseInt((String) property); } catch (NumberFormatException e) { throw new IllegalArgumentException("Cannot parse array index: " + property, e); } } throw new IllegalArgumentException("Cannot coerce property to array index: " + property); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\ArrayELResolver.java
1
请完成以下Java代码
public I_AD_Rule retrieveById(final Properties ctx, final int AD_Rule_ID) { if (AD_Rule_ID <= 0) { return null; } return s_cacheById.getOrLoad(AD_Rule_ID, () -> { final I_AD_Rule rule = InterfaceWrapperHelper.create(ctx, AD_Rule_ID, I_AD_Rule.class, ITrx.TRXNAME_None); s_cacheByValue.put(rule.getValue(), rule); return rule; }); } @Override public I_AD_Rule retrieveByValue(final Properties ctx, final String ruleValue) { if (ruleValue == null) { return null; } return s_cacheByValue.getOrLoad(ruleValue, () -> { final I_AD_Rule rule = retrieveByValue_NoCache(ctx, ruleValue); if (rule != null) { s_cacheById.put(rule.getAD_Rule_ID(), rule); } return rule; }); } private final I_AD_Rule retrieveByValue_NoCache(final Properties ctx, final String ruleValue)
{ return Services.get(IQueryBL.class) .createQueryBuilder(I_AD_Rule.class, ctx, ITrx.TRXNAME_None) .addEqualsFilter(I_AD_Rule.COLUMNNAME_Value, ruleValue) .addOnlyActiveRecordsFilter() .create() .firstOnly(I_AD_Rule.class); } @Override public List<I_AD_Rule> retrieveByEventType(final Properties ctx, final String eventType) { return Services.get(IQueryBL.class) .createQueryBuilder(I_AD_Rule.class, ctx, ITrx.TRXNAME_None) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_Rule.COLUMNNAME_EventType, eventType) .create() .list(I_AD_Rule.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\script\impl\ADRuleDAO.java
1
请完成以下Java代码
public String getType() { return TYPE; } public void execute(TimerJobConfiguration configuration, ExecutionEntity execution, CommandContext commandContext, String tenantId) { DeploymentCache deploymentCache = Context .getProcessEngineConfiguration() .getDeploymentCache(); String definitionKey = configuration.getTimerElementKey(); ProcessDefinition processDefinition = deploymentCache.findDeployedLatestProcessDefinitionByKeyAndTenantId(definitionKey, tenantId); try { startProcessInstance(commandContext, tenantId, processDefinition); }
catch (RuntimeException e) { throw e; } } protected void startProcessInstance(CommandContext commandContext, String tenantId, ProcessDefinition processDefinition) { if(!processDefinition.isSuspended()) { RuntimeService runtimeService = commandContext.getProcessEngineConfiguration().getRuntimeService(); runtimeService.createProcessInstanceByKey(processDefinition.getKey()).processDefinitionTenantId(tenantId).execute(); } else { LOG.ignoringSuspendedJob(processDefinition); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\TimerStartEventJobHandler.java
1
请完成以下Java代码
public class UserAccount { @NotNull(groups = BasicInfo.class) @Size(min = 4, max = 15, groups = BasicInfo.class) private String password; @NotBlank(groups = BasicInfo.class) private String name; @Min(value = 18, message = "Age should not be less than 18", groups = AdvanceInfo.class) private int age; @NotBlank(groups = AdvanceInfo.class) private String phone; @Valid @NotNull(groups = AdvanceInfo.class) private UserAddress useraddress; public UserAddress getUseraddress() { return useraddress; } public void setUseraddress(UserAddress useraddress) { this.useraddress = useraddress; } public UserAccount() { } public UserAccount(String email, String password, String name, int age) { this.password = password; this.name = name; } public String getName() { return name; }
public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
repos\tutorials-master\spring-boot-modules\spring-boot-mvc\src\main\java\com\baeldung\springvalidation\domain\UserAccount.java
1
请完成以下Java代码
private String readWithOptimisticLock(String key) throws InterruptedException { long stamp = lock.tryOptimisticRead(); String value = map.get(key); if (!lock.validate(stamp)) { stamp = lock.readLock(); try { sleep(5000); return map.get(key); } finally { lock.unlock(stamp); logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp); } } return value; } public static void main(String[] args) { final int threadCount = 4; final ExecutorService service = Executors.newFixedThreadPool(threadCount); StampedLockDemo object = new StampedLockDemo(); Runnable writeTask = () -> { try { object.put("key1", "value1"); } catch (InterruptedException e) { e.printStackTrace(); }
}; Runnable readTask = () -> { try { object.get("key1"); } catch (InterruptedException e) { e.printStackTrace(); } }; Runnable readOptimisticTask = () -> { try { object.readWithOptimisticLock("key1"); } catch (InterruptedException e) { e.printStackTrace(); } }; service.submit(writeTask); service.submit(writeTask); service.submit(readTask); service.submit(readOptimisticTask); service.shutdown(); } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced\src\main\java\com\baeldung\concurrent\locks\StampedLockDemo.java
1
请在Spring Boot框架中完成以下Java代码
public class CustomWebSecurityConfigurerAdapter { @Bean public InMemoryUserDetailsManager userDetailsService() { PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); UserDetails user = User.withUsername("user1") .password(encoder.encode("user1Pass")) .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry.requestMatchers("/securityNone/**").permitAll() .anyRequest().authenticated() )
.httpBasic(Customizer.withDefaults()); http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class); return http.build(); } @Bean public SecurityFilterChain securedFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry.requestMatchers("/secured/**").authenticated()) .httpBasic(Customizer.withDefaults()); http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class); return http.build(); } }
repos\tutorials-master\spring-security-modules\spring-security-web-rest-basic-auth\src\main\java\com\baeldung\filter\CustomWebSecurityConfigurerAdapter.java
2
请完成以下Java代码
public Builder setColumnName(final String columnName) { this._sqlColumnName = columnName; return this; } private String getColumnName() { return _sqlColumnName; } public Builder setVirtualColumnSql(@Nullable final ColumnSql virtualColumnSql) { this._virtualColumnSql = virtualColumnSql; return this; } @Nullable private ColumnSql getVirtualColumnSql() { return _virtualColumnSql; } public Builder setMandatory(final boolean mandatory) { this.mandatory = mandatory; return this; } public Builder setHideGridColumnIfEmpty(final boolean hideGridColumnIfEmpty) { this.hideGridColumnIfEmpty = hideGridColumnIfEmpty; return this; } public Builder setValueClass(final Class<?> valueClass) { this._valueClass = valueClass; return this; } private Class<?> getValueClass() { if (_valueClass != null) { return _valueClass; } return getWidgetType().getValueClass(); } public Builder setWidgetType(final DocumentFieldWidgetType widgetType) { this._widgetType = widgetType; return this; } private DocumentFieldWidgetType getWidgetType() { Check.assumeNotNull(_widgetType, "Parameter widgetType is not null"); return _widgetType; } public Builder setMinPrecision(@NonNull final OptionalInt minPrecision) { this.minPrecision = minPrecision; return this; } private OptionalInt getMinPrecision() { return minPrecision; }
public Builder setSqlValueClass(final Class<?> sqlValueClass) { this._sqlValueClass = sqlValueClass; return this; } private Class<?> getSqlValueClass() { if (_sqlValueClass != null) { return _sqlValueClass; } return getValueClass(); } public Builder setLookupDescriptor(@Nullable final LookupDescriptor lookupDescriptor) { this._lookupDescriptor = lookupDescriptor; return this; } public OptionalBoolean getNumericKey() { return _numericKey; } public Builder setKeyColumn(final boolean keyColumn) { this.keyColumn = keyColumn; return this; } public Builder setEncrypted(final boolean encrypted) { this.encrypted = encrypted; return this; } /** * Sets ORDER BY priority and direction (ascending/descending) * * @param priority priority; if positive then direction will be ascending; if negative then direction will be descending */ public Builder setDefaultOrderBy(final int priority) { if (priority >= 0) { orderByPriority = priority; orderByAscending = true; } else { orderByPriority = -priority; orderByAscending = false; } return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlDocumentFieldDataBindingDescriptor.java
1
请完成以下Java代码
public abstract class AbstractOAuth2AuthorizationGrantRequest { private final AuthorizationGrantType authorizationGrantType; private final ClientRegistration clientRegistration; /** * Sub-class constructor. * @param authorizationGrantType the authorization grant type * @param clientRegistration the client registration * @since 5.5 */ protected AbstractOAuth2AuthorizationGrantRequest(AuthorizationGrantType authorizationGrantType, ClientRegistration clientRegistration) { Assert.notNull(authorizationGrantType, "authorizationGrantType cannot be null"); Assert.notNull(clientRegistration, "clientRegistration cannot be null"); this.authorizationGrantType = authorizationGrantType; this.clientRegistration = clientRegistration; }
/** * Returns the authorization grant type. * @return the authorization grant type */ public AuthorizationGrantType getGrantType() { return this.authorizationGrantType; } /** * Returns the {@link ClientRegistration client registration}. * @return the {@link ClientRegistration} * @since 5.5 */ public ClientRegistration getClientRegistration() { return this.clientRegistration; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\endpoint\AbstractOAuth2AuthorizationGrantRequest.java
1
请在Spring Boot框架中完成以下Java代码
public String getDespatchPattern() { return despatchPattern; } /** * Sets the value of the despatchPattern property. * * @param value * allowed object is * {@link String } * */ public void setDespatchPattern(String value) { this.despatchPattern = value; } /** * Gets the value of the cumulativeQuantity property. * * @return * possible object is * {@link ConditionalUnitType } * */ public ConditionalUnitType getCumulativeQuantity() { return cumulativeQuantity; } /** * Sets the value of the cumulativeQuantity property. * * @param value * allowed object is * {@link ConditionalUnitType } * */
public void setCumulativeQuantity(ConditionalUnitType value) { this.cumulativeQuantity = value; } /** * Gets the value of the planningQuantityExtension property. * * @return * possible object is * {@link PlanningQuantityExtensionType } * */ public PlanningQuantityExtensionType getPlanningQuantityExtension() { return planningQuantityExtension; } /** * Sets the value of the planningQuantityExtension property. * * @param value * allowed object is * {@link PlanningQuantityExtensionType } * */ public void setPlanningQuantityExtension(PlanningQuantityExtensionType value) { this.planningQuantityExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\PlanningQuantityType.java
2
请在Spring Boot框架中完成以下Java代码
public User save(UserRegistrationDto registration) { User user = new User(); user.setFirstName(registration.getFirstName()); user.setLastName(registration.getLastName()); user.setEmail(registration.getEmail()); user.setPassword(passwordEncoder.encode(registration.getPassword())); user.setRoles(Arrays.asList(new Role("ROLE_USER"))); return userRepository.save(user); } @Override public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
User user = userRepository.findByEmail(email); if (user == null){ throw new UsernameNotFoundException("Invalid username or password."); } return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), mapRolesToAuthorities(user.getRoles())); } private Collection<? extends GrantedAuthority> mapRolesToAuthorities(Collection<Role> roles){ return roles.stream() .map(role -> new SimpleGrantedAuthority(role.getName())) .collect(Collectors.toList()); } }
repos\Spring-Boot-Advanced-Projects-main\Springboot-Registration-Page\src\main\java\aspera\registration\service\UserServiceImpl.java
2
请完成以下Java代码
public String getCamundaHistoryTimeToLiveString() { return camundaHistoryTimeToLiveAttribute.getValue(this); } @Override public void setCamundaHistoryTimeToLiveString(String historyTimeToLive) { camundaHistoryTimeToLiveAttribute.setValue(this, historyTimeToLive); } @Override public String getVersionTag() { return camundaVersionTag.getValue(this); } @Override public void setVersionTag(String inputVariable) { camundaVersionTag.setValue(this, inputVariable); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Decision.class, DMN_ELEMENT_DECISION) .namespaceUri(LATEST_DMN_NS) .extendsType(DrgElement.class) .instanceProvider(new ModelTypeInstanceProvider<Decision>() { public Decision newInstance(ModelTypeInstanceContext instanceContext) { return new DecisionImpl(instanceContext); } }); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); questionChild = sequenceBuilder.element(Question.class) .build(); allowedAnswersChild = sequenceBuilder.element(AllowedAnswers.class) .build(); variableChild = sequenceBuilder.element(Variable.class) .build(); informationRequirementCollection = sequenceBuilder.elementCollection(InformationRequirement.class) .build(); knowledgeRequirementCollection = sequenceBuilder.elementCollection(KnowledgeRequirement.class) .build();
authorityRequirementCollection = sequenceBuilder.elementCollection(AuthorityRequirement.class) .build(); supportedObjectiveChildElementCollection = sequenceBuilder.elementCollection(SupportedObjectiveReference.class) .build(); impactedPerformanceIndicatorRefCollection = sequenceBuilder.elementCollection(ImpactedPerformanceIndicatorReference.class) .uriElementReferenceCollection(PerformanceIndicator.class) .build(); decisionMakerRefCollection = sequenceBuilder.elementCollection(DecisionMakerReference.class) .uriElementReferenceCollection(OrganizationUnit.class) .build(); decisionOwnerRefCollection = sequenceBuilder.elementCollection(DecisionOwnerReference.class) .uriElementReferenceCollection(OrganizationUnit.class) .build(); usingProcessCollection = sequenceBuilder.elementCollection(UsingProcessReference.class) .build(); usingTaskCollection = sequenceBuilder.elementCollection(UsingTaskReference.class) .build(); expressionChild = sequenceBuilder.element(Expression.class) .build(); // camunda extensions camundaHistoryTimeToLiveAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_HISTORY_TIME_TO_LIVE) .namespace(CAMUNDA_NS) .build(); camundaVersionTag = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_VERSION_TAG) .namespace(CAMUNDA_NS) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\DecisionImpl.java
1
请完成以下Java代码
public EncapsulatedLogic getEncapsulatedLogic() { return encapsulatedLogicChild.getChild(this); } public void setEncapsulatedLogic(EncapsulatedLogic encapsulatedLogic) { encapsulatedLogicChild.setChild(this, encapsulatedLogic); } public Variable getVariable() { return variableChild.getChild(this); } public void setVariable(Variable variable) { variableChild.setChild(this, variable); } public Collection<KnowledgeRequirement> getKnowledgeRequirement() { return knowledgeRequirementCollection.get(this); } public Collection<AuthorityRequirement> getAuthorityRequirement() { return authorityRequirementCollection.get(this); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(BusinessKnowledgeModel.class, DMN_ELEMENT_BUSINESS_KNOWLEDGE_MODEL) .namespaceUri(LATEST_DMN_NS) .extendsType(DrgElement.class) .instanceProvider(new ModelTypeInstanceProvider<BusinessKnowledgeModel>() {
public BusinessKnowledgeModel newInstance(ModelTypeInstanceContext instanceContext) { return new BusinessKnowledgeModelImpl(instanceContext); } }); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); encapsulatedLogicChild = sequenceBuilder.element(EncapsulatedLogic.class) .build(); variableChild = sequenceBuilder.element(Variable.class) .build(); knowledgeRequirementCollection = sequenceBuilder.elementCollection(KnowledgeRequirement.class) .build(); authorityRequirementCollection = sequenceBuilder.elementCollection(AuthorityRequirement.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\BusinessKnowledgeModelImpl.java
1
请完成以下Java代码
class ForkProcessCommand extends RunProcessCommand { private static final String MAIN_CLASS = "org.springframework.boot.loader.launch.JarLauncher"; private final Command command; ForkProcessCommand(Command command) { super(new JavaExecutable().toString()); this.command = command; } @Override public String getName() { return this.command.getName(); } @Override public String getDescription() { return this.command.getDescription(); } @Override public @Nullable String getUsageHelp() { return this.command.getUsageHelp(); }
@Override public @Nullable String getHelp() { return this.command.getHelp(); } @Override public Collection<OptionHelp> getOptionsHelp() { return this.command.getOptionsHelp(); } @Override public ExitStatus run(String... args) throws Exception { List<String> fullArgs = new ArrayList<>(); fullArgs.add("-cp"); fullArgs.add(System.getProperty("java.class.path")); fullArgs.add(MAIN_CLASS); fullArgs.add(this.command.getName()); fullArgs.addAll(Arrays.asList(args)); run(fullArgs); return ExitStatus.OK; } }
repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\shell\ForkProcessCommand.java
1
请在Spring Boot框架中完成以下Java代码
public void createProjectLine(@NonNull final CreateProjectLineRequest request) { final I_C_ProjectLine record = InterfaceWrapperHelper.newInstance(I_C_ProjectLine.class); record.setAD_Org_ID(request.getOrgId().getRepoId()); record.setC_Project_ID(request.getProjectId().getRepoId()); record.setC_ProjectIssue_ID(request.getProjectIssueId()); record.setM_Product_ID(request.getProductId().getRepoId()); record.setCommittedQty(request.getCommittedQty()); record.setDescription(request.getDescription()); save(record); } public void createProjectLine( @NonNull final CreateProjectRequest.ProjectLine request, @NonNull final ProjectId projectId, @NonNull final OrgId orgId) { final I_C_ProjectLine record = InterfaceWrapperHelper.newInstance(I_C_ProjectLine.class); record.setAD_Org_ID(orgId.getRepoId()); record.setC_Project_ID(projectId.getRepoId()); record.setM_Product_ID(request.getProductId().getRepoId()); record.setPlannedQty(request.getPlannedQty().toBigDecimal()); record.setC_UOM_ID(request.getPlannedQty().getUomId().getRepoId()); save(record); } public ProjectLine changeProjectLine( @NonNull final ProjectAndLineId projectLineId, @NonNull final Consumer<ProjectLine> updater) { final I_C_ProjectLine record = retrieveLineRecordById(projectLineId); final ProjectLine line = toProjectLine(record); updater.accept(line); updateRecord(record, line); save(record); return line; } public void linkToOrderLine( @NonNull final ProjectAndLineId projectLineId, @NonNull final OrderAndLineId orderLineId) { final I_C_ProjectLine record = retrieveLineRecordById(projectLineId); record.setC_Order_ID(orderLineId.getOrderRepoId()); record.setC_OrderLine_ID(orderLineId.getOrderLineRepoId());
save(record); } public void markLinesAsProcessed(@NonNull final ProjectId projectId) { for (final I_C_ProjectLine lineRecord : queryLineRecordsByProjectId(projectId).list()) { lineRecord.setProcessed(true); InterfaceWrapperHelper.saveRecord(lineRecord); } } public void markLinesAsNotProcessed(@NonNull final ProjectId projectId) { for (final I_C_ProjectLine lineRecord : queryLineRecordsByProjectId(projectId).list()) { lineRecord.setProcessed(false); InterfaceWrapperHelper.saveRecord(lineRecord); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\project\service\ProjectLineRepository.java
2
请完成以下Java代码
public int getPickFrom_Locator_ID() { return get_ValueAsInt(COLUMNNAME_PickFrom_Locator_ID); } /** * PriorityRule AD_Reference_ID=154 * Reference name: _PriorityRule */ public static final int PRIORITYRULE_AD_Reference_ID=154; /** High = 3 */ public static final String PRIORITYRULE_High = "3"; /** Medium = 5 */ public static final String PRIORITYRULE_Medium = "5"; /** Low = 7 */ public static final String PRIORITYRULE_Low = "7"; /** Urgent = 1 */ public static final String PRIORITYRULE_Urgent = "1"; /** Minor = 9 */ public static final String PRIORITYRULE_Minor = "9"; @Override public void setPriorityRule (final @Nullable java.lang.String PriorityRule) {
set_Value (COLUMNNAME_PriorityRule, PriorityRule); } @Override public java.lang.String getPriorityRule() { return get_ValueAsString(COLUMNNAME_PriorityRule); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Workplace.java
1
请在Spring Boot框架中完成以下Java代码
private DQVAR1 createDQVAR1( @NonNull final String documentId, @NonNull final EDIExpDesadvLineType line, @NonNull final BigDecimal quantityDiff, @NonNull final DecimalFormat decimalFormat) { final DQVAR1 dqvar1 = DESADV_objectFactory.createDQVAR1(); dqvar1.setDOCUMENTID(documentId); dqvar1.setLINENUMBER(extractLineNumber(line, decimalFormat)); dqvar1.setQUANTITY(formatNumber(quantityDiff, decimalFormat)); dqvar1.setDISCREPANCYCODE(extractDiscrepancyCode(line.getIsSubsequentDeliveryPlanned(), quantityDiff).toString()); return dqvar1; } @NonNull private BigDecimal extractQtyDelivered(@Nullable final SinglePack singlePack) { if (singlePack == null) { return ZERO; } final BigDecimal qtyDelivered = singlePack.getPackItem().getQtyCUsPerLU(); if (qtyDelivered == null) { return ZERO; } return qtyDelivered;
} private DiscrepencyCode extractDiscrepancyCode( @Nullable final String isSubsequentDeliveryPlanned, @NonNull final BigDecimal diff) { final DiscrepencyCode discrepancyCode; if (diff.signum() > 0) { discrepancyCode = DiscrepencyCode.OVSH; // = Over-shipped return discrepancyCode; } if (Boolean.parseBoolean(isSubsequentDeliveryPlanned)) { discrepancyCode = DiscrepencyCode.BFOL; // = Shipment partial - back order to follow } else { discrepancyCode = DiscrepencyCode.BCOM; // = shipment partial - considered complete, no backorder; } return discrepancyCode; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\desadvexport\stepcom\StepComXMLDesadvBean.java
2
请完成以下Java代码
public String getElementVariableName() { return elementVariableName; } public boolean hasElementVariable() { return StringUtils.isNotEmpty(elementVariableName); } public void setElementVariableName(String elementVariableName) { this.elementVariableName = elementVariableName; } public String getElementIndexVariableName() { return elementIndexVariableName; } public boolean hasElementIndexVariable() { return StringUtils.isNotEmpty(elementIndexVariableName); } public void setElementIndexVariableName(String elementIndexVariableName) { this.elementIndexVariableName = elementIndexVariableName; } public boolean hasLimitedInstanceCount() { return maxInstanceCount != null && maxInstanceCount > 0; } public Integer getMaxInstanceCount() { return maxInstanceCount; } public void setMaxInstanceCount(Integer maxInstanceCount) { this.maxInstanceCount = maxInstanceCount; }
public VariableAggregationDefinitions getAggregations() { return aggregations; } public void setAggregations(VariableAggregationDefinitions aggregations) { this.aggregations = aggregations; } public void addAggregation(VariableAggregationDefinition aggregation) { if (this.aggregations == null) { this.aggregations = new VariableAggregationDefinitions(); } this.aggregations.getAggregations().add(aggregation); } @Override public String toString() { return "RepetitionRule{" + " maxInstanceCount='" + (hasLimitedInstanceCount() ? maxInstanceCount : "unlimited") + "'" + " repetitionCounterVariableName='" + repetitionCounterVariableName + "'" + " collectionVariableName='" + collectionVariableName + "'" + " elementVariableName='" + elementVariableName + "'" + " elementIndexVariableName='" + elementIndexVariableName + "'" + " } " + super.toString(); } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\RepetitionRule.java
1
请在Spring Boot框架中完成以下Java代码
private Element getTopLevelType(Element element) { if (!(element.getEnclosingElement() instanceof TypeElement)) { return element; } return getTopLevelType(element.getEnclosingElement()); } private ItemMetadata resolveItemMetadataGroup(String prefix, MetadataGenerationEnvironment environment) { Element propertyElement = environment.getTypeUtils().asElement(getType()); String nestedPrefix = ConfigurationMetadata.nestedPrefix(prefix, getName()); String dataType = environment.getTypeUtils().getQualifiedName(propertyElement); String ownerType = environment.getTypeUtils().getQualifiedName(getDeclaringElement()); String sourceMethod = (getGetter() != null) ? getGetter().toString() : null; return ItemMetadata.newGroup(nestedPrefix, dataType, ownerType, sourceMethod); } private ItemMetadata resolveItemMetadataProperty(String prefix, MetadataGenerationEnvironment environment) { String dataType = resolveType(environment); String ownerType = environment.getTypeUtils().getQualifiedName(getDeclaringElement()); String description = resolveDescription(environment); Object defaultValue = resolveDefaultValue(environment); ItemDeprecation deprecation = resolveItemDeprecation(environment); return ItemMetadata.newProperty(prefix, getName(), dataType, ownerType, null, description, defaultValue, deprecation); } protected final ItemDeprecation resolveItemDeprecation(MetadataGenerationEnvironment environment, Element... elements) { boolean deprecated = Arrays.stream(elements).anyMatch(environment::isDeprecated); return deprecated ? environment.resolveItemDeprecation(getGetter()) : null; } private String resolveType(MetadataGenerationEnvironment environment) { return environment.getTypeUtils().getType(getDeclaringElement(), getType()); }
/** * Resolve the property description. * @param environment the metadata generation environment * @return the property description */ protected abstract String resolveDescription(MetadataGenerationEnvironment environment); /** * Resolve the default value for this property. * @param environment the metadata generation environment * @return the default value or {@code null} */ protected abstract Object resolveDefaultValue(MetadataGenerationEnvironment environment); /** * Resolve the {@link ItemDeprecation} for this property. * @param environment the metadata generation environment * @return the deprecation or {@code null} */ protected abstract ItemDeprecation resolveItemDeprecation(MetadataGenerationEnvironment environment); /** * Return true if this descriptor is for a property. * @param environment the metadata generation environment * @return if this is a property */ abstract boolean isProperty(MetadataGenerationEnvironment environment); }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\PropertyDescriptor.java
2
请在Spring Boot框架中完成以下Java代码
private static Money extractPayAmt(final I_C_Payment payment) { final CurrencyId currencyId = CurrencyId.ofRepoId(payment.getC_Currency_ID()); return Money.of(payment.getPayAmt(), currencyId); } // metas: us025b private I_C_BankStatement getCreateCashStatement(final I_C_Payment payment) { final Properties ctx = InterfaceWrapperHelper.getCtx(payment); final String trxName = InterfaceWrapperHelper.getTrxName(payment); final int C_BP_BankAccount_ID = payment.getC_BP_BankAccount_ID(); final LocalDate statementDate = TimeUtil.asLocalDate(payment.getDateTrx()); String whereClause = I_C_BankStatement.COLUMNNAME_C_BP_BankAccount_ID + "=?" + " AND TRUNC(" + I_C_BankStatement.COLUMNNAME_StatementDate + ")=?" + " AND " + I_C_BankStatement.COLUMNNAME_Processed + "=?"; I_C_BankStatement bs = new Query(ctx, I_C_BankStatement.Table_Name, whereClause, trxName) .setParameters(new Object[] { C_BP_BankAccount_ID, statementDate, false }) .firstOnly(I_C_BankStatement.class); if (bs != null) { return bs; } // Get BankAccount/CashBook I_C_BP_BankAccount ba = InterfaceWrapperHelper.create(ctx, C_BP_BankAccount_ID, I_C_BP_BankAccount.class, trxName); if (ba == null || ba.getC_BP_BankAccount_ID() <= 0) { throw new AdempiereException("@NotFound@ @C_BP_BankAccount_ID@ (ID=" + C_BP_BankAccount_ID + ")"); }
// Create Statement return createBankStatement(ba, statementDate); } private I_C_BankStatement createBankStatement(final I_C_BP_BankAccount account, final LocalDate statementDate) { final BankStatementId bankStatementId = bankStatementDAO.createBankStatement(BankStatementCreateRequest.builder() .orgId(OrgId.ofRepoId(account.getAD_Org_ID())) .orgBankAccountId(BankAccountId.ofRepoId(account.getC_BP_BankAccount_ID())) .statementDate(statementDate) .name(statementDate.toString()) .build()); return bankStatementDAO.getById(bankStatementId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\service\impl\CashStatementBL.java
2
请在Spring Boot框架中完成以下Java代码
public class GetProductsRouteHelper { @NonNull public ImmutableMap<String, JsonUOM> getUOMMappingRules(@NonNull final JsonExternalSystemRequest request) { final String shopware6UOMMappings = request.getParameters().get(ExternalSystemConstants.PARAM_UOM_MAPPINGS); if (Check.isBlank(shopware6UOMMappings)) { return ImmutableMap.of(); } final ObjectMapper mapper = JsonObjectMapperHolder.sharedJsonObjectMapper(); try { return mapper.readValue(shopware6UOMMappings, JsonUOMMappings.class) .getJsonUOMMappingList() .stream() .collect(ImmutableMap.toImmutableMap(JsonUOMMapping::getExternalCode, JsonUOMMapping::getUom)); } catch (final JsonProcessingException e) { throw new RuntimeException(e); } } @NonNull public TaxCategoryProvider getTaxCategoryProvider(@NonNull final JsonExternalSystemRequest request) { return TaxCategoryProvider.builder() .normalRates(request.getParameters().get(ExternalSystemConstants.PARAM_NORMAL_VAT_RATES)) .reducedRates(request.getParameters().get(ExternalSystemConstants.PARAM_REDUCED_VAT_RATES)) .build(); } @Nullable public PriceListBasicInfo getTargetPriceListInfo(@NonNull final JsonExternalSystemRequest request) { final String targetPriceListIdStr = request.getParameters().get(ExternalSystemConstants.PARAM_TARGET_PRICE_LIST_ID);
if (Check.isBlank(targetPriceListIdStr)) { return null; } final JsonMetasfreshId priceListId = JsonMetasfreshId.of(Integer.parseInt(targetPriceListIdStr)); final PriceListBasicInfo.PriceListBasicInfoBuilder targetPriceListInfoBuilder = PriceListBasicInfo.builder(); targetPriceListInfoBuilder.priceListId(priceListId); final String isTaxIncluded = request.getParameters().get(ExternalSystemConstants.PARAM_IS_TAX_INCLUDED); if (isTaxIncluded == null) { throw new RuntimeCamelException("isTaxIncluded is missing although priceListId is specified, targetPriceListId: " + priceListId); } targetPriceListInfoBuilder.isTaxIncluded(Boolean.parseBoolean(isTaxIncluded)); final String targetCurrencyCode = request.getParameters().get(ExternalSystemConstants.PARAM_PRICE_LIST_CURRENCY_CODE); if (targetCurrencyCode == null) { throw new RuntimeCamelException("targetCurrencyCode param is missing although priceListId is specified, targetPriceListId: " + priceListId); } targetPriceListInfoBuilder.currencyCode(targetCurrencyCode); return targetPriceListInfoBuilder.build(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\product\GetProductsRouteHelper.java
2
请在Spring Boot框架中完成以下Java代码
private PickingJobScheduleCollection getJobSchedules() { if (this._onlyPickingJobSchedules == null) { this._onlyPickingJobSchedules = retrieveJobSchedules(); } return this._onlyPickingJobSchedules; } private PickingJobScheduleCollection retrieveJobSchedules() { return query.isScheduledForWorkplaceOnly() ? pickingJobScheduleService.list(query.toPickingJobScheduleQuery()) : PickingJobScheduleCollection.EMPTY; } private PickingJobCandidateList aggregate() { final ImmutableList.Builder<PickingJobCandidate> result = ImmutableList.builder(); orderBasedAggregates.values().forEach(aggregation -> result.add(aggregation.toPickingJobCandidate())); productBasedAggregates.values().forEach(aggregation -> result.add(aggregation.toPickingJobCandidate())); deliveryLocationBasedAggregates.values().forEach(aggregation -> result.add(aggregation.toPickingJobCandidate())); return PickingJobCandidateList.ofList(result.build()); } private void add(@NonNull final ScheduledPackageable item) { final PickingJobAggregationType aggregationType = configService.getAggregationType(item.getCustomerId()); switch (aggregationType) { case SALES_ORDER: { orderBasedAggregates.computeIfAbsent(OrderBasedAggregationKey.of(item), OrderBasedAggregation::new).add(item);
break; } case PRODUCT: { productBasedAggregates.computeIfAbsent(ProductBasedAggregationKey.of(item), ProductBasedAggregation::new).add(item); break; } case DELIVERY_LOCATION: { deliveryLocationBasedAggregates.computeIfAbsent(DeliveryLocationBasedAggregationKey.of(item), DeliveryLocationBasedAggregation::new).add(item); break; } default: { throw new AdempiereException("Unknown aggregation type: " + aggregationType); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\retrieve\PickingJobCandidateRetrieveCommand.java
2
请完成以下Java代码
public class WebProjectRequest extends ProjectRequest { private final Map<String, Object> parameters = new LinkedHashMap<>(); /** * Return the additional parameters that can be used to further identify the request. * @return the parameters */ public Map<String, Object> getParameters() { return this.parameters; } /** * Initialize the state of this request with defaults defined in the * {@link InitializrMetadata metadata}. * @param metadata the metadata to use
*/ public void initialize(InitializrMetadata metadata) { BeanWrapperImpl bean = new BeanWrapperImpl(this); metadata.defaults().forEach((key, value) -> { if (bean.isWritableProperty(key)) { // We want to be able to infer a package name if none has been // explicitly set if (!key.equals("packageName")) { bean.setPropertyValue(key, value); } } }); } }
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\project\WebProjectRequest.java
1
请完成以下Java代码
public int getW_MailMsg_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_MailMsg_ID); if (ii == null) return 0; return ii.intValue(); } public I_W_Store getW_Store() throws RuntimeException { return (I_W_Store)MTable.get(getCtx(), I_W_Store.Table_Name) .getPO(getW_Store_ID(), get_TrxName()); } /** Set Web Store. @param W_Store_ID A Web Store of the Client */ public void setW_Store_ID (int W_Store_ID) {
if (W_Store_ID < 1) set_Value (COLUMNNAME_W_Store_ID, null); else set_Value (COLUMNNAME_W_Store_ID, Integer.valueOf(W_Store_ID)); } /** Get Web Store. @return A Web Store of the Client */ public int getW_Store_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_Store_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_MailMsg.java
1
请完成以下Java代码
public class WeightNetAttributeValueCallout extends AbstractWeightAttributeValueCallout { public WeightNetAttributeValueCallout() { super(); } /** * Recalculates the gross weight based on the current values of the given <code>attributeSet</code>'s WeightNet and WeightTare values. * * @see org.adempiere.mm.attributes.api.impl.AttributeSetCalloutExecutor#executeCallouts(IAttributeSet, I_M_Attribute, Object, Object) the implementation */ @Override public void onValueChanged0(final IAttributeValueContext attributeValueContext, final IAttributeSet attributeSet, final I_M_Attribute attribute, final Object valueOld, final Object valueNew) { recalculateWeightGross(attributeSet); huReceiptScheduleBL.adjustPlanningHUStorageFromNetWeight(attributeSet); } /** * @return {@link BigDecimal#ZERO} */ @Override public Object generateSeedValue(final IAttributeSet attributeSet, final I_M_Attribute attribute, final Object valueInitialDefault) { // we don't support a value different from null Check.assumeNull(valueInitialDefault, "valueInitialDefault null"); return BigDecimal.ZERO; } @Override public String getAttributeValueType() { return X_M_Attribute.ATTRIBUTEVALUETYPE_Number; } @Override public boolean canGenerateValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute) { return true; } @Override public BigDecimal generateNumericValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute) { return BigDecimal.ZERO; } @Override protected boolean isExecuteCallout(final IAttributeValueContext attributeValueContext, final IAttributeSet attributeSet, final I_M_Attribute attribute, final Object valueOld, final Object valueNew) { final IWeightable weightable = getWeightableOrNull(attributeSet);
if (weightable == null) { return false; } final AttributeCode attributeCode = AttributeCode.ofString(attribute.getValue()); if (!weightable.isWeightNetAttribute(attributeCode)) { return false; } if (!weightable.hasWeightNet()) { return false; } if (!weightable.hasWeightTare()) { return false; } if (!(attributeValueContext instanceof IHUAttributePropagationContext)) { return false; } final IHUAttributePropagationContext huAttributePropagationContext = (IHUAttributePropagationContext)attributeValueContext; final AttributeCode attr_WeightGross = weightable.getWeightGrossAttribute(); if (huAttributePropagationContext.isExternalInput() && huAttributePropagationContext.isValueUpdatedBefore(attr_WeightGross)) { // // Gross weight was set externally. Do not modify it. return false; } return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\WeightNetAttributeValueCallout.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonCache { @NonNull JsonCacheStats stats; @Nullable Map<String, String> sample; public static JsonCache of(@NonNull final CCache<?, ?> cache, final int sampleLimit) { //noinspection unchecked return JsonCache.builder() .stats(JsonCacheStats.of(cache.stats())) .sample(extractSample((CCache<Object, Object>)cache, sampleLimit)) .build(); } private static Map<String, String> extractSample(final CCache<Object, Object> cache, final int sampleLimit) { final HashMap<String, String> sample = sampleLimit > 0 ? new HashMap<>(sampleLimit) : new HashMap<>();
for (final Object key : cache.keySet()) { if (sampleLimit > 0 && sample.size() > sampleLimit) { break; } final Object value = cache.get(key); sample.put(key != null ? key.toString() : null, value != null ? value.toString() : null); } return sample; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\rest\JsonCache.java
2
请在Spring Boot框架中完成以下Java代码
public class Address extends BaseModel { public Address(String addressLine1, String addressLine2, String city) { super(); this.addressLine1 = addressLine1; this.addressLine2 = addressLine2; this.city = city; } private String addressLine1; private String addressLine2; private String city; public String getAddressLine1() { return addressLine1; } public void setAddressLine1(String addressLine1) { this.addressLine1 = addressLine1; } public String getAddressLine2() { return addressLine2;
} public void setAddressLine2(String addressLine2) { this.addressLine2 = addressLine2; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Override public String toString() { return "Address [id=" + id + ", addressLine1=" + addressLine1 + ", addressLine2=" + addressLine2 + ", city=" + city + "]"; } }
repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\ebean\model\Address.java
2
请完成以下Java代码
LocalDate computeEasterDateWithButcherMeeusAlgorithm(int year) { int a = year % 19; int b = year / 100; int c = year % 100; int d = b / 4; int e = b % 4; int f = (b + 8) / 25; int g = (b - f + 1) / 3; int h = (19*a + b - d - g + 15) % 30; int i = c / 4; int k = c % 4; int l = (2*e + 2*i - h - k + 32) % 7; int m = (a + 11*h + 22*l) / 451; int t = h + l - 7*m + 114; int n = t / 31; int o = t % 31; return LocalDate.of(year, n, o+1); } LocalDate computeEasterDateWithConwayAlgorithm(int year) { int s = year / 100; int t = year % 100;
int a = t / 4; int p = s % 4; int x = (9 - 2*p) % 7; int y = (x + t + a) % 7; int g = year % 19; int G = g + 1; int b = s / 4; int r = 8 * (s + 11) / 25; int C = -s + b + r; int d = (11*G + C) % 30; d = (d + 30) % 30; int h = (551 - 19*d + G) / 544; int e = (50 - d - h) % 7; int f = (e + y) % 7; int R = 57 - d - f - h; if (R <= 31) { return LocalDate.of(year, 3, R); } return LocalDate.of(year, 4, R-31); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-8\src\main\java\com\baeldung\algorithms\eastersunday\EasterDateCalculator.java
1
请完成以下Java代码
public boolean isTableName(final String expectedTableName) {return Objects.equals(tableName, expectedTableName);} public boolean isInventoryLine() {return isTableName(TABLE_NAME_M_InventoryLine);} public boolean isCostRevaluationLine() {return isTableName(TABLE_NAME_M_CostRevaluationLine);} public boolean isMatchInv() { return isTableName(TABLE_NAME_M_MatchInv); } public PPCostCollectorId getCostCollectorId() { return getId(PPCostCollectorId.class); }
public <T extends RepoIdAware> T getId(final Class<T> idClass) { if (idClass.isInstance(id)) { return idClass.cast(id); } else { throw new AdempiereException("Expected id to be of type " + idClass + " but it was " + id); } } public static boolean equals(CostingDocumentRef ref1, CostingDocumentRef ref2) {return Objects.equals(ref1, ref2);} public TableRecordReference toTableRecordReference() {return TableRecordReference.of(tableName, id);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostingDocumentRef.java
1
请在Spring Boot框架中完成以下Java代码
public static final AvailableToPromiseMultiQuery of(@NonNull final AvailableToPromiseQuery query) { return builder() .query(query) .addToPredefinedBuckets(DEFAULT_addToPredefinedBuckets) .build(); } private final Set<AvailableToPromiseQuery> queries; private static final boolean DEFAULT_addToPredefinedBuckets = true; private final boolean addToPredefinedBuckets; @Builder private AvailableToPromiseMultiQuery( @NonNull @Singular final ImmutableSet<AvailableToPromiseQuery> queries, final Boolean addToPredefinedBuckets)
{ Check.assumeNotEmpty(queries, "queries is not empty"); this.queries = queries; this.addToPredefinedBuckets = CoalesceUtil.coalesce(addToPredefinedBuckets, DEFAULT_addToPredefinedBuckets); } /** * {@code true} means that the system will initially create one empty result group for the {@link AttributesKey}s of each included {@link AvailableToPromiseQuery}. * ATP quantity that are retrieved may be added to multiple result groups, depending on those groups attributes keys * If no ATP quantity matches a particular group, it will remain empty.<br> * {@code false} means that the system will create result groups on the fly for the respective ATP records that it finds. */ public boolean isAddToPredefinedBuckets() { return addToPredefinedBuckets; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\atp\AvailableToPromiseMultiQuery.java
2
请完成以下Java代码
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set 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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_RegistrationValue.java
1
请在Spring Boot框架中完成以下Java代码
public void save(List<ColumnInfo> columnInfos) { columnInfoRepository.saveAll(columnInfos); } @Override public void generator(GenConfig genConfig, List<ColumnInfo> columns) { if (genConfig.getId() == null) { throw new BadRequestException(CONFIG_MESSAGE); } try { GenUtil.generatorCode(columns, genConfig); } catch (IOException e) { log.error(e.getMessage(), e); throw new BadRequestException("生成失败,请手动处理已生成的文件"); } } @Override public ResponseEntity<Object> preview(GenConfig genConfig, List<ColumnInfo> columns) { if (genConfig.getId() == null) { throw new BadRequestException(CONFIG_MESSAGE); }
List<Map<String, Object>> genList = GenUtil.preview(columns, genConfig); return new ResponseEntity<>(genList, HttpStatus.OK); } @Override public void download(GenConfig genConfig, List<ColumnInfo> columns, HttpServletRequest request, HttpServletResponse response) { if (genConfig.getId() == null) { throw new BadRequestException(CONFIG_MESSAGE); } try { File file = new File(GenUtil.download(columns, genConfig)); String zipPath = file.getPath() + ".zip"; ZipUtil.zip(file.getPath(), zipPath); FileUtil.downloadFile(request, response, new File(zipPath), true); } catch (IOException e) { throw new BadRequestException("打包失败"); } } }
repos\eladmin-master\eladmin-generator\src\main\java\me\zhengjie\service\impl\GeneratorServiceImpl.java
2
请完成以下Java代码
public void removeVariablesLocal() { } public void deleteVariablesLocal() { } @Override public Object setVariableLocal(String variableName, Object value) { return null; } @Override public void setVariablesLocal(Map<String, ? extends Object> variables) { } @Override public boolean isEventScope() { return isEventScope; } @Override public void setEventScope(boolean isEventScope) { this.isEventScope = isEventScope; } @Override public StartingExecution getStartingExecution() { return startingExecution; } @Override public void disposeStartingExecution() { startingExecution = null; } public String updateProcessBusinessKey(String bzKey) { return getProcessInstance().updateProcessBusinessKey(bzKey); } @Override public String getTenantId() { return null; // Not implemented } // NOT IN V5 @Override public boolean isMultiInstanceRoot() { return false; } @Override public void setMultiInstanceRoot(boolean isMultiInstanceRoot) { } @Override public String getPropagatedStageInstanceId() { return null; } // No support for transient variables in v5 @Override public void setTransientVariablesLocal(Map<String, Object> transientVariables) { throw new UnsupportedOperationException(); } @Override public void setTransientVariableLocal(String variableName, Object variableValue) { throw new UnsupportedOperationException(); } @Override public void setTransientVariables(Map<String, Object> transientVariables) { throw new UnsupportedOperationException(); } @Override public void setTransientVariable(String variableName, Object variableValue) { throw new UnsupportedOperationException(); } @Override public Object getTransientVariableLocal(String variableName) {
throw new UnsupportedOperationException(); } @Override public Map<String, Object> getTransientVariablesLocal() { throw new UnsupportedOperationException(); } @Override public Object getTransientVariable(String variableName) { throw new UnsupportedOperationException(); } @Override public Map<String, Object> getTransientVariables() { throw new UnsupportedOperationException(); } @Override public void removeTransientVariableLocal(String variableName) { throw new UnsupportedOperationException(); } @Override public void removeTransientVariablesLocal() { throw new UnsupportedOperationException(); } @Override public void removeTransientVariable(String variableName) { throw new UnsupportedOperationException(); } @Override public void removeTransientVariables() { throw new UnsupportedOperationException(); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\runtime\ExecutionImpl.java
1
请完成以下Java代码
public synchronized void addEventListener(ActivitiEventListener listenerToAdd, ActivitiEventType... types) { if (listenerToAdd == null) { throw new ActivitiIllegalArgumentException("Listener cannot be null."); } if (types == null || types.length == 0) { addEventListener(listenerToAdd); } else { for (ActivitiEventType type : types) { addTypedEventListener(listenerToAdd, type); } } } public void removeEventListener(ActivitiEventListener listenerToRemove) { eventListeners.remove(listenerToRemove); for (List<ActivitiEventListener> listeners : typedListeners.values()) { listeners.remove(listenerToRemove); } } public void dispatchEvent(ActivitiEvent event) { if (event == null) { throw new ActivitiIllegalArgumentException("Event cannot be null."); } if (event.getType() == null) { throw new ActivitiIllegalArgumentException("Event type cannot be null."); } // Call global listeners if (!eventListeners.isEmpty()) { for (ActivitiEventListener listener : eventListeners) { dispatchEvent(event, listener); } } // Call typed listeners, if any List<ActivitiEventListener> typed = typedListeners.get(event.getType()); if (typed != null && !typed.isEmpty()) { for (ActivitiEventListener listener : typed) {
dispatchEvent(event, listener); } } } protected void dispatchEvent(ActivitiEvent event, ActivitiEventListener listener) { try { listener.onEvent(event); } catch (Throwable t) { if (listener.isFailOnException()) { throw new ActivitiException("Exception while executing event-listener", t); } else { // Ignore the exception and continue notifying remaining listeners. The listener // explicitly states that the exception should not bubble up LOG.warn("Exception while executing event-listener, which was ignored", t); } } } protected synchronized void addTypedEventListener(ActivitiEventListener listener, ActivitiEventType type) { List<ActivitiEventListener> listeners = typedListeners.get(type); if (listeners == null) { // Add an empty list of listeners for this type listeners = new CopyOnWriteArrayList<ActivitiEventListener>(); typedListeners.put(type, listeners); } if (!listeners.contains(listener)) { listeners.add(listener); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\delegate\event\impl\ActivitiEventSupport.java
1
请完成以下Java代码
public void setC_Invoice_Candidate_Assigned_ID (int C_Invoice_Candidate_Assigned_ID) { if (C_Invoice_Candidate_Assigned_ID < 1) set_Value (COLUMNNAME_C_Invoice_Candidate_Assigned_ID, null); else set_Value (COLUMNNAME_C_Invoice_Candidate_Assigned_ID, Integer.valueOf(C_Invoice_Candidate_Assigned_ID)); } /** Get Zugeordneter Rechnungskandidat. @return Zugeordneter Rechnungskandidat */ @Override public int getC_Invoice_Candidate_Assigned_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_Candidate_Assigned_ID); if (ii == null) return 0; return ii.intValue(); } /** Set C_Invoice_Candidate_Assignment. @param C_Invoice_Candidate_Assignment_ID C_Invoice_Candidate_Assignment */ @Override public void setC_Invoice_Candidate_Assignment_ID (int C_Invoice_Candidate_Assignment_ID) { if (C_Invoice_Candidate_Assignment_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Assignment_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Assignment_ID, Integer.valueOf(C_Invoice_Candidate_Assignment_ID)); } /** Get C_Invoice_Candidate_Assignment. @return C_Invoice_Candidate_Assignment */ @Override public int getC_Invoice_Candidate_Assignment_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_Candidate_Assignment_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Vertrag-Rechnungskandidat. @param C_Invoice_Candidate_Term_ID Vertrag-Rechnungskandidat */ @Override public void setC_Invoice_Candidate_Term_ID (int C_Invoice_Candidate_Term_ID)
{ if (C_Invoice_Candidate_Term_ID < 1) set_Value (COLUMNNAME_C_Invoice_Candidate_Term_ID, null); else set_Value (COLUMNNAME_C_Invoice_Candidate_Term_ID, Integer.valueOf(C_Invoice_Candidate_Term_ID)); } /** Get Vertrag-Rechnungskandidat. @return Vertrag-Rechnungskandidat */ @Override public int getC_Invoice_Candidate_Term_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_Candidate_Term_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Zugeordnete Menge wird in Summe einbez.. @param IsAssignedQuantityIncludedInSum Zugeordnete Menge wird in Summe einbez. */ @Override public void setIsAssignedQuantityIncludedInSum (boolean IsAssignedQuantityIncludedInSum) { set_Value (COLUMNNAME_IsAssignedQuantityIncludedInSum, Boolean.valueOf(IsAssignedQuantityIncludedInSum)); } /** Get Zugeordnete Menge wird in Summe einbez.. @return Zugeordnete Menge wird in Summe einbez. */ @Override public boolean isAssignedQuantityIncludedInSum () { Object oo = get_Value(COLUMNNAME_IsAssignedQuantityIncludedInSum); 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.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Invoice_Candidate_Assignment.java
1
请完成以下Java代码
public void handleBpmnError(String externalTaskId, String workerId, String errorCode) { handleBpmnError(externalTaskId, workerId, errorCode, null, null); } @Override public void handleBpmnError(String externalTaskId, String workerId, String errorCode, String errorMessage) { handleBpmnError(externalTaskId, workerId, errorCode, errorMessage, null); } @Override public void handleBpmnError(String externalTaskId, String workerId, String errorCode, String errorMessage, Map<String, Object> variables) { commandExecutor.execute(new HandleExternalTaskBpmnErrorCmd(externalTaskId, workerId, errorCode, errorMessage, variables)); } @Override public void unlock(String externalTaskId) { commandExecutor.execute(new UnlockExternalTaskCmd(externalTaskId)); } public void setRetries(String externalTaskId, int retries, boolean writeUserOperationLog) { commandExecutor.execute(new SetExternalTaskRetriesCmd(externalTaskId, retries, writeUserOperationLog)); } @Override public void setPriority(String externalTaskId, long priority) { commandExecutor.execute(new SetExternalTaskPriorityCmd(externalTaskId, priority)); } public ExternalTaskQuery createExternalTaskQuery() { return new ExternalTaskQueryImpl(commandExecutor); } @Override public List<String> getTopicNames() { return commandExecutor.execute(new GetTopicNamesCmd(false,false,false)); } @Override public List<String> getTopicNames(boolean withLockedTasks, boolean withUnlockedTasks, boolean withRetriesLeft) { return commandExecutor.execute(new GetTopicNamesCmd(withLockedTasks, withUnlockedTasks, withRetriesLeft)); } public String getExternalTaskErrorDetails(String externalTaskId) {
return commandExecutor.execute(new GetExternalTaskErrorDetailsCmd(externalTaskId)); } @Override public void setRetries(String externalTaskId, int retries) { setRetries(externalTaskId, retries, true); } @Override public void setRetries(List<String> externalTaskIds, int retries) { updateRetries() .externalTaskIds(externalTaskIds) .set(retries); } @Override public Batch setRetriesAsync(List<String> externalTaskIds, ExternalTaskQuery externalTaskQuery, int retries) { return updateRetries() .externalTaskIds(externalTaskIds) .externalTaskQuery(externalTaskQuery) .setAsync(retries); } @Override public UpdateExternalTaskRetriesSelectBuilder updateRetries() { return new UpdateExternalTaskRetriesBuilderImpl(commandExecutor); } @Override public void extendLock(String externalTaskId, String workerId, long lockDuration) { commandExecutor.execute(new ExtendLockOnExternalTaskCmd(externalTaskId, workerId, lockDuration)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ExternalTaskServiceImpl.java
1
请完成以下Java代码
public void setHostKey (java.lang.String HostKey) { set_Value (COLUMNNAME_HostKey, HostKey); } @Override public java.lang.String getHostKey() { return (java.lang.String)get_Value(COLUMNNAME_HostKey); } /** * Status AD_Reference_ID=540384 * Reference name: C_Print_Job_Instructions_Status */ public static final int STATUS_AD_Reference_ID=540384; /** Pending = P */ public static final String STATUS_Pending = "P"; /** Send = S */
public static final String STATUS_Send = "S"; /** Done = D */ public static final String STATUS_Done = "D"; /** Error = E */ public static final String STATUS_Error = "E"; @Override public void setStatus (java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return (java.lang.String)get_Value(COLUMNNAME_Status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_Job_Instructions.java
1
请在Spring Boot框架中完成以下Java代码
public class RedisConfig extends CachingConfigurerSupport { @Bean @Override public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); } }; } @SuppressWarnings("rawtypes") @Bean public CacheManager cacheManager(RedisTemplate redisTemplate) { RedisCacheManager rcm = new RedisCacheManager(redisTemplate); //设置缓存过期时间
//rcm.setDefaultExpiration(60);//秒 return rcm; } @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } }
repos\spring-boot-quick-master\quick-redies\src\main\java\com\quick\redis\config\RedisConfig.java
2
请完成以下Java代码
public @Nullable LoggerConfiguration getLoggerConfiguration(String loggerName) { Logger logger = Logger.getLogger(loggerName); if (logger == null) { return null; } LogLevel level = LEVELS.convertNativeToSystem(logger.getLevel()); LogLevel effectiveLevel = LEVELS.convertNativeToSystem(getEffectiveLevel(logger)); String name = (StringUtils.hasLength(logger.getName()) ? logger.getName() : ROOT_LOGGER_NAME); Assert.state(effectiveLevel != null, "effectiveLevel must not be null"); return new LoggerConfiguration(name, level, effectiveLevel); } private Level getEffectiveLevel(Logger root) { Logger logger = root; while (logger.getLevel() == null) { logger = logger.getParent(); } return logger.getLevel(); } @Override public Runnable getShutdownHandler() { return () -> LogManager.getLogManager().reset(); } @Override public void cleanUp() { this.configuredLoggers.clear(); } /** * {@link LoggingSystemFactory} that returns {@link JavaLoggingSystem} if possible. */
@Order(Ordered.LOWEST_PRECEDENCE - 1024) public static class Factory implements LoggingSystemFactory { private static final boolean PRESENT = ClassUtils.isPresent("java.util.logging.LogManager", Factory.class.getClassLoader()); @Override public @Nullable LoggingSystem getLoggingSystem(ClassLoader classLoader) { if (PRESENT) { return new JavaLoggingSystem(classLoader); } return null; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\java\JavaLoggingSystem.java
1
请完成以下Java代码
public class FileValueImpl implements FileValue { private static final long serialVersionUID = 1L; protected String mimeType; protected String filename; protected byte[] value; protected FileValueType type; protected String encoding; protected boolean isTransient; public FileValueImpl(byte[] value, FileValueType type, String filename, String mimeType, String encoding) { this.value = value; this.type = type; this.filename = filename; this.mimeType = mimeType; this.encoding = encoding; } public FileValueImpl(FileValueType type, String filename) { this(null, type, filename, null, null); } @Override public String getFilename() { return filename; } @Override public String getMimeType() { return mimeType; } public void setMimeType(String mimeType) { this.mimeType = mimeType; } public void setValue(byte[] bytes) { this.value = bytes; } @Override public InputStream getValue() { if (value == null) { return null; } return new ByteArrayInputStream(value); } @Override public ValueType getType() { return type; } public void setEncoding(String encoding) {
this.encoding = encoding; } public void setEncoding(Charset encoding) { this.encoding = encoding.name(); } @Override public Charset getEncodingAsCharset() { if (encoding == null) { return null; } return Charset.forName(encoding); } @Override public String getEncoding() { return encoding; } /** * Get the byte array directly without wrapping it inside a stream to evade * not needed wrapping. This method is intended for the internal API, which * needs the byte array anyways. */ public byte[] getByteArray() { return value; } @Override public String toString() { return "FileValueImpl [mimeType=" + mimeType + ", filename=" + filename + ", type=" + type + ", isTransient=" + isTransient + "]"; } @Override public boolean isTransient() { return isTransient; } public void setTransient(boolean isTransient) { this.isTransient = isTransient; } }
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\value\FileValueImpl.java
1
请在Spring Boot框架中完成以下Java代码
public Builder samlResponse(String samlResponse) { this.parameters.put(Saml2ParameterNames.SAML_RESPONSE, samlResponse); return this; } /** * Use this SAML 2.0 Message Binding * * By default, the asserting party's configured binding is used * @param binding the SAML 2.0 Message Binding to use * @return the {@link Saml2LogoutRequest.Builder} for further configurations */ public Builder binding(Saml2MessageBinding binding) { this.binding = binding; return this; } /** * Use this location for the SAML 2.0 logout endpoint * * By default, the asserting party's endpoint is used * @param location the SAML 2.0 location to use * @return the {@link Saml2LogoutRequest.Builder} for further configurations */ public Builder location(String location) { this.location = location; return this; } /** * Use this value for the relay state when sending the Logout Request to the * asserting party * * It should not be URL-encoded as this will be done when the response is sent * @param relayState the relay state * @return the {@link Builder} for further configurations */ public Builder relayState(String relayState) { this.parameters.put(Saml2ParameterNames.RELAY_STATE, relayState); return this; } /** * Use this {@link Consumer} to modify the set of query parameters * * No parameter should be URL-encoded as this will be done when the response is * sent, though any signature specified should be Base64-encoded * @param parametersConsumer the {@link Consumer} * @return the {@link Builder} for further configurations */ public Builder parameters(Consumer<Map<String, String>> parametersConsumer) { parametersConsumer.accept(this.parameters); return this; } /**
* Use this strategy for converting parameters into an encoded query string. The * resulting query does not contain a leading question mark. * * In the event that you already have an encoded version that you want to use, you * can call this by doing {@code parameterEncoder((params) -> encodedValue)}. * @param encoder the strategy to use * @return the {@link Saml2LogoutRequest.Builder} for further configurations * @since 5.8 */ public Builder parametersQuery(Function<Map<String, String>, String> encoder) { this.encoder = encoder; return this; } /** * Build the {@link Saml2LogoutResponse} * @return a constructed {@link Saml2LogoutResponse} */ public Saml2LogoutResponse build() { return new Saml2LogoutResponse(this.location, this.binding, this.parameters, this.encoder); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\logout\Saml2LogoutResponse.java
2
请完成以下Java代码
public class FeelElContextFactory implements ElContextFactory { public static final FeelEngineLogger LOG = FeelLogger.ENGINE_LOGGER; protected CustomFunctionMapper customFunctionMapper = new CustomFunctionMapper(); public ELContext createContext(ExpressionFactory expressionFactory, VariableContext variableContext) { ELResolver elResolver = createElResolver(); FunctionMapper functionMapper = createFunctionMapper(); VariableMapper variableMapper = createVariableMapper(expressionFactory, variableContext); return new FeelElContext(elResolver, functionMapper, variableMapper); } public ELResolver createElResolver() { return new SimpleResolver(true); }
public FunctionMapper createFunctionMapper() { CompositeFunctionMapper functionMapper = new CompositeFunctionMapper(); functionMapper.add(new FeelFunctionMapper()); functionMapper.add(customFunctionMapper); return functionMapper; } public VariableMapper createVariableMapper(ExpressionFactory expressionFactory, VariableContext variableContext) { return new FeelTypedVariableMapper(expressionFactory, variableContext); } public void addCustomFunction(String name, Method method) { customFunctionMapper.addMethod(name, method); } }
repos\camunda-bpm-platform-master\engine-dmn\feel-juel\src\main\java\org\camunda\bpm\dmn\feel\impl\juel\el\FeelElContextFactory.java
1
请在Spring Boot框架中完成以下Java代码
public class PagesController { @RequestMapping("/multipleHttpLinks") public String getMultipleHttpLinksPage() { return "multipleHttpElems/multipleHttpLinks"; } @RequestMapping("/admin/myAdminPage") public String getAdminPage() { return "multipleHttpElems/myAdminPage"; } @RequestMapping("/user/general/myUserPage") public String getUserPage() { return "multipleHttpElems/myUserPage"; } @RequestMapping("/user/private/myPrivateUserPage") public String getPrivateUserPage() { return "multipleHttpElems/myPrivateUserPage"; } @RequestMapping("/guest/myGuestPage") public String getGuestPage() { return "multipleHttpElems/myGuestPage"; }
@RequestMapping("/userLogin") public String getUserLoginPage() { return "multipleHttpElems/login"; } @RequestMapping("/userLoginWithWarning") public String getUserLoginPageWithWarning() { return "multipleHttpElems/loginWithWarning"; } @RequestMapping("/403") public String getAccessDeniedPage() { return "403"; } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-2\src\main\java\com\baeldung\multipleentrypoints\PagesController.java
2
请完成以下Java代码
public void setS_Resource_ID (int S_Resource_ID) { if (S_Resource_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID)); } @Override public int getS_Resource_ID() { return get_ValueAsInt(COLUMNNAME_S_Resource_ID); } @Override public void setStatus_Print_Job_Instructions (boolean Status_Print_Job_Instructions) { set_ValueNoCheck (COLUMNNAME_Status_Print_Job_Instructions, Boolean.valueOf(Status_Print_Job_Instructions)); } @Override public boolean isStatus_Print_Job_Instructions() { return get_ValueAsBoolean(COLUMNNAME_Status_Print_Job_Instructions); } @Override public void setTrayNumber (int TrayNumber) { set_ValueNoCheck (COLUMNNAME_TrayNumber, Integer.valueOf(TrayNumber)); } @Override public int getTrayNumber() {
return get_ValueAsInt(COLUMNNAME_TrayNumber); } @Override public void setWP_IsError (boolean WP_IsError) { set_ValueNoCheck (COLUMNNAME_WP_IsError, Boolean.valueOf(WP_IsError)); } @Override public boolean isWP_IsError() { return get_ValueAsBoolean(COLUMNNAME_WP_IsError); } @Override public void setWP_IsProcessed (boolean WP_IsProcessed) { set_ValueNoCheck (COLUMNNAME_WP_IsProcessed, Boolean.valueOf(WP_IsProcessed)); } @Override public boolean isWP_IsProcessed() { return get_ValueAsBoolean(COLUMNNAME_WP_IsProcessed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Order_MFGWarehouse_Report_PrintInfo_v.java
1
请完成以下Java代码
public List<ImmutablePair<String, String>> listDeploymentIdMappings() { this.resultType = ResultType.LIST_DEPLOYMENT_ID_MAPPINGS; List<ImmutablePair<String, String>> ids = null; if (commandExecutor != null) { ids = (List<ImmutablePair<String, String>>) commandExecutor.execute(this); } else { ids = evaluateExpressionsAndExecuteDeploymentIdMappingsList(Context.getCommandContext()); } if (ids != null) { QueryMaxResultsLimitUtil.checkMaxResultsLimit(ids.size()); } return ids; } public List<String> evaluateExpressionsAndExecuteIdsList(CommandContext commandContext) { validate(); evaluateExpressions(); return !hasExcludingConditions() ? executeIdsList(commandContext) : new ArrayList<>(); } public List<String> executeIdsList(CommandContext commandContext) { throw new UnsupportedOperationException("executeIdsList not supported by " + getClass().getCanonicalName()); } public List<ImmutablePair<String, String>> evaluateExpressionsAndExecuteDeploymentIdMappingsList(CommandContext commandContext) { validate(); evaluateExpressions();
return !hasExcludingConditions() ? executeDeploymentIdMappingsList(commandContext) : new ArrayList<>(); } public List<ImmutablePair<String, String>> executeDeploymentIdMappingsList(CommandContext commandContext) { throw new UnsupportedOperationException("executeDeploymentIdMappingsList not supported by " + getClass().getCanonicalName()); } protected void checkMaxResultsLimit() { if (maxResultsLimitEnabled) { QueryMaxResultsLimitUtil.checkMaxResultsLimit(maxResults); } } public void enableMaxResultsLimit() { maxResultsLimitEnabled = true; } public void disableMaxResultsLimit() { maxResultsLimitEnabled = false; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\AbstractQuery.java
1
请在Spring Boot框架中完成以下Java代码
public RpPayWay getDataById(String id) { return rpPayWayDao.getById(id); } @Override public PageBean listPage(PageParam pageParam, RpPayWay rpPayWay) { Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("status", PublicStatusEnum.ACTIVE.name()); paramMap.put("payProductCode", rpPayWay.getPayProductCode()); paramMap.put("payWayName", rpPayWay.getPayWayName()); paramMap.put("payTypeName", rpPayWay.getPayTypeName()); return rpPayWayDao.listPage(pageParam, paramMap); } @Override public RpPayWay getByPayWayTypeCode(String payProductCode, String payWayCode, String payTypeCode){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("payProductCode", payProductCode); paramMap.put("payTypeCode", payTypeCode); paramMap.put("payWayCode", payWayCode); paramMap.put("status", PublicStatusEnum.ACTIVE.name()); return rpPayWayDao.getBy(paramMap); } /** * 绑定支付费率 * @param payWayCode * @param payTypeCode * @param payRate */ @Override public void createPayWay(String payProductCode, String payWayCode, String payTypeCode, Double payRate) throws PayBizException { RpPayWay payWay = getByPayWayTypeCode(payProductCode,payWayCode,payTypeCode); if(payWay!=null){ throw new PayBizException(PayBizException.PAY_TYPE_IS_EXIST,"支付渠道已存在"); } RpPayProduct rpPayProduct = rpPayProductService.getByProductCode(payProductCode, null); if(rpPayProduct.getAuditStatus().equals(PublicEnum.YES.name())){ throw new PayBizException(PayBizException.PAY_PRODUCT_IS_EFFECTIVE,"支付产品已生效,无法绑定!"); }
RpPayWay rpPayWay = new RpPayWay(); rpPayWay.setPayProductCode(payProductCode); rpPayWay.setPayRate(payRate); rpPayWay.setPayWayCode(payWayCode); rpPayWay.setPayWayName(PayWayEnum.getEnum(payWayCode).getDesc()); rpPayWay.setPayTypeCode(payTypeCode); rpPayWay.setPayTypeName(PayTypeEnum.getEnum(payTypeCode).getDesc()); rpPayWay.setStatus(PublicStatusEnum.ACTIVE.name()); rpPayWay.setCreateTime(new Date()); rpPayWay.setId(StringUtil.get32UUID()); saveData(rpPayWay); } /** * 根据支付产品获取支付方式 */ @Override public List<RpPayWay> listByProductCode(String payProductCode){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("payProductCode", payProductCode); paramMap.put("status", PublicStatusEnum.ACTIVE.name()); return rpPayWayDao.listBy(paramMap); } /** * 获取所有支付方式 */ @Override public List<RpPayWay> listAll(){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("status", PublicStatusEnum.ACTIVE.name()); return rpPayWayDao.listBy(paramMap); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\service\impl\RpPayWayServiceImpl.java
2
请完成以下Java代码
private int getReturnsDocTypeId(final String docBaseType, final boolean isSOTrx, final int adClientId, final int adOrgId) { return returnsDocTypeIdProvider.getReturnsDocTypeId(docBaseType, isSOTrx, adClientId, adOrgId); } public ReturnsInOutHeaderFiller setBPartnerId(final int bpartnerId) { this.bpartnerId = bpartnerId; return this; } private int getBPartnerId() { return bpartnerId; } public ReturnsInOutHeaderFiller setBPartnerLocationId(final int bpartnerLocationId) { this.bpartnerLocationId = bpartnerLocationId; return this; } private int getBPartnerLocationId() { return bpartnerLocationId; } public ReturnsInOutHeaderFiller setMovementDate(final Timestamp movementDate) { this.movementDate = movementDate; return this; } private Timestamp getMovementDate() { return movementDate; } public ReturnsInOutHeaderFiller setWarehouseId(final int warehouseId) { this.warehouseId = warehouseId; return this; } private int getWarehouseId() { return warehouseId; } public ReturnsInOutHeaderFiller setOrder(@Nullable final I_C_Order order) { this.order = order; return this; } private I_C_Order getOrder() { return order; } public ReturnsInOutHeaderFiller setExternalId(@Nullable final String externalId)
{ this.externalId = externalId; return this; } private String getExternalId() { return this.externalId; } private String getExternalResourceURL() { return this.externalResourceURL; } public ReturnsInOutHeaderFiller setExternalResourceURL(@Nullable final String externalResourceURL) { this.externalResourceURL = externalResourceURL; return this; } public ReturnsInOutHeaderFiller setDateReceived(@Nullable final Timestamp dateReceived) { this.dateReceived = dateReceived; return this; } private Timestamp getDateReceived() { return dateReceived; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\ReturnsInOutHeaderFiller.java
1
请完成以下Java代码
public static class DefaultKafkaListenerObservationConvention implements KafkaListenerObservationConvention { /** * A singleton instance of the convention. */ public static final DefaultKafkaListenerObservationConvention INSTANCE = new DefaultKafkaListenerObservationConvention(); @Override @NonNull public KeyValues getLowCardinalityKeyValues(KafkaRecordReceiverContext context) { String groupId = context.getGroupId(); KeyValues keyValues = KeyValues.of( ListenerLowCardinalityTags.LISTENER_ID.withValue(context.getListenerId()), ListenerLowCardinalityTags.MESSAGING_SYSTEM.withValue("kafka"), ListenerLowCardinalityTags.MESSAGING_OPERATION.withValue("process"), ListenerLowCardinalityTags.MESSAGING_SOURCE_NAME.withValue(context.getSource()), ListenerLowCardinalityTags.MESSAGING_SOURCE_KIND.withValue("topic") ); if (StringUtils.hasText(groupId)) { keyValues = keyValues .and(ListenerLowCardinalityTags.MESSAGING_CONSUMER_GROUP.withValue(groupId)); } return keyValues; } @Override @NonNull public KeyValues getHighCardinalityKeyValues(KafkaRecordReceiverContext context) { String clientId = context.getClientId(); String consumerId = getConsumerId(context.getGroupId(), clientId); KeyValues keyValues = KeyValues.of(
ListenerHighCardinalityTags.MESSAGING_PARTITION.withValue(context.getPartition()), ListenerHighCardinalityTags.MESSAGING_OFFSET.withValue(context.getOffset()) ); if (StringUtils.hasText(clientId)) { keyValues = keyValues .and(ListenerHighCardinalityTags.MESSAGING_CLIENT_ID.withValue(clientId)); } if (StringUtils.hasText(consumerId)) { keyValues = keyValues .and(ListenerHighCardinalityTags.MESSAGING_CONSUMER_ID.withValue(consumerId)); } return keyValues; } @Override public String getContextualName(KafkaRecordReceiverContext context) { return context.getSource() + " process"; } private static @Nullable String getConsumerId(@Nullable String groupId, @Nullable String clientId) { if (StringUtils.hasText(groupId)) { if (StringUtils.hasText(clientId)) { return groupId + " - " + clientId; } return groupId; } return clientId; } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\micrometer\KafkaListenerObservation.java
1
请完成以下Java代码
public class HibernateOneToManyAnnotationMain { private static final Logger LOGGER = LoggerFactory.getLogger(HibernateOneToManyAnnotationMain.class); public static void main(String[] args) { Cart cart = new Cart(); Item item1 = new Item(cart); Item item2 = new Item(cart); Set<Item> itemsSet = new HashSet<>(); itemsSet.add(item1); itemsSet.add(item2); cart.setItems(itemsSet); SessionFactory sessionFactory = HibernateAnnotationUtil.getSessionFactory(); Session session = sessionFactory.getCurrentSession(); LOGGER.info("Session created"); try { // start transaction Transaction tx = session.beginTransaction(); // Save the Model object session.persist(cart);
session.persist(item1); session.persist(item2); // Commit transaction tx.commit(); LOGGER.info("Cart ID={}", cart.getId()); LOGGER.info("item1 ID={}, Foreign Key Cart ID={}", item1.getId(), item1.getCart().getId()); LOGGER.info("item2 ID={}, Foreign Key Cart ID={}", item2.getId(), item2.getCart().getId()); } catch (Exception e) { LOGGER.error("Exception occurred", e); } finally { if (!sessionFactory.isClosed()) { LOGGER.info("Closing SessionFactory"); sessionFactory.close(); } } } }
repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\oneToMany\main\HibernateOneToManyAnnotationMain.java
1
请完成以下Java代码
public static Date getYesterdayStartTime() { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.add(Calendar.DATE, -1); return DateUtil.beginOfDay(calendar.getTime()); } /** * 昨天结束时间 * * @return */ public static Date getYesterdayEndTime() { return DateUtil.endOfDay(getYesterdayStartTime()); } /** * 明天开始时间 * * @return */ public static Date getTomorrowStartTime() { return DateUtil.beginOfDay(DateUtil.tomorrow()); } /** * 明天结束时间 * * @return */ public static Date getTomorrowEndTime() { return DateUtil.endOfDay(DateUtil.tomorrow()); }
/** * 今天开始时间 * * @return */ public static Date getTodayStartTime() { return DateUtil.beginOfDay(new Date()); } /** * 今天结束时间 * * @return */ public static Date getTodayEndTime() { return DateUtil.endOfDay(new Date()); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\DateRangeUtils.java
1
请在Spring Boot框架中完成以下Java代码
public static List toList() { OrderFromEnum[] ary = OrderFromEnum.values(); List list = new ArrayList(); for (int i = 0; i < ary.length; i++) { Map<String, String> map = new HashMap<String, String>(); map.put("desc", ary[i].getDesc()); list.add(map); } return list; } public static OrderFromEnum getEnum(String name) { OrderFromEnum[] arry = OrderFromEnum.values(); for (int i = 0; i < arry.length; i++) { if (arry[i].name().equalsIgnoreCase(name)) { return arry[i]; } } return null; }
/** * 取枚举的json字符串 * * @return */ public static String getJsonStr() { OrderFromEnum[] enums = OrderFromEnum.values(); StringBuffer jsonStr = new StringBuffer("["); for (OrderFromEnum senum : enums) { if (!"[".equals(jsonStr.toString())) { jsonStr.append(","); } jsonStr.append("{id:'").append(senum).append("',desc:'").append(senum.getDesc()).append("'}"); } jsonStr.append("]"); return jsonStr.toString(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\enums\OrderFromEnum.java
2
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public int getInstances() { return instances; } public void setInstances(int instances) { this.instances = instances; } public int getFailedJobs() { return failedJobs; } public void setFailedJobs(int failedJobs) { this.failedJobs = failedJobs; }
public List<IncidentStatistics> getIncidentStatistics() { return incidentStatistics; } public void setIncidentStatistics(List<IncidentStatistics> incidentStatistics) { this.incidentStatistics = incidentStatistics; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", instances=" + instances + ", failedJobs=" + failedJobs + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ActivityStatisticsImpl.java
1
请完成以下Java代码
public class PropertiesReader { /** * Properties managed by this reader. */ private Properties properties; /** * Reads the property file with the given name. * * @param propertyFileName the name of the property file to read * @throws IOException if the file is not found or there's a problem reading it */ public PropertiesReader(String propertyFileName) throws IOException { InputStream is = getClass().getClassLoader()
.getResourceAsStream(propertyFileName); this.properties = new Properties(); this.properties.load(is); } /** * Gets the property with the given name from the property file. * @param propertyName the name of the property to read * @return the property with the given name */ public String getProperty(String propertyName) { return this.properties.getProperty(propertyName); } }
repos\tutorials-master\maven-modules\maven-properties\src\main\java\com\baeldung\maven\properties\PropertiesReader.java
1
请完成以下Java代码
public void setParameterName(String parameterName) { Assert.notNull(parameterName, "parameterName cannot be null"); this.parameterName = parameterName; } /** * Sets the name of the HTTP header that should be used to provide the token. * @param headerName the name of the HTTP header that should be used to provide the * token */ public void setHeaderName(String headerName) { Assert.notNull(headerName, "headerName cannot be null"); this.headerName = headerName; } /** * Sets the name of the cookie that the expected CSRF token is saved to and read from. * @param cookieName the name of the cookie that the expected CSRF token is saved to * and read from */ public void setCookieName(String cookieName) { Assert.notNull(cookieName, "cookieName cannot be null"); this.cookieName = cookieName; } private String getRequestContext(HttpServletRequest request) { String contextPath = request.getContextPath(); return (contextPath.length() > 0) ? contextPath : "/"; } /** * Factory method to conveniently create an instance that creates cookies where * {@link Cookie#isHttpOnly()} is set to false. * @return an instance of CookieCsrfTokenRepository that creates cookies where * {@link Cookie#isHttpOnly()} is set to false. */ public static CookieCsrfTokenRepository withHttpOnlyFalse() { CookieCsrfTokenRepository result = new CookieCsrfTokenRepository(); result.cookieHttpOnly = false; return result; } private String createNewToken() { return UUID.randomUUID().toString(); } private Cookie mapToCookie(ResponseCookie responseCookie) { Cookie cookie = new Cookie(responseCookie.getName(), responseCookie.getValue());
cookie.setSecure(responseCookie.isSecure()); cookie.setPath(responseCookie.getPath()); cookie.setMaxAge((int) responseCookie.getMaxAge().getSeconds()); cookie.setHttpOnly(responseCookie.isHttpOnly()); if (StringUtils.hasLength(responseCookie.getDomain())) { cookie.setDomain(responseCookie.getDomain()); } if (StringUtils.hasText(responseCookie.getSameSite())) { cookie.setAttribute("SameSite", responseCookie.getSameSite()); } return cookie; } /** * Set the path that the Cookie will be created with. This will override the default * functionality which uses the request context as the path. * @param path the path to use */ public void setCookiePath(String path) { this.cookiePath = path; } /** * Get the path that the CSRF cookie will be set to. * @return the path to be used. */ public @Nullable String getCookiePath() { return this.cookiePath; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\csrf\CookieCsrfTokenRepository.java
1
请完成以下Java代码
public boolean isProductIncluded(final I_C_RfQ_TopicSubscriber subscriber, final int M_Product_ID) { final List<I_C_RfQ_TopicSubscriberOnly> restrictions = Services.get(IRfqTopicDAO.class).retrieveRestrictions(subscriber); // No restrictions if (restrictions.isEmpty()) { return true; } for (final I_C_RfQ_TopicSubscriberOnly restriction : restrictions) { if (!restriction.isActive()) { continue; } // Product if (restriction.getM_Product_ID() == M_Product_ID)
{ return true; } // Product Category if (Services.get(IProductBL.class).isProductInCategory(ProductId.ofRepoIdOrNull(M_Product_ID), ProductCategoryId.ofRepoIdOrNull(restriction.getM_Product_Category_ID()))) { return true; } } // must be on "positive" list return false; } // isIncluded }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\impl\RfqTopicBL.java
1
请完成以下Java代码
public void execute(DelegateExecution execution) { ProcessDefinition processDefinition = ProcessDefinitionUtil.getProcessDefinition(execution.getProcessDefinitionId()); String deploymentId = processDefinition.getDeploymentId(); KieBase knowledgeBase = RulesHelper.findKnowledgeBaseByDeploymentId(deploymentId); KieSession ksession = knowledgeBase.newKieSession(); if (variablesInputExpressions != null) { Iterator<Expression> itVariable = variablesInputExpressions.iterator(); while (itVariable.hasNext()) { Expression variable = itVariable.next(); ksession.insert(variable.getValue(execution)); } } if (!rulesExpressions.isEmpty()) { RulesAgendaFilter filter = new RulesAgendaFilter(); Iterator<Expression> itRuleNames = rulesExpressions.iterator(); while (itRuleNames.hasNext()) { Expression ruleName = itRuleNames.next(); filter.addSuffic(ruleName.getValue(execution).toString()); } filter.setAccept(!exclude); ksession.fireAllRules(filter); } else { ksession.fireAllRules(); } Collection<? extends Object> ruleOutputObjects = ksession.getObjects(); if (ruleOutputObjects != null && !ruleOutputObjects.isEmpty()) { Collection<Object> outputVariables = new ArrayList<>(ruleOutputObjects);
execution.setVariable(resultVariable, outputVariables); } ksession.dispose(); leave(execution); } @Override public void addRuleVariableInputIdExpression(Expression inputId) { this.variablesInputExpressions.add(inputId); } @Override public void addRuleIdExpression(Expression inputId) { this.rulesExpressions.add(inputId); } @Override public void setExclude(boolean exclude) { this.exclude = exclude; } @Override public void setResultVariable(String resultVariableName) { this.resultVariable = resultVariableName; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\behavior\BusinessRuleTaskActivityBehavior.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isUseFrameworkRetryFilter() { return useFrameworkRetryFilter; } public void setUseFrameworkRetryFilter(boolean useFrameworkRetryFilter) { this.useFrameworkRetryFilter = useFrameworkRetryFilter; } public int getStreamingBufferSize() { return streamingBufferSize; } public void setStreamingBufferSize(int streamingBufferSize) { this.streamingBufferSize = streamingBufferSize; } public @Nullable String getTrustedProxies() { return trustedProxies; }
public void setTrustedProxies(String trustedProxies) { this.trustedProxies = trustedProxies; } @Override public String toString() { return new ToStringCreator(this).append("routes", routes) .append("routesMap", routesMap) .append("streamingMediaTypes", streamingMediaTypes) .append("streamingBufferSize", streamingBufferSize) .append("trustedProxies", trustedProxies) .toString(); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\config\GatewayMvcProperties.java
2
请在Spring Boot框架中完成以下Java代码
public JwtTokenFilter jwtTokenFilter() { return new JwtTokenFilter(); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .cors() .and() .exceptionHandling().authenticationEntryPoint(new Http401AuthenticationEntryPoint("Unauthenticated")) .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .authorizeRequests() .antMatchers(HttpMethod.OPTIONS).permitAll() .antMatchers(HttpMethod.GET, "/articles/feed").authenticated() .antMatchers(HttpMethod.POST, "/users", "/users/login").permitAll() .antMatchers(HttpMethod.GET, "/articles/**", "/profiles/**", "/tags").permitAll() .anyRequest().authenticated(); http.addFilterBefore(jwtTokenFilter(), UsernamePasswordAuthenticationFilter.class); }
@Bean public CorsConfigurationSource corsConfigurationSource() { final CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(asList("*")); configuration.setAllowedMethods(asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH")); // setAllowCredentials(true) is important, otherwise: // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. configuration.setAllowCredentials(true); // setAllowedHeaders is important! Without it, OPTIONS preflight request // will fail with 403 Invalid CORS request configuration.setAllowedHeaders(asList("Authorization", "Cache-Control", "Content-Type")); final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } }
repos\spring-boot-realworld-example-app-master (1)\src\main\java\io\spring\api\security\WebSecurityConfig.java
2
请完成以下Java代码
public String getType() { return TYPE; } @Override public Object getPersistentState() { Map<String, Object> persistentState = (HashMap) super.getPersistentState(); persistentState.put("repeat", repeat); return persistentState; } @Override public String toString() { return this.getClass().getSimpleName() + "[repeat=" + repeat + ", id=" + id + ", revision=" + revision
+ ", duedate=" + duedate + ", repeatOffset=" + repeatOffset + ", lockOwner=" + lockOwner + ", lockExpirationTime=" + lockExpirationTime + ", executionId=" + executionId + ", processInstanceId=" + processInstanceId + ", isExclusive=" + isExclusive + ", retries=" + retries + ", jobHandlerType=" + jobHandlerType + ", jobHandlerConfiguration=" + jobHandlerConfiguration + ", exceptionByteArray=" + exceptionByteArray + ", exceptionByteArrayId=" + exceptionByteArrayId + ", exceptionMessage=" + exceptionMessage + ", deploymentId=" + deploymentId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TimerEntity.java
1
请完成以下Java代码
public BigDecimal getMultiplyRate( @NonNull final CurrencyId fromCurrencyId, @NonNull final CurrencyId toCurrencyId) { final BigDecimal multiplyRate = getMultiplyRateOrNull(fromCurrencyId, toCurrencyId); if (multiplyRate == null) { throw new AdempiereException("No fixed conversion rate found from " + fromCurrencyId + " to " + toCurrencyId + "." + " Available rates are: " + rates.values()); } return multiplyRate; } public boolean hasMultiplyRate( @NonNull final CurrencyId fromCurrencyId, @NonNull final CurrencyId toCurrencyId) { return getMultiplyRateOrNull(fromCurrencyId, toCurrencyId) != null; } @Nullable private BigDecimal getMultiplyRateOrNull( @NonNull final CurrencyId fromCurrencyId, @NonNull final CurrencyId toCurrencyId) {
final FixedConversionRate rate = rates.get(FixedConversionRateKey.builder() .fromCurrencyId(fromCurrencyId) .toCurrencyId(toCurrencyId) .build()); return rate != null ? rate.getMultiplyRate() : null; } @Value @Builder private static class FixedConversionRateKey { @NonNull CurrencyId fromCurrencyId; @NonNull CurrencyId toCurrencyId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\FixedConversionRateMap.java
1
请完成以下Java代码
public static Student createDeepCopy(Student student) { ObjectMapper objectMapper = new ObjectMapper(); try { return objectMapper.readValue(objectMapper.writeValueAsString(student), Student.class); } catch (JsonProcessingException e) { throw new IllegalArgumentException(e); } } public static List<Student> deepCopyUsingJackson(List<Student> students) { return students.stream() .map(Student::createDeepCopy) .collect(Collectors.toList()); } public static List<Student> deepCopyUsingCloneable(List<Student> students) { return students.stream() .map(Student::clone) .collect(Collectors.toList()); } public static List<Student> deepCopyUsingCopyConstructor(List<Student> students) { return students.stream() .map(Student::new) .collect(Collectors.toList()); } public static List<Student> deepCopyUsingSerialization(List<Student> students) { return students.stream() .map(SerializationUtils::clone) .collect(Collectors.toList()); } public int getStudentId() { return studentId; } public void setStudentId(int studentId) { this.studentId = studentId; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public Course getCourse() { return course; }
public void setCourse(Course course) { this.course = course; } @Override public Student clone() { Student student; try { student = (Student) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } student.course = this.course.clone(); return student; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student that = (Student) o; return Objects.equals(studentId,that.studentId) && Objects.equals(studentName, that.studentName) && Objects.equals(course, that.course); } @Override public int hashCode() { return Objects.hash(studentId,studentName,course); } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-patterns-2\src\main\java\com\baeldung\deepcopyarraylist\Student.java
1
请在Spring Boot框架中完成以下Java代码
class DummyService { private static final Logger log = LoggerFactory.getLogger(DummyService.class); private final MeterRegistry meterRegistry; private final Meter.MeterProvider<Counter> counterProvider; private final Meter.MeterProvider<Timer> timerProvider; public DummyService(MeterRegistry meterRegistry) { this.meterRegistry = meterRegistry; this.counterProvider = Counter.builder("bar.count") .withRegistry(meterRegistry); this.timerProvider = Timer.builder("bar.time") .withRegistry(meterRegistry); } public String foo(String deviceType) { log.info("foo({})", deviceType); Counter.builder("foo.count") .tag("device.type", deviceType) .register(meterRegistry) .increment(); String response = Timer.builder("foo.time") .tag("device.type", deviceType) .register(meterRegistry) .record(this::invokeSomeLogic); return response; } public String bar(String device) { log.info("bar({})", device); counterProvider.withTag("device.type", device) .increment();
String response = timerProvider.withTag("device.type", device) .record(this::invokeSomeLogic); return response; } @Timed("buzz.time") @Counted("buzz.count") public String buzz(@MeterTag("device.type") String device) { log.info("buzz({})", device); return invokeSomeLogic(); } private String invokeSomeLogic() { long sleepMs = ThreadLocalRandom.current() .nextInt(0, 100); try { Thread.sleep(sleepMs); } catch (InterruptedException e) { throw new RuntimeException(e); } return "dummy response"; } }
repos\tutorials-master\spring-boot-modules\spring-boot-3-observation\src\main\java\com\baeldung\micrometer\tags\dummy\DummyService.java
2
请完成以下Java代码
public Void execute(CommandContext commandContext) { if (task == null) { throw new ActivitiIllegalArgumentException("task is null"); } if (task.getRevision() == 0) { task.insert(null, true); // Need to to be done here, we can't make it generic for standalone tasks // and tasks from a process, as the order of setting properties is // completely different. if (Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.TASK_CREATED, task), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG);
if (task.getAssignee() != null) { // The assignment event is normally fired when calling setAssignee. However, this // doesn't work for standalone tasks as the commandcontext is not available. Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.TASK_ASSIGNED, task), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); } } } else { task.update(); } return null; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cmd\SaveTaskCmd.java
1
请完成以下Java代码
public class InvocationImpl extends ExpressionImpl implements Invocation { protected static ChildElement<Expression> expressionChild; protected static ChildElementCollection<Binding> bindingCollection; public InvocationImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public Expression getExpression() { return expressionChild.getChild(this); } public void setExpression(Expression expression) { expressionChild.setChild(this, expression); } public Collection<Binding> getBindings() { return bindingCollection.get(this); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Invocation.class, DMN_ELEMENT_INVOCATION)
.namespaceUri(LATEST_DMN_NS) .extendsType(Expression.class) .instanceProvider(new ModelTypeInstanceProvider<Invocation>() { public Invocation newInstance(ModelTypeInstanceContext instanceContext) { return new InvocationImpl(instanceContext); } }); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); expressionChild = sequenceBuilder.element(Expression.class) .build(); bindingCollection = sequenceBuilder.elementCollection(Binding.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\InvocationImpl.java
1
请完成以下Java代码
public QueueProcessorStatistics clone() { return new QueueProcessorStatistics(this); } @Override public long getCountAll() { return countAll; } @Override public void incrementCountAll() { countAll++; } @Override public long getCountProcessed() { return countProcessed; } @Override public void incrementCountProcessed() { countProcessed++; } @Override public long getCountErrors() { return countErrors; } @Override public void incrementCountErrors() {
countErrors++; } @Override public long getQueueSize() { return queueSize; } @Override public void incrementQueueSize() { queueSize++; } @Override public void decrementQueueSize() { queueSize--; } @Override public long getCountSkipped() { return countSkipped; } @Override public void incrementCountSkipped() { countSkipped++; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\QueueProcessorStatistics.java
1
请完成以下Java代码
public List<String> getIds() { return ids; } public void setIds(List<String> ids) { this.ids = ids; } public DeploymentMappings getIdMappings() { return idMappings; } public void setIdMappings(DeploymentMappings idMappings) { this.idMappings = idMappings; }
public boolean isFailIfNotExists() { return failIfNotExists; } public void setFailIfNotExists(boolean failIfNotExists) { this.failIfNotExists = failIfNotExists; } public String getBatchId() { return batchId; } public void setBatchId(String batchId) { this.batchId = batchId; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\BatchConfiguration.java
1
请完成以下Java代码
public final String getMessage() { return message; } /** * @param argMessage * the message to set */ public final void setMessage(final String argMessage) { this.message = argMessage; } /** * @return the navTabId */ public final String getNavTabId() { return navTabId; } /** * @param argNavTabId * the navTabId to set */ public final void setNavTabId(final String argNavTabId) { this.navTabId = argNavTabId; } /** * @return the callbackType */ public final String getCallbackType() { return callbackType; } /**
* @param argCallbackType * the callbackType to set */ public final void setCallbackType(final String argCallbackType) { this.callbackType = argCallbackType; } /** * @return the forwardUrl */ public final String getForwardUrl() { return forwardUrl; } /** * @param argForwardUrl * the forwardUrl to set */ public final void setForwardUrl(final String argForwardUrl) { this.forwardUrl = argForwardUrl; } }
repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\dwz\DwzAjax.java
1
请完成以下Java代码
public String getJobDefinitionId() { return jobDefinitionId; } protected String resolveJobDefinitionId(S context) { return jobDefinitionId; } public void setJobDefinitionId(String jobDefinitionId) { this.jobDefinitionId = jobDefinitionId; } public String getJobHandlerType() { return jobHandlerType; } protected JobHandler resolveJobHandler() { JobHandler jobHandler = Context.getProcessEngineConfiguration().getJobHandlers().get(jobHandlerType); ensureNotNull("Cannot find job handler '" + jobHandlerType + "' from job '" + this + "'", "jobHandler", jobHandler); return jobHandler; } protected String resolveJobHandlerType(S context) { return jobHandlerType; } protected abstract JobHandlerConfiguration resolveJobHandlerConfiguration(S context); protected boolean resolveExclusive(S context) { return exclusive; } protected int resolveRetries(S context) { return Context.getProcessEngineConfiguration().getDefaultNumberOfRetries(); } public Date resolveDueDate(S context) { ProcessEngineConfiguration processEngineConfiguration = Context.getProcessEngineConfiguration(); if (processEngineConfiguration != null && (processEngineConfiguration.isJobExecutorAcquireByDueDate() || processEngineConfiguration.isEnsureJobDueDateNotNull())) { return ClockUtil.getCurrentTime(); } else { return null; } } public boolean isExclusive() { return exclusive; } public void setExclusive(boolean exclusive) { this.exclusive = exclusive; } public String getActivityId() { if (activity != null) { return activity.getId(); } else { return null;
} } public ActivityImpl getActivity() { return activity; } public void setActivity(ActivityImpl activity) { this.activity = activity; } public ProcessDefinitionImpl getProcessDefinition() { if (activity != null) { return activity.getProcessDefinition(); } else { return null; } } public String getJobConfiguration() { return jobConfiguration; } public void setJobConfiguration(String jobConfiguration) { this.jobConfiguration = jobConfiguration; } public ParameterValueProvider getJobPriorityProvider() { return jobPriorityProvider; } public void setJobPriorityProvider(ParameterValueProvider jobPriorityProvider) { this.jobPriorityProvider = jobPriorityProvider; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\JobDeclaration.java
1